Skip to content

MCP Protocol

Technical reference for the Nefia MCP server protocol.

Nefia includes a built-in MCP (Model Context Protocol) server that enables AI agents to manage remote hosts through a structured tool interface. The server exposes 205 core tools for command execution, file management, host discovery, playbook management, system queries, package management, user management, cron management, service management, network diagnostics, firewall management, system updates, mount management, container management, queue management, scheduling, reactor automation, compliance, diagnostics, VPN management, device security, webhooks, backups, composite workflows, and privilege escalation over JSON-RPC 2.0 via stdio. When the approval workflow is enabled in the configuration, 2 additional approval tools are available (207 tools total). All 207 tools include outputSchema definitions so AI agents can predict response structure before calling. The server also provides 51 workflow prompts, 22 resources (20 static + 2 templates), and progressive tool discovery. Tools are organized into 18 categories: agent, audit, automation, cluster, composite, container, core, fs, infra, management, network, ops, pki, policy, security, system-mutation, system-query, and vpn.

Starting the Server

bash
nefia mcp serve

The server reads from stdin and writes to stdout using the MCP protocol (JSON-RPC 2.0, UTF-8). AI agents connect by spawning the nefia mcp serve process and communicating over its standard I/O streams.

Connection Setup

Claude Desktop / Claude Code

json
{
  "mcpServers": {
    "nefia": {
      "command": "nefia",
      "args": ["mcp", "serve"]
    }
  }
}

Or via the Claude Code CLI:

bash
claude mcp add nefia -- nefia mcp serve

Codex CLI (OpenAI)

Add to ~/.codex/config.toml:

toml
[mcp_servers.nefia]
command = "nefia"
args = ["mcp", "serve"]

The server initializes by loading nefia.yaml, establishing VPN connections, and advertising available tools. Configuration changes are hot-reloaded during the session.

Common Setup Issues

  • Authentication required. Run nefia login before starting the server. The MCP server is not auth-exempt, so it exits immediately without a valid session. Most MCP clients suppress stderr, making this look like a silent connection failure.
  • PATH resolution. MCP clients do not load shell profiles. If nefia is not in the system-wide PATH, use the absolute path (e.g., /usr/local/bin/nefia). Run which nefia to find it.
  • Windows. Some MCP clients require cmd /c to launch executables: "command": "cmd", "args": ["/c", "nefia", "mcp", "serve"]. Alternatively, use PowerShell: "command": "powershell", "args": ["-Command", "nefia mcp serve"].

Tool Reference

Session Tools

Sessions provide a persistent, sandboxed context for file operations on a specific host. Each MCP client is limited to 50 concurrent sessions. Attempting to open a 51st session returns an error. The server tracks session ownership per client, so nefia.session.list returns only the calling client's own sessions, and clients cannot see or interfere with other clients' sessions.

nefia.session.open -- Open a session

Creates a new session bound to a host and root directory. All subsequent file operations within the session are confined to the root. The cwd (working directory) defaults to root if not specified. Multiple sessions can be open simultaneously for different hosts (up to 50 per client).

Parameters:

ParameterTypeRequiredDescription
host_idstringyesTarget host ID as defined in the configuration (e.g., pc-office, server-dev).
rootstringnoRoot directory on the remote host. All file paths will be resolved relative to this. Defaults to the host's configured root.
cwdstringnoInitial working directory (relative to root). Defaults to root if not specified.

Returns:

FieldTypeDescription
session_idstringUnique session identifier for subsequent operations.
resolved_rootstringEffective root directory on the remote host.
resolved_cwdstringEffective working directory (resolved from cwd parameter or defaulting to root).

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true

nefia.session.close -- Close a session

Closes an active session and releases associated resources. After closing, the session_id becomes invalid and cannot be reused. Any in-flight operations on the session will be cancelled.

Parameters:

ParameterTypeRequiredDescription
session_idstringyesSession ID returned by nefia.session.open.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false

Execution Tools

nefia.exec -- Execute a command

Runs a shell command on one or more remote hosts. Target selection uses either session_id (execute on the session's host in the session's working directory) or target (a selector expression), but not both.

The command is passed to the remote shell (zsh on macOS, bash on Linux, PowerShell on Windows). Note that PowerShell uses different escaping rules -- special characters like $, (, ) may need escaping with a backtick or wrapping in single quotes.

Parameters:

ParameterTypeRequiredDescription
commandstringyesShell command to execute on the remote host(s).
session_idstringnoSession ID (use this or target, not both).
targetstringnoHost selector: all, host:<id>, group:<name>, or tag:k=v.
timeout_msintnoCommand timeout in milliseconds. Defaults to the configured timeout (30m). Hard-capped at 2 hours (7,200,000 ms).
concurrencyintnoMaximum number of hosts to execute on concurrently. Defaults to configured value (50).
progress_intervalstringnoInterval for progress notifications during long-running commands (e.g., 30s, 1m).
envobjectnoEnvironment variables to inject. Keys must match [a-zA-Z_][a-zA-Z0-9_]*. Secret provider references (${provider:path}) are resolved.
dry_runbooleannoIf true, resolve targets and check policy without executing. Returns host list with allowed/denied status.
batch_sizeintnoNumber of hosts per batch for rolling execution. 0 = all at once (default).
batch_waitstringnoPause between batches. Go duration format (e.g., 5s, 30s, 1m).
subsetintnoExecute on a random subset of N hosts from the resolved target. 0 = all hosts (default).
rerunstringnoRe-execute on hosts from a previous job. failure = only failed hosts, success = only successful hosts. Requires last_job_id.
last_job_idstringnoJob ID from a previous exec result. Required when rerun is set.
fail_fastbooleannoStop execution immediately on the first host failure. Remaining hosts are skipped.
min_success_ratenumbernoMinimum success rate (0.0–1.0) required to continue execution. If the success rate drops below this threshold, remaining hosts are skipped.
stdinstringnoStandard input to pipe to the command.
working_directorystringnoWorking directory for command execution (relative to session root or host root).
uidstringnoRun as this user (uid or username) on the target host.

Returns (per host):

FieldTypeDescription
host_idstringHost identifier.
okbooleanWhether the command succeeded (exit code 0).
stdoutstringStandard output.
stderrstringStandard error.
exit_codeintProcess exit code (0 = success).
duration_msintegerCommand execution duration in milliseconds.
truncatedbooleanWhether stdout/stderr was truncated.
error_codestringStructured error code (e.g., E5001) if the command failed.
error_messagestringHuman-readable error message.
error_hintsstring[]Suggested actions to resolve the error.

Output buffer per host is capped at 50 MB (or max_output_bytes * 2) to prevent memory exhaustion.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.exec.sudo -- Execute with sudo

Runs a command with sudo privilege escalation on remote hosts. Requires sudo.enabled: true in configuration and NOPASSWD configured in sudoers for the SSH user on target hosts.

Parameters:

ParameterTypeRequiredDescription
commandstringyesShell command to execute with sudo privileges.
session_idstringnoSession ID (use this or target, not both).
targetstringnoHost selector: all, host:<id>, group:<name>, or tag:k=v.
userstringnoUser to run as (default: root). Must be a valid Unix username.
timeout_msintnoCommand timeout in milliseconds. Hard-capped at 2 hours.
concurrencyintnoMaximum number of hosts to execute on concurrently (default: 50).
progress_intervalstringnoInterval for progress notifications during long-running commands.

Returns (per host):

FieldTypeDescription
host_idstringHost identifier.
okbooleanWhether the command succeeded (exit code 0).
exit_codeintProcess exit code.
stdoutstringStandard output.
stderrstringStandard error.
duration_msintExecution duration in milliseconds.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

File System Tools

File system tools accept either session_id or host_id to identify the target host. When using session_id, paths are resolved relative to the session root. When using host_id, paths are resolved relative to the host's configured root.

nefia.fs.read -- Read a file

Returns the file content as UTF-8 text. For large files (over 10 MB), use nefia.fs.stream_read instead.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile path relative to the root directory (e.g., src/main.go, config.yaml).
max_bytesintnoMaximum bytes to read. Defaults to configured limit (10 MB).

Returns:

FieldTypeDescription
contentstringFile contents (UTF-8 or base64-encoded).
is_base64booleanWhether content is base64-encoded.
truncatedbooleanWhether output was truncated due to max_bytes.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.write -- Write a file

Writes content to a file on a remote host. Provide either content (UTF-8 text) or content_base64 (binary data), not both. Creates the file if it does not exist; overwrites if it does.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile path relative to the root directory.
contentstringnoUTF-8 text content to write.
content_base64stringnoBase64-encoded binary content for non-text files (images, archives, etc.).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.fs.patch -- Patch a file

Applies a unified diff to an existing file. Supports an optional expected_sha256 for optimistic concurrency control -- the patch is rejected if the file has been modified since reading.

This is safer than nefia.fs.write for modifying existing files, as it applies only the intended changes rather than replacing the entire file.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile path relative to the root directory.
unified_diffstringyesUnified diff to apply (standard diff -u format).
expected_sha256stringnoSHA-256 hex digest of the current file content. Patch is rejected if the file has been modified.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true

nefia.fs.list -- List directory

Lists entries in a directory. Returns file names, sizes, permissions, and modification times. Does not recurse into subdirectories.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesDirectory path relative to the root directory (e.g., src/, .).

Returns:

FieldTypeDescription
entriesobject[]Array of { name, type, size, mtime } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.stat -- File metadata

Returns metadata for a file or directory. Useful for checking if a file exists before reading or writing.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile or directory path relative to the root directory.

Returns:

FieldTypeDescription
namestringFile or directory name.
typestringEntry type: file, dir, or symlink.
sizeintSize in bytes.
mtimestringLast modification time (RFC 3339).
modestringUnix permission string (e.g., 0755).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.stream_read -- Stream a file to local disk

Streams a remote file to a local file path without buffering in memory. Use this for large files (up to 3 GB) that would exceed the 10 MB inline limit of nefia.fs.read. The transfer uses approximately 32 KB of memory.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
remote_pathstringyesRemote file path to download.
local_pathstringyesLocal file path to save to.
progress_intervalstringnoInterval for progress notifications during transfer (e.g., 5s, 1m).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.stream_write -- Stream a local file to a remote host

Streams a local file to a remote file path without buffering in memory. Uses atomic write (temp file + rename) to prevent partial writes. Supports files up to 3 GB.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
remote_pathstringyesRemote file path to write to.
local_pathstringyesLocal file path to upload from.
expected_sha256stringnoSHA-256 hex digest of the local file. If provided, the local file is hashed before upload and rejected on mismatch.
progress_intervalstringnoInterval for progress notifications during transfer (e.g., 5s, 1m).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.fs.stream_read_resumable -- Resumable download

Stream a remote file to a local path with resume support. If a previous partial download exists at local_path, the transfer continues from the last checkpoint instead of starting over.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
remote_pathstringyesRemote file path to download.
local_pathstringyesLocal file path to save to (absolute, must be under home or tmp directory).
progress_intervalstringnoInterval for progress notifications during transfer.

Returns:

FieldTypeDescription
okbooleanWhether the transfer completed successfully.
bytesintTotal bytes transferred.
sha256stringSHA-256 hex digest of the transferred file.
resumedbooleanWhether the transfer was resumed from a previous checkpoint.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.stream_write_resumable -- Resumable upload

Stream a local file to a remote path with resume support. If a previous partial upload exists, the transfer continues from the last checkpoint instead of starting over.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
remote_pathstringyesRemote file path to write to.
local_pathstringyesLocal file path to upload from (absolute, must be under home or tmp directory).
expected_sha256stringnoSHA-256 hex digest of the local file for integrity verification.
progress_intervalstringnoInterval for progress notifications during transfer.

Returns:

FieldTypeDescription
okbooleanWhether the transfer completed successfully.
bytesintTotal bytes transferred.
sha256stringSHA-256 hex digest of the transferred file.
resumedbooleanWhether the transfer was resumed from a previous checkpoint.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.fs.mkdir -- Create a directory

Create a directory (and any missing parents) on a remote host. If the directory already exists, the operation succeeds silently (idempotent).

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesDirectory path to create (relative to root). Parent directories are created automatically.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.remove -- Remove a file or directory

Remove a file or directory on a remote host. By default, only removes files or empty directories. Set recursive=true to remove directories and all their contents.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile or directory path to remove (relative to root).
recursivebooleannoRemove directories and all contents recursively (default: false).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.fs.chmod -- Change file permissions

Change file permissions on a remote host. Supports numeric modes (e.g. 755) and symbolic modes (e.g. u+x, go-w). Not supported on Windows — use nefia.exec with icacls commands instead.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile or directory path (relative to root).
modestringyesPermission mode: numeric (e.g. 755, 0644) or symbolic (e.g. u+x, go-w, a+r).
recursivebooleannoApply permissions recursively to directory contents (default: false).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.fs.chown -- Change file ownership

Change file ownership on a remote host. Specify owner as user or user:group. Not supported on Windows — use nefia.exec with icacls instead.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile or directory path (relative to root).
ownerstringyesNew owner in user or user:group format (e.g. root, www-data:www-data).
recursivebooleannoApply ownership change recursively to directory contents (default: false).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.fs.find -- Search for files

Search for files on a remote host with flexible filtering. Returns matching files with metadata (path, type, size, mtime, mode). Results are limited to max_results (default 1000, max 10000).

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesRoot directory to search in (relative to root).
namestringnoGlob pattern to match filenames (e.g. *.log, config.*).
typestringnoFilter by entry type: file, dir, or symlink.
max_depthintnoMaximum directory depth to search (0 = unlimited).
max_resultsintnoMaximum number of results to return (default: 1000, max: 10000).
modified_afterstringnoOnly include files modified after this timestamp (RFC 3339).
modified_beforestringnoOnly include files modified before this timestamp (RFC 3339).
size_minintnoMinimum file size in bytes.
size_maxintnoMaximum file size in bytes.

Returns:

FieldTypeDescription
entriesobject[]Array of { path, type, size, mtime, mode } objects.
truncatedbooleanWhether results were truncated due to max_results.
total_scannedintTotal number of entries scanned.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.tail -- Read last N lines of a file

Read the last N lines of a file on a remote host. Optionally filter output with a grep pattern (fixed-string match). Useful for reading log files without downloading the entire file.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesFile path to read (relative to root).
linesintnoNumber of lines to read from the end (default: 50, max: 5000).
grepstringnoOptional fixed-string pattern to filter lines (case-sensitive).

Returns:

FieldTypeDescription
contentstringThe tail content of the file.
line_countintNumber of lines returned.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.move -- Move or rename a file

Move or rename a file or directory on a remote host. This tool is NOT idempotent — moving to an existing destination may overwrite it.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
srcstringyesSource path.
dststringyesDestination path.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false

nefia.fs.grep -- Search for a pattern in files

Search for a pattern in remote files recursively from the given path using grep. Returns matching lines with file paths. Prefer this over nefia.exec + grep for structured output.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
patternstringyesSearch pattern (grep basic regex).
pathstringyesPath to search in (file or directory).
max_resultsintnoMaximum number of matches to return (default: 100, max: 1000).

Returns:

FieldTypeDescription
matchesobject[]Array of { path, line, content } objects.
total_countintTotal number of matches found.
truncatedbooleanWhether results were truncated due to max_results.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.fs.du -- Disk usage

Get disk usage for a path on a remote host. Returns the total size in bytes and a human-readable format. Prefer this over nefia.exec + du for structured output.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesPath to check disk usage for.

Returns:

FieldTypeDescription
pathstringPath that was checked.
size_bytesintTotal size in bytes.
human_sizestringHuman-readable size (e.g., 1.2 GB).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Discovery Tools

nefia.hosts.list -- List hosts

Returns all enrolled hosts, optionally filtered by tag. Use this to discover available hosts before opening sessions or running commands.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoOptional session ID to verify the caller has an active session.
tagstringnoFilter hosts by tag in key=value format (e.g., env=prod, role=web).

Returns:

FieldTypeDescription
hostsobject[]Array of host objects with id, address, os, user, vpn_status, tags, and group membership.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Playbook Tools

nefia.playbook.run -- Run a playbook

Executes a multi-step playbook on target hosts. Steps support OS filtering, template variables (Go text/template), conditional execution, output capture, and retry logic.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector: all, host:<id>, group:<name>, or tag:k=v.
playbookobjectyesPlaybook definition (see schema below).
varsobjectnoTemplate variable overrides (key-value strings, override playbook defaults).
dry_runbooleannoPreview execution plan without running (default: false).
step_timeout_msintnoDefault step timeout in milliseconds (applied to steps without explicit timeout).
concurrencyintnoMaximum number of hosts to process in parallel (default: 50).

Playbook definition schema:

FieldTypeRequiredDescription
namestringyesUnique playbook name.
descriptionstringnoHuman-readable description.
versionintnoSchema version (1).
varsobjectnoDefault template variables (key-value strings).
stepsarrayyesArray of step objects (see below).

Step schema:

Each step must have a name and exactly one action: exec (shell command string), fs_write (object with path and content fields), or fs_read (object with path field).

FieldTypeRequiredDescription
namestringyesStep name.
execstringnoShell command to execute.
fs_writeobjectnoFile write operation with path and content fields.
fs_readobjectnoFile read operation with path field.
osstringnoOS filter: macos, linux, or windows. Step is skipped if host OS does not match.
continue_on_errorbooleannoContinue to next step on failure (default: false).
timeout_msintnoStep timeout in milliseconds.
registerstringnoSave step result under this name for use in subsequent when conditions and templates. Name must use [a-zA-Z0-9_] only (no hyphens).
whenstringnoCondition expression. Step is skipped if false. Supports Go templates and comparisons.
retryobjectnoRetry configuration with max_attempts (1-1000) and interval_ms (>= 0).

Template variables:

VariableDescription
{{ .Host.ID }}Host identifier.
{{ .Host.OS }}Host OS (macos, linux, windows).
{{ .Host.Address }}Host address.
{{ .Vars.key }}User-defined variable.
{{ .Steps.<name>.Output }}Captured output from a registered step.
{{ .Steps.<name>.OK }}Whether a registered step succeeded (bool).
{{ .Steps.<name>.ExitCode }}Exit code of a registered step.
{{ .Steps.<name>.Skipped }}Whether a registered step was skipped.

Returns:

FieldTypeDescription
playbook_namestringName of the executed playbook.
host_resultsobject[]Per-host results (see below).
total_hostsintTotal number of targeted hosts.
success_countintNumber of hosts that completed all steps successfully.
fail_countintNumber of hosts with at least one failed step.
elapsed_msintTotal wall-clock duration across all hosts in milliseconds.

Each entry in host_results:

FieldTypeDescription
host_idstringHost identifier.
okbooleanWhether all steps succeeded on this host.
stepsobject[]Per-step results (see below).
elapsed_msintTotal execution time for this host in milliseconds.

Each entry in steps:

FieldTypeDescription
step_namestringStep name as defined in the playbook.
step_indexintZero-based index of the step.
actionstringAction type: exec, fs_write, fs_read, or skipped.
okbooleanWhether the step succeeded.
outputstringStep output (present when the step produced output).
errorstringError message (present when the step failed).
skippedbooleanWhether the step was skipped due to OS filter or when condition.
duration_msintStep execution duration in milliseconds.
exit_codeintProcess exit code (for exec steps).
attemptsintNumber of attempts (present when retry was configured).

In dry-run mode, returns { ok: boolean, dry_run: true } instead.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

System Information Tools

nefia.facts -- Gather host facts

Gathers structured system information from target hosts in a single SSH round-trip per host. More efficient than running multiple nefia.exec calls. Supports macOS, Linux, and Windows.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector: all, host:<id>, group:<name>, or tag:k=v.
categoriesstringnoComma-separated list of categories to collect (default: all). Options: os, disk, memory, cpu, uptime, network.
concurrencyintnoMaximum number of hosts to query in parallel (default: configured value).

Returns:

FieldTypeDescription
resultsobject[]Per-host results (see below).
summaryobjectSummary with total_hosts, success_count, and fail_count.

Each entry in results:

FieldTypeDescription
host_idstringHost identifier.
okbooleanWhether fact gathering succeeded for this host.
factsobjectGathered facts (present when ok is true). Contains os, disk, memory, cpu, uptime, and network objects depending on requested categories.
errorstringError message (present when ok is false).
elapsed_msintGathering duration in milliseconds.

The facts object contains only the requested categories. Each category structure:

  • os -- { name, version, kernel, arch }
  • disk -- { mounts: [{ path, total_bytes, used_bytes, usage_percent }] }
  • memory -- { total_bytes, used_bytes, available_bytes }
  • cpu -- { count, model, load_avg }
  • uptime -- { seconds, boot_time }
  • network -- { interfaces: [{ name, ipv4, ipv6 }] }

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.session.summary -- Session activity summary

Generate an AI-consumable summary of a session's activity. Returns structured data including commands executed, files read/written, error count, duration, and a markdown-formatted narrative. The summary is also persisted to disk for later retrieval.

Use this to understand what happened during a session without reading raw audit logs.

Parameters:

ParameterTypeRequiredDescription
session_idstringyesSession ID to summarize.

Returns:

FieldTypeDescription
session_idstringThe session ID.
host_idstringThe host this session is connected to.
durationstringSession duration (e.g., 5m23s).
command_countintNumber of commands executed.
commandsstring[]List of command strings executed.
files_readstring[]List of file paths read.
files_writtenstring[]List of file paths written.
error_countintNumber of errors encountered.
markdownstringMarkdown-formatted narrative summary of session activity.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

System Query Tools

System query tools provide structured access to host system information without running raw commands. All tools support macOS, Linux, and Windows.

nefia.sys.processes -- List running processes

List running processes on a remote host with CPU and memory usage. Returns process list sorted by the specified field (default: CPU).

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
filterstringnoFilter processes by name (case-insensitive substring match).
sort_bystringnoSort field: cpu, memory, or pid (default: cpu).
limitintnoMaximum number of processes to return (default: 50, max: 500).

Returns:

FieldTypeDescription
processesobject[]Array of { pid, user, name, cpu_percent, memory_percent, memory_rss_bytes, command, state } objects.
total_countintTotal number of running processes on the host.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.services -- List system services

List system services on a remote host. Uses systemctl on Linux, launchctl on macOS, and Get-Service on Windows.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
filterstringnoFilter services by name (case-insensitive substring match).
statusstringnoFilter by status: running, stopped, failed, or all (default: all).

Returns:

FieldTypeDescription
servicesobject[]Array of { name, display_name, status, enabled, pid, type } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.ports -- List network connections

List network connections and listening ports on a remote host. Uses ss on Linux, lsof on macOS, and Get-NetTCPConnection on Windows.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
statestringnoFilter by connection state: listen, established, or all (default: all).

Returns:

FieldTypeDescription
connectionsobject[]Array of { protocol, local_addr, local_port, remote_addr, remote_port, state, pid, process } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.users -- List user accounts

List system user accounts on a remote host. Uses getent passwd on Linux, dscl on macOS, and Get-LocalUser on Windows.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
include_systembooleannoInclude system accounts with UID < 1000 (default: false).

Returns:

FieldTypeDescription
usersobject[]Array of { username, uid, gid, home, shell, groups, is_system } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.logs -- Query system logs

Query system logs on a remote host. Uses journalctl on Linux, log show on macOS, and Get-EventLog on Windows.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
sourcestringnoLog source: syslog, journal, auth, kern, or a systemd unit name (Linux) / event log name (Windows).
linesintnoMaximum number of log entries to return (default: 100, max: 5000).
sincestringnoStart time: RFC 3339 timestamp or relative duration (e.g. 1h, 30m, 2d).
untilstringnoEnd time: RFC 3339 timestamp or relative duration.
grepstringnoPattern to filter log messages (case-insensitive on macOS/Linux).
prioritystringnoMinimum priority level: emerg, err, warning, or info.

Returns:

FieldTypeDescription
entriesobject[]Array of { timestamp, source, priority, message } objects.
truncatedbooleanWhether results were truncated due to lines limit.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.service.control -- Control a system service

Start, stop, restart, enable, or disable a system service on a remote host. On Linux/macOS, non-status actions require sudo privileges (the command is automatically wrapped with sudo when enabled). Uses systemctl on Linux, launchctl on macOS, and *-Service cmdlets on Windows.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
servicestringyesService name (e.g. nginx, sshd, com.apple.sshd, wuauserv).
actionstringyesAction: start, stop, restart, enable, disable, or status.

Returns:

FieldTypeDescription
okbooleanWhether the action completed successfully.
servicestringService name.
previous_statusstringService status before the action.
current_statusstringService status after the action.
messagestringStatus or error message.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Approval Tools

When the approval workflow is enabled in the configuration (approval.enabled: true), 2 additional tools are advertised. These tools allow AI agents to list pending approval requests and (attempt to) respond to them.

nefia.approval.list -- List pending approvals

Lists all pending approval requests. Returns details about operations that are waiting for human approval.

Parameters: None.

Returns:

FieldTypeDescription
pendingobject[]Array of pending approval requests. Each entry contains id, tool, command, path, host_id, and created_at. Empty array when no requests are pending.
enabledbooleanWhether the approval workflow is currently enabled.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.approval.respond -- Respond to an approval request

Responds to one or more pending approval requests. Supports both single and bulk approval.

Security: This tool is deliberately blocked in MCP mode to prevent self-approval attacks where an AI agent approves its own requests. Calling this tool always returns an AccessDenied error (-32013). Approvals must be handled via the TUI dashboard or CLI (nefia approval respond), where operators can review and approve or deny pending requests.

Parameters:

ParameterTypeRequiredDescription
request_idstringnoThe approval request ID to respond to (use this or request_ids, not both).
request_idsstring[]noMultiple approval request IDs to respond to with the same decision (use this or request_id, not both).
approvedbooleanyestrue to approve, false to deny.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false

VPN & Connectivity Tools

nefia.vpn.status -- VPN tunnel status

Returns whether the WireGuard tunnel is ready, the local VPN address, and detailed status for each peer including transport type (direct/derp/turn), last handshake time, and transfer statistics.

Parameters: None.

Returns:

FieldTypeDescription
readybooleanWhether the VPN tunnel is active.
local_addrstringLocal VPN address.
peersobject[]Array of { host_id, public_key, endpoint, vpn_addr, transport, healthy, last_handshake, transfer_rx, transfer_tx } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.vpn.diagnose -- VPN diagnostics

Run VPN diagnostics and return issues with recommendations. Checks tunnel readiness, DERP relay connectivity, multipath status, and peer health. Use this when VPN connectivity problems are suspected before attempting SSH operations.

Parameters: None.

Returns:

FieldTypeDescription
tunnel_readybooleanWhether the tunnel is up.
local_addrstringLocal VPN address.
derp_connectedbooleanWhether the DERP relay is connected.
multipath_activebooleanWhether multipath is active.
peer_countintTotal number of peers.
healthy_peersintNumber of healthy peers.
issuesstring[]Detected issues.
recommendationsstring[]Actionable recommendations.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.vpn.ping -- Test VPN connectivity

Test VPN connectivity to a specific host by attempting a TCP dial. Measures round-trip latency through the VPN tunnel and reports the transport path used (direct, DERP relay, or TURN).

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to ping.

Returns:

FieldTypeDescription
host_idstringHost identifier.
vpn_addrstringVPN address of the host.
reachablebooleanWhether the host is reachable.
latency_msintRound-trip latency in milliseconds.
transportstringTransport path used (direct, derp, turn).
errorstringError message if unreachable.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Policy & Intelligence Tools

nefia.policy.test -- Pre-check policy

Pre-check whether a command, path, or operation would be allowed by the policy engine. Use this before executing operations to avoid POLICY_DENIED errors. At least one of command, path, or operation must be provided.

Parameters:

ParameterTypeRequiredDescription
commandstringnoShell command to test (e.g., rm -rf /tmp/*).
pathstringnoFile path to test (e.g., /etc/shadow).
host_idstringnoHost ID for role-based evaluation. If omitted, global rules are checked.
operationstringnoMCP operation type (e.g., exec, fs.write).

Returns:

FieldTypeDescription
allowedbooleanWhether the operation would be allowed.
reasonstringDenial reason (present when denied).
denial_typestringType of denial rule that matched.
rule_matchedstringThe specific rule that triggered.
jit_availablebooleanWhether JIT temporary access is available.
modestringCurrent policy mode (enforce, warn, off).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.policy.test_batch -- Batch policy test

Test multiple commands, paths, or operations against the policy engine in a single call. Accepts up to 50 tests and returns per-test results plus a summary. Use this instead of calling nefia.policy.test in a loop.

Parameters:

ParameterTypeRequiredDescription
testsobject[]yesArray of policy test items (max 50). Each must have at least one of command, path, or operation.

Each test object:

FieldTypeRequiredDescription
commandstringnoCommand to test.
pathstringnoFile path to test.
host_idstringnoHost context for the test.
operationstringnoOperation type to test (e.g., exec, fs_read, fs_write).

Returns:

FieldTypeDescription
resultsobject[]Per-test results with allowed, reason, denial_type, rule_matched fields.
all_allowedbooleanWhether all tests passed.
summaryobjectSummary with total, allowed, and denied counts.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Host Inventory Tools

nefia.hosts.show -- Host details

Get detailed information about a specific host. Returns all host configuration including ID, address, user, OS, shell, root directory, role, tags, group membership, and VPN status with transport type.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to look up.

Returns:

FieldTypeDescription
idstringHost identifier.
addressstringHost address.
userstringSSH user.
osstringOperating system.
shellstringDefault shell.
rootstringRoot directory.
rolestringAssigned role.
tagsobjectKey-value tags.
groupsstring[]Group memberships.
vpnobjectVPN status with status, vpn_addr, and transport fields.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.hosts.update -- Update host metadata

Update host metadata (tags or role). Changes are persisted to the config file and hot-reloaded immediately.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to update.
tagsobjectnoReplace all tags with these key-value pairs.
set_tagsobjectnoMerge these tags into existing tags (add or overwrite keys).
remove_tagsstring[]noRemove these tag keys.
rolestringnoSet the host's role.

Returns:

FieldTypeDescription
host_idstringHost identifier.
tagsobjectUpdated tags.
groupsstring[]Updated group memberships.
rolestringUpdated role.
updatedbooleanWhether any changes were made.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false

JIT Access Tools

nefia.jit.request -- Request temporary access

Request temporary elevated access via the Just-In-Time access system. Creates a pending access request that must be approved by an operator. Requires JIT to be enabled in the configuration.

Parameters:

ParameterTypeRequiredDescription
rolestringyesRole to request access for (must match a policy-defined role).
host_patternsstring[]yesHost ID patterns (e.g., ["web-*", "db-prod"]).
durationstringyesRequested duration (e.g., 1h, 30m, 4h).
reasonstringyesBusiness justification for the request.

Returns:

FieldTypeDescription
request_idstringUnique request identifier.
statusstringRequest status (e.g., pending).

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false

nefia.jit.list -- List JIT requests

List JIT access requests and active grants. Use this to check if you have an active grant before running privileged operations.

Parameters:

ParameterTypeRequiredDescription
statusstringnoFilter by status: pending, approved, denied, expired, revoked, or all (default: all).

Returns:

FieldTypeDescription
requestsobject[]Array of { id, requester_id, role, host_patterns, duration, reason, status, created_at } objects.
grantsobject[]Array of { request_id, role, host_patterns, expires_at } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Audit Tools

nefia.audit.search -- Search audit logs

Search the append-only audit log by date range, job ID, session ID, host ID, or operation type. At least one filter must be provided.

Parameters:

ParameterTypeRequiredDescription
start_datestringnoStart date inclusive (YYYY-MM-DD).
end_datestringnoEnd date inclusive (YYYY-MM-DD).
job_idstringnoFilter by job ID.
session_idstringnoFilter by session ID.
host_idstringnoFilter by host ID.
op_kindstringnoFilter by operation kind (e.g., exec, fs_write).
limitintnoMaximum records to return (default: 100, max: 1000).

Returns:

FieldTypeDescription
recordsobject[]Array of { seq, timestamp, job_id, session_id, host_id, op_kind, user } objects.
totalintTotal matching records.
truncatedbooleanWhether results were truncated.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.audit.export -- Export audit logs

Export audit records for the specified date range in JSONL or CSV format. Useful for compliance reporting and external analysis.

Parameters:

ParameterTypeRequiredDescription
start_datestringnoStart date in YYYY-MM-DD format.
end_datestringnoEnd date in YYYY-MM-DD format.
formatstringnoExport format: jsonl or csv (default: jsonl).

Returns:

FieldTypeDescription
contentstringExported audit data.
record_countintNumber of exported records.
formatstringExport format used.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Agent Management Tools

nefia.agent.status -- Agent status

Get the status of a nefia-agent running on a target host. Queries the agent for its version, OS, architecture, and uptime.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to query.

Returns:

FieldTypeDescription
host_idstringHost identifier.
versionstringAgent version.
osstringOperating system.
archstringArchitecture (amd64, arm64).
uptimestringAgent uptime.
statusstringAgent status.
errorstringError message if query failed.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.agent.upgrade -- Upgrade agent

Upgrade the nefia-agent on a target host. Pushes the new agent binary and restarts the service. If version is omitted, upgrades to the current operator CLI version.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to upgrade.
versionstringnoTarget version (e.g., 1.2.3). Defaults to current CLI version.

Returns:

FieldTypeDescription
host_idstringHost identifier.
previous_versionstringVersion before upgrade.
new_versionstringVersion after upgrade.
restartedbooleanWhether the agent was restarted.
statusstringUpgrade status.
errorstringError message if upgrade failed.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Schedule Tools

nefia.schedule.list -- List schedules

List all scheduled playbook executions with their runtime state.

Parameters: None.

Returns:

FieldTypeDescription
schedulesobject[]Array of { id, name, description, cron_expr, timezone, playbook_ref, target, enabled, last_run_at, last_run_ok, next_run_at } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.schedule.create -- Create a schedule

Create a new scheduled playbook execution. Defines a recurring schedule using a cron expression.

Parameters:

ParameterTypeRequiredDescription
namestringyesUnique schedule name.
cron_exprstringyesCron expression (5-field: min hour dom mon dow).
playbook_refstringyesPlaybook file path or name.
targetstringyesHost selector.
descriptionstringnoHuman-readable description.
timezonestringnoIANA timezone (default: UTC).
varsobjectnoTemplate variable overrides.
enabledbooleannoWhether the schedule is active (default: true).
overlap_policystringnoBehavior if previous run is active: skip, cancel_running, or allow (default: skip).
max_retriesintnoMaximum retry attempts on failure (default: 0).
missed_run_policystringnoBehavior for missed runs: skip or run_once (default: skip).
concurrencyintnoMaximum concurrent hosts.
step_timeout_msintnoDefault step timeout in milliseconds.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false

nefia.schedule.delete -- Delete a schedule

Delete a scheduled playbook execution. Removes the schedule definition and its runtime state. This cannot be undone.

Parameters:

ParameterTypeRequiredDescription
idstringyesSchedule ID or name.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false

nefia.schedule.show -- Show schedule details

Show detailed information about a specific schedule including the definition, next run time, and last run status.

Parameters:

ParameterTypeRequiredDescription
idstringyesSchedule ID or name.

Returns:

FieldTypeDescription
idstringSchedule identifier.
namestringSchedule name.
cron_exprstringCron expression.
timezonestringIANA timezone.
playbook_refstringPlaybook reference.
targetstringHost selector.
enabledbooleanWhether the schedule is active.
last_run_atstringLast run timestamp.
last_run_okbooleanWhether the last run succeeded.
next_run_atstringNext scheduled run time.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.schedule.update -- Update a schedule

Partially update a schedule definition. Only provided fields are changed; omitted fields remain unchanged.

Parameters:

ParameterTypeRequiredDescription
idstringyesSchedule ID or name.
namestringnoNew schedule name.
descriptionstringnoNew description.
cron_exprstringnoNew cron expression (5-field format).
timezonestringnoIANA timezone (e.g., America/New_York).
targetstringnoHost selector expression.
varsobjectnoPlaybook variables to set.
overlap_policystringnoBehavior if previous run is active: skip, queue, or allow.
missed_run_policystringnoBehavior for missed runs: skip or run_once.
concurrencyintnoMaximum concurrent hosts.
step_timeout_msintnoPer-step timeout in milliseconds.
max_retriesintnoMaximum retry attempts on failure.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.schedule.enable -- Enable a schedule

Re-enable a previously disabled schedule so it will run on its cron expression again. Idempotent — enabling an already-enabled schedule is a no-op.

Parameters:

ParameterTypeRequiredDescription
idstringyesSchedule ID or name.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.schedule.disable -- Disable a schedule

Disable a schedule without deleting it. Prevents the schedule from running until re-enabled with nefia.schedule.enable. The schedule definition is preserved. Idempotent.

Parameters:

ParameterTypeRequiredDescription
idstringyesSchedule ID or name.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.schedule.history -- Schedule execution history

Show recent execution records for a schedule including run time, success/failure, and host counts.

Parameters:

ParameterTypeRequiredDescription
idstringyesSchedule ID or name.
limitintnoMaximum entries to return (default: 20, max: 100).

Returns:

FieldTypeDescription
schedule_idstringSchedule identifier.
schedule_namestringSchedule name.
entriesobject[]Array of { run_at, ok, elapsed, hosts_total, hosts_ok, hosts_fail, error } objects.
totalintTotal number of history entries.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

File Copy Tool

nefia.fs.copy -- Copy a file on remote host

Copy a file from src to dst on the same remote host. Both paths are resolved relative to the session's or host's root directory.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
srcstringyesSource file path (relative to root).
dststringyesDestination file path (relative to root).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Playbook Discovery Tools

nefia.playbook.list -- List playbooks

List all available playbooks. Discovers playbooks from standard search directories (./playbooks/ and config directory). Returns name, path, description, and step count for each playbook.

Parameters: None.

Returns:

FieldTypeDescription
playbooksobject[]Array of { name, path, description, step_count } objects.
warningsstring[]Any warnings encountered during discovery.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.playbook.show -- Show playbook details

Show full details of a playbook. Resolves by name or file path and returns the full definition including all steps, variables, and metadata.

Parameters:

ParameterTypeRequiredDescription
name_or_pathstringyesPlaybook name (e.g., deploy) or file path (e.g., ./playbooks/deploy.yaml).

Returns:

FieldTypeDescription
namestringPlaybook name.
pathstringResolved file path.
descriptionstringPlaybook description.
stepsobject[]Full step definitions.
varsobjectDefault template variables.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.playbook.validate -- Validate a playbook

Validate a playbook without executing it. Checks structure, step definitions, and template syntax.

Parameters:

ParameterTypeRequiredDescription
name_or_pathstringyesPlaybook name or file path to validate.

Returns:

FieldTypeDescription
validbooleanWhether the playbook is valid.
errorsstring[]Validation errors.
warningsstring[]Validation warnings.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Queue Tools

Queue tools manage offline command queuing. When a command targets a host that is offline, it can be queued for later execution when the host comes online.

nefia.queue.list -- List queue entries

List queued offline commands, optionally filtered by status.

Parameters:

ParameterTypeRequiredDescription
statusstringnoFilter by status: pending, running, completed, failed, expired, or cancelled.

Returns:

FieldTypeDescription
entriesobject[]Array of { id, host_id, command, status, created_at, expires_at } objects.
totalintTotal number of entries.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.queue.show -- Show queue entry details

Show details of a single queue entry.

Parameters:

ParameterTypeRequiredDescription
entry_idstringyesQueue entry ID.

Returns:

FieldTypeDescription
idstringEntry identifier.
host_idstringTarget host.
commandstringQueued command.
statusstringEntry status.
created_atstringCreation timestamp.
expires_atstringExpiration timestamp.
errorstringError message (if failed).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.queue.cancel -- Cancel a queue entry

Cancel a pending queue entry. Only entries with status pending can be cancelled.

Parameters:

ParameterTypeRequiredDescription
entry_idstringyesQueue entry ID to cancel.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false

nefia.queue.retry -- Retry a queue entry

Retry a failed or expired queue entry. Creates a new pending entry with the same command and host. The original entry is preserved.

Parameters:

ParameterTypeRequiredDescription
entry_idstringyesQueue entry ID to retry.
ttlstringnoTime-to-live for the new entry (default: 1h).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false

Multi-Host File Operations

nefia.push -- Push file to multiple hosts

Distribute a file to all hosts matching the target selector. Supports batch execution for staged rollouts.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector.
remote_pathstringyesDestination file path on remote hosts.
contentstringnoFile content as UTF-8 text (mutually exclusive with content_base64).
content_base64stringnoFile content as base64 (mutually exclusive with content).
batch_sizeintnoNumber of hosts per batch (0 = all at once).
batch_waitstringnoPause between batches (Go duration format).
subsetintnoDeploy to a random subset of N hosts.
dry_runbooleannoResolve targets without writing files.
no_recursebooleannoDo not recurse into subdirectories when pushing directories.
forcebooleannoOverwrite existing files without confirmation.
excludestring[]noHost IDs to exclude from the push operation.
modestringnoFile permissions to set (e.g., 0644).
ownerstringnoFile ownership (user:group).
backup_existingbooleannoBack up existing files before overwriting.

Returns:

FieldTypeDescription
hostsobject[]Per-host results with host_id, ok, and error fields.
success_countintNumber of successful hosts.
fail_countintNumber of failed hosts.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.sync -- Sync directory to multiple hosts

Synchronize files from a local directory to a remote directory on all matching hosts. Only changed files are transferred (by modification time or checksum). Optionally deletes remote files not present locally.

Parameters:

ParameterTypeRequiredDescription
local_dirstringyesLocal directory path on the operator machine.
remote_dirstringyesDestination directory on remote hosts.
targetstringyesHost selector.
checksumbooleannoUse checksums instead of modification time for change detection.
deletebooleannoDelete remote files not present in local directory.
dry_runbooleannoPreview changes without transferring files.
excludestring[]noGlob patterns to exclude (e.g., ["*.log", ".git"]).
batch_sizeintnoNumber of hosts per batch.
batch_waitstringnoPause between batches.
subsetintnoSync to a random subset of N hosts.
preservebooleannoPreserve file permissions and ownership during sync.
conflict_resolutionstringnoStrategy for handling conflicts: overwrite, skip, or newer (default: overwrite).

Returns:

FieldTypeDescription
hostsobject[]Per-host results with host_id, ok, transferred, deleted, skipped, total_bytes, duration_ms, and error fields.
success_countintNumber of successful hosts.
fail_countintNumber of failed hosts.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Diagnostics Tools

nefia.status -- System-wide status

Get a system-wide status overview in a single call. Returns VPN tunnel status, host counts, queue depth, active session count, and configuration summary.

Parameters: None.

Returns:

FieldTypeDescription
vpnobjectVPN status with ready, peer_count, and healthy_peers fields.
hostsobjectHost counts with total, online, and offline fields.
queueobjectQueue depth with pending, running, completed, and failed fields.
sessionsobjectSession info with active count.
configobjectConfiguration summary with policy_mode and vpn_enabled fields.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.doctor -- Health checks

Run comprehensive health checks. Validates configuration, VPN connectivity, audit logging, and optionally tests connectivity to a specific host.

Parameters:

ParameterTypeRequiredDescription
host_idstringnoTest connectivity to a specific host.
strictbooleannoIf true, treat warnings as failures.

Returns:

FieldTypeDescription
checksobject[]Array of { name, status, message } objects. Status is pass, warn, or fail.
summaryobjectSummary with total, pass, warn, and fail counts.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.session.list -- List active sessions

List the calling client's active MCP sessions. Each client sees only its own sessions; sessions opened by other clients are not included.

Parameters: None.

Returns:

FieldTypeDescription
sessionsobject[]Array of { session_id, host_id, root_dir, created_at } objects (scoped to the calling client).
countintNumber of active sessions for this client.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.explain -- Explain an error code

Get detailed explanation and remediation for an error code. Provides suggested actions, diagnostics commands, and example tool calls. Use error codes from previous tool responses (e.g., HOST_NOT_FOUND, SSH_AUTH_FAILED).

Parameters:

ParameterTypeRequiredDescription
error_codestringyesError code string from a previous tool response.

Returns:

FieldTypeDescription
error_codestringThe error code queried.
knownbooleanWhether the error code is recognized.
suggested_actionsstring[]Recommended actions to resolve the error.
diagnosticsstring[]Diagnostic tool calls to run.
exampleobjectExample tool call to try.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.recording.list -- List recordings

List session recordings. Returns metadata for stored session recordings (asciicast format) for audit and replay.

Parameters:

ParameterTypeRequiredDescription
limitintnoMaximum recordings to return (default: 50).

Returns:

FieldTypeDescription
recordingsobject[]Array of { session_id, host_id, started_at, duration, size } objects.
totalintTotal number of recordings.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.recording.show -- Show recording details

Show metadata for a specific session recording.

Parameters:

ParameterTypeRequiredDescription
session_idstringyesSession ID of the recording.

Returns:

FieldTypeDescription
session_idstringSession identifier.
host_idstringHost identifier.
started_atstringRecording start time.
durationstringRecording duration.
sizeintRecording file size in bytes.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.recording.delete -- Delete a recording

Permanently delete the recording for the given session. Idempotent — deleting a non-existent recording is a no-op.

Parameters:

ParameterTypeRequiredDescription
session_idstringyesSession ID of the recording to delete.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false

Reactor Tools

nefia.reactor.status -- Reactor engine status

Show reactor engine status including whether the reactor is running, total number of rules, and per-rule status with hit counts.

Parameters: None.

Returns:

FieldTypeDescription
runningbooleanWhether the reactor engine is active.
total_rulesintTotal number of configured rules.
rulesobject[]Array of { name, event_pattern, host_pattern, action_type, hit_count } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.reactor.events -- Recent reactor events

List recent events processed by the reactor engine. Useful for debugging event-driven automation.

Parameters:

ParameterTypeRequiredDescription
limitintnoMaximum events to return (default: 50, max: 200).

Returns:

FieldTypeDescription
eventsobject[]Array of { event_type, host_id, matched_rule, action_taken, processed_at, error } objects.
totalintTotal number of events.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Compliance Tools

nefia.compliance.report -- Generate compliance report

Generate a compliance report for a security framework. Evaluates the current configuration and audit evidence against the specified framework's controls. Returns control-level pass/fail status, gaps, and recommendations.

Parameters:

ParameterTypeRequiredDescription
frameworkstringyesCompliance framework: soc2, iso27001, or hipaa.
periodstringnoReporting period. Go duration (e.g., 720h) or Nd format (e.g., 30d, 90d). Default: 30d.

Returns:

FieldTypeDescription
frameworkstringFramework evaluated.
generated_atstringReport generation timestamp.
period_startstringReporting period start.
period_endstringReporting period end.
summaryobjectSummary with total_controls, pass_count, fail_count, partial_count, and compliance_score.
controlsobject[]Per-control results.
gapsstring[]Identified compliance gaps.
disclaimerstringReport disclaimer.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Security & Reliability Tools

nefia.cancel -- Cancel a running job

Cancel a running exec or playbook job. Sends a cancellation signal to the job. The job will stop as soon as the current in-flight commands complete.

Parameters:

ParameterTypeRequiredDescription
job_idstringyesJob ID from a previous exec or playbook result summary.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false

nefia.power.wake -- Wake-on-LAN

Send a Wake-on-LAN magic packet to wake a host. Optionally waits for the host to come online after waking.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to wake (must have a MAC address configured).
proxy_host_idstringnoSend WoL via this proxy host (must be on same LAN).
waitbooleannoWait for the host to come online after waking.
timeoutstringnoHow long to wait (default: 60s). Only used when wait=true.

Returns:

FieldTypeDescription
host_idstringHost identifier.
mac_addrstringMAC address used.
proxy_hoststringProxy host used (if any).
sentbooleanWhether the packet was sent.
onlinebooleanWhether the host came online (when wait=true).
errorstringError message if failed.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.secrets.list -- List secret providers

List configured secret providers. Returns names and types of configured providers (e.g., env, file, vault). No secret values are returned.

Parameters: None.

Returns:

FieldTypeDescription
providersobject[]Array of { name, type } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.secrets.test -- Test secret provider connectivity

Attempt a test connection to a named secret provider to verify it is reachable and configured correctly. No secret values are read or returned.

Parameters:

ParameterTypeRequiredDescription
providerstringyesProvider name (from nefia.secrets.list).

Returns:

FieldTypeDescription
providerstringProvider name.
okbooleanWhether the provider is reachable.
errorstringError message if unreachable.
latencystringConnection latency.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Infrastructure & Configuration Tools

nefia.config.show -- Show configuration

Show the current Nefia configuration with sensitive fields masked. Useful for verifying configuration without shell access. Fields matching key, secret, password, or token are replaced with ***.

Parameters: None.

Returns:

FieldTypeDescription
fieldsobjectFlattened configuration as key→value pairs with sensitive values masked.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.vpn.revoke -- Revoke VPN access

Revoke VPN access for a specific host or all hosts. Revoked hosts must re-enroll via nefia vpn invite to regain connectivity. One of host_id or all must be provided.

Parameters:

ParameterTypeRequiredDescription
host_idstringnoHost ID to revoke (use this or all).
allbooleannoRevoke all hosts (true). Use with caution.

Returns:

FieldTypeDescription
revokedstring[]List of host IDs whose VPN access was revoked.
allbooleanWhether all hosts were revoked.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false

nefia.netcheck -- Network diagnostics

Run network connectivity diagnostics. Detects NAT type, tests STUN/DERP/TURN reachability, and reports the public address. Use this as an alternative to nefia.vpn.diagnose for network-level analysis.

Parameters: None.

Returns:

FieldTypeDescription
natstringNAT type: full-cone, restricted, port-restricted, symmetric, or unknown.
stun_reachablebooleanWhether STUN servers are reachable.
derp_reachablebooleanWhether the DERP relay is reachable.
turn_reachablebooleanWhether TURN servers are reachable.
public_addrstringDetected public IP address and port.
issuesstring[]Detected issues.
recommendationsstring[]Actionable recommendations.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Device Security Tools

nefia.device_lock.status -- Device lock status

Check the Ed25519-based device-lock status for a host. Returns whether device verification is enabled, whether the device is verified, and the device key fingerprint.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to check.

Returns:

FieldTypeDescription
host_idstringHost identifier.
enabledbooleanWhether device-lock is enabled.
verifiedbooleanWhether the device is verified.
device_keystringPublic key fingerprint (if registered).
registered_atstringRegistration timestamp (RFC 3339).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.device_lock.verify -- Verify device lock

Perform cryptographic challenge verification against a host's registered Ed25519 device key. This is a read-only, idempotent operation — no state is modified.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to verify.

Returns:

FieldTypeDescription
host_idstringHost identifier.
validbooleanWhether the device key verification passed.
messagestringStatus or error message.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.posture.check -- Device posture check

Evaluate device posture compliance for a host. Checks firewall status, disk encryption, OS version, and other posture rules defined in the configuration. Returns pass/fail with violations and remediation hints.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to check.

Returns:

FieldTypeDescription
host_idstringHost identifier.
passedbooleanWhether all posture checks passed.
modestringPosture mode: off, warn, or enforce.
violationsstring[]List of failed posture checks.
hintsstring[]Remediation hints for violations.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Webhook Tools

nefia.webhook.list -- List webhooks

List configured webhooks with masked URLs. Returns webhook names, event subscriptions, and active status.

Parameters: None.

Returns:

FieldTypeDescription
webhooksobject[]Array of { name, url, events, active } objects. URLs are masked for security.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.webhook.test -- Test webhook delivery

Send a test event to a named webhook and verify delivery. Returns the HTTP status code, success status, and response latency.

Parameters:

ParameterTypeRequiredDescription
namestringyesWebhook name (from nefia.webhook.list).

Returns:

FieldTypeDescription
namestringWebhook name.
status_codeintHTTP response status code.
okbooleanWhether the test delivery succeeded.
errorstringError message if delivery failed.
latencystringRound-trip delivery latency.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true

Backup Tools

nefia.backup.list -- List configuration backups

List available configuration backups with metadata. Restore operations are available via the CLI only (nefia backup restore).

Parameters: None.

Returns:

FieldTypeDescription
backupsobject[]Array of { label, path, size, created_at } objects.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.backup.create -- Create a configuration backup

Create a backup of the current Nefia configuration and state. The backup includes nefia.yaml and related state files. Labels must match [A-Za-z0-9][A-Za-z0-9._-]{0,63}.

Parameters:

ParameterTypeRequiredDescription
labelstringnoOptional label for the backup. Must match [A-Za-z0-9][A-Za-z0-9._-]{0,63}.

Returns:

FieldTypeDescription
labelstringBackup label.
pathstringBackup file path.
sizeintBackup file size in bytes.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false

Power Management Tools

nefia.power.reboot -- Reboot a remote host

Reboot a remote host. Requires sudo privileges. Optionally waits for the host to come back online.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector expression.
forcebooleannoForce immediate reboot without graceful shutdown.
delay_msintegernoDelay in milliseconds before rebooting (default: 0).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.power.shutdown -- Shut down a remote host

Shut down a remote host. Requires sudo privileges. This is a destructive, non-reversible operation.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector expression.
forcebooleannoForce immediate shutdown.
delay_msintegernoDelay in milliseconds before shutting down (default: 0).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Package Management Tools

nefia.sys.package.list -- List installed packages

List installed packages on a remote host. Detects the package manager automatically (apt, yum, dnf, brew, choco).

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
querystringnoFilter packages by name substring.
limitintnoMaximum number of packages to return (default: 200, max: 5000).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.package.install -- Install a package

Install a package on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
packagesstring[]yesPackage names to install (max 50).
versionstringnoSpecific version to install.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.sys.package.remove -- Remove a package

Remove a package from a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
packagesstring[]yesPackage names to remove (max 50).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

User Management Tools

nefia.sys.user.create -- Create a user account

Create a user account on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
usernamestringyesUsername to create.
uidintnoUser ID.
home_dirstringnoHome directory path.
create_homebooleannoCreate the home directory (default: false).
shellstringnoLogin shell (e.g., /bin/bash).
groupsstring[]noAdditional group memberships.
systembooleannoCreate a system account (UID below 1000).
expiry_datestringnoAccount expiry date (YYYY-MM-DD).
commentstringnoUser comment (GECOS field).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.sys.user.modify -- Modify a user account

Modify an existing user account on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
usernamestringyesUsername to modify.
shellstringnoNew login shell.
groupsstring[]noNew group memberships (replaces existing).
append_groupsstring[]noGroups to add (preserves existing).
homestringnoNew home directory.
lockbooleannoLock the account.
unlockbooleannoUnlock the account.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.sys.user.delete -- Delete a user account

Delete a user account from a remote host. Requires sudo privileges. Protected system accounts (root, sshd, nobody, etc.) cannot be deleted.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
usernamestringyesUsername to delete.
remove_homebooleannoRemove the user's home directory (default: false).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Process Management Tools

nefia.sys.kill -- Send signal to a process

Send a signal to a process on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pidintyesProcess ID to signal.
signalstringnoSignal to send: SIGTERM, SIGKILL, SIGHUP, SIGINT, SIGUSR1, SIGUSR2 (default: SIGTERM).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

Cron Management Tools

nefia.sys.cron.list -- List cron jobs

List cron jobs on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
userstringnoFilter by user.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.cron.create -- Create a cron job

Create a cron job on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
schedulestringyesCron schedule expression (5-field: min hour dom mon dow).
commandstringyesCommand to execute.
userstringnoUser to run the cron job as.
commentstringnoComment describing the cron job.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true

nefia.sys.cron.delete -- Delete a cron job

Delete a cron job from a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
idstringyesCron job ID or comment identifier.
userstringnoUser who owns the cron job.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

System Information Tools (Extended)

nefia.sys.network -- Network interface information

Get network interface information from a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.disk -- Disk usage information

Get disk usage and partition information from a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.env -- Environment variables

Get environment variables from a remote host. Sensitive values matching *_KEY, *_SECRET, *_TOKEN, *_PASSWORD, *_CREDENTIAL are automatically masked.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
filterstringnoFilter by name (case-insensitive substring match).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.group.list -- List system groups

List system groups on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.logs.search -- Search system logs

Search system logs with keywords, service, and severity filtering. More structured than nefia.sys.logs for targeted log investigation.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
keywordsstring[]yesKeywords to search for (all must match).
servicesstring[]noFilter by service/unit names.
severitystringnoMinimum severity: emerg, alert, crit, err, warning, notice, info, debug.
sincestringnoStart time (RFC 3339 or relative duration).
untilstringnoEnd time (RFC 3339 or relative duration).
correlatebooleannoMerge and sort entries from all sources by timestamp.
limitintnoMaximum results (default: 500, max: 5000).
targetstringnoHost selector for fleet-wide log search (e.g., "all", "group:prod"). Mutually exclusive with session_id/host_id.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Extended File System Tools

nefia.fs.symlink -- Create a symbolic link

Create a symbolic link on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
targetstringyesLink target path.
pathstringyesPath where the symlink will be created.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.readlink -- Read symbolic link target

Read the target of a symbolic link on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathstringyesSymbolic link path.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.fs.archive.create -- Create an archive

Create a tar.gz or zip archive on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
pathsstring[]yesPaths to include in the archive.
output_pathstringyesOutput archive path.
formatstringnoArchive format: tar.gz or zip (default: tar.gz).

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true

nefia.fs.archive.extract -- Extract an archive

Extract a tar.gz or zip archive on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
archivestringyesArchive file path.
output_pathstringyesOutput directory for extracted files.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.fs.diff -- Compare two files

Compare two files on a remote host and return a unified diff.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
path_astringyesFirst file path.
path_bstringyesSecond file path.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Host Group Tools

nefia.hosts.groups -- List host groups

List all host groups with member counts.

Parameters: None.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Service Management Tools

nefia.sys.service.enable -- Enable a service

Enable a service to start on boot.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
servicestringyesService name.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.service.disable -- Disable a service

Disable a service from starting on boot.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
servicestringyesService name.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.service.reload -- Reload a service

Reload a service's configuration without restarting it.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
servicestringyesService name.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.service.logs -- Get service logs

Get logs for a specific service.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
servicestringyesService name.
linesintnoNumber of lines to return (default: 100).
sincestringnoStart time (RFC 3339 or relative duration).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.service.show -- Show service details

Show detailed status and configuration for a specific service.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
servicestringyesService name.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Network Diagnostics Tools

nefia.net.ping -- Ping a target

Ping a target from a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
targetstringyesHostname or IP to ping.
countintnoNumber of pings (default: 4).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.net.traceroute -- Trace route to a target

Trace the network route to a target from a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
targetstringyesHostname or IP to trace.
max_hopsintnoMaximum hops (default: 30).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.net.dns -- DNS lookup

Perform a DNS lookup from a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
namestringyesDomain name to look up.
record_typestringnoRecord type: A, AAAA, CNAME, MX, NS, TXT, SRV, PTR, SOA (default: A).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.net.connections -- List network connections

List network connections on a remote host, optionally filtered by state.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
statestringnoFilter by state: established, listen, time_wait, close_wait, all (default: all).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.net.listen -- List listening ports

List all listening ports on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Firewall Management Tools

nefia.net.firewall.list -- List firewall rules

List firewall rules on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.net.firewall.add -- Add a firewall rule

Add a firewall rule on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
actionstringyesRule action: allow, deny, or reject.
directionstringyesTraffic direction: in or out.
protocolstringnoProtocol: tcp, udp, icmp, or any (default: any).
portintnoPort number.
port_rangestringnoPort range (e.g., 8000-9000).
sourcestringnoSource address or CIDR.
destinationstringnoDestination address or CIDR.
rulestringnoRaw firewall rule string (backend-specific).
commentstringnoRule description.
priorityintnoRule priority.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.net.firewall.remove -- Remove a firewall rule

Remove a firewall rule from a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
rule_idstringyesRule ID or name to remove.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.net.firewall.status -- Firewall status

Check firewall status on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

System Update Tools

nefia.sys.update.check -- Check for updates

Check for available system updates on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
security_onlybooleannoOnly check for security updates (default: false).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.update.apply -- Apply system updates

Apply system updates on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
packagesstring[]noSpecific packages to update (max 50). If omitted, updates all.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.sys.hostname -- Get or set hostname

Get or set the system hostname on a remote host. Setting requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
new_hostnamestringnoNew hostname to set. If omitted, returns the current hostname.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.time -- System time information

Get time information, set timezone, or trigger NTP sync on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
set_timezonestringnoIANA timezone to set (e.g., America/New_York).
ntp_syncbooleannoTrigger NTP time synchronization.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.sysctl.list -- List sysctl parameters

List kernel sysctl parameters on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
patternstringnoFilter by pattern (e.g., net.ipv4).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.sysctl.set -- Set a sysctl parameter

Set a kernel sysctl parameter on a remote host. Requires sudo privileges. Values are validated against a regex whitelist.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
keystringyesSysctl parameter name (e.g., net.ipv4.ip_forward).
valuestringyesParameter value.
persistbooleannoPersist across reboots (default: false).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

Mount Management Tools

nefia.sys.mount.list -- List mount points

List mount points on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.sys.mount -- Mount a device

Mount a device on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
devicestringyesDevice path (e.g., /dev/sdb1).
mount_pointstringyesMount point path.
fs_typestringnoFilesystem type (e.g., ext4, xfs, nfs).
optionsstringnoMount options (e.g., ro,noexec).
readonlybooleannoMount as read-only.
persistentbooleannoAdd to fstab for persistence across reboots.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.sys.umount -- Unmount a device

Unmount a mount point on a remote host. Requires sudo privileges.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
mount_pointstringyesMount point to unmount.
forcebooleannoForce unmount (default: false).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

Container Management Tools

nefia.container.list -- List containers

List containers (Docker or Podman) on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
allbooleannoInclude stopped containers (default: false).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.container.logs -- Get container logs

Get logs from a container on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
container_idstringyesContainer name or ID.
tailintnoNumber of lines from the end (default: 100).
sincestringnoStart time (RFC 3339 or relative duration).
untilstringnoEnd time (RFC 3339 or relative duration).
timestampsbooleannoInclude timestamps in output.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.container.start -- Start a container

Start a stopped container on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
container_idstringyesContainer name or ID.

Annotations: readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.container.stop -- Stop a container

Stop a running container on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
container_idstringyesContainer name or ID.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.container.restart -- Restart a container

Restart a container on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
container_idstringyesContainer name or ID.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.container.inspect -- Inspect a container

Get detailed information about a container on a remote host.

Parameters:

ParameterTypeRequiredDescription
session_idstringnoSession ID (use this or host_id).
host_idstringnoHost ID (use this or session_id).
container_idstringyesContainer name or ID.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

VPN Extended Tools

nefia.vpn.key.rotate -- Rotate VPN keys

Rotate VPN WireGuard keys for a host. The host will need to reconnect after key rotation.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to rotate keys for.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.conn.health -- Connection health check

Check connection health for a specific host or all hosts. Tests VPN tunnel, SSH connectivity, and SFTP subsystem.

Parameters:

ParameterTypeRequiredDescription
host_idstringnoHost ID to check (omit for all hosts).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Composite Tools

Composite tools combine multiple operations into a single, higher-level workflow for common patterns.

nefia.run -- One-shot command execution

Execute a command on a host without opening a session. Simpler alternative to session.open + exec + session.close for one-off commands.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesTarget host ID.
commandstringyesCommand to execute.
timeout_msintnoTimeout in milliseconds (max: 7,200,000 / 2 hours). Uses configured default when omitted.
envobjectnoEnvironment variables to inject (env var blacklist enforced).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.investigate -- Comprehensive host investigation

Run a comprehensive investigation of a host, gathering facts, processes, services, ports, disk, and network information in a single call.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to investigate.
sectionsstring[]noSections to include: facts, processes, services, ports, disk, network (default: all).
timeout_msintnoTimeout in milliseconds (max: 600,000 / 10 min). Uses configured default when omitted.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.file.deploy -- Deploy a file with verification

Deploy a file to a remote host with optional mode, ownership, backup, and verification.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector expression.
remote_pathstringyesDestination file path.
contentstringnoFile content (UTF-8).
content_base64stringnoFile content (base64-encoded).
modestringnoFile permissions (e.g., 0644).
ownerstringnoFile ownership (user:group).
backup_existingbooleannoBack up existing file before overwriting.
verify_commandstringnoCommand to verify deployment.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true

nefia.service.deploy -- Atomic service deployment

Atomically deploy a service with config push, verification, and rollback on failure.

Parameters:

ParameterTypeRequiredDescription
targetstringyesHost selector expression.
service_namestringyesService name.
config_pathstringyesRemote config file path.
config_contentstringyesConfig file content.
verify_commandstringnoCommand to verify the config (e.g., nginx -t).
health_commandstringnoCommand to check service health after restart.
health_timeout_msintnoTimeout for health check.
rollback_on_failurebooleannoRollback config and restart on failure (default: true).

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.config.apply -- Atomic config update

Atomically update a config file with validation and optional service reload.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesTarget host ID.
config_pathstringyesConfig file path.
contentstringyesNew config content.
validate_commandstringnoCommand to validate config (e.g., nginx -t).
reload_servicestringnoService to reload after update.
verify_commandstringnoCommand to verify after reload.

Annotations: readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true

nefia.system.baseline -- Capture system state snapshot

Capture a system state snapshot for drift detection. Returns packages, services, ports, disk usage, users, and network configuration.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to snapshot.
sectionsstring[]noSections to include: packages, services, ports, disk, users, network (default: all).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

nefia.system.health -- Comprehensive health check

Run comprehensive health checks on a host, including VPN, services, disk, load, ports, and memory.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to check.
checksstring[]noChecks to run: vpn, services, disk, load, ports, memory (default: all).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true

Discovery & Policy Tools

nefia.tools.schema -- Get tool schema

Get the full JSON schema for a specific tool. Useful for progressive discovery — when the compact tool listing does not include enough detail, call this tool to get the complete parameter schema.

Parameters:

ParameterTypeRequiredDescription
tool_namestringyesTool name (e.g., nefia.exec, nefia.fs.read).

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.policy.capabilities -- Policy capabilities for a host

Read the effective policy capabilities for a specific host. Returns which operations are allowed and denied.

Parameters:

ParameterTypeRequiredDescription
host_idstringyesHost ID to check.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

nefia.approval.check -- Check if approval is required

Check if a specific tool call would require approval before execution.

Parameters:

ParameterTypeRequiredDescription
tool_namestringyesTool name to check.
host_idstringnoHost context for the check.

Annotations: readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false

Tool Summary

The current nefia mcp serve command exposes 205 core tools, plus 2 conditional approval tools (207 total when approval is enabled):

#ToolCategoryRead-OnlyDestructive
1nefia.session.openSessionnono
2nefia.session.closeSessionnoyes
3nefia.session.summarySessionyesno
4nefia.session.listSessionyesno
5nefia.execExecutionnoyes
6nefia.exec.sudoExecutionnoyes
7nefia.cancelExecutionnoyes
8nefia.fs.readFile Systemyesno
9nefia.fs.writeFile Systemnoyes
10nefia.fs.patchFile Systemnono
11nefia.fs.listFile Systemyesno
12nefia.fs.statFile Systemyesno
13nefia.fs.copyFile Systemnoyes
14nefia.fs.moveFile Systemnoyes
15nefia.fs.grepFile Systemyesno
16nefia.fs.duFile Systemyesno
17nefia.fs.stream_readFile Systemyesno
18nefia.fs.stream_writeFile Systemnoyes
19nefia.fs.stream_read_resumableFile Systemyesno
20nefia.fs.stream_write_resumableFile Systemnoyes
21nefia.fs.mkdirFile Systemnono
22nefia.fs.removeFile Systemnoyes
23nefia.fs.chmodFile Systemnoyes
24nefia.fs.chownFile Systemnoyes
25nefia.fs.findFile Systemyesno
26nefia.fs.tailFile Systemyesno
27nefia.fs.symlinkFile Systemnono
28nefia.fs.readlinkFile Systemyesno
29nefia.fs.archive.createFile Systemnono
30nefia.fs.archive.extractFile Systemnoyes
31nefia.fs.diffFile Systemyesno
32nefia.pushMulti-Host Filenoyes
33nefia.syncMulti-Host Filenoyes
34nefia.hosts.listDiscoveryyesno
35nefia.hosts.showDiscoveryyesno
36nefia.hosts.updateDiscoverynono
37nefia.hosts.groupsDiscoveryyesno
38nefia.playbook.runPlaybooknoyes
39nefia.playbook.listPlaybookyesno
40nefia.playbook.showPlaybookyesno
41nefia.playbook.validatePlaybookyesno
42nefia.factsSystem Infoyesno
43nefia.sys.processesSystem Queryyesno
44nefia.sys.servicesSystem Queryyesno
45nefia.sys.portsSystem Queryyesno
46nefia.sys.usersSystem Queryyesno
47nefia.sys.logsSystem Queryyesno
48nefia.sys.logs.searchSystem Queryyesno
49nefia.sys.service.controlSystem Querynoyes
50nefia.sys.networkSystem Queryyesno
51nefia.sys.diskSystem Queryyesno
52nefia.sys.envSystem Queryyesno
53nefia.sys.killSystem Querynoyes
54nefia.sys.group.listSystem Queryyesno
55nefia.sys.package.listPackageyesno
56nefia.sys.package.installPackagenoyes
57nefia.sys.package.removePackagenoyes
58nefia.sys.user.createUser Mgmtnoyes
59nefia.sys.user.modifyUser Mgmtnoyes
60nefia.sys.user.deleteUser Mgmtnoyes
61nefia.sys.cron.listCronyesno
62nefia.sys.cron.createCronnono
63nefia.sys.cron.deleteCronnoyes
64nefia.sys.service.enableServicenono
65nefia.sys.service.disableServicenono
66nefia.sys.service.reloadServicenono
67nefia.sys.service.logsServiceyesno
68nefia.sys.service.showServiceyesno
69nefia.net.pingNetworkyesno
70nefia.net.tracerouteNetworkyesno
71nefia.net.dnsNetworkyesno
72nefia.net.connectionsNetworkyesno
73nefia.net.listenNetworkyesno
74nefia.net.firewall.listFirewallyesno
75nefia.net.firewall.addFirewallnoyes
76nefia.net.firewall.removeFirewallnoyes
77nefia.net.firewall.statusFirewallyesno
78nefia.sys.update.checkSystem Updateyesno
79nefia.sys.update.applySystem Updatenoyes
80nefia.sys.hostnameSystem Updatenono
81nefia.sys.timeSystem Updatenono
82nefia.sys.sysctl.listSystem Updateyesno
83nefia.sys.sysctl.setSystem Updatenoyes
84nefia.sys.mount.listMountyesno
85nefia.sys.mountMountnoyes
86nefia.sys.umountMountnoyes
87nefia.container.listContaineryesno
88nefia.container.logsContaineryesno
89nefia.container.startContainernono
90nefia.container.stopContainernoyes
91nefia.container.restartContainernoyes
92nefia.container.inspectContaineryesno
93nefia.vpn.statusVPNyesno
94nefia.vpn.diagnoseVPNyesno
95nefia.vpn.pingVPNyesno
96nefia.vpn.revokeVPNnoyes
97nefia.vpn.key.rotateVPNnoyes
98nefia.netcheckVPNyesno
99nefia.conn.healthVPNyesno
100nefia.policy.testPolicyyesno
101nefia.policy.test_batchPolicyyesno
102nefia.policy.capabilitiesPolicyyesno
103nefia.jit.requestJIT Accessnono
104nefia.jit.listJIT Accessyesno
105nefia.audit.searchAudityesno
106nefia.audit.exportAudityesno
107nefia.agent.statusAgentyesno
108nefia.agent.upgradeAgentnoyes
109nefia.schedule.listScheduleyesno
110nefia.schedule.showScheduleyesno
111nefia.schedule.createSchedulenono
112nefia.schedule.updateSchedulenono
113nefia.schedule.deleteSchedulenoyes
114nefia.schedule.enableSchedulenono
115nefia.schedule.disableSchedulenono
116nefia.schedule.historyScheduleyesno
117nefia.queue.listQueueyesno
118nefia.queue.showQueueyesno
119nefia.queue.cancelQueuenoyes
120nefia.queue.retryQueuenoyes
121nefia.statusDiagnosticsyesno
122nefia.doctorDiagnosticsyesno
123nefia.explainDiagnosticsyesno
124nefia.recording.listDiagnosticsyesno
125nefia.recording.showDiagnosticsyesno
126nefia.recording.deleteDiagnosticsnoyes
127nefia.reactor.statusReactoryesno
128nefia.reactor.eventsReactoryesno
129nefia.compliance.reportComplianceyesno
130nefia.power.wakePowernoyes
131nefia.power.rebootPowernoyes
132nefia.power.shutdownPowernoyes
133nefia.secrets.listSecurityyesno
134nefia.secrets.testSecurityyesno
135nefia.config.showConfigurationyesno
136nefia.device_lock.statusSecurityyesno
137nefia.device_lock.verifySecurityyesno
138nefia.posture.checkSecurityyesno
139nefia.webhook.listWebhookyesno
140nefia.webhook.testWebhookyesno
141nefia.backup.listBackupyesno
142nefia.backup.createBackupnono
143nefia.runCompositenoyes
144nefia.investigateCompositeyesno
145nefia.file.deployCompositenoyes
146nefia.service.deployCompositenoyes
147nefia.config.applyCompositenoyes
148nefia.system.baselineCompositeyesno
149nefia.system.healthCompositeyesno
150nefia.tools.schemaDiscoveryyesno
151nefia.approval.checkDiscoveryyesno
152nefia.cluster.initClusternoyes
153nefia.cluster.statusClusteryesno
154nefia.cluster.membersClusteryesno
155nefia.cluster.add_peerClusternoyes
156nefia.cluster.remove_peerClusternoyes
157nefia.sshca.initSSH CAnoyes
158nefia.sshca.sign_userSSH CAnoyes
159nefia.sshca.sign_hostSSH CAnoyes
160nefia.sshca.statusSSH CAyesno
161nefia.sshca.trustSSH CAnoyes
162nefia.sshca.server_snippetSSH CAyesno
163nefia.mtls.initmTLSnoyes
164nefia.mtls.issue_clientmTLSnoyes
165nefia.mtls.statusmTLSyesno
166nefia.mtls.revokemTLSnoyes
167nefia.team.currentTeamyesno
168nefia.team.listTeamyesno
169nefia.team.useTeamnono
170nefia.team.createTeamnoyes
171nefia.team.inviteTeamnoyes
172nefia.team.joinTeamnono
173nefia.team.membersTeamyesno
174nefia.team.leaveTeamnoyes
175nefia.team.roleTeamnoyes
176nefia.profile.listProfileyesno
177nefia.profile.showProfileyesno
178nefia.profile.createProfilenono
179nefia.profile.deleteProfilenoyes
180nefia.profile.set_defaultProfilenono
181nefia.backup.restoreBackupnoyes
182nefia.backup.verifyBackupyesno
183nefia.webhook.createWebhooknoyes
184nefia.webhook.deleteWebhooknoyes
185nefia.webhook.updateWebhooknono
186nefia.reactor.rule.createReactornoyes
187nefia.reactor.rule.deleteReactornoyes
188nefia.reactor.rule.enableReactornono
189nefia.hosts.importDiscoverynoyes
190nefia.hosts.removeDiscoverynoyes
191nefia.hosts.refreshDiscoverynono
192nefia.vpn.configVPNyesno
193nefia.vpn.enroll_statusVPNyesno
194nefia.vpn.inviteVPNnoyes
195nefia.vpn.invite_listVPNyesno
196nefia.vpn.invite_revokeVPNnoyes
197nefia.vpn.peer.statsVPNyesno
198nefia.device_lock.initSecuritynoyes
199nefia.device_lock.revokeSecuritynoyes
200nefia.device_lock.signSecuritynono
201nefia.audit.verifyAudityesno
202nefia.recording.exportAudityesno
203nefia.schedule.triggerSchedulenoyes
204nefia.agent.pinAgentnono
205nefia.validateDiagnosticsyesno
206nefia.approval.listApprovalyesno
207nefia.approval.respondApprovalnono

Tool Annotations

Every tool declares annotations that inform the AI agent about the tool's behavior:

AnnotationDescription
readOnlyHinttrue if the tool only reads data and makes no changes.
destructiveHinttrue if the tool can modify or delete data on the target.
idempotentHinttrue if calling the tool multiple times with the same parameters produces the same result.
openWorldHinttrue if the tool interacts with external systems beyond Nefia's control.

AI agents can use these annotations to make safer decisions about when to invoke destructive tools and when to request user confirmation.

Progressive Discovery & Compact Mode

The MCP server supports progressive tool discovery to minimize token usage. By default, tools/list returns tools in compact mode (~3,000 tokens) instead of full schemas (~27,000 tokens).

Compact Mode

In compact mode, each tool includes:

FieldDescription
nameTool name (e.g., nefia.exec).
titleHuman-readable title (MCP spec 2025-06-18).
descriptionFirst line of the full description.
categoryTool category (one of 18 categories).
typical_sequenceCross-references to related tools for workflow planning.
required_paramsCount of required parameters.
hintsFlags: destructive, read_only, idempotent.
related_toolsSemantically related tools for cross-reference.
enumEnum values for constrained parameters.

Control Parameters

ParameterTypeDescription
_meta_compactbooleanForce compact mode (default: true).
_meta_fullbooleanForce full schema mode.
_meta_categoriesstring[]Filter tools by category.

Precedence: _meta_compact takes priority over _meta_full.

On-Demand Schema Fetch

Use nefia.tools.schema to fetch the full schema for a specific tool:

json
{ "method": "tools/call", "params": { "name": "nefia.tools.schema", "arguments": { "tool": "nefia.exec" } } }

outputSchema

All 207 tools include outputSchema definitions that describe the structure of their response. AI agents can predict the response shape before calling a tool, enabling more reliable parsing and error handling.

All 205 core tools include related_tools in _meta for bidirectional semantic cross-references. This enables AI agents to discover related tools without fetching full schemas. For example, nefia.exec references nefia.sys.processes, nefia.sys.services, and nefia.sys.ports.

Resources

The MCP server exposes 22 read-only resources (20 static + 2 templates) that AI agents can query for context. Resources are accessed via the resources/read method with a uri parameter.

Static Resources

URINameDescription
nefia://hostsHost ListAll configured hosts with VPN status, tags, and OS information. Sensitive VPN fields (InviteNonce, InviteExpires) are redacted; only status, vpn_addr, hostname, and os_name are exposed.
nefia://sessionsActive SessionsCurrently active MCP sessions.
nefia://policy/rulesPolicy RulesCurrent policy configuration summary (non-sensitive).
nefia://audit/recentRecent Audit LogsLast 50 audit log entries.
nefia://audit/statsAudit StatisticsAudit log statistics and summary metrics.
nefia://config/summaryConfiguration SummaryServer configuration overview (non-sensitive).
nefia://tools/categoriesTool CategoriesTool categorization with descriptions.
nefia://error-codesError CodesAll domain error codes with descriptions and recovery tools.
nefia://workflowsWorkflowsAvailable workflow prompts with descriptions.
nefia://vpn/statusVPN StatusCurrent VPN tunnel status and peer information.
nefia://cluster/statusCluster StatusRaft cluster status (leader, followers, term).
nefia://agent/fleetAgent FleetAgent status across all enrolled hosts.
nefia://tools/graphTool GraphTool dependency and relationship graph.
nefia://quick-startQuick StartGetting started guide for AI agents.
nefia://hosts/healthHost HealthHealth status for all hosts.
nefia://queue/stateQueue StateCurrent queue state and pending entries.
nefia://permissions/matrixPermissions MatrixPermission matrix for tools and hosts.
nefia://tools/approval-mapApproval MapWhich tools require approval and under what conditions.
nefia://vpn/invitesVPN InvitationsActive VPN enrollment invitations. Returns structured fields: host_id, os, expires_at, max_uses, used_count, and fleet.
nefia://device-lock/statusDevice Lock StatusDevice-lock authority status, public key fingerprint, and signed host count.

Resource Templates

URI TemplateNameDescription
nefia://hosts/{id}Host DetailDetailed information for a specific host.
nefia://hosts/{id}/capabilitiesHost CapabilitiesPolicy capabilities and allowed operations for a host.

All resources return application/json content. The subscribe/unsubscribe methods exist, but the current CLI server does not emit automatic notifications/resources/updated events for these resources.

Prompts

The MCP server provides 51 pre-built prompt templates that guide AI agents through common workflows. Prompts are accessed via the prompts/get method with a name and arguments.

Core Workflows

health-check -- Verify target connectivity

Guides the agent through checking host connectivity and reporting status.

ArgumentRequiredDescription
targetnoHost selector (e.g., all, host:pc-office, tag:env=prod). Defaults to all.
deploy-file -- Deploy file to multiple hosts

Guides the agent through deploying a file to target hosts with verification.

ArgumentRequiredDescription
targetyesHost selector for deployment targets.
source_pathyesPath of the file to deploy on the remote host.
dest_pathyesDestination path on the remote hosts.
diagnose-connectivity -- Troubleshoot host connectivity

Guides the agent through diagnosing connectivity issues with a specific host, including VPN status checks, basic command tests, and audit log review.

ArgumentRequiredDescription
host_idyesID of the host to diagnose.
security-audit -- Run security audit

Guides the agent through a security audit of target hosts, checking users, ports, updates, and firewall status.

ArgumentRequiredDescription
targetyesHost selector for audit targets.
checksnoComma-separated checks to run: users, ports, updates, firewall. Defaults to all.
bulk-exec -- Execute on multiple hosts with risk assessment

Guides the agent through executing a command across multiple hosts with safety checks and rollback guidance.

ArgumentRequiredDescription
targetyesHost selector for execution targets.
commandyesCommand to execute.
dry_runnoIf true, only preview without executing.

Policy & Access Workflows

policy-check-and-exec -- Check policy before executing

Pre-checks policy before execution, handling denials and JIT access requests.

ArgumentRequiredDescription
targetyesHost selector.
commandyesCommand to execute.
jit-elevated-exec -- Execute with JIT elevated access

Requests JIT elevated access and executes a command after approval.

ArgumentRequiredDescription
targetyesHost selector.
commandyesCommand requiring elevated access.
roleyesRole to request.
reasonyesBusiness justification.

File & Config Workflows

file-edit-workflow -- Safe file editing workflow

Guides through reading, editing, and verifying file changes with backup.

ArgumentRequiredDescription
host_idyesTarget host.
pathyesFile path to edit.

System Management Workflows

system-setup -- New system setup

Guides through initial system setup including user creation, package installation, and service configuration.

ArgumentRequiredDescription
host_idyesTarget host to set up.
incident-response -- Incident response workflow

Structured incident response: gather facts, check logs, identify issues, and remediate.

ArgumentRequiredDescription
host_idyesAffected host.
descriptionyesIncident description.
batch-rollout -- Staged batch rollout

Guides through rolling out changes across a fleet in stages with verification.

ArgumentRequiredDescription
targetyesHost selector.
commandyesCommand to roll out.
error-recovery -- Error recovery workflow

Guides through diagnosing and recovering from a specific error code.

ArgumentRequiredDescription
error_codeyesError code to recover from.

Operations Workflows

software-upgrade -- Software upgrade workflow

Guides through safely upgrading software packages with pre/post checks.

ArgumentRequiredDescription
targetyesHost selector.
packageyesPackage to upgrade.
config-sync -- Configuration synchronization

Synchronize configuration files across multiple hosts.

ArgumentRequiredDescription
targetyesHost selector.
config_pathyesConfiguration file path.
log-analysis -- Log analysis workflow

Structured log analysis: search, correlate, and identify patterns.

ArgumentRequiredDescription
host_idyesTarget host.
keywordsyesKeywords to search for.
secret-rotation -- Secret rotation workflow

Guides through rotating secrets and updating dependent services.

ArgumentRequiredDescription
provideryesSecret provider name.
compliance-audit -- Compliance audit workflow

Comprehensive compliance audit against a security framework.

ArgumentRequiredDescription
frameworkyesFramework: soc2, iso27001, or hipaa.
network-diagnostics -- Network diagnostics workflow

Comprehensive network diagnostics including ping, traceroute, DNS, and firewall checks.

ArgumentRequiredDescription
host_idyesTarget host.
target_hostnoRemote target to diagnose connectivity to.

Operations Workflows

verify-and-rollback -- Verify changes and rollback if needed

Guides through verifying deployed changes and rolling back on failure.

ArgumentRequiredDescription
host_idyesTarget host.
serviceyesService to verify.
service-management -- Service lifecycle management

Manage service lifecycle: enable, start, monitor, and troubleshoot.

ArgumentRequiredDescription
host_idyesTarget host.
serviceyesService name.
container-operations -- Container management workflow

Manage container lifecycle: list, inspect, logs, restart.

ArgumentRequiredDescription
host_idyesTarget host.
firewall-management -- Firewall rule management

Review, add, and verify firewall rules.

ArgumentRequiredDescription
host_idyesTarget host.
system-update -- System update workflow

Safely check, apply, and verify system updates.

ArgumentRequiredDescription
targetyesHost selector.
host-investigation -- Comprehensive host investigation

Deep investigation of a host's state, performance, and configuration.

ArgumentRequiredDescription
host_idyesTarget host.
disk-cleanup -- Disk cleanup workflow

Identify and clean up disk space on a host.

ArgumentRequiredDescription
host_idyesTarget host.

Security Workflows

ssh-hardening -- SSH hardening workflow

Harden SSH configuration on target hosts.

ArgumentRequiredDescription
host_idyesTarget host.
package-upgrade-safe -- Safe package upgrade workflow

Safely upgrade packages with backup, verification, and rollback.

ArgumentRequiredDescription
targetyesHost selector.
packageyesPackage to upgrade.
database-backup-verify -- Database backup and verify

Create and verify database backups.

ArgumentRequiredDescription
host_idyesDatabase host.
log-investigation -- Log investigation workflow

Deep log investigation with correlation across services.

ArgumentRequiredDescription
host_idyesTarget host.
timeframenoTime range to investigate (e.g., 1h, 24h).
user-onboarding -- User onboarding workflow

Set up a new user account with proper access and configuration.

ArgumentRequiredDescription
host_idyesTarget host.
usernameyesUsername to create.

Infrastructure Workflows

cluster-management -- Initialize and manage a Raft cluster

Guides the agent through initializing a Raft cluster, adding peers, monitoring status, and performing failover.

ArgumentRequiredDescription
actionnoCluster action: init, status, add-peer, or failover. Defaults to status.
sshca-setup -- Initialize SSH CA and manage certificates

Guides the agent through initializing the SSH Certificate Authority, signing user and host certificates, and configuring trust.

ArgumentRequiredDescription
actionnoSSH CA action: init, sign-user, sign-host, or trust. Defaults to init.
mtls-gateway-setup -- Configure mTLS gateway for AI agents

Guides the agent through initializing the mTLS CA, issuing client certificates, and verifying mTLS status.

ArgumentRequiredDescription
client_namenoName for the client certificate to issue.
team-onboarding -- Create a team and invite members

Guides the agent through creating a team workspace, inviting members, and assigning roles.

ArgumentRequiredDescription
team_namenoName for the new team.
backup-and-restore -- Create, verify, and restore backups

Guides the agent through creating a backup, verifying its integrity, and restoring from a backup archive.

ArgumentRequiredDescription
actionnoBackup action: create, verify, or restore. Defaults to create.
webhook-reactor-setup -- Configure event-driven automation

Guides the agent through creating webhooks, setting up reactor rules, and testing the event pipeline.

ArgumentRequiredDescription
actionnoSetup action: webhook, reactor, or test. Defaults to webhook.
vpn-troubleshooting -- Diagnose and resolve VPN issues

Guides the agent through diagnosing VPN connectivity problems, checking peer status, and rebuilding tunnels.

ArgumentRequiredDescription
targetnoHost selector for VPN diagnostics. Defaults to all.
device-verification -- Initialize and manage device verification

Guides the agent through initializing device-lock, signing devices, and verifying authorization.

ArgumentRequiredDescription
actionnoDevice lock action: init, sign, or verify. Defaults to init.
cluster-failover -- Detect and recover from cluster failures

Guides the agent through detecting cluster leader failures and performing safe failover recovery.

ArgumentRequiredDescription
target_nodenoNode ID to promote as new leader.
host-onboarding -- End-to-end host onboarding workflow

Guides the agent through importing hosts, generating VPN invitations, enrolling agents, and verifying connectivity.

ArgumentRequiredDescription
sourcenoImport source: ssh-config, ansible, csv, or manual. Defaults to manual.
agent-fleet-management -- Manage agent versions and health

Guides the agent through checking agent versions, upgrading fleet-wide, pinning versions, and monitoring health.

ArgumentRequiredDescription
targetnoHost selector for agent management. Defaults to all.

Advanced Workflows

performance-troubleshoot -- Performance troubleshooting workflow

Guides through diagnosing performance issues: CPU, memory, disk I/O, network, and process analysis.

ArgumentRequiredDescription
host_idyesTarget host to investigate.
canary-deploy -- Canary deployment workflow

Guides through canary deployment: deploy to a subset, monitor metrics, and promote or rollback.

ArgumentRequiredDescription
targetyesHost selector for canary targets.
serviceyesService to deploy.
config-audit -- Configuration audit workflow

Audit configuration consistency across hosts and detect drift.

ArgumentRequiredDescription
targetyesHost selector for audit targets.

Resilience Workflows

database-restore -- Database restore workflow

Guides through database restore from backup with verification and rollback.

ArgumentRequiredDescription
host_idyesDatabase host.
backup_pathyesPath to the backup archive.
cascading-error-handling -- Cascading error handling workflow

Guides through handling cascading failures across dependent services.

ArgumentRequiredDescription
host_idyesStarting host.
serviceyesService experiencing failures.
multi-host-coordination -- Multi-host coordination workflow

Coordinate operations across multiple hosts with dependency ordering and rollback.

ArgumentRequiredDescription
targetyesHost selector.
operationyesOperation to coordinate.
performance-baseline -- Performance baseline workflow

Establish and compare performance baselines for hosts.

ArgumentRequiredDescription
host_idyesTarget host.
ssl-cert-renewal -- SSL certificate renewal workflow

Guides through SSL/TLS certificate renewal, validation, and service restart.

ArgumentRequiredDescription
host_idyesTarget host.
cert_pathnoPath to the certificate file.
capacity-planning -- Capacity planning workflow

Analyze resource usage trends and plan capacity requirements.

ArgumentRequiredDescription
targetyesHost selector for analysis targets.
maintenance-window -- Maintenance window workflow

Coordinate a maintenance window: pre-checks, execution, verification, and sign-off.

ArgumentRequiredDescription
targetyesHost selector for maintenance targets.
descriptionyesDescription of the maintenance activity.

Error Handling

The MCP server uses two error categories:

  • Domain errors (tool execution failures) are returned as successful JSON-RPC responses with isError: true in the content. These indicate that the tool was invoked but the operation failed (e.g., file not found, permission denied, policy blocked).
  • Protocol errors (invalid params, unknown tool) are returned as standard JSON-RPC error responses. These indicate that the request itself was malformed.

All domain errors include structured remediation data in the data field:

FieldTypeDescription
error_codestringUppercase domain code (e.g., HOST_NOT_FOUND, POLICY_DENIED).
hintstringHuman-readable error message.
transientbooleanWhether the error is transient (safe to retry).
retry_after_msintSuggested wait time before retry (present for transient errors).
recovery_toolstringMCP tool to call for recovery (e.g., nefia.hosts.list, nefia.vpn.diagnose).
suggested_actionsstring[]Actionable remediation steps.
diagnosticsstring[]Diagnostic commands to run.
exampleobjectExample tool call the agent can try.
host_idstringContext: host involved in the error.
pathstringContext: file path involved in the error.
commandstringContext: command that caused the error.
invalid_paramstringParameter name that failed validation (for INVALID_PARAMS errors).
constraintstringDescription of the constraint that was violated.
example_valuestringExample of a valid value for the invalid parameter.
rule_namestringName of the policy rule that matched (for POLICY_DENIED errors).
denied_patternstringThe specific pattern that was denied by policy.
failure_stagestringStage where a composite operation failed (e.g., "download", "validate", "rollback").
rollback_statusstringStatus of the rollback operation after a composite failure ("success", "failed", "skipped").

The transient flag indicates whether the error is temporary (e.g., network timeout, rate limit) or permanent (e.g., policy denied, host not found). AI agents should only retry operations when transient is true. The recovery_tool field suggests which MCP tool to call to resolve the error — for example, HOST_NOT_FOUND suggests calling nefia.hosts.list, and SFTP_FAILED suggests calling nefia.vpn.diagnose.

Error Classification

Error classification is performed exclusively via sentinel error matching with errors.Is(). No string-based fallback is used. All domain errors are produced using the types.Errorf(types.ErrXxx, "message") pattern and are mapped to the appropriate RPC error code through precise error-chain matching with errors.Is().

Related sentinel errors are grouped under the same RPC code. For example, ErrFileNotFound, ErrPermissionDenied, and ErrFileTooLarge all map to SFTPFailed (-32006), while ErrVPNSetupFailed, ErrDERPConnectFailed, and ErrDERPAuthFailed all map to VPNFailed (-32009).

Domain Error Codes

CodeNameDescription
-32001PolicyDeniedThe operation was blocked by the policy engine.
-32002PathDeniedThe requested path is outside the session root (sandbox escape).
-32003SSHAuthFailedSSH authentication failed (invalid key, no auth methods accepted).
-32004SSHConnFailedSSH connection failed (host unreachable, no active VPN).
-32005CmdTimeoutThe command exceeded its configured timeout.
-32006SFTPFailedAn SFTP operation failed. This code also covers FILE_NOT_FOUND, PERMISSION_DENIED, and FILE_TOO_LARGE errors.
-32007SessionNotFoundThe specified session ID does not exist or has expired.
-32008HostNotFoundThe specified host ID was not found in the configuration.
-32009VPNFailedA VPN tunnel operation failed (tunnel down, dial error). This code also covers VPN_SETUP_FAILED, DERP_CONNECT_FAILED, and DERP_AUTH_FAILED errors.
-32010SessionRequiredA session is required but was not provided.
-32011PlaybookFailedThe playbook definition is invalid or execution failed.
-32012CommandFailedThe remote command completed but returned a non-zero exit code.
-32013AccessDeniedAuthentication, licensing, or team permission error.
-32014CancelledThe operation was cancelled by the user or timed out.
-32015DeviceLockDeniedThe device failed device-lock verification (Ed25519 key mismatch).
-32016PostureDeniedThe device did not meet the required posture policy.
-32017SecretResolveFailedA secret reference could not be resolved.
-32018ClusterNotLeaderThis operation must be performed on the Raft cluster leader.
-32019ServerNotInitializedThe MCP client has not sent the initialize handshake.
-32020SudoDisabledSudo is not enabled in the configuration.
-32021SudoDeniedThe sudo command was denied by the policy engine.
-32022JITRequiredJust-In-Time access is required for this operation.
-32023VPNNotReadyThe VPN tunnel is not yet established. Transient — retry after delay.
-32024ScheduleNotFoundThe specified schedule was not found.
-32025QueueEntryNotFoundThe specified queue entry was not found.
-32026QueueInvalidStateThe queue entry is in an invalid state for this operation.
-32027JobNotFoundThe specified job ID was not found.
-32028ConcurrencyLimitAll concurrent dispatch slots are in use. Transient — includes retry_after_ms.
-32029RateLimitedThe request was rejected because the MCP rate limit was exceeded. The response includes a retry_after_ms field.
-32030AuthRequiredAuthentication is required for this operation (team/auth context).
-32031ServiceDeployFailedThe service.deploy composite operation failed during one of its stages.
-32032ConfigApplyFailedThe config.apply composite operation failed during one of its stages.
-32033BaselineDriftThe system.baseline comparison detected configuration drift.
-32034MountFailedA filesystem mount operation failed.
-32035ContainerFailedA container operation failed.
-32036ClusterJoinFailedThe node failed to join the Raft cluster. Transient — retry after delay.
-32037SSHCASigningFailedSSH CA certificate signing failed.
-32038StreamTimeoutA streaming file transfer timed out. Transient — retry with nefia.fs.stream_read_resumable.
-32039FeatureDisabledThe requested feature is not enabled in nefia.yaml. Enable it in the configuration and retry.
-32601MethodNotFoundThe requested tool or method does not exist. Use nefia.tools.schema to discover available tools.

Sentinel Error Grouping

Multiple sentinel errors may map to the same RPC code. AI agents should use the error_code field (e.g., SFTP_FAILED) to determine the broad category and the hint field to identify the specific cause (e.g., "file not found: /path/to/file").

RPC CodeSentinel Errors
-32004 (SSHConnFailed)ErrSSHConnFailed, ErrSSHSessionFailed
-32006 (SFTPFailed)ErrSFTPFailed, ErrFileNotFound, ErrPermissionDenied, ErrFileTooLarge
-32009 (VPNFailed)ErrVPNFailed, ErrVPNSetupFailed, ErrDERPConnectFailed, ErrDERPAuthFailed
-32012 (CommandFailed)ErrCmdExitNonZero
-32013 (AccessDenied)ErrAuthRequired, ErrAuthExpired, ErrDeviceLimitExceeded, ErrLicenseDenied, ErrTeamNotFound, ErrTeamAccessDenied, ErrTeamMemberLimit, ErrTeamInviteInvalid
-32602 (InvalidParams)ErrConfigInvalid, ErrSelectorInvalid

All other domain error codes have a one-to-one mapping to their sentinel errors.

Protocol Error Codes

CodeNameDescription
-32700ParseErrorInvalid JSON was received.
-32600InvalidRequestThe JSON sent is not a valid request object.
-32601MethodNotFoundThe method does not exist or is not available.
-32602InvalidParamsInvalid method parameter(s).
-32603InternalErrorInternal JSON-RPC error.

The server uses a blocking dispatch semaphore (50 concurrent request slots). When all slots are in use, incoming requests wait for a slot to become available rather than being rejected immediately. If the request's context is cancelled while waiting (e.g., client disconnect or timeout), the server returns -32603 (internal error) with the message: "server is busy: all request slots are in use; retry after a short delay or reduce concurrent requests with --concurrency". Lightweight methods (such as approval responses) bypass the semaphore entirely to prevent deadlocks.

Multi-Host Response Format

When a tool targets multiple hosts, the response includes additional tracking fields:

FieldTypeDescription
operation_idstringUnique job ID for tracking the multi-host operation.
partial_successbooleantrue if some hosts succeeded and others failed.
failure_summaryobjectFailures grouped by error code, each with count, host_ids (max 20), and recovery_tool.

Rate Limiting

The MCP server enforces rate limits configured in nefia.yaml under the mcp.rate_limit section. When the limit is exceeded, the server returns error code -32029 (RateLimited) with a retry_after_ms field indicating how long to wait.

yaml
mcp:
  rate_limit:
    rate: 1.0      # requests per second
    burst: 10

Limits & Safety

The MCP server enforces hard limits on content size and execution time to protect both the operator host and remote targets.

Content Field Limit (7 MB)

All MCP content fields (content and content_base64 in tool parameters and responses) are capped at 7 MB (7,340,032 bytes). Both text and base64-encoded content are subject to this limit. Because base64 encoding inflates data by approximately 33%, a 7 MB base64 string corresponds to roughly 5.25 MB of decoded binary data.

Requests that exceed the content limit are rejected with an InvalidParams error before any remote operation is attempted. For files larger than the content limit, use nefia.fs.stream_read and nefia.fs.stream_write, which transfer data without buffering in the MCP content field.

Exec Timeout Cap (2 Hours)

The maximum allowed timeout for nefia.exec operations is 2 hours (7,200,000 ms), regardless of the value requested by the client. If a client specifies a timeout_ms value greater than 7,200,000, it is silently clamped to the cap. The default timeout comes from the configuration (typically 30 minutes) and applies when timeout_ms is omitted.

Per-Client Session Limit (50)

Each MCP client is limited to 50 concurrent sessions. Attempting to open a 51st session returns an error. Sessions are tracked per client, so separate clients each have their own independent limit. This prevents a single client from exhausting server resources.

Log Sanitization

MCP notification logs automatically redact sensitive fields before emission:

  • URLs: Query parameters in URLs are replaced with ?REDACTED
  • Headers: Authorization and Proxy-Authorization header values are masked
  • Parameters: command, verify_command, path, token, secret, and password values are redacted
  • Bearer tokens: Strings of 12 or more alphanumeric characters matching bearer token patterns are masked

This ensures that sensitive data does not leak into MCP log notifications, even when verbose logging is enabled.

Host Resource Redaction

The nefia://hosts/inventory resource and host-related resources redact sensitive VPN fields. Only status, vpn_addr, hostname, and os_name are exposed in VPN information. Internal fields such as InviteNonce and InviteExpires are stripped from the response.

mTLS Client Identity

When mTLS is enabled, the MCP server extracts the AgentIdentity from the client certificate, including a Serial field derived from the certificate's serial number. This serial is logged in MCP client connection messages and used for multi-client identification in audit logs, enabling operators to trace which client certificate was used for each MCP session.

Approval Configuration

The mcp.approval section is active when enabled: true and nefia mcp serve is running. In the current implementation:

  • approval-specific MCP tools are advertised when approval is enabled; when disabled, they are still advertised with (not configured) descriptions for discoverability
  • tools and hosts use exact matching
  • commands and paths use prefix matching (e.g., command pattern rm matches rm -rf /, path pattern /etc matches /etc/passwd)
  • the first matching rule wins
  • require_approval: false acts as an explicit exemption rule
  • nefia.sshca.sign_user has mandatory approval that cannot be exempted by rules; it always requires human approval when the approval workflow is enabled

Error Recovery Decision Tree

AI agents should follow this decision tree when a tool call returns an error:

  1. Extract the error code from the details.error_code field in the error response (e.g., HOST_NOT_FOUND, POLICY_DENIED, SSH_AUTH_FAILED).

  2. Check if the error is retryable:

    • RATE_LIMITED: Wait for retry_after_ms, then retry the same call.
    • SSH_CONN_FAILED: Call nefia.vpn.diagnose to check connectivity, then retry after the issue is resolved.
    • CMD_TIMEOUT: Increase timeout_ms or split the command into smaller operations.
    • POLICY_DENIED: Do not retry. Explain to the user why the operation was blocked.
    • HOST_NOT_FOUND: Call nefia.hosts.list to find the correct host ID.
    • SESSION_NOT_FOUND: The session expired or was closed. Open a new session with nefia.session.open.
  3. Call nefia.explain for remediation guidance:

    json
    { "method": "tools/call", "params": { "name": "nefia.explain", "arguments": { "error_code": "SSH_AUTH_FAILED" } } }

    The response includes suggested_actions, diagnostics (tool calls to run), and an example (a tool call to try).

  4. Follow the suggested actions from nefia.explain. Run the recommended diagnostics tools and adjust your approach based on results.

  5. If the error persists after remediation, report the error to the user with the error code, hint message, and the steps you have already taken.

Configuration

Configure MCP rate limits, policy mode, and server settings.

CLI Reference

Full reference for the nefia mcp serve command.

Sessions Guide

Learn how sessions provide sandboxed file operations for MCP tools.

Agent Patterns

Best practices for AI agents using Nefia MCP tools.