MCP servers 2026-10-11 01:44 UTC
unifi-mcp-server
Committed by enuno. Update Category: New Features & Capability Expansion. Commit details: feat(fleet): Phase 4 — multi-replica sessions, shared rate limits, worker tier, fleet_* read tools (#204). This update introduces new capabilities and expands supported use cases.
CommitRaw commit message
feat(fleet): Phase 4 — multi-replica sessions, shared rate limits, worker tier, fleet_* read tools (#204)
* test(audit): force write failure via opener so chain test passes as root
chmod 0o400 does not stop root from appending, so the test failed in
root containers. Patch the logger's opener to raise instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test: cover dns_management, content_filtering and MCP resources
dns_management 6% -> 96%, content_filtering 8% -> 97%, and the clients,
devices, networks, site_manager and protect resources to 100%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test: cover site_manager_client and Protect device families
site_manager_client 23% -> 100% via httpx.MockTransport; protect_devices
41% -> 99% with tests parametrised over devices, lights, sensors, chimes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(a2a): cover HTTP handlers, router and ASGI entry point
http_handlers 41% -> 99%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(protect): cover Protect meta info, viewer and live view writes
protect_views 67% -> 99%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* fix(registry): coerce string dry_run before it reaches the tool
63 mutating tools take dry_run: bool | str and test it with a bare
'if dry_run:'. An MCP client sending dry_run="false" with confirm=True
got a preview instead of the change, while the wrapper's audit recorder
(which does coerce) logged the call as a success.
Normalise dry_run once in the registry wrapper. A string that is not
clearly false stays a preview, so unrecognised values fail safe.
Also silence the pre-existing attr-defined error on the per-instance
tool-name registry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test: cover Cloud Connector write tools and ProtectClient request paths
connector 73% -> 100%, protect_client 74% -> 97%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(cache): cover Redis error paths, @cached, warm_cache and ReadCache edges
cache 69% -> 96%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test: cover the Supermemory client and python -m entry point
memory 0% -> 98%, __main__ 0% -> 100%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(firewall): cover match-target helpers, zone resolution and delete paths
firewall_policies 78% -> 94%.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(firewall): give client mocks a real site-name map
On a bare AsyncMock, client._site_uuid_to_name.get() returns an
un-awaited coroutine, which became the site segment of every endpoint
and raised 27 'coroutine was never awaited' warnings per run.
The .secrets.baseline change only moves line numbers of entries that
were already allowlisted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(main): cover resource handlers, lifespan, start-up audit and transports
main 78% -> 92%. main() is exercised for stdio, streamable_http (session
guard, A2A, metrics) and sse with mcp.run patched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(registry): require every mutating tool to declare dry_run
UNIFI_DRY_RUN withholds mutating tools it cannot gate, so a new write
tool without a dry_run parameter would silently disappear from dry-run
sessions. All 42 modules with mutating tools already comply.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* docs: sync tool/test counts and Phase 4-5 status with the code
Measured on this branch: 343 tools in local mode across 60 modules,
3,152 unit tests, 93% line coverage. Marks done what has shipped
(coverage target, issue #96 closed, dry-run on every mutating tool,
RBAC and server-issued tokens, /metrics, Protect v7 and Phase 6) and
narrows multi-controller and audit items to what is still open. Notes
the undeclared fastapi import in src/webhooks/receiver.py, and adds a
CHANGELOG entry for the dry_run coercion fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* fix(types): clear the remaining mypy errors in src/
mypy src/ goes from 31 errors to none. Mostly annotations and casts
where values come from untyped JSON; behaviour changes are limited to:
- update/delete_firewall_policy raise ValueError('settings is required')
instead of AttributeError when called without settings
- A2AJSONEncoder no longer passes dataclass *classes* to asdict()
Optional-import fallbacks (redis, supermemory) carry ignores that hold
whether or not the package is installed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* ci: make the mypy step blocking
mypy src/ is clean, so drop continue-on-error and add typecheck to
'make ci', which mirrors the blocking CI jobs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test: address CodeQL findings in new tests
Move the awaited delete() calls out of assert statements, and import
src.cache one way only in test_cache_paths.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* build: cap fastmcp below 4 and mcp below 2
fastmcp 4.1.0 / mcp 2.3.0 break per-session controller selection
(select_controller no longer sticks for later calls in a session) and
return an MCP error instead of 401 for bad or revoked tokens; 4 fleet
tests fail with them. The lower-bound-only pins let pip and CI's
unlocked install pick them up.
uv.lock keeps the same package versions; the marker changes are uv's
own re-resolution output.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* style(scripts): black-format and add docstrings to the audit scripts
Clears the black and ruff (D103) failures in the Pre-commit Hooks job,
which were also failing on main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* chore(security): refresh .secrets.baseline
Adds the 12 false positives found by detect-secrets and updates the
line numbers of 9 already-allowlisted entries. All 12 were reviewed:
example values in the vendored API specs under scripts/ and fake test
fixtures (test_metrics_route, test_mobility, test_wifi_tools,
test_audit_encryption). None come from this PR's changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* ci(security): ignore the generated_at timestamp in the baseline drift check
detect-secrets rewrites generated_at on every scan, so the
'git diff --exit-code' step failed even when the baseline matched.
Diff with -I on that line: a timestamp-only rewrite now passes, while a
new finding still fails the job (checked by planting a fake key).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* ci(security): scan git-tracked files only in the secrets job
--all-files also reads untracked runner files: on GitHub Actions it
flagged the commit hash in .git/FETCH_HEAD, failing the job with a
correct baseline. Scanning tracked files matches the pre-commit hook
and still covers everything a PR adds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* fix(webhooks): port the receiver to Starlette and fail closed without a secret
The receiver imported fastapi, which is not a dependency, so it could
not be imported in a real install (its tests faked the module). It also
never verified signatures: WEBHOOK_SECRET, documented in README, API.md
and docker-compose.yml, was not a Settings field, so getattr() always
returned None and every unsigned request was accepted.
- register_routes() mounts a plain Starlette endpoint via add_route(),
so it works on Starlette, FastAPI or FastMCP's HTTP app
- Settings.webhook_secret reads WEBHOOK_SECRET (blank = unset, hidden
from repr)
- without a secret every request gets 503; every request needs a valid
X-UniFi-Signature (hex HMAC-SHA256 of the raw body)
- 401 and 429 are returned as such instead of being caught and turned
into 500s
- pydantic v2 field_validator instead of the deprecated validator
The compose env-var test now also checks WEBHOOK_* names, which is how
the missing field went unnoticed. API.md describes the receiver as it
is: a component to mount, not an endpoint the server serves by itself.
.secrets.baseline: one allowlisted entry moved from line 31 to 18.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* fix: address Copilot review on pooling, A2A request handling and pagination
- UniFiClient/ProtectClient.close() never closes a pooled HTTP client:
a second close() used to fall through to aclose() on the client the
pool still hands to other callers
- A2AHTTPRouter: http.disconnect ends the request; receive() keeps
returning it, so the old loop spun forever
- _payload_from_request returns {} unless the JSON body is an object,
so [] or "text" no longer reach handlers that call .get()
- list_protect_devices paginates locally only, like its sibling tools;
sending limit/offset too applied the offset twice if the API honours it
- README: CI check counts 18 -> 25
Each new test fails on the previous code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(webhooks): mount POST /webhooks/unifi when WEBHOOK_SECRET is set
On network transports main() now calls register_webhook_route(), which
mounts the receiver (with the default handlers) as a FastMCP custom
route only when Settings.webhook_secret is set. Without the secret no
webhook route exists; stdio serves no HTTP and never mounts it.
The route is not behind the MCP bearer token, since UniFi cannot send
one: every delivery must carry a valid X-UniFi-Signature instead. A test
drives FastMCP's real HTTP app to show a signed delivery succeeds with
no bearer token and an unsigned one gets 401.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* fix(webhooks): clear the read cache on device and client events
The default handlers called the legacy invalidate_cache(), which deletes
'devices:{site}:*'-style keys that nothing writes any more, so the live
ReadCache ('unifi:v1:{controller}:...') was never cleared. It also dialed
localhost:6379 on every event even without Redis configured.
The handlers now take the server's read cache (main passes its
read_cache, None without Redis) and call the new
ReadCache.invalidate_all() on device.* and client.* events. A webhook
payload does not name its controller, so every controller's reads are
cleared: exact with one controller, extra misses but never stale reads
in a fleet. Alerts and generic events leave the cache alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(fleet): MCP_STATELESS_HTTP mode, refusing select_controller clearly
Phase 4 spike (docs/FLEET_SCALING_PLAN.md): FastMCP keys session state
by the mcp-session-id header. A stateful Streamable HTTP session lives in
one replica's memory (another replica answers 404 Session not found), and
a stateless server never issues a session id, so each request gets a
fresh state key and a selection vanishes on the next call. Sticky routing
on mcp-session-id is therefore the supported multi-replica mode.
MCP_STATELESS_HTTP=true runs Streamable HTTP without sessions so any
replica can answer any request. In that mode select_controller is
refused with a message to pass controller=<name>, session state is
ignored, and the routing errors name only the explicit argument.
The SessionlessRequestGuard (issue #173) is installed only in stateful
mode: it answers every sessionless non-initialize request with 400, so
it would refuse every stateless tool call, and stateless transports end
with each response, so the leak it prevents cannot occur.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(fleet): share controller rate limits across replicas through Redis
Each replica gave every controller the full UNIFI_RATE_LIMIT_REQUESTS
budget, so N replicas sent N times the configured rate. With Redis
configured, pooled connections now draw from one sliding window per
controller in Redis, and calls to api.ui.com from one window per API key
(the cloud API limits per key, not per console).
The window is a sorted set of Redis TIME stamps updated in one MULTI
transaction, so it needs no Lua (fakeredis cannot run Lua without lupa)
and cannot burst at a window boundary. Keys live under
unifi:ratelimit:v1:, outside the unifi:v1: namespace ReadCache clears,
and carry only a hash of the API key. If Redis stops answering the
limiter falls back to the per-process bucket with one warning.
Without Redis nothing changes, and redis is still not imported.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(fleet): announce registry changes to every replica over Redis pub/sub
A registry change made through one replica's admin tools reloaded only
that replica's snapshot; the others served the old one until their next
UNIFI_FLEET_REGISTRY_REFRESH_SECONDS refresh. With Redis configured,
PostgresRegistry.changed() now refreshes and publishes on
unifi:registry:v1:changed, and every replica's listener reloads its
snapshot at once. The periodic refresh stays as the backstop.
A replica skips its own messages. Redis trouble never fails a change:
publish logs a warning, the listener reconnects, and a refresh that fails
after a message is logged without stopping the listener.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* docs(fleet): record the Phase 4 session spike and the multi-replica setup
The fleet plan records the spike (stateful sessions are replica-local,
stateless servers issue no session id), the decision (sticky routing
supported, MCP_STATELESS_HTTP as the session-less mode, Redis
session_state_store dropped) and what Phase 4a delivered.
MULTI_CONTROLLER.md gains a 'Running several replicas' section with an
nginx consistent-hash example; API.md documents MCP_STATELESS_HTTP.
.secrets.baseline: four allowlisted API.md entries move down one line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(fleet): store controller health, sites and device inventory snapshots
Migration 0004 adds the sites and device_inventory tables and the health,
health_detail, health_checked_at, last_seen_at and capabilities columns of
controllers (docs/FLEET_SCALING_PLAN.md §3.2). SnapshotStore records health
and replaces a controller's site snapshot or one site's device snapshot,
removing rows the controller no longer reports; deleting a controller or a
site removes its snapshots.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(worker): add the fleet worker tier with leased shards
python -m src.worker health-checks every registered controller and keeps
its site and (local controllers) device inventory snapshots current
(docs/FLEET_SCALING_PLAN.md §3.5). With Redis, workers heartbeat into a
sorted set, split controllers by rendezvous hashing and hold a SET NX PX
lease on each, so a dead worker's controllers move after
UNIFI_FLEET_WORKER_LEASE_SECONDS and a clean shutdown hands them over at
once; without Redis one worker owns everything. First runs are spread over
each interval by a hash of the controller name and later ones jittered
+/-10%, at most UNIFI_FLEET_WORKER_CONCURRENCY at once. Health is degraded
after a failure and down after UNIFI_FLEET_WORKER_DOWN_AFTER in a row. The
worker starts the registry without seeding it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* docs(fleet): document the worker tier and add it to the fleet compose file
Records 4b in docs/FLEET_SCALING_PLAN.md (decisions: rendezvous hashing,
GET+PEXPIRE lease renewal, cloud controllers get sites only; cloud-account
discovery deferred), adds "Fleet workers" to MULTI_CONTROLLER.md, the
UNIFI_FLEET_WORKER_* settings to API.md and .env.example, a worker service
to docker-compose.fleet.yml, and the CHANGELOG, TODO and DEVELOPMENT_PLAN
status. The test Postgres now deletes its data directory at the end of the
session; "stop" left several hundred MB behind on every run until the disk
filled. .secrets.baseline: four API.md line shifts, no new entries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* feat(fleet): add fleet-wide read tools over snapshots and live fan-out
With DATABASE_URL, four read-tier tools in module "fleet", limited to the
caller's controller scope (docs/FLEET_SCALING_PLAN.md §3.4):
- fleet_health, fleet_sites and fleet_inventory answer from the worker's
snapshots in one query, with the age of every entry; health older than
three intervals is stale, and fleet_inventory filters by model, state
and firmware_below (numeric version comparison).
- fleet_fanout runs one read-tier tool live on many controllers with
bounded concurrency, a per-controller timeout and an overall deadline,
returning a result or an error per controller. Each call goes through
FastMCP and the tool wrapper, so role, module filters, controller scope
and the read cache apply as for a direct call; write, destructive and
fleet_* tools are refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NKGQizs8aPuwDxqK16up84
* test(fleet): verify 3 replicas + 2 workers with real processes
scripts/verify_fleet_scale.py (make verify-fleet-scale) starts Postgres
(pgserver), Redis (fakeredis over TCP), an HTTPS mock answering as 40
controllers (two unreachable), three `python -m src` replicas and two
`python -m src.worker` processes, then checks: the workers split the
fleet; health is recorded; a SIGKILLed worker's controllers move within
the lease plus a tick and keep being checked; a controller registered on
one replica is listed by the others at once; three replicas never exceed
one controller's rate limit; fleet_fanout returns partial results; and
fleet_health/fleet_inventory rea…