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:
nefia mcp serveThe 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:
-
Log in first. The MCP server requires authentication. Run
nefia loginin 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. -
Ensure
nefiais in your PATH. MCP clients spawn the server process directly without loading your shell profile (.zshrc,.bashrc, etc.). Ifnefiawas installed viago installor 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
nefiapath: runwhich nefiaon macOS/Linux, orwhere nefia/Get-Command nefia(PowerShell) on Windows. -
Windows: use the
cmd /cwrapper. On Windows, some MCP clients cannot execute.exefiles 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:
{
"mcpServers": {
"nefia": {
"command": "nefia",
"args": ["mcp", "serve"]
}
}
}Claude Code
Add Nefia as an MCP server in your project settings:
claude mcp add nefia -- nefia mcp serveCodex CLI (OpenAI)
Add the following to ~/.codex/config.toml:
[mcp_servers.nefia]
command = "nefia"
args = ["mcp", "serve"]OpenClaw
Add Nefia to your openclaw.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
| Tool | Description |
|---|---|
nefia.session.open | Open a sandboxed session on a host with a root directory |
nefia.session.close | Close an active session and release locks |
nefia.session.summary | Generate an AI-consumable summary of a session's activity |
nefia.session.list | List 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
| Tool | Description |
|---|---|
nefia.exec | Execute 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.sudo | Execute a command with sudo privilege escalation (requires sudo.enabled: true and NOPASSWD in sudoers) |
nefia.cancel | Cancel a running exec or playbook job |
File Operations
| Tool | Description |
|---|---|
nefia.fs.read | Read a file from a remote host |
nefia.fs.write | Write content to a remote file |
nefia.fs.patch | Apply a unified diff patch to a remote file |
nefia.fs.list | List directory entries with sizes and permissions |
nefia.fs.stat | Get file metadata (size, permissions, modification time) |
nefia.fs.copy | Copy a file on a remote host |
nefia.fs.stream_read | Stream a large file download from remote to local |
nefia.fs.stream_write | Stream a large file upload from local to remote |
nefia.fs.stream_read_resumable | Resumable download — continues interrupted transfers from last checkpoint |
nefia.fs.stream_write_resumable | Resumable upload — continues interrupted transfers from last checkpoint |
nefia.fs.mkdir | Create a directory (and missing parents) on a remote host |
nefia.fs.remove | Remove a file or directory (supports recursive) |
nefia.fs.chmod | Change file permissions (numeric or symbolic modes, macOS/Linux only) |
nefia.fs.chown | Change file ownership (user or user:group, macOS/Linux only) |
nefia.fs.find | Search for files with filtering by name, type, size, and date |
nefia.fs.tail | Read last N lines of a file with optional grep filtering |
nefia.fs.move | Move or rename a file/directory on a remote host |
nefia.fs.grep | Search for a pattern in remote files (structured output with file paths and line numbers) |
nefia.fs.du | Get disk usage for a path on a remote host |
nefia.fs.symlink | Create a symbolic link on a remote host |
nefia.fs.readlink | Read the target of a symbolic link |
nefia.fs.archive.create | Create a tar.gz/zip archive on a remote host |
nefia.fs.archive.extract | Extract a tar.gz/zip archive on a remote host |
nefia.fs.diff | Compare two files on a remote host and return unified diff |
Multi-Host File Operations
| Tool | Description |
|---|---|
nefia.push | Push a file to multiple hosts with batch and subset support |
nefia.sync | Sync a local directory to multiple hosts. Only changed files are transferred. |
Host Inventory
| Tool | Description |
|---|---|
nefia.hosts.list | List all enrolled hosts with VPN status and tags |
nefia.hosts.show | Get detailed information about a specific host |
nefia.hosts.update | Update host metadata (tags or role) |
nefia.hosts.groups | List all host groups with member counts |
nefia.hosts.import | Import hosts from SSH config, Ansible inventory, CSV, or known_hosts. |
nefia.hosts.remove | Remove a host from the configuration. |
nefia.hosts.refresh | Refresh host metadata by reconnecting and gathering system facts. |
Playbooks
| Tool | Description |
|---|---|
nefia.playbook.run | Execute a multi-step playbook with dry-run support |
nefia.playbook.list | List all available playbooks |
nefia.playbook.show | Show full details of a playbook |
nefia.playbook.validate | Validate a playbook without executing |
System Information
| Tool | Description |
|---|---|
nefia.facts | Gather structured system facts (OS, disk, memory, CPU, uptime, network) |
nefia.sys.processes | List running processes with CPU/memory usage (sorted, filterable) |
nefia.sys.services | List system services with status (systemctl / launchctl / Get-Service) |
nefia.sys.ports | List network connections and listening ports (ss / lsof / Get-NetTCPConnection) |
nefia.sys.users | List user accounts with UID, groups, and home directory |
nefia.sys.logs | Query system logs with time range, priority, and pattern filtering |
nefia.sys.logs.search | Search logs with keywords, service, and severity filtering |
nefia.sys.service.control | Start, stop, restart, enable, or disable a system service |
nefia.sys.network | Get network interface information |
nefia.sys.disk | Get disk usage and partition information |
nefia.sys.env | Get environment variables (sensitive values masked) |
nefia.sys.kill | Send a signal to a process on a remote host |
nefia.sys.group.list | List system groups |
Package Management
| Tool | Description |
|---|---|
nefia.sys.package.list | List installed packages on a remote host |
nefia.sys.package.install | Install a package on a remote host |
nefia.sys.package.remove | Remove a package from a remote host |
User Management
| Tool | Description |
|---|---|
nefia.sys.user.create | Create a user account on a remote host |
nefia.sys.user.modify | Modify a user account on a remote host |
nefia.sys.user.delete | Delete a user account from a remote host |
Cron Management
| Tool | Description |
|---|---|
nefia.sys.cron.list | List cron jobs on a remote host |
nefia.sys.cron.create | Create a cron job on a remote host |
nefia.sys.cron.delete | Delete a cron job from a remote host |
Service Management
| Tool | Description |
|---|---|
nefia.sys.service.enable | Enable a service to start on boot |
nefia.sys.service.disable | Disable a service from starting on boot |
nefia.sys.service.reload | Reload a service configuration |
nefia.sys.service.logs | Get service logs |
nefia.sys.service.show | Show detailed service status and configuration |
Network Diagnostics
| Tool | Description |
|---|---|
nefia.net.ping | Ping a target from a remote host |
nefia.net.traceroute | Trace route to a target from a remote host |
nefia.net.dns | DNS lookup with record type support (A/AAAA/CNAME/MX/NS/TXT/SRV/PTR/SOA) |
nefia.net.connections | List network connections with state filtering |
nefia.net.listen | List listening ports on a remote host |
Firewall Management
| Tool | Description |
|---|---|
nefia.net.firewall.list | List firewall rules |
nefia.net.firewall.add | Add a firewall rule |
nefia.net.firewall.remove | Remove a firewall rule |
nefia.net.firewall.status | Check firewall status |
System Updates
| Tool | Description |
|---|---|
nefia.sys.update.check | Check for available system updates |
nefia.sys.update.apply | Apply system updates |
nefia.sys.hostname | Get or set system hostname |
nefia.sys.time | Get time info, set timezone, or trigger NTP sync |
nefia.sys.sysctl.list | List sysctl parameters |
nefia.sys.sysctl.set | Set a sysctl parameter |
Mount Management
| Tool | Description |
|---|---|
nefia.sys.mount.list | List mount points |
nefia.sys.mount | Mount a device |
nefia.sys.umount | Unmount a device |
Container Management
| Tool | Description |
|---|---|
nefia.container.list | List containers (Docker/Podman) |
nefia.container.logs | Get container logs |
nefia.container.start | Start a container |
nefia.container.stop | Stop a container |
nefia.container.restart | Restart a container |
nefia.container.inspect | Inspect container details |
VPN & Connectivity
| Tool | Description |
|---|---|
nefia.vpn.status | Get VPN tunnel status and peer connectivity information |
nefia.vpn.diagnose | Run VPN diagnostics with issues and recommendations |
nefia.vpn.ping | Test VPN connectivity to a specific host |
nefia.vpn.revoke | Revoke VPN access for a host or all hosts. Requires re-enrollment via nefia vpn invite. |
nefia.vpn.key.rotate | Rotate VPN keys for a host |
nefia.netcheck | Run network diagnostics (NAT type detection, STUN/DERP/TURN reachability). Alternative to nefia.vpn.diagnose for network-level analysis. |
nefia.conn.health | Check connection health for a specific host or all hosts |
nefia.vpn.config | Show current VPN configuration. |
nefia.vpn.enroll_status | Check enrollment status for a host. |
nefia.vpn.invite | Generate a VPN enrollment invitation. |
nefia.vpn.invite_list | List active VPN invitations. |
nefia.vpn.invite_revoke | Revoke a pending VPN invitation. |
nefia.vpn.peer.stats | Show per-peer VPN traffic statistics. |
Policy
| Tool | Description |
|---|---|
nefia.policy.test | Pre-check if a command, path, or operation would be allowed by the policy engine |
nefia.policy.test_batch | Test multiple commands/paths/operations against policy in a single call (up to 50 tests) |
JIT Access
| Tool | Description |
|---|---|
nefia.jit.request | Request temporary elevated access |
nefia.jit.list | List JIT access requests and active grants |
Audit
| Tool | Description |
|---|---|
nefia.audit.search | Search audit logs with filters (date, host, operation, job ID) |
nefia.audit.export | Export audit logs in JSONL or CSV format |
nefia.audit.verify | Verify audit log hash chain integrity. |
Agent Management
| Tool | Description |
|---|---|
nefia.agent.status | Get nefia-agent status on a target host |
nefia.agent.upgrade | Upgrade nefia-agent to a specified version |
nefia.agent.pin | Pin a host's agent to a specific version, preventing auto-updates. |
Schedule
| Tool | Description |
|---|---|
nefia.schedule.list | List all scheduled playbook executions |
nefia.schedule.show | Show detailed information about a specific schedule |
nefia.schedule.create | Create a new scheduled playbook execution |
nefia.schedule.update | Partially update a schedule definition |
nefia.schedule.delete | Delete a scheduled playbook execution |
nefia.schedule.enable | Enable a disabled schedule |
nefia.schedule.disable | Disable a schedule without deleting it |
nefia.schedule.history | Show execution history for a schedule |
nefia.schedule.trigger | Manually trigger a schedule for immediate execution. |
Queue Management
| Tool | Description |
|---|---|
nefia.queue.list | List queued offline commands |
nefia.queue.show | Show details of a single queue entry |
nefia.queue.cancel | Cancel a pending queue entry |
nefia.queue.retry | Retry a failed, expired, or cancelled queue entry |
Diagnostics
| Tool | Description |
|---|---|
nefia.status | System-wide status overview (VPN, hosts, queue, sessions, config) |
nefia.doctor | Run comprehensive health checks with pass/warn/fail status |
nefia.explain | Get detailed error remediation guidance for AI agents |
nefia.validate | Validate connectivity to target hosts. |
nefia.recording.list | List session recordings |
nefia.recording.show | Show metadata for a specific session recording |
nefia.recording.delete | Delete a session recording |
nefia.recording.export | Export a recording in a specified format. |
Reactor
| Tool | Description |
|---|---|
nefia.reactor.status | Show reactor engine status including rules and hit counts |
nefia.reactor.events | List recent events processed by the reactor engine |
nefia.reactor.rule.create | Create a new reactor rule with event pattern and action. |
nefia.reactor.rule.delete | Delete a reactor rule by ID. |
nefia.reactor.rule.enable | Enable or disable a reactor rule. |
Power Management
| Tool | Description |
|---|---|
nefia.power.wake | Send Wake-on-LAN magic packet to an offline host |
nefia.power.reboot | Reboot a remote host |
nefia.power.shutdown | Shut down a remote host |
Secrets & Compliance
| Tool | Description |
|---|---|
nefia.secrets.list | List configured secret providers (no values exposed) |
nefia.secrets.test | Test connectivity to a secret provider |
nefia.compliance.report | Generate a compliance report (SOC 2, ISO 27001, HIPAA) |
Configuration & Backups
| Tool | Description |
|---|---|
nefia.config.show | Show current configuration with sensitive fields masked |
nefia.backup.list | List available configuration backups |
nefia.backup.create | Create a configuration backup (nefia.yaml + state) |
nefia.backup.verify | Verify the integrity of a backup archive. |
nefia.backup.restore | Restore configuration and state from a backup archive. |
Device Security
| Tool | Description |
|---|---|
nefia.device_lock.status | Check Ed25519 device-lock status for a host |
nefia.device_lock.verify | Verify device-lock with cryptographic challenge |
nefia.device_lock.init | Initialize the device-lock authority with Ed25519 key pair. |
nefia.device_lock.sign | Sign a host's WireGuard public key, marking it as trusted. |
nefia.device_lock.revoke | Revoke trust for a host's public key. |
nefia.posture.check | Evaluate device posture compliance (firewall, encryption, OS version) |
Webhooks
| Tool | Description |
|---|---|
nefia.webhook.list | List configured webhooks with masked URLs |
nefia.webhook.test | Send a test event to verify webhook delivery |
nefia.webhook.create | Create a new webhook endpoint. |
nefia.webhook.update | Update an existing webhook configuration. |
nefia.webhook.delete | Delete a webhook endpoint. |
Composite Tools
| Tool | Description |
|---|---|
nefia.run | One-shot command execution without session (simpler alternative to session.open + exec) |
nefia.investigate | Comprehensive host investigation (facts, processes, services, ports, disk, network) |
nefia.file.deploy | Deploy a file with verification (push + checksum verify) |
nefia.service.deploy | Atomic service deployment with health check and rollback |
nefia.config.apply | Atomic config update with validation and service reload |
nefia.system.baseline | Capture system state snapshot for drift detection |
nefia.system.health | Run comprehensive health checks (VPN, services, disk, load, ports, memory) |
Discovery & Policy
| Tool | Description |
|---|---|
nefia.tools.schema | Get the full JSON schema for any tool (progressive discovery) |
nefia.policy.capabilities | Read policy capabilities for a host |
nefia.approval.check | Check 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:
{
"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:
{
"method": "tools/list",
"params": { "_meta_full": true }
}Cluster Management
| Tool | Description |
|---|---|
nefia.cluster.init | Initialize a new Raft cluster on this node. |
nefia.cluster.status | Show cluster status (leader, term, commit index). |
nefia.cluster.members | List all cluster members and their state. |
nefia.cluster.add_peer | Add a new peer node to the cluster. |
nefia.cluster.remove_peer | Remove a peer node from the cluster. |
SSH Certificate Authority
| Tool | Description |
|---|---|
nefia.sshca.init | Initialize the SSH CA with Ed25519 key pair. |
nefia.sshca.sign_user | Issue a short-lived user certificate. Requires mandatory human approval — the approval workflow must be enabled and this tool cannot bypass it. |
nefia.sshca.sign_host | Issue a host certificate for a target SSH server. |
nefia.sshca.status | Check SSH CA status and certificate details. |
nefia.sshca.trust | Register CA in operator's known_hosts. |
nefia.sshca.server_snippet | Generate SSH server configuration snippet for a host. |
Mutual TLS
| Tool | Description |
|---|---|
nefia.mtls.init | Initialize the mTLS CA and server certificate. |
nefia.mtls.issue_client | Issue a client certificate with configurable TTL. |
nefia.mtls.status | Check mTLS CA and certificate status. |
nefia.mtls.revoke | Revoke an issued client certificate. |
Team Management
| Tool | Description |
|---|---|
nefia.team.current | Show the currently active team. |
nefia.team.list | List teams you belong to. |
nefia.team.use | Switch to a different team context. |
nefia.team.create | Create a new team workspace. |
nefia.team.invite | Generate a team invite code. |
nefia.team.join | Join a team using an invite code. |
nefia.team.members | List members of the current team. |
nefia.team.leave | Leave the current team. |
nefia.team.role | Change a member's role (owner, admin, member). |
Profile Management
| Tool | Description |
|---|---|
nefia.profile.list | List all operator profiles. |
nefia.profile.show | Show details of a specific profile. |
nefia.profile.create | Create a new profile. |
nefia.profile.delete | Delete a profile. |
nefia.profile.set_default | Set the default profile. |
Rate Limiting
Configure rate limits for MCP operations in your nefia.yaml:
mcp:
rate_limit:
rate: 1.0 # requests per second
burst: 10 # max burst sizeWhen 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/messagewithtype: "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
| Tool | Description |
|---|---|
nefia.approval.list | List all pending approval requests |
nefia.approval.respond | Respond 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:
toolsuses exact tool-name matchingcommandsandpathsuse prefix matchinghostsuses exact matchingrequire_approval: falseacts 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:
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:
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: truein 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.
{
"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_FOUNDsuggestsnefia.hosts.list, andSFTP_FAILEDsuggestsnefia.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:
The AI agent discovers available hosts:
{ "tool": "nefia.hosts.list" }It gathers system facts from the target:
{ "tool": "nefia.facts", "arguments": { "target": "host:prod-web-1" } }It opens a session to inspect configuration files:
{ "tool": "nefia.session.open", "arguments": { "host_id": "prod-web-1", "root": "/etc/nginx" } }It reads the Nginx configuration and identifies the issue:
{ "tool": "nefia.fs.read", "arguments": { "session_id": "a1b2c3d4", "path": "nginx.conf" } }It applies a patch to fix the configuration:
{ "tool": "nefia.fs.patch", "arguments": { "session_id": "a1b2c3d4", "path": "nginx.conf", "unified_diff": "--- a/nginx.conf\n+++ b/nginx.conf\n@@ ... @@\n ..." } }It reloads Nginx (triggers approval if configured):
{ "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
| Parameter | Default | Description |
|---|---|---|
| Rate | 100 req/s | Maximum sustained request rate. |
| Burst | 200 | Maximum burst size (allows short spikes above the rate). |
| Concurrent Dispatch | 50 | Maximum concurrent tool executions. |
These defaults apply when mcp.rate_limit is not configured in nefia.yaml. Operators can customize them:
mcp:
rate_limit:
rate: 1.0 # more conservative: 1 request per second
burst: 10Handling 429 (Rate Limited) Responses
When the rate limit is exceeded, the server returns error code -32029 (RateLimited) with a retry_after_ms field:
{
"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.execper host, usetarget: "group:production"to execute on all hosts in one call. - Use
nefia.factsinstead of multiplenefia.execcalls. A singlenefia.factscall gathers OS, disk, memory, CPU, uptime, and network information in one SSH round-trip per host. - Use
nefia.statusfor 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.
Related
Technical reference for domain error codes, tool schemas, and protocol details.
Full reference for all Nefia CLI commands including mcp serve.
Learn how sessions provide sandboxed, persistent file operation contexts.
Organize target PCs with hosts, groups, and tag-based targeting.
Best practices for AI agents using Nefia MCP tools.