@aidalinfo/unifi-mcp
v0.7.0
Published
UniFi (Ubiquiti) MCP server, read-only by default — Site Manager + Network Integration API, Prometheus exporter and Prometheus/Loki history, unofficial internal API and UNAS health over SSH
Maintainers
Readme
@aidalinfo/unifi-mcp
MCP server for UniFi (Ubiquiti), with two modes like @aidalinfo/proxmox-mcp:
readonly(default): only read tools are exposed.full: read tools plus a small set of operational write tools (restart a device, PoE power-cycle a port, guest access, hotspot vouchers).
In readonly mode the write tools are never registered, so the model cannot call them.
There is deliberately no configuration CRUD (networks, Wi-Fi, firewall). Add it later if
needed, behind full.
Two APIs, two ways to reach the Network API
| API | What | Auth |
|---|---|---|
| Site Manager (api.ui.com) | Account-wide: every console/host, site, device, ISP metrics | Key from unifi.ui.com → API |
| Network Integration API | Per-site detail: devices, clients, networks/VLANs, Wi-Fi, firewall, VPN, vouchers | Same cloud key (through the cloud connector), or a local key |
The Network API is reached in one of two ways:
- Cloud connector (default):
api.ui.com/v1/connector/consoles/{consoleId}/proxy/network/integration/.... It needs nothing on the LAN. It requires console firmware ≥ 5.0.3 and a key with the Network scope. - Local: when
UNIFI_LOCAL_URL+UNIFI_LOCAL_API_KEYare set, calls go straight tohttps://<console>/proxy/network/integration/.... Local wins over cloud when both are configured, unless a tool is given an explicitconsoleId. That call then goes through the cloud connector.UNIFI_TLS_INSECURE=truedisables TLS verification for the local console only: it is scoped to that request agent, never toapi.ui.com.
Site Manager tools are only registered when UNIFI_API_KEY is set.
Tools
Start here: unifi_capabilities lists the configured APIs, the consoles and their apps (Network,
Drive…), checks the Network API of every console (version, or why it cannot be reached), then probes every official route on a site (limit=1):
each family is marked ✓ available, ✗ not exposed (404) or ? not verified (other error, console
unreachable). It then lists what the official APIs do not expose.
The same limits are sent to the client as MCP server instructions.
Site report: unifi_site_report reviews one site in a single call: anomalies first (offline or unhealthy
devices, pending firmware, devices missing from the account view, internet packet loss ≥ 2 % or uptime < 99 %
over 24h), then device health, client counts and the 24h internet line. The internet and account-view parts need
the cloud key and are skipped on a local-only console.
Site Manager (cloud key): unifi_hosts, unifi_host_info, unifi_account_sites,
unifi_account_devices, unifi_firmware_status (devices with an update, devices not online, unknown ones, grouped by console),
unifi_sdwan (SD-WAN hubs/spokes, WAN state, tunnel status), unifi_isp_metrics (one line per site:
ISP, avg/max latency, max loss, min uptime, latest throughput; duration or a bounded from/to window;
optional siteId / hostId filter; the raw series is ~1 MB, so use unifi_raw_get for it).
Network, read (both modes): unifi_network_info, unifi_sites, unifi_devices,
unifi_device_info (detail + latest stats), unifi_pending_devices, unifi_clients,
unifi_client_info, unifi_networks, unifi_wifi, unifi_wans, unifi_firewall_zones,
unifi_firewall_policies, unifi_acl_rules, unifi_traffic_lists (address/port groups),
unifi_dns_policies, unifi_radius_profiles, unifi_device_tags, unifi_vpn_servers,
unifi_vpn_site_to_site, unifi_vpn_sessions (active remote-user VPN and Teleport clients: assigned IP,
connected since, duration), unifi_vouchers, unifi_raw_get (GET only, api: network | site-manager).
Network, diagnostics: unifi_topology (gateway → switches → APs from uplinks, clients per device),
unifi_switch_ports (state, speed, PoE, LAG), unifi_switching (LAGs, stacks, MC-LAG),
unifi_ap_radios (channel, width, standard, TX retries), unifi_device_health (CPU, memory, uptime,
heartbeat, firmware; flags problems first).
Write (full only): unifi_device_restart, unifi_port_power_cycle, unifi_guest_access,
unifi_voucher_create, unifi_voucher_delete.
Account view cross-check. The Site Manager account view misses devices (offline ones in particular) and keeps
a stale upToDate for devices that are offline. unifi_account_devices and unifi_firmware_status therefore also
read the device list of every site of every console through the Network API (networkCheck, default true;
one site list plus one device list per site), match devices by MAC and:
- list the devices the account view misses, per console and site;
- never count a device that is not online as up to date: it is flagged « firmware not confirmed », with the newest version seen on the same model when it is behind;
- count an update the Network API reports even when Site Manager says
upToDate; - list the consoles whose Network API could not be read (key without connector rights, console offline…).
networkCheck: false keeps the Site Manager view only, and says so.
Every Network tool takes two optional parameters:
consoleId: cloud mode only. It defaults toUNIFI_CONSOLE_ID, or to the only console on the account.site: a site id or name. It defaults to the only site.
When there are several consoles or sites, the error message lists them. List tools page through
offset/limit (200 per page, capped at 2000 items) and accept a UniFi filter expression,
e.g. state.eq('OFFLINE').
Coverage and limits
Checked route by route against the official specs: Network Integration API 10.3.58 → 10.6.106 (the 44 routes did not change) and Site Manager API v1.0.0.
| Asked for (issue #42) | Status | Where |
|---|---|---|
| Consoles, sites, devices, firmware, ISP metrics, SD-WAN | ✅ | Site Manager |
| Topology, device health (latest sample), switch ports, LAG, AP radios | ✅ partial | Network: no counters, VLAN per port, STP, LLDP, radio utilisation or TX power (see the internal API rows below) |
| Clients, networks/VLANs, Wi-Fi, WANs, firewall, ACL, address/port groups, DNS, RADIUS | ✅ | Network |
| VPN servers and site-to-site tunnels | ✅ list only | Network: name, type, enabled — no detail or tunnel status |
| Active VPN sessions (remote users, Teleport) | ✅ | Network: unifi_vpn_sessions, from the client list (type VPN / TELEPORT). Past sessions: event log |
| Events, alarms, IDS/IPS — filtered by category, severity, device or client, paged | ⚠ optional | internal API (unifi_events, unifi_alarms, unifi_ips_events), from Network 7 to 11; or Loki (unifi_events_search) |
| Admin audit log | ⚠ optional | internal API (unifi_audit_log) or Loki (unifi_admin_audit) |
| Device history: since when, how many times, availability, changes | ⚠ optional | Prometheus via the exporter (unifi_device_history, unifi_availability_report, unifi_changes) |
| ISP history beyond 30 days | ⚠ optional | Prometheus via the exporter (unifi_isp_history) |
| Time series (site, AP, client, gateway) | ⚠ optional | internal API (unifi_stats_history): stat/report up to Network 10, the statistics engine on Network 11 |
| Client history: connections, roaming, disconnections, signal, rates, traffic | ⚠ optional | internal API (unifi_client_history) |
| Radio utilisation, interference, TX power, clients per radio | ⚠ optional | internal API (unifi_radio_diagnostics) |
| Port counters, PoE, LLDP, temperatures, fans | ⚠ optional | internal API (unifi_port_diagnostics, unifi_offline_root_cause) |
| DHCP leases and IP conflicts, static and policy-based routes, port forwarding | ⚠ optional | internal API (unifi_dhcp_leases, unifi_routing) |
| Custom NAT rules, VLANs per port, DPI per VLAN or over a chosen period | ❌ | not read yet: their internal routes are not confirmed |
| VPN state and active remote users, DPI traffic | ⚠ optional | internal API (unifi_vpn_status, unifi_dpi_traffic) |
| Per-tunnel VPN state: IPsec SAs, VPN client connections, WireGuard peers | ⚠ optional | internal API (unifi_vpn_tunnels); the last handshake is shown only when the console reports it |
| Configuration backups (metadata: date, size, version) | ⚠ optional | internal API (unifi_config_backups); backups are never created, deleted or downloaded |
| UniFi Drive / UNAS: disks, SMART, RAID, volumes | ✅ over SSH | no official API: unas_* tools, closed command list (see below) |
| UniFi Drive / UNAS: shares, quotas, users, backup jobs | ❌ | only in the undocumented Drive API (/proxy/drive/api/…, local session) |
⚠ optional rows need one of the read-only sources below. Each source's tools are registered only when it is
configured, and unifi_capabilities says which sources are on.
Beyond the official APIs (all read-only)
History and events: Prometheus + Loki (issue #73)
The MCP keeps no history of its own. It reuses the observability platform:
UniFi Network ──► unifi-mcp-exporter ──► Prometheus ─┐
UNAS (SSH RO) ──► unifi-mcp-exporter ──► Prometheus ─┼──► unifi-mcp (synthesis and diagnosis)
UniFi syslog ───► Alloy / Promtail ────► Loki ───────┘- Prometheus holds the metrics and time series. They are filled by
unifi-mcp-exporter. - Loki holds the syslog: events, IDS/IPS, admin audit. It is fed by the consoles' Activity Logging / SIEM setting, through Alloy or Promtail.
- Grafana / Alertmanager handle dashboards and alerts.
- The MCP only reads Prometheus and Loki, and turns their data into answers.
Exporter (unifi-mcp-exporter)
The exporter is a separate process, shipped as an immutable image (Dockerfile) with a
recommended scripts/docker-compose.exporter.yml.
- It reuses the MCP client and its read-only protections: official UniFi APIs, and the closed-list SSH session to the UNAS.
- It collects every
UNIFI_EXPORTER_INTERVALseconds (default 60, from 30 to 3600) and serves the last snapshot. A scrape is therefore instant and never multiplies API calls. - It stores nothing and needs no database.
- Endpoints:
/metrics(Prometheus text format, checked withpromtool check metrics);/healthz, which answers 503 once the snapshot is older than three intervals.
- It binds to
127.0.0.1:9877by default (UNIFI_EXPORTER_BIND,UNIFI_EXPORTER_PORT).
A failed source never fakes an outage. A console, site or UNAS that cannot be read gets
unifi_exporter_source_up{…} 0, and its device series are simply absent. Absent means unknown, never "device
down". The MCP tools then report the gap as UNKNOWN (no data).
| Metric | Labels | Meaning |
|---|---|---|
| unifi_exporter_source_up | source (network, isp, unas), console, site / nas, part | 1 = read, 0 = failed |
| unifi_exporter_last_success_timestamp_seconds | source | last collection that read data (STALE detection) |
| unifi_exporter_collect_duration_seconds, unifi_exporter_collect_errors | source | collection cost and partial failures |
| unifi_exporter_series, unifi_exporter_series_dropped, unifi_exporter_build_info | — / version | cardinality guard (20 000 series max) |
| unifi_device_info | console, site, device_id, name, model, mac, firmware | identity (value 1) |
| unifi_device_up | console, site, device_id | 1 ONLINE, 0 otherwise |
| unifi_device_uptime_seconds, unifi_device_cpu_ratio, unifi_device_memory_ratio, unifi_device_firmware_update_available | same | latest statistics |
| unifi_device_ports_up, unifi_device_ports_total | same | ports with link |
| unifi_port_up, unifi_port_speed_mbps, unifi_port_poe_up | + port | per port |
| unifi_radio_channel, unifi_radio_channel_width_mhz, unifi_radio_tx_retries_ratio | + band | per radio |
| unifi_site_devices, unifi_site_devices_online, unifi_site_clients | console, site | per site |
| unifi_isp_info (+ isp), unifi_isp_latency_avg_ms, unifi_isp_latency_max_ms, unifi_isp_packet_loss_ratio, unifi_isp_uptime_ratio, unifi_isp_download_kbps, unifi_isp_upload_kbps | console, site_id | last Site Manager 5-minute sample |
| unas_disk_info (+ model, rotational), unas_disk_size_bytes, unas_disk_smart_readable, unas_disk_smart_passed, unas_disk_temperature_celsius, unas_disk_power_on_seconds, unas_disk_reallocated_sectors, unas_disk_pending_sectors, unas_disk_offline_uncorrectable_sectors, unas_disk_nvme_* | nas, disk | SMART |
| unas_raid_active, unas_raid_degraded, unas_raid_members_expected, unas_raid_members_up, unas_raid_members_faulty, unas_raid_sync_progress_ratio (+ action, only while running) | nas, array, level | md arrays |
| unas_volume_size_bytes, unas_volume_used_bytes, unas_volume_avail_bytes, unas_volume_used_ratio | nas, volume, kind, fstype | filesystems |
| unas_alerts | nas, level | same rules as unas_health |
The labels are kept bounded and free of sensitive data:
- Bounded cardinality: at most one series per device, port, radio, disk, array or volume, and a hard cap of
20 000 series per collection (
unifi_exporter_series_droppedcounts the overflow). - Never in a label: IP addresses, serial numbers, client data, VPN users, file or share paths, keys or credentials.
- Data volumes are named
data0,data1… instead of their/volume/<uuid>path. - The NAS appears under a configured name (
UNIFI_UNAS_NAME), never under its address.
Example scrape configuration (the target address is yours):
scrape_configs:
- job_name: unifi-mcp-exporter
scrape_interval: 60s
static_configs:
- targets: ["unifi-mcp-exporter:9877"]MCP side: Prometheus for history, Loki for events
| Variable | Role |
|---|---|
| UNIFI_PROMETHEUS_URL | enables unifi_device_history, unifi_availability_report, unifi_changes, unifi_isp_history on Prometheus |
| UNIFI_PROMETHEUS_TOKEN or UNIFI_PROMETHEUS_BASIC_AUTH (user:password) | optional auth, never in the URL |
| UNIFI_PROMETHEUS_SCRAPE_INTERVAL | scrape interval of the exporter job (default 60 s): smallest step, outage counting |
| UNIFI_LOKI_URL | enables unifi_events_search, unifi_admin_audit on Loki |
| UNIFI_LOKI_TOKEN / UNIFI_LOKI_BASIC_AUTH, UNIFI_LOKI_TENANT | optional auth and X-Scope-OrgID |
| UNIFI_LOKI_SELECTOR | stream selector of the UniFi syslog (default {job="unifi-syslog"}); a single selector, no pipeline |
How the tools query the backends:
- Fixed queries. Every query follows a fixed template.
- In PromQL, tool input only becomes an exact, escaped label value, or a regex alternation of values that Prometheus itself returned. That is how a site name is resolved.
- In LogQL, it only becomes an escaped, case-insensitive literal line filter.
- Bounded windows.
- At most 400 days.
- At most 1000 points per series (the step grows with the window) and 500 series per answer.
- 15 s timeout, 8 MiB answers.
- On Loki, at most 5000 lines scanned per search, and the tool says when that cap is reached.
- Explicit failures. When a backend fails, the tool answers
Unavailable: Prometheus|Loki — …, never an empty list.- Each history answer ends with the time of the exporter's last collection, flagged STALE after 15 minutes.
- Each event answer says whether the Loki feed is alive (lines received over the last 24 h). So « no event » is never confused with « no feed ».
- Trusted timestamps. Loki lines are parsed with the CEF parser below, which masks secrets. The time shown is Loki's, not the one the sender wrote.
Expected Loki stream: one stream per console, label job="unifi-syslog" (or your selector) and, if available,
host. Example Alloy pipeline (adapt the addresses):
loki.source.syslog "unifi" {
listener {
address = "0.0.0.0:6514"
protocol = "tcp"
labels = { job = "unifi-syslog" }
}
relabel_rules = loki.relabel.unifi.rules
forward_to = [loki.write.default.receiver]
}
loki.relabel "unifi" {
forward_to = []
rule {
source_labels = ["__syslog_message_hostname"]
target_label = "host"
}
}Restrict the listener to the consoles' addresses (firewall / VPN), and prefer TCP or TLS to UDP: over UDP a sender address can be spoofed.
Deprecated: the PostgreSQL store (0.3.0 – 0.4.0)
The PostgreSQL store comes from earlier versions: the unifi-mcp-collect collector, the unifi-mcp-syslog
receiver, UNIFI_HISTORY_DB_URL, and scripts/history-setup.sql. It still works, for compatibility only, and
will be removed in a later version.
- Not needed with Prometheus + Loki. When
UNIFI_PROMETHEUS_URLandUNIFI_LOKI_URLare both set, the MCP ignoresUNIFI_HISTORY_DB_URL. - One backend per tool family. If only one of the two is set, Prometheus (or Loki) wins for its family. The PostgreSQL store serves only the other family.
- Do not run both. Never run the collector or the receiver alongside the exporter / Alloy: there would be two stores for the same data. Both binaries print a deprecation warning at start-up.
Migration:
- Deploy the exporter and the Alloy pipeline.
- Set
UNIFI_PROMETHEUS_URL/UNIFI_LOKI_URLon the MCP. - Stop
unifi-mcp-collect/unifi-mcp-syslog. - Keep the database read-only for as long as its history is useful, then drop it.
Internal console API — [unofficial] (UNIFI_ENABLE_INTERNAL_API=true)
The API behind the UniFi web UI (/proxy/network/api/s/{site}/…, /proxy/network/v2/api/site/{site}/…)
has what the official one lacks. It is undocumented, and its routes and fields can change between Network
versions. So these tools are marked [unofficial] and off by default, and a missing route answers
Unavailable: … (404).
| Tool | Route | Gives |
|---|---|---|
| unifi_events | v2 system-log/{class}, falls back to stat/event | event log over a period, by category (devices, clients, wan, vpn, admin, updates, threats, critical), severity, device, client or text |
| unifi_alarms | stat/alarm, falls back to v2 system-log/critical | active or archived alarms; on Network 11, the critical entries of the system log |
| unifi_ips_events | stat/ips/event, falls back to v2 system-log/threat-alert | IDS/IPS detections: signature, action, source → destination |
| unifi_audit_log | v2 system-log/admin-activity, falls back to stat/event | admin logins and configuration changes: who, when, what |
| unifi_stats_history | stat/report/{5minutes,hourly,daily}.{site,ap,user,gw}; on Network 11 v2 stats/source, v2 stats/recent/series | time series, with min / avg / max |
| unifi_client_history | stat/sta, v2 clients/history, the event log and the client series above | one client over a period: where it is now, connections / roaming / disconnections, signal, rates, retries, traffic |
| unifi_radio_diagnostics | stat/device | per radio: channel and width, TX power, channel utilisation (own traffic vs other networks and interference), clients, TX retries, satisfaction; APs sharing a channel |
| unifi_port_diagnostics | stat/device | per port: errors, drops, duplex, PoE watts and faults, STP, LLDP. Per device: temperatures, fan, PoE budget |
| unifi_dhcp_leases | stat/sta | IP per client, fixed IPs, IP conflicts |
| unifi_routing | rest/routing, v2 trafficroutes, stat/routing, rest/portforward | static, policy-based and active routes, port forwards |
| unifi_vpn_status | stat/health, rest/networkconf | VPN health, active remote users, each VPN (remote user, site-to-site, client): type, subnets, peer — PSK and keys never shown |
| unifi_vpn_tunnels | stat/ipsec-sa, v2 vpn/connections, v2 wireguard/users | per tunnel: IPsec security associations (state, peers, IKE, uptime, bytes), VPN client connections, WireGuard peers (state, IP, bytes, last handshake when reported). Each route is optional: a missing one is marked unavailable. raw: true adds the sanitised JSON, bounded |
| unifi_config_backups | cmd/backup (list-backups only) | Network auto-backups: file name, date, size, version; flags a missing or old last backup |
| unifi_dpi_traffic | stat/sitedpi, stat/stadpi | traffic per category or application, for the site or one client (needs DPI on the gateway) |
| unifi_offline_root_cause | stat/device, the event log (v2 system-log/device-alert or stat/event) | for an offline device: its uplink switch port (link, PoE, errors, LLDP) or mesh parent, whether the upstream device is down, its last events (or that the event log cannot be read), and the likely cause |
Network versions. UniFi Network 11 removed the classic routes stat/event (404), the alarm list (400) and
stat/ips/event (404), and answers stat/report with an empty list. The tools therefore read both generations:
- Events, alarms, IDS/IPS, audit: the system log (Network 8+) first, the classic route otherwise. Each answer
names its source (
system-log/all,stat/event…). On Network 11unifi_alarmsreturns the critical entries of the system log, which have no acknowledged state, and says so. - Time series:
v2 stats/sourcesays which statistics engine the console uses. On Network 11 the series come fromv2 stats/recent/series: the console picks the bucket size (5 minutes for a day, 1 hour for a week, 8 hours beyond) and its history starts at the upgrade to Network 11. A schema the console does not offer answers with the list of the ones it has (schemaargument). When the console's answer about its engine is not understood, the classic reports are read, and an empty one is thenUnavailablerather than « no data ». - Neither generation available:
Unavailable: …, as an error. - A refusal is not a missing route. A 403 or a 5xx fails the tool. So does a query the system log rejects (400) when there is no classic log to read instead. Only a 404 / 405, or the 400 Network 11 answers on the routes it removed, starts a fallback.
- Entries the tool cannot attribute.
unifi_offline_root_causeandunifi_client_historylook for the device or the client in the entry'sparameters. When the log has entries but none names one in a field the tool reads, the answer is « unknown », not « none ».
Filters, paging and raw detail.
unifi_events,unifi_alarms,unifi_ips_eventsandunifi_audit_logtakefrom/to(at most 400 days),limit(at most 500, default 100) andoffset.- One call reads at most the 1000 newest entries of the window, in at most 20 requests. When older ones were left out, the answer says how many the console holds and asks for a narrower window or category. The classic event log only goes back 30 days, and says so.
- A message never inlines a parameter named like a secret (
{PASSWORD},{…TOKEN}…): it shows[REDACTED]. raw: true(unifi_events,unifi_audit_log) adds the sanitised JSON of the entries shown: 20 entries and 20 000 characters at most.
The tools are read-only by construction:
- Closed list of routes. Every request is checked against it right before it is sent.
POSTgoes only to the query routes above, with a body built by the tool from validated numbers, MACs and enums. A system-log body may only hold the window, the page and the fixed filter lists of its class: thetext,device,clientandseverityfilters are applied by the MCP and never sent to the console.- There is no
restwrite. The onlycmd/…route iscmd/backup, and only with the exact body{"cmd":"list-backups"}: creating, deleting or exporting a backup is refused before the request is sent. A View Only account may be refused this route: the tool then answersUnavailable, not an empty list. unifi_vpn_tunnelsnever calls the routes that export a VPN configuration, and the central redaction also drops any string that embeds a key (PEM private key, WireGuardPrivateKey = …, OpenVPN inline secret).
- Dedicated local account with the View Only role and without MFA (
UNIFI_INTERNAL_USERNAME/UNIFI_INTERNAL_PASSWORD).- The session uses a cookie plus a CSRF token, and logs in again once on a 401.
- The password is only ever sent to
/api/auth/login.
- Pinned certificates. Consoles use self-signed certificates, so each one is pinned by its SHA-256
fingerprint.
- The handshake is checked before the login is written to the socket, so a console with another certificate receives nothing.
- Get the fingerprint with
echo | openssl s_client -connect <ip>:443 2>/dev/null | openssl x509 -noout -fingerprint -sha256.
UNIFI_ENABLE_INTERNAL_API=true
UNIFI_INTERNAL_CONSOLES=marly=https://192.168.0.1|C9:FD:4E:…:A5:71,clisson44=https://10.44.0.1|…
UNIFI_INTERNAL_USERNAME=mcp-readonly
UNIFI_INTERNAL_PASSWORD=…The consoles are reached on the LAN or through the site VPN (UDM IPsec / WireGuard), like the UNAS. We have not verified whether the cloud connector forwards these routes, so the tools never call them through it.
How gaps are reported:
- A list route that the console's Network version does not have answers
Unavailable: …as an error, never an empty list. - Firewall: zone-based model only.
unifi_firewall_zonesandunifi_firewall_policiescover only the zone-based firewall (UniFi Network 9+). A site never migrated from the legacy firewall makes the API answer 400 "Zone Based Firewall is not configured" even though legacy rules exist; the tools turn it intoUnavailable: this site uses the legacy firewall model, which is not exposed by the official UniFi API. It does not mean the site has no firewall rules. - Any other feature switched off on the site answers
Not configured: …. - Only a 404 is a capability gap: a 401, 403, timeout or 5xx fails the tool (e.g.
unifi_switching). - A site passed as a UUID that does not exist answers
Site … not found, notUnavailable. unifi_topologyflags devices whose detail could not be read (uplink unknown) instead of showing them as roots of a complete tree;unifi_switch_ports/unifi_ap_radiossay when the 100-device cap is hit.- Targeting a console without the Network app (e.g. a UNAS) says so explicitly.
- Every JSON a tool returns, and every object inlined in a text line (SD-WAN errors, traffic list
entries), goes through a central redaction: passwords, passphrases (the Wi-Fi
passphraseandpresharedKeysof a broadcast detail), secrets, PSK, private keys, API keys, tokens, invitation/enrollment codes and signed URL queries become[REDACTED]. Voucher codes stay visible inunifi_vouchers: they are what the tool is for.
UNAS over SSH (unas_*)
Ubiquiti publishes no API for UniFi Drive. When UNIFI_UNAS_HOST is set, four read-only tools read disk,
RAID and volume health over SSH:
| Tool | Commands run on the UNAS | Gives |
|---|---|---|
| unas_disks | lsblk -J -b -d …, then smartctl -a -j /dev/<disk> per disk | model, size, serial, SMART status, temperature, power-on hours, reallocated / pending / uncorrectable sectors (NVMe: media errors, wear) |
| unas_pools | cat /proc/mdstat, then mdadm --detail /dev/<md> per array | RAID level, members, faulty member, degraded state, rebuild / resync progress |
| unas_volumes | df -P -B1 -T | fill rate of each data filesystem (one line per device, no file listing) |
| unas_health | the three above | verdict and alerts first: SMART failed, degraded or inactive array, rebuild in progress, volume ≥ 85 % (critical ≥ 95 %), disk temperature (HDD ≥ 55 / 60 °C, SSD ≥ 70 / 80 °C) |
Safety, by construction:
- Closed command list. The tools take no argument. The only values spliced into a command are disk
and array names reported by the NAS itself, checked against
sd[a-z],nvme<n>n<n>andmd<n>before use; every command is checked again against the allowlist right before it is sent. There is no free command tool. - Pinned host key (
UNIFI_UNAS_HOST_KEY): a NAS answering with another key is refused before any authentication. - Key auth only: no password, no keyboard-interactive fallback; the key file must be
chmod 600. On Windows, Node cannot read NTFS ACLs, so this check is skipped with a warning: restrict the key to your account yourself,icacls <key> /inheritance:r /grant:r "%USERNAME%:R". - A rejected UNAS configuration only disables the
unas_*tools: the rest of the server starts, andunifi_capabilitiesgives the reason. - Per-command timeout 20 s, session 90 s, output capped at 512 KiB.
- A missing command answers
Unavailable: … on the UNAS, never an empty list.
Setup: enable SSH on the UNAS (UniFi OS → Settings → Control Plane → Console → Advanced → SSH), add a dedicated public key, then pin the host key:
ssh-keygen -t ed25519 -N "" -C unifi-mcp-readonly -f ~/.ssh/unas_mcp_readonly
ssh-keyscan -t ed25519 <unas-ip> | ssh-keygen -lf - # → SHA256:… for UNIFI_UNAS_HOST_KEYUniFi OS only offers root over SSH. So the key is also locked on the UNAS side with a forced command,
scripts/unas-readonly-wrapper.sh: it runs only the exact commands
above (same patterns as assertAllowed, multi-line input refused, globbing off) and refuses anything else,
so a stolen key gives no shell. Install it as /root/.ssh/unifi-mcp-readonly.sh (chmod 700) and add the
key to /root/.ssh/authorized_keys as:
command="/root/.ssh/unifi-mcp-readonly.sh",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty,no-user-rc ssh-ed25519 AAAA… unifi-mcp-readonlyThe MCP must reach the UNAS network: on the LAN, or through the site VPN as usual.
Key scopes
- Site Manager tools: any key from unifi.ui.com → API.
- Network tools through the cloud connector: a key allowed to use the connector. A Site Manager-only
key gets
403 insufficient permissions for this hoston every console; the error says so. - Network tools locally: a key from UniFi Network → Settings → Control Plane → Integrations, plus
UNIFI_LOCAL_URLreachable from the machine running the MCP.
Environment
| Var | Required | Default | Role |
|---|---|---|---|
| UNIFI_API_KEY | one of the two | — | Site Manager key (unifi.ui.com → API) |
| UNIFI_CONSOLE_ID | no | — | Pin the console used by Network tools (cloud) |
| UNIFI_API_BASE | no | https://api.ui.com | Override the cloud base URL |
| UNIFI_LOCAL_URL | one of the two | — | e.g. https://192.168.1.1 (console reachable from this machine) |
| UNIFI_LOCAL_API_KEY | with UNIFI_LOCAL_URL | — | UniFi Network → Settings → Control Plane → Integrations |
| UNIFI_TLS_INSECURE | no | false | true for the console's self-signed cert (local only) |
| UNIFI_MODE | no | readonly | readonly | full |
| UNIFI_PROMETHEUS_URL (+ _TOKEN / _BASIC_AUTH, UNIFI_PROMETHEUS_SCRAPE_INTERVAL) | no | — | history tools on Prometheus |
| UNIFI_LOKI_URL (+ _TOKEN / _BASIC_AUTH, UNIFI_LOKI_TENANT, UNIFI_LOKI_SELECTOR) | no | — | event and audit tools on Loki |
| UNIFI_EXPORTER_BIND / UNIFI_EXPORTER_PORT / UNIFI_EXPORTER_INTERVAL / UNIFI_UNAS_NAME | exporter | 127.0.0.1 / 9877 / 60 / unas | exporter listener, collection interval, NAS label |
| UNIFI_HISTORY_DB_URL | no | — | deprecated PostgreSQL store (ignored when Prometheus and Loki are both set) |
| UNIFI_HISTORY_RETENTION_DAYS | no | 90 | collector / receiver: rows older than this are purged |
| UNIFI_SYSLOG_ALLOWED_SOURCES | receiver | — | IPs / CIDRs allowed to send syslog |
| UNIFI_SYSLOG_BIND | no | 127.0.0.1 | receiver bind address |
| UNIFI_SYSLOG_UDP_PORT / UNIFI_SYSLOG_TCP_PORT | no | UDP 5514 | receiver ports |
| UNIFI_SYSLOG_TLS_CERT / UNIFI_SYSLOG_TLS_KEY | no | — | TLS on the TCP port |
| UNIFI_SYSLOG_RATE_PER_SOURCE | no | 200 | messages per second per source |
| UNIFI_ENABLE_INTERNAL_API | no | false | true enables the [unofficial] internal API tools |
| UNIFI_INTERNAL_CONSOLES | with the above | — | name=https://host[:port]\|<SHA-256 fingerprint>, comma-separated |
| UNIFI_INTERNAL_USERNAME / UNIFI_INTERNAL_PASSWORD | with the above | — | local View Only account, no MFA |
| UNIFI_UNAS_HOST | no | — | UNAS IP or hostname; enables the unas_* tools |
| UNIFI_UNAS_KEY_FILE | with UNIFI_UNAS_HOST | — | dedicated private key (chmod 600); no password auth |
| UNIFI_UNAS_HOST_KEY | with UNIFI_UNAS_HOST | — | pinned host key, SHA256:… (comma-separated if several) |
| UNIFI_UNAS_USER | no | root | SSH user |
| UNIFI_UNAS_PORT | no | 22 | SSH port |
Register
Claude Code:
claude mcp add unifi --scope user \
-e UNIFI_API_KEY=... \
-e UNIFI_CONSOLE_ID=... \
-e UNIFI_MODE=readonly \
-- npx -y @aidalinfo/unifi-mcpClaude Desktop on Windows (%APPDATA%\Claude\claude_desktop_config.json):
"unifi": {
"command": "cmd",
"args": ["/c", "npx", "-y", "@aidalinfo/unifi-mcp"],
"env": { "UNIFI_API_KEY": "...", "UNIFI_CONSOLE_ID": "...", "UNIFI_MODE": "readonly" }
}In a PowerShell terminal, if the execution policy blocks npx.ps1, call npx.cmd instead
(npx.cmd -y @aidalinfo/unifi-mcp). For the UNAS key, use a Windows path
("UNIFI_UNAS_KEY_FILE": "C:\\Users\\<you>\\.ssh\\unas_mcp_readonly") and restrict it with icacls as above.
Each person registers the server with their own key. When the account has several consoles, the console
is not picked automatically: set UNIFI_CONSOLE_ID to the one you query most (id from unifi_hosts), and
pass consoleId to reach another one. Consoles without the Network app (e.g. a UNAS) are never picked.
Safety
- API paths are validated: no
.., no encoded dots or slashes, and no?or#. The final URL must stay under its base. Ids are encoded, and dot-only console ids are rejected. - List helpers stop on an empty page, a repeated
nextToken, 50 pages, or 2000 items. - API keys are never logged.
Development
npm install
npm test # jest: mode gating, transports, pagination, site resolution, write payloads
# history / syslog integration tests run against a throwaway PostgreSQL:
docker run -d --rm --name unifi-pg -e POSTGRES_PASSWORD=test -p 127.0.0.1:55432:5432 postgres:16-alpine
UNIFI_TEST_PG_URL=postgres://postgres:[email protected]:55432/postgres npm test
npm run buildValidation status
- Run on Pulse hardware (Site Manager key):
unifi_hosts,unifi_account_sites,unifi_account_devices,unifi_isp_metrics. ISP metrics live at/v1/isp-metrics/{5m|1h};durationmust be24hwith5m, and7dor30dwith1h. - UNAS (
unas_*), run on UNAS-PRO-LABO (UniFi OS 5.1, Debian 11, smartctl 7.2) on 2026-10-13: all four tools, through the forced command; wrong host key refused before auth;idand chained commands refused by the wrapper. Layout seen: 3 × 16 TB in md3 (RAID 5) → LVM → btrfs on/volume/<uuid>, md0 (RAID 1) for the system./rootlives on the persistent overlay; check after a UniFi OS update that the key and the wrapper are still there. - Exporter, Prometheus and Loki backends: the exporter ran against UNAS-PRO-LABO (bare and as the Docker image,
read-only container, no capabilities); its output passes
promtool check metrics. The history tools ran on a real Prometheus 2.54 with 27 h of backfilled exporter series (outages, data gap reported as UNKNOWN, firmware change, reboot, ISP loss, STALE footer). The event tools ran on a real Loki 3.1 (CEF parsing, masked secrets, Loki time instead of a forged sender time, feed status). - History store and syslog receiver (deprecated): tested against PostgreSQL 16 (collection passes with a changing fake fleet, read-only reader session, purge; UDP and TCP syslog sockets end to end). Not yet deployed: the collector needs a Coolify scheduled task, the receiver a service reachable by the consoles.
- Internal API (
[unofficial]): certificate pinning checked against the Marly UDM Pro (right pin → request sent, wrong pin → nothing sent, no pin → refused). Route shapes follow the classic controller API; they still need a run with a View Only local account, in particularv2 system-log/all(falls back tostat/event). - Events, time series, client history and radio tools (0.7.0): the system-log classes, their request bodies and
the statistics engine of Network 11 follow the community reference client (Art-of-WiFi UniFi-API-client), not a
capture from our consoles. To check on a console with a View Only local account: the names of the
parametersof a system-log entry (device and client filters), the schema names of the statistics engine (wirelessBySiteByDevice,activityBySiteByClient,systemBySiteByDevice,wanBySite,clientCountBySite), andv2 trafficroutes. - Not run on real hardware yet: every Network tool, including the diagnostics. The test key was
Site Manager-only, so the connector answered 403. The cloud prefix used is
/v1/connector/consoles/{id}/proxy/network/integration; some third-party docs drop/proxy. - Renderers read fields checked against the Network API 10.6.106 spec. A field that comes back as
?has a different name on our firmware. The*_infotools andunifi_raw_getreturn the raw (redacted) JSON. - The action payloads (
RESTART,POWER_CYCLE,AUTHORIZE_GUEST_ACCESS/UNAUTHORIZE_GUEST_ACCESS) follow the Integration API v1 spec.
