Skip to content

MCP Integration

Connect AI agents to your infrastructure using the Model Context Protocol.

Nefia includes a built-in MCP (Model Context Protocol) server that lets AI agents manage your infrastructure through the same policy-governed interface as the CLI. AI agents can execute commands, read and write files, and gather system facts — all within the guardrails you define.

What is MCP?

The Model Context Protocol is an open standard for connecting AI models to external tools. Instead of giving an AI agent raw SSH access, MCP provides a structured interface where every operation is:

  • Named and typed — Each tool has a schema describing its inputs and outputs.
  • Policy-governed — The same allow/deny rules from your Nefia policy engine apply to MCP operations.
  • Audited — Every MCP call is recorded in the append-only audit log.

Starting the MCP Server

Launch the MCP server on your operator PC:

bash
nefia mcp serve

The server communicates over stdio using JSON-RPC 2.0. AI agents connect by spawning the nefia mcp serve process and reading/writing to its stdin/stdout.

Prerequisites

Before connecting an AI agent, make sure the following are in place:

  1. Log in first. The MCP server requires authentication. Run nefia login in your terminal before starting the server. If you skip this step, the server exits immediately with an error — but most MCP clients don't display stderr, so it will look like a silent connection failure.

  2. Ensure nefia is in your PATH. MCP clients spawn the server process directly without loading your shell profile (.zshrc, .bashrc, etc.). If nefia was installed via go install or placed in a custom directory, the client may not find it. Use the full path to be safe:

    json
    {
      "mcpServers": {
        "nefia": {
          "command": "/usr/local/bin/nefia",
          "args": ["mcp", "serve"]
        }
      }
    }

    To find your nefia path: run which nefia on macOS/Linux, or where nefia / Get-Command nefia (PowerShell) on Windows.

  3. Windows: use the cmd /c wrapper. On Windows, some MCP clients cannot execute .exe files directly. Wrap the command:

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

Connecting AI Agents

Claude Desktop

Add Nefia to your Claude Desktop MCP configuration:

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

Claude Code

Add Nefia as an MCP server in your project settings:

bash
claude mcp add nefia -- nefia mcp serve

Codex CLI (OpenAI)

Add the following to ~/.codex/config.toml:

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

OpenClaw

Add Nefia to your openclaw.json:

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

OpenClaw's always-on, autonomous nature makes it a powerful but sensitive integration. See the dedicated OpenClaw Integration guide for security hardening, approval workflows, and best practices.

Other MCP Clients

Any MCP client that supports stdio transport can connect by spawning nefia mcp serve and communicating over stdin/stdout with JSON-RPC 2.0. Once connected, the AI agent discovers all available tools automatically through the MCP handshake.

Available Tools

The MCP server exposes 207 tools (205 core plus 2 approval workflow tools), 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. The approval tools are always advertised to AI agents for discoverability, even when the approval workflow is not configured. All tools include outputSchema definitions for predictable response parsing. The server also provides 51 workflow prompts, 22 resources (20 static + 2 templates), and progressive tool discovery via nefia.tools.schema with compact mode (~3,000 tokens vs ~27,000 full).

Session Management

ToolDescription
nefia.session.openOpen a sandboxed session on a host with a root directory
nefia.session.closeClose an active session and release locks
nefia.session.summaryGenerate an AI-consumable summary of a session's activity
nefia.session.listList all active sessions

Each MCP client is limited to 50 concurrent sessions. Attempting to open a 51st session returns an error. nefia.session.list returns only the calling client's own sessions — one client cannot see or close sessions created by another client.

Command Execution

ToolDescription
nefia.execExecute a shell command on one or more hosts. Supports env, dry_run, batch_size, batch_wait, subset, rerun, and last_job_id for production-grade orchestration.
nefia.exec.sudoExecute a command with sudo privilege escalation (requires sudo.enabled: true and NOPASSWD in sudoers)
nefia.cancelCancel a running exec or playbook job

File Operations

ToolDescription
nefia.fs.readRead a file from a remote host
nefia.fs.writeWrite content to a remote file
nefia.fs.patchApply a unified diff patch to a remote file
nefia.fs.listList directory entries with sizes and permissions
nefia.fs.statGet file metadata (size, permissions, modification time)
nefia.fs.copyCopy a file on a remote host
nefia.fs.stream_readStream a large file download from remote to local
nefia.fs.stream_writeStream a large file upload from local to remote
nefia.fs.stream_read_resumableResumable download — continues interrupted transfers from last checkpoint
nefia.fs.stream_write_resumableResumable upload — continues interrupted transfers from last checkpoint
nefia.fs.mkdirCreate a directory (and missing parents) on a remote host
nefia.fs.removeRemove a file or directory (supports recursive)
nefia.fs.chmodChange file permissions (numeric or symbolic modes, macOS/Linux only)
nefia.fs.chownChange file ownership (user or user:group, macOS/Linux only)
nefia.fs.findSearch for files with filtering by name, type, size, and date
nefia.fs.tailRead last N lines of a file with optional grep filtering
nefia.fs.moveMove or rename a file/directory on a remote host
nefia.fs.grepSearch for a pattern in remote files (structured output with file paths and line numbers)
nefia.fs.duGet disk usage for a path on a remote host
nefia.fs.symlinkCreate a symbolic link on a remote host
nefia.fs.readlinkRead the target of a symbolic link
nefia.fs.archive.createCreate a tar.gz/zip archive on a remote host
nefia.fs.archive.extractExtract a tar.gz/zip archive on a remote host
nefia.fs.diffCompare two files on a remote host and return unified diff

Multi-Host File Operations

ToolDescription
nefia.pushPush a file to multiple hosts with batch and subset support
nefia.syncSync a local directory to multiple hosts. Only changed files are transferred.

Host Inventory

ToolDescription
nefia.hosts.listList all enrolled hosts with VPN status and tags
nefia.hosts.showGet detailed information about a specific host
nefia.hosts.updateUpdate host metadata (tags or role)
nefia.hosts.groupsList all host groups with member counts
nefia.hosts.importImport hosts from SSH config, Ansible inventory, CSV, or known_hosts.
nefia.hosts.removeRemove a host from the configuration.
nefia.hosts.refreshRefresh host metadata by reconnecting and gathering system facts.

Playbooks

ToolDescription
nefia.playbook.runExecute a multi-step playbook with dry-run support
nefia.playbook.listList all available playbooks
nefia.playbook.showShow full details of a playbook
nefia.playbook.validateValidate a playbook without executing

System Information

ToolDescription
nefia.factsGather structured system facts (OS, disk, memory, CPU, uptime, network)
nefia.sys.processesList running processes with CPU/memory usage (sorted, filterable)
nefia.sys.servicesList system services with status (systemctl / launchctl / Get-Service)
nefia.sys.portsList network connections and listening ports (ss / lsof / Get-NetTCPConnection)
nefia.sys.usersList user accounts with UID, groups, and home directory
nefia.sys.logsQuery system logs with time range, priority, and pattern filtering
nefia.sys.logs.searchSearch logs with keywords, service, and severity filtering
nefia.sys.service.controlStart, stop, restart, enable, or disable a system service
nefia.sys.networkGet network interface information
nefia.sys.diskGet disk usage and partition information
nefia.sys.envGet environment variables (sensitive values masked)
nefia.sys.killSend a signal to a process on a remote host
nefia.sys.group.listList system groups

Package Management

ToolDescription
nefia.sys.package.listList installed packages on a remote host
nefia.sys.package.installInstall a package on a remote host
nefia.sys.package.removeRemove a package from a remote host

User Management

ToolDescription
nefia.sys.user.createCreate a user account on a remote host
nefia.sys.user.modifyModify a user account on a remote host
nefia.sys.user.deleteDelete a user account from a remote host

Cron Management

ToolDescription
nefia.sys.cron.listList cron jobs on a remote host
nefia.sys.cron.createCreate a cron job on a remote host
nefia.sys.cron.deleteDelete a cron job from a remote host

Service Management

ToolDescription
nefia.sys.service.enableEnable a service to start on boot
nefia.sys.service.disableDisable a service from starting on boot
nefia.sys.service.reloadReload a service configuration
nefia.sys.service.logsGet service logs
nefia.sys.service.showShow detailed service status and configuration

Network Diagnostics

ToolDescription
nefia.net.pingPing a target from a remote host
nefia.net.tracerouteTrace route to a target from a remote host
nefia.net.dnsDNS lookup with record type support (A/AAAA/CNAME/MX/NS/TXT/SRV/PTR/SOA)
nefia.net.connectionsList network connections with state filtering
nefia.net.listenList listening ports on a remote host

Firewall Management

ToolDescription
nefia.net.firewall.listList firewall rules
nefia.net.firewall.addAdd a firewall rule
nefia.net.firewall.removeRemove a firewall rule
nefia.net.firewall.statusCheck firewall status

System Updates

ToolDescription
nefia.sys.update.checkCheck for available system updates
nefia.sys.update.applyApply system updates
nefia.sys.hostnameGet or set system hostname
nefia.sys.timeGet time info, set timezone, or trigger NTP sync
nefia.sys.sysctl.listList sysctl parameters
nefia.sys.sysctl.setSet a sysctl parameter

Mount Management

ToolDescription
nefia.sys.mount.listList mount points
nefia.sys.mountMount a device
nefia.sys.umountUnmount a device

Container Management

ToolDescription
nefia.container.listList containers (Docker/Podman)
nefia.container.logsGet container logs
nefia.container.startStart a container
nefia.container.stopStop a container
nefia.container.restartRestart a container
nefia.container.inspectInspect container details

VPN & Connectivity

ToolDescription
nefia.vpn.statusGet VPN tunnel status and peer connectivity information
nefia.vpn.diagnoseRun VPN diagnostics with issues and recommendations
nefia.vpn.pingTest VPN connectivity to a specific host
nefia.vpn.revokeRevoke VPN access for a host or all hosts. Requires re-enrollment via nefia vpn invite.
nefia.vpn.key.rotateRotate VPN keys for a host
nefia.netcheckRun network diagnostics (NAT type detection, STUN/DERP/TURN reachability). Alternative to nefia.vpn.diagnose for network-level analysis.
nefia.conn.healthCheck connection health for a specific host or all hosts
nefia.vpn.configShow current VPN configuration.
nefia.vpn.enroll_statusCheck enrollment status for a host.
nefia.vpn.inviteGenerate a VPN enrollment invitation.
nefia.vpn.invite_listList active VPN invitations.
nefia.vpn.invite_revokeRevoke a pending VPN invitation.
nefia.vpn.peer.statsShow per-peer VPN traffic statistics.

Policy

ToolDescription
nefia.policy.testPre-check if a command, path, or operation would be allowed by the policy engine
nefia.policy.test_batchTest multiple commands/paths/operations against policy in a single call (up to 50 tests)

JIT Access

ToolDescription
nefia.jit.requestRequest temporary elevated access
nefia.jit.listList JIT access requests and active grants

Audit

ToolDescription
nefia.audit.searchSearch audit logs with filters (date, host, operation, job ID)
nefia.audit.exportExport audit logs in JSONL or CSV format
nefia.audit.verifyVerify audit log hash chain integrity.

Agent Management

ToolDescription
nefia.agent.statusGet nefia-agent status on a target host
nefia.agent.upgradeUpgrade nefia-agent to a specified version
nefia.agent.pinPin a host's agent to a specific version, preventing auto-updates.

Schedule

ToolDescription
nefia.schedule.listList all scheduled playbook executions
nefia.schedule.showShow detailed information about a specific schedule
nefia.schedule.createCreate a new scheduled playbook execution
nefia.schedule.updatePartially update a schedule definition
nefia.schedule.deleteDelete a scheduled playbook execution
nefia.schedule.enableEnable a disabled schedule
nefia.schedule.disableDisable a schedule without deleting it
nefia.schedule.historyShow execution history for a schedule
nefia.schedule.triggerManually trigger a schedule for immediate execution.

Queue Management

ToolDescription
nefia.queue.listList queued offline commands
nefia.queue.showShow details of a single queue entry
nefia.queue.cancelCancel a pending queue entry
nefia.queue.retryRetry a failed, expired, or cancelled queue entry

Diagnostics

ToolDescription
nefia.statusSystem-wide status overview (VPN, hosts, queue, sessions, config)
nefia.doctorRun comprehensive health checks with pass/warn/fail status
nefia.explainGet detailed error remediation guidance for AI agents
nefia.validateValidate connectivity to target hosts.
nefia.recording.listList session recordings
nefia.recording.showShow metadata for a specific session recording
nefia.recording.deleteDelete a session recording
nefia.recording.exportExport a recording in a specified format.

Reactor

ToolDescription
nefia.reactor.statusShow reactor engine status including rules and hit counts
nefia.reactor.eventsList recent events processed by the reactor engine
nefia.reactor.rule.createCreate a new reactor rule with event pattern and action.
nefia.reactor.rule.deleteDelete a reactor rule by ID.
nefia.reactor.rule.enableEnable or disable a reactor rule.

Power Management

ToolDescription
nefia.power.wakeSend Wake-on-LAN magic packet to an offline host
nefia.power.rebootReboot a remote host
nefia.power.shutdownShut down a remote host

Secrets & Compliance

ToolDescription
nefia.secrets.listList configured secret providers (no values exposed)
nefia.secrets.testTest connectivity to a secret provider
nefia.compliance.reportGenerate a compliance report (SOC 2, ISO 27001, HIPAA)

Configuration & Backups

ToolDescription
nefia.config.showShow current configuration with sensitive fields masked
nefia.backup.listList available configuration backups
nefia.backup.createCreate a configuration backup (nefia.yaml + state)
nefia.backup.verifyVerify the integrity of a backup archive.
nefia.backup.restoreRestore configuration and state from a backup archive.

Device Security

ToolDescription
nefia.device_lock.statusCheck Ed25519 device-lock status for a host
nefia.device_lock.verifyVerify device-lock with cryptographic challenge
nefia.device_lock.initInitialize the device-lock authority with Ed25519 key pair.
nefia.device_lock.signSign a host's WireGuard public key, marking it as trusted.
nefia.device_lock.revokeRevoke trust for a host's public key.
nefia.posture.checkEvaluate device posture compliance (firewall, encryption, OS version)

Webhooks

ToolDescription
nefia.webhook.listList configured webhooks with masked URLs
nefia.webhook.testSend a test event to verify webhook delivery
nefia.webhook.createCreate a new webhook endpoint.
nefia.webhook.updateUpdate an existing webhook configuration.
nefia.webhook.deleteDelete a webhook endpoint.

Composite Tools

ToolDescription
nefia.runOne-shot command execution without session (simpler alternative to session.open + exec)
nefia.investigateComprehensive host investigation (facts, processes, services, ports, disk, network)
nefia.file.deployDeploy a file with verification (push + checksum verify)
nefia.service.deployAtomic service deployment with health check and rollback
nefia.config.applyAtomic config update with validation and service reload
nefia.system.baselineCapture system state snapshot for drift detection
nefia.system.healthRun comprehensive health checks (VPN, services, disk, load, ports, memory)

Discovery & Policy

ToolDescription
nefia.tools.schemaGet the full JSON schema for any tool (progressive discovery)
nefia.policy.capabilitiesRead policy capabilities for a host
nefia.approval.checkCheck if a tool call would require approval

Compact Tool Discovery

By default, tools/list returns tool schemas in compact mode, reducing token usage by ~90%. Compact responses include only the tool name, description, category, typical_sequence, and hints (destructive, read_only, idempotent).

To retrieve full JSON Schema definitions for specific tools, use nefia.tools.schema:

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

To request full schemas for all tools at once, pass _meta_full: true in tools/list:

json
{
  "method": "tools/list",
  "params": { "_meta_full": true }
}

Cluster Management

ToolDescription
nefia.cluster.initInitialize a new Raft cluster on this node.
nefia.cluster.statusShow cluster status (leader, term, commit index).
nefia.cluster.membersList all cluster members and their state.
nefia.cluster.add_peerAdd a new peer node to the cluster.
nefia.cluster.remove_peerRemove a peer node from the cluster.

SSH Certificate Authority

ToolDescription
nefia.sshca.initInitialize the SSH CA with Ed25519 key pair.
nefia.sshca.sign_userIssue a short-lived user certificate. Requires mandatory human approval — the approval workflow must be enabled and this tool cannot bypass it.
nefia.sshca.sign_hostIssue a host certificate for a target SSH server.
nefia.sshca.statusCheck SSH CA status and certificate details.
nefia.sshca.trustRegister CA in operator's known_hosts.
nefia.sshca.server_snippetGenerate SSH server configuration snippet for a host.

Mutual TLS

ToolDescription
nefia.mtls.initInitialize the mTLS CA and server certificate.
nefia.mtls.issue_clientIssue a client certificate with configurable TTL.
nefia.mtls.statusCheck mTLS CA and certificate status.
nefia.mtls.revokeRevoke an issued client certificate.

Team Management

ToolDescription
nefia.team.currentShow the currently active team.
nefia.team.listList teams you belong to.
nefia.team.useSwitch to a different team context.
nefia.team.createCreate a new team workspace.
nefia.team.inviteGenerate a team invite code.
nefia.team.joinJoin a team using an invite code.
nefia.team.membersList members of the current team.
nefia.team.leaveLeave the current team.
nefia.team.roleChange a member's role (owner, admin, member).

Profile Management

ToolDescription
nefia.profile.listList all operator profiles.
nefia.profile.showShow details of a specific profile.
nefia.profile.createCreate a new profile.
nefia.profile.deleteDelete a profile.
nefia.profile.set_defaultSet the default profile.

Rate Limiting

Configure rate limits for MCP operations in your nefia.yaml:

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

When the rate limit is exceeded, the MCP server returns a JSON-RPC error with data.retry_after_ms. Well-behaved AI agents should wait for that interval before retrying.

Approval Workflow

The MCP server supports an approval workflow that pauses matching operations until a human approves or denies them. The two approval tools (nefia.approval.list and nefia.approval.respond) are always advertised to AI agents so they can discover the workflow, but they only become functional when the approval workflow is enabled in the configuration.

When mcp.approval.enabled: true, the MCP server:

  • Evaluates each tool invocation against the configured approval rules
  • Pauses matching operations and sends a notifications/message with type: "approval_required"
  • Blocks until a human responds or the configured timeout elapses (default: 30 seconds)
  • Applies default_action (default: "deny") when the timeout expires

Approval Tools

ToolDescription
nefia.approval.listList all pending approval requests
nefia.approval.respondRespond to pending approval request(s) — supports single (request_id) and bulk (request_ids). Blocked in MCP; use CLI or TUI.

Rule Matching

Rule matching uses the first-match-wins strategy:

  • tools uses exact tool-name matching
  • commands and paths use prefix matching
  • hosts uses exact matching
  • require_approval: false acts as an explicit exemption rule

Policy Enforcement

The MCP server enforces the same policy rules as the CLI. The policy engine is configured under policy in nefia.yaml. There is no way for an AI agent to bypass a deny rule or access a restricted path.

The policy engine has three modes:

  • off -- No policy evaluation; all operations are allowed.
  • warn -- Violations are logged as warnings but operations proceed.
  • enforce (default) -- Violations are blocked and operations are rejected.

Policy evaluation uses deny_commands, allow_commands, deny_paths, and allowed_roots. Deny rules are checked first. If an allow list is defined, the operation must match at least one allow pattern:

yaml
policy:
  mode: enforce
  deny_commands:
    - "^rm -rf /$"
    - "^mkfs\\."
  allow_commands:
    - "^systemctl (status|reload)"
    - "^cat "
    - "^ls "
  deny_paths:
    - "^/etc/shadow$"
    - "^/etc/passwd$"
  allowed_roots:
    - "^/home/"
    - "^/var/www/"

For role-based access control, define named roles with their own rule sets:

yaml
policy:
  mode: enforce
  roles:
    - name: developer
      hosts: ["^dev-"]
      allow_commands: ["^git ", "^make "]
      deny_paths: ["^/etc/"]
    - name: operator
      hosts: [".*"]
      deny_commands: ["^rm -rf /"]

roles[].hosts is matched against host IDs, and the active role comes from the target host's role field in nefia.yaml. The current implementation does not derive roles from the operator identity.

Error Handling

The MCP server classifies errors from tool execution into two categories:

  • Domain errors -- The tool invocation was accepted but the operation failed (e.g., file not found, permission denied, policy blocked). These are returned as successful JSON-RPC responses with isError: true in the content. AI agents can inspect these errors and self-correct.
  • Protocol errors -- The request itself is malformed (e.g., unknown tool, missing parameters). These are returned as standard JSON-RPC error responses.

All error classification is performed via sentinel error matching with errors.Is(). No string-comparison fallback is used. Each domain error includes error_code, hint, and suggested_actions to help AI agents determine the next course of action.

json
{
  "content": [
    {
      "type": "text",
      "text": "{\"error\":\"file not found: config.yaml\",\"code\":-32006,\"details\":{\"error_code\":\"SFTP_FAILED\",\"hint\":\"file not found: config.yaml\",\"suggested_actions\":[\"Verify the remote path exists\",\"Check file permissions on the remote host\"]}}"
    }
  ],
  "isError": true
}

Each error response includes additional context fields to help AI agents self-recover:

  • transient -- Whether the error is temporary (safe to retry) or permanent.
  • retry_after_ms -- Suggested wait time before retry (present for transient errors like rate limiting or VPN timeouts).
  • recovery_tool -- The MCP tool to call for recovery. For example, HOST_NOT_FOUND suggests nefia.hosts.list, and SFTP_FAILED suggests nefia.vpn.diagnose.
  • host_id, path, command -- Context fields identifying the host, file path, or command involved in the error.

For a complete list of error codes, see the MCP Protocol Reference.

Audit Logging

Every MCP tool invocation is recorded in the append-only audit log. Each entry includes the tool name, parameters, target host, result status, and timestamp. This provides a complete trail of all AI agent activity for compliance and debugging.

Example: Claude Managing a Web Server

Here is a practical example of an AI agent using Nefia MCP to diagnose and fix a web server issue:

1

The AI agent discovers available hosts:

json
{ "tool": "nefia.hosts.list" }
2

It gathers system facts from the target:

json
{ "tool": "nefia.facts", "arguments": { "target": "host:prod-web-1" } }
3

It opens a session to inspect configuration files:

json
{ "tool": "nefia.session.open", "arguments": { "host_id": "prod-web-1", "root": "/etc/nginx" } }
4

It reads the Nginx configuration and identifies the issue:

json
{ "tool": "nefia.fs.read", "arguments": { "session_id": "a1b2c3d4", "path": "nginx.conf" } }
5

It applies a patch to fix the configuration:

json
{ "tool": "nefia.fs.patch", "arguments": { "session_id": "a1b2c3d4", "path": "nginx.conf", "unified_diff": "--- a/nginx.conf\n+++ b/nginx.conf\n@@ ... @@\n ..." } }
6

It reloads Nginx (triggers approval if configured):

json
{ "tool": "nefia.exec", "arguments": { "target": "host:prod-web-1", "command": "nginx -t && systemctl reload nginx" } }

Every step in this workflow is logged in the audit trail, policy-checked, and sandboxed to the session root.

Rate Limiting Best Practices

The MCP server enforces rate limits to protect both the operator host and remote targets. Understanding and working within these limits is essential for reliable AI agent operation.

Default Limits

ParameterDefaultDescription
Rate100 req/sMaximum sustained request rate.
Burst200Maximum burst size (allows short spikes above the rate).
Concurrent Dispatch50Maximum concurrent tool executions.

These defaults apply when mcp.rate_limit is not configured in nefia.yaml. Operators can customize them:

yaml
mcp:
  rate_limit:
    rate: 1.0    # more conservative: 1 request per second
    burst: 10

Handling 429 (Rate Limited) Responses

When the rate limit is exceeded, the server returns error code -32029 (RateLimited) with a retry_after_ms field:

json
{
  "error": {
    "code": -32029,
    "message": "rate limit exceeded",
    "data": { "retry_after_ms": 1500 }
  }
}

AI agents should wait for the specified retry_after_ms duration before retrying. Do not retry immediately -- this will only prolong the rate limiting.

Reducing Request Count

  • Use batch parameters. Instead of calling nefia.exec per host, use target: "group:production" to execute on all hosts in one call.
  • Use nefia.facts instead of multiple nefia.exec calls. A single nefia.facts call gathers OS, disk, memory, CPU, uptime, and network information in one SSH round-trip per host.
  • Use nefia.status for quick checks. One call returns VPN status, host counts, queue depth, and session count -- avoiding multiple separate queries.
  • Use sessions for multi-step operations. Opening a session avoids re-specifying host_id on every call.

Exec Extensions

The nefia.exec tool supports additional parameters for production-grade orchestration:

  • env -- Inject environment variables into remote commands. Secret provider references (${provider:path}) are automatically resolved.
  • dry_run -- Preview target resolution and policy checks without executing. Returns which hosts would be targeted and whether the operation is allowed.
  • batch_size / batch_wait -- Rolling execution across large fleets. Execute on N hosts at a time with configurable pause between batches.
  • subset -- Execute on a random subset of N hosts for canary testing.
  • rerun / last_job_id -- Re-execute on hosts from a previous job. Target only failed or successful hosts.
  • fail_fast -- Stop execution immediately when the first host fails. Remaining hosts are skipped.
  • min_success_rate -- Minimum success rate (0.0–1.0) required to continue. If the rate drops below this threshold, remaining hosts are skipped.
  • stdin -- Standard input to pipe to the command.
  • working_directory -- Working directory for command execution (relative to session or host root).

For full tool reference and schemas, see the MCP Protocol Reference.

MCP Protocol Reference

Technical reference for domain error codes, tool schemas, and protocol details.

CLI Reference

Full reference for all Nefia CLI commands including mcp serve.

Sessions

Learn how sessions provide sandboxed, persistent file operation contexts.

Host Management

Organize target PCs with hosts, groups, and tag-based targeting.

Agent Patterns

Best practices for AI agents using Nefia MCP tools.