agentleFS
sirkirbysirkirby/unifi-mcp/.agents/skills/live-smoke-testing/SKILL.md

myco:live-smoke-testing

Skill1.1k starsChanged 9 days agoMITView on GitHub

Activate this skill when running, interpreting, extending, or debugging the live hardware smoke test harness in `scripts/live_smoke.py`. Covers all aspects of manifest-driven live testing against real UniFi hardware: .env credential setup, tool classification tiers, --phase flag selection to bound blast radius, the human-in-the-loop confirmation gate for mutations, artifact interpretation in live-smoke-results/, adding new tools to the harness, and recognizing known API contract failure patterns that mock-based CI cannot catch. Apply this skill even if the user doesn't explicitly ask about the harness — activate whenever a PR requires live smoke evidence, a new tool category needs coverage, or an API contract mismatch is suspected. CRITICAL: Treat live smoke as a PRE-MERGE BLOCKING GATE when code changes API response parsing (new fields, filtering logic, payload normalization).

  • Reads credentials
  • Installs packages

1 other project uses a version of this.

Trending

More talk lately.about the whole repository

Jan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 1 mentionMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 0 mentionsAug 2026: 1 mentionSep 2026: 1 mentionOct 2026: 3 mentionsNov 2026: 38 mentionsDec 2026: 5 mentions
Jan 2026Jul 2026Dec 2026
Mentions a month of the sirkirby/unifi-mcp repository that our weekly crawl found. There is no adoption data for this file yet.

Most recently taken up by

Who's talking about sirkirby/unifi-mcp

The biggest 5 of 49 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 49

Talked about on GitHub (49 times).

On GitHub · 49

44 more on GitHub

The file

Show its rules and text

We split this skill into the rules it gives an agent

22 rules. About 0 are common, 10 are distinctive, and 12 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈10

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 12

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Before any live run, ensure:

    line 29
  2. Distinctive:

    When branching or bisecting, confirm you have the current harness code before running.

    line 59
  3. Very specific:

    Start every new tool or hardware target with --phase readonly.

    line 199
  4. Very specific:

    Never skip directly to approved on a first run against a new tool or new hardware.

    line 202
  5. Very specific:

    Use --phase inventory to audit tier assignments without making any live calls.

    line 203
  6. Distinctive:

    Never feed it Network, Protect or Access IDs.

    line 232
  7. Very specific:

    Reports: never carry the key, request headers or a traceback: the key is replaced with *REDACTED* in error text and transport exceptions …

    line 236
  8. Distinctive:

    When it leaves no session, setup is a failed record naming the login error and no other tool runs.

    line 321
  9. Distinctive:

    Never skip Stage 1 — even for tools you've run before, always review the preview against current hardware state.

    line 353
  10. Very specific:

    If the preview shows unexpected scope, wrong site, or wrong resource count, stop.

    line 356
  11. Distinctive:

    Disposable resource rule for destructive operations: When a lifecycle method exercises destructive operations (archive, bulk-delete, …

    line 361
  12. Very specific:

    When you see a live smoke failure with no corresponding unit test failure, assume API contract mismatch first.

    line 445
  13. Very specific:

    When a new tool is scaffolded and registered in the server's tools_manifest.json, extend the harness as follows:

    line 450
  14. Very specific:

    If the tool should be read_only: Ensure readOnlyHint=True is set on ToolAnnotations in the tool function.

    line 460
  15. Very specific:

    Building preview args from live values: When constructing confirm=False preview args for a new capability tool, reuse the device-inventory …

    line 469
  16. Very specific:

    If the tool is risky/destructive: Add it to RISKY_OPERATION_NAMES (the set at line ~90 in scripts/live_smoke.py) or set …

    line 491
  17. Distinctive:

    Advance to safe/approved phase: after readonly passes cleanly.

    line 502
  18. Distinctive:

    Run probe scripts in any PR that touches tool registration or schema changes:

    line 521
  19. Distinctive:

    All three app servers start cleanly inside their respective images

    line 534
  20. Very specific:

    All tools are discoverable in each image's tools_manifest.json

    line 535
  21. Very specific:

    .env is gitignored — never commit credentials: If you see UNIFI_HOST or UNIFI_PASSWORD in a diff, abort the commit immediately and rotate …

    line 582
  22. Distinctive:

    Credential rotation invalidates prior artifacts: If credentials changed between runs, artifacts from prior runs cannot be used as PR …

    line 619

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Live Smoke Testing Against Real UniFi Hardware

scripts/live_smoke.py is the manifest-driven live hardware test harness. It validates API contracts that mock-based CI (unit tests, golden fixtures) structurally cannot catch — auth token expiry, payload normalization, API version mismatches, and hardware-specific field assumptions. Live smoke runs caught multiple critical bugs before merge. Run live smoke before every major merge that touches API-facing code.

Prerequisites

Before any live run, ensure:

  1. .env file at project root (gitignored) with real credentials:
    UNIFI_HOST=<controller-hostname-or-ip>
    UNIFI_USERNAME=<admin-username>
    UNIFI_PASSWORD=<admin-password>
    UNIFI_SITE=<site-id>           # usually "default"
    # For Access domain:
    UNIFI_ACCESS_API_KEY=<access-api-key>
  2. Per-server tools_manifest.json is up-to-date — the harness auto-discovers tools from each server's manifest. During development, verify your local module's manifest is current:
    # Check where each server's manifest is located
    find . -name "tools_manifest.json" -type f
    New tools registered in the manifest are automatically included in smoke runs; no manual harness edits are needed just to add read-only or preview coverage for a newly registered tool. If adding a new tool, verify the manifest entry exists and safety_tier() classification is correct (see Procedure A).
  3. Target hardware is reachable — verify connectivity before running:
    curl -k https://$UNIFI_HOST
  4. Branch context — the harness lives in scripts/live_smoke.py on the main branch. When branching or bisecting, confirm you have the current harness code before running.
  5. Git worktree .env placement — scripts/live_smoke.py derives its repo root from its own file location (Path(__file__).resolve().parents[1]) and loads .env from that root. In a git worktree the root resolves to the worktree directory, NOT the main checkout. Copy or symlink your credentials file from the main checkout into the worktree root before running:
    ln -s /path/to/main-checkout/.env /path/to/worktree/.env
    Omitting this causes silent credential-not-found failures with no warning.
  6. Use uv run, not system python3 — the repo's dependencies are managed by uv and are not installed in the system Python environment. Always invoke the harness via:
    uv run python scripts/live_smoke.py --server network --phase safe
    Running with bare python3 will fail with import errors for aiounifi, dotenv, and other dependencies not available outside the uv-managed virtual environment.
  7. Invoke uv run from the workspace root with --all-packages in the monorepo. Running uv run python scripts/live_smoke.py from a package subdirectory (or without --all-packages) can fail with ModuleNotFoundError: mcp because the workspace's shared dependency isn't resolved into that package's isolated env. Run from the repo root:
    uv run --all-packages python scripts/live_smoke.py --server network --phase safe
    mcp can also silently vanish from the root .venv after make pre-commit, uv lock, or bare uv sync — any of these run without --all-packages and re-resolve the root env without the workspace-shared dependency. If a previously-working smoke run suddenly hits ModuleNotFoundError: mcp, re-run uv sync --all-packages before assuming a code regression.

Procedure 0: PRE-MERGE BLOCKING GATE — API Response Parsing Changes

Trigger Criteria — Live Smoke is Mandatory Before Merge:

Code changes in any of these categories require a pre-merge live smoke run that must PASS before the PR can be merged:

  • Manager response normalization logic — changes to how API response payloads are converted to domain models (e.g., field mapping, null handling, type coercion in manager classes)
  • New API response fields — adding handling for fields that are new to the UniFi API or new to a particular controller firmware version
  • Filtering or field selection logic — changes to which fields are extracted from responses, or conditional inclusion/exclusion of fields based on hardware or firmware state
  • Payload shape transformation — restructuring nested payloads, flattening, or re-nesting fields for compatibility with domain models
  • Version-dependent API contracts — changes that assume an API endpoint behaves differently across firmware versions

Why this is a blocking gate: Mock-based CI uses golden fixtures (static JSON files) that cannot evolve with real hardware firmware updates. Changes to response parsing are invisible to unit tests — they pass against the fixed fixture forever, but fail against real hardware running a different API version. The Access proxy incident exemplifies this: unit tests passed; live hardware returned auth-wrapped-in-200 errors invisible to mocks.

Ship doctrine — verify the changed code path, not an adjacent green path: Smoke evidence only counts if it exercises the specific code modified by the PR. If your PR touches the alarm manager, a passing run that exercises only the client manager is not evidence. Identify the tools that invoke the changed code and name them explicitly in the PR smoke evidence block.

Execution:

# For the affected domain(s) (e.g., network, protect, access):
uv run python scripts/live_smoke.py --server <domain> --phase readonly
uv run python scripts/live_smoke.py --server <domain> --phase safe
# Both must exit status 0 with no failed/exception records in artifacts

Sign-off: Include in the PR description:

**Live Smoke Evidence:**
- ✓ network readonly: 45 tools, 0 failures
- ✓ network safe: 12 lifecycle ops, 0 failures
- Artifacts: [link to live-smoke-results/{server}-{timestamp}.json]

The PR reviewer must confirm both phases passed and inspect the artifact for correct payloads before approving merge. This is equivalent to a code review checkpoint — it verifies API contract assumptions against reality before the code lands on main.

Procedure A: Understand Tool Classification Tiers

The harness classifies tools dynamically from manifest annotations and the RISKY_OPERATION_NAMES set (line ~90 in scripts/live_smoke.py). safety_tier() on LiveSmokeRunner drives phase inclusion.

Tier (safety_tier value)How it's determinedRun gate
read_onlyreadOnlyHint: true annotation in manifestIncluded in readonly and safe phases
preview_or_safe_lifecycleHas confirm param; not in RISKY_OPERATION_NAMESPreview (confirm=False) in preview/safe; lifecycle pairs in lifecycle/safe
requires_approvalIn RISKY_OPERATION_NAMES set OR destructiveHint: trueExcluded from automated runs; listed in pending_approval; manual only
defer_heavy_readIn STREAM_OR_HEAVY_READS set (streaming/export tools)Skipped unless --include-heavy-reads passed
mutating_requires_reviewHas writes but no confirm param and not explicitly riskyFlagged for manual review

Classification is driven by manifest annotations — not static tier lists. When in doubt, set destructiveHint: true on the tool's ToolAnnotations. A tool missing readOnlyHint that does only reads is silently treated as mutating; fix the annotation. Meta tools are the exception: the preview phase skips them (skipped, "meta tool, not a controller write"), because some are not read-only (*_batch_cancel) yet never reach the controller or take confirm. Their behaviour is covered by unit tests, not live smoke.

Procedure B: Run the Harness with --phase Control

The --phase flag bounds blast radius. The --server flag is required for all MCP-direct phases. Always start at the safest phase and advance only after the prior phase passes cleanly.

# Safest run — readonly + preview + safe lifecycles (default phase is "safe")
uv run python scripts/live_smoke.py --server network --phase safe

# Read-only tools only (narrowest scope)
uv run python scripts/live_smoke.py --server network --phase readonly

# Preview phase — all mutating tools called with confirm=False
uv run python scripts/live_smoke.py --server protect --phase preview

# Approved operations — runs all safe lifecycles plus explicitly approved mutations
uv run python scripts/live_smoke.py --server network --phase approved

# Run all servers at once (requires full .env with Access and Protect creds;
# Site Manager runs last and is skipped when no Site Manager key is set)
uv run python scripts/live_smoke.py --server all --phase safe

# Site Manager (cloud, key-only) — see Procedure B2
uv run --all-packages python scripts/live_smoke.py --server sitemanager --phase readonly

# InnerSpace (console login) — see Procedure B3
uv run --all-packages python scripts/live_smoke.py --server innerspace --phase readonly
uv run --all-packages python scripts/live_smoke.py --server innerspace --phase lifecycle

# Drive (NAS login, read-only) — see Procedure B4
uv run --all-packages python scripts/live_smoke.py --server drive --phase readonly

# Inventory — prints safety_tier classification for every tool; no live calls
uv run python scripts/live_smoke.py --server network --phase inventory

Phase progression guidance:

  • Start every new tool or hardware target with --phase readonly.
  • Advance to --phase safe only after readonly passes cleanly.
  • Advance to --phase approved only after safe passes cleanly.
  • Never skip directly to approved on a first run against a new tool or new hardware.
  • Use --phase inventory to audit tier assignments without making any live calls.
  • Phase scope has expanded over the project lifecycle: earlier phases were intentionally narrow (deployment/auth only, no controller-touching); later phases added full Protect physical actions and Access lock/unlock patterns. Expect further expansion for each new REST endpoint domain.

Expected output: The harness streams per-tool status to stdout. A passing run exits with a summary count. Any failed or exception status line requires investigation before merge.

Procedure B2: Site Manager Target (--server sitemanager)

Site Manager talks only to Ubiquiti's cloud with one account-wide key. It has no console host, no hardware prerequisite and no support-bundle tool.

  • Key: UNIFI_SITEMANAGER_API_KEY, or its _FILE / _COMMAND form, in .env, the environment, or the settings file named by UNIFI_SETTINGS_FILE. Never UNIFI_API_KEY: that is a console's local key and the harness does not consider it.
  • Absent key = skip, not validation. With none of the three spellings set, the target writes one __setup__ record with status skipped_no_credentials and exits 0. It imports no server, runs no key provider and makes no request. A skip proves nothing about Site Manager; never cite it as live evidence. --server all still runs the three console servers as before.
  • Configured but broken = failure. Two spellings at once, an unreadable _FILE, a failing _COMMAND (resolved by the server's own resolver) or a UNIFI_SETTINGS_FILE that cannot be applied is a failed setup record and exit 1. A wrong key fails at the first read (401).
  • What runs: the nine domain tools, all read-only, each once. Lists are one page of 5; ISP metrics use 5m over 24h with one period. Detail arguments come only from Site Manager's own lists: host_id from sitemanager_list_hosts, config_id from sitemanager_list_sdwan_configs, the host_id/site_id pair from sitemanager_list_sites. An account with no SD-WAN configuration or no usable site skips that tool with a reason. Never feed it Network, Protect or Access IDs.
  • Phases: readonly and safe run the reads; preview, lifecycle and approved have nothing to run. --phase support --server sitemanager writes an unsupported report and exits 2; the support phase covers network, protect and access only.
  • Reports never carry the key, request headers or a traceback: the key is replaced with ***REDACTED*** in error text and transport exceptions are recorded by class name only.
  • Account-wide reads are an explicit operator run; never run them from setup validation.

Procedure B3: InnerSpace Target (--server innerspace)

InnerSpace is read and written through a console login session. It is a registered harness target (--server innerspace) with no support-bundle tool; SUPPORT_BUNDLE_SERVERS stays network, protect and access.

  • Prerequisites: a console with the InnerSpace application installed and running, and a UniFi OS account that can open it. Credentials are UNIFI_INNERSPACE_HOST, UNIFI_INNERSPACE_USERNAME and UNIFI_INNERSPACE_PASSWORD (or the _FILE / _COMMAND forms). Never UNIFI_API_KEY: a console's local key is not used for InnerSpace.
  • What runs: nine read tools and 15 write tools. innerspace_get_status runs first; when it reports InnerSpace not installed or not running, every other tool is recorded as skipped with that reason. The reads that need plan_id (innerspace_list_walls, innerspace_list_placed_devices, innerspace_get_plan_asset) take the first id from the innerspace_list_floor_plans result of the seed phase, and are skipped only when that list is empty or failed. Never feed them Network, Protect, Access or Site Manager IDs.
  • Write lifecycles: lifecycle and safe change only objects the run creates: the wall lifecycle below and the attenuation-object lifecycle. approved runs those, then one lifecycle per other write kind, each of which changes objects the run did not create, under approved:* phase labels as Network's approved-only lifecycles do. Each previews first, confirms, reads back fresh, and restores in a finally whenever its change was sent, then reads back again. A failed restore is a failed check, and its entry stays in created_resources with no match in cleaned_resources: that difference is what to put back by hand. Values read from the console appear in recorded arguments as <read from the console>, and plan titles never appear. Wall types: the create is previewed and never confirmed, since no tool removes a wall type; the first wall type that does not override a built-in material has its attenuation changed by 1 dB and restored (skipped when there is none). Floor plans: the first plan's title gets the suffix smoke and is renamed back; the first two plans of one site swap places in the plan order and the order is restored (skipped when no site has two plans; the restore numbers the plans 1, 2, 3 ... in their original order, so the swap is confirmed only when the stored values already are 1 to N in plan order and is otherwise only previewed, since a tie, a gap or another start would come back renumbered and neighbouring values stack floors for coverage); the first plan's floor attenuation is set to 25 dB (30 when it is already 25) and restored, read through a preview because no read tool returns it. Attenuation: on the wall lifecycle's plan, one shelf_small square at (0.1, 0.2)-(0.4, 0.5) m in the frame is created, listed through innerspace_get_project with include_shapes, changed to server_rack (read back by a fresh preview of the same update, which must have nothing left to change) and removed, also after a failed step or a create with an unknown outcome that names one id; attenuation-object types are handled as wall types are. Project unit and plan scale run last, because the replace is destructive and devices on the plan shift on the image until the restore. A metric project is set to imperial, the scale line of the wall lifecycle's plan is replaced by (0, 0)-(100, 0) in plan units at 10 ft, and the plan must read back 10 plan units per foot (the approved:verify-imperial-scale check, the live proof that an imperial project's scale goes out in metres with positions in plan units); then the original line and length from the replace's preview go back, then the original unit, and both are read back. The restored scale matches within 0.1 %, since the preview shows the length to 4 decimals.
  • Phases: readonly and safe run the reads. preview records each write as skipped, because no write argument is discovered, or as pending approval for the removals and innerspace_set_plan_scale. lifecycle (and safe) runs one wall lifecycle on the first plan whose map reads back an image scale of exactly 1 and an offset of (0, 0) (a scale of null, which is also how a map with a y scale unlike its x reads, does not count): a create preview, then a create of one short wall at (0.1, 0.1)-(0.6, 0.1) m in the frame, a read-back, a variant-only update to glass, a read-back, and a remove with a final read-back. The remove runs whenever the create may have landed (an unknown outcome that names one id included), also after a failed step. It needs InnerSpace installed and running; otherwise the create is refused and nothing else runs. approved runs the same and then the lifecycles that change the project's own objects, the unit and scale lifecycle last. --phase support --server innerspace is unsupported, as for Site Manager.
  • Evidence: a run against a console shows what the console accepted at that version; unit tests cannot. Say which kind of evidence you have, and record the controller and InnerSpace versions. Plan geometry, floor plans and device positions describe a building: keep reports out of the repository.
  • Negative control: with the InnerSpace application stopped, a read must fail with the fixed "not running" text (HTTP 502 over the API), never as a missing resource. For the writes, UNIFI_INNERSPACE_READ_ONLY=true must refuse the create preview with the read-only text and leave the plan unchanged.
  • Login rate limit: the console allows about 14 logins an hour. One harness run reuses one session; do not loop runs.

Procedure B4: Drive Target (--server drive)

UniFi Drive is read through a login session on the NAS (a UNAS or another console running Drive). It is a registered harness target with no support-bundle tool.

  • Credentials: UNIFI_DRIVE_HOST, UNIFI_DRIVE_USERNAME and UNIFI_DRIVE_PASSWORD (or the _FILE / _COMMAND forms), a local UniFi OS account on the NAS. They never fall back to the shared UNIFI_* connection values.
  • Connection check: the server makes no startup login, so the first read (drive_get_system_info, run in the seed phase after registration) is the connection check. When it leaves no session, setup is a failed record naming the login error and no other tool runs.
  • What runs: the seven domain tools are all read-only. drive_get_shared_drive takes the first id from the drive_list_shared_drives seed result and is skipped only when that list is empty or failed. An empty NFS connection list is a valid result on a NAS with no NFS clients.
  • Phases: readonly and safe run the reads; preview only skips the meta-tools, and lifecycle and approved have nothing to run. --phase support --server drive is unsupported.
  • Evidence: record the NAS model, UniFi OS version and Drive app version. Disk serials, share names and interface addresses describe the hardware: keep reports out of the repository.

Procedure C: Human-in-the-Loop Mutation Gate

Mutation tools require a two-stage human gate. The preview phase (included in safe) handles Stage 1 automatically; Stage 2 requires human review before running --phase approved.

Stage 1 — Preview phase (harness does this automatically during safe/preview):

The harness calls all preview_or_safe_lifecycle tools with confirm=False. This returns a preview payload without executing any write. Review the output in the terminal and in the per-server artifact file in live-smoke-results/.

Stage 2 — Human approval, then approved phase:

# After reviewing Stage 1 preview output, if all looks correct:
uv run python scripts/live_smoke.py --server network --phase approved

The approved phase runs explicitly coded lifecycle methods (e.g., lifecycle_network_dns(), lifecycle_network_oon_policy()) that execute idempotent create+delete pairs with confirm=True.

Rules:

  • Never skip Stage 1 — even for tools you've run before, always review the preview against current hardware state. A lifecycle run against stale assumptions can leave orphaned resources on the controller.
  • If the preview shows unexpected scope, wrong site, or wrong resource count, stop. Investigate the tool's argument construction before proceeding to approved.
  • Safe-lifecycle runs should leave zero net hardware changes. After an approved run, verify the controller UI shows no orphaned test resources.

Disposable resource rule for destructive operations: When a lifecycle method exercises destructive operations (archive, bulk-delete, format), always target a disposable resource created specifically for that run (e.g., a DNS record named smoke-test-<timestamp>). Never run destructive smoke against a production resource. If a dedicated test resource cannot be guaranteed (e.g., hardware-bound resources like camera channels), add the tool to RISKY_OPERATION_NAMES to exclude it from automated phases and require explicit human approval.

Pre-existing infrastructure guard (distinct from the disposable-resource rule above): the safe phase can mutate settings on pre-existing, non-disposable infrastructure — e.g. a gateway's broadcast_ping setting — in addition to resources the run itself created. The disposable-resource rule only covers destructive ops on run-created resources; it does not cover safe-phase writes to settings on hardware that already existed before the run. Safe-phase lifecycle methods must reject writes to any resource ID not created by the run itself — verify the target ID against the run's own created_resources list before mutating.

VLAN reserved-range bug: the disposable-network VLAN picker used for approved-phase lifecycle testing selected a controller-reserved VLAN (>=4010), causing the lifecycle create to fail against real hardware even though the harness logic was correct. Fix: bound the VLAN scan range strictly below 4000 when generating disposable test VLANs — controllers reserve the upper range internally and will reject or silently reassign IDs at/above 4010.

Procedure D: Interpret Artifacts in live-smoke-results/

Each run writes one JSON file per server, stamped with a timestamp:

live-smoke-results/{server}-{timestamp}.json

The file contains a SmokeReport serialized as JSON:

{
  "server": "network",
  "started_at": "2026-05-01T12:00:00+00:00",
  "finished_at": "2026-05-01T12:03:45+00:00",
  "connected": true,
  "records": [
    {
      "tool": "unifi_list_clients",
      "phase": "readonly",
      "status": "ok",
      "args": {},
      "duration_ms": 342,
      "success": true,
      "error": null,
      "summary": { ... }
    }
  ],
  "created_resources": [],
  "cleaned_resources": [],
  "pending_approval": []
}

Status values per record:

  • "ok" — tool completed; success is true; inspect summary for shape correctness.
  • "failed" — tool returned success: false; check error field.
  • "skipped" — tool excluded from current phase or args unavailable; not a failure.
  • "exception" — Python exception raised during invocation; check error for traceback.

API contract mismatches show up in summary content, not always as "failed". For example, an Access proxy returning HTTP 200 with an auth-failure body: status is "ok" but success is false or summary contains no usable data. Always inspect summary content and pending_approval, not just the overall status counts.

live-smoke-results/*.json stores only per-tool summaries, not full response payloads — a status: "ok" run proves nothing when a PR changes which fields get populated. The artifact's summary field is a truncated/derived view, not the raw API response, so it cannot confirm that a specific field was newly populated or correctly filtered. To verify response-shape changes, run an in-process one-shot probe script that prints the raw payload, and diff it against the same probe run on git checkout origin/main for a before/after comparison — the smoke artifact alone is not sufficient evidence for field-level changes.

Confirmed API contract failure patterns (discovered through live testing; mocks did not catch any of these):

PatternSymptom in artifactRoot cause
Access proxy auth maskingstatus: ok, empty/error summaryToken expiry → proxy returns 404 wrapped in 200
OON payload normalizationCreate succeeds, object malformedManager-side shape translation required; API expects different field structure
Alarm archive preview semanticsPreview count ≠ actual archived countMismatch between filter used in preview vs. execution
hardware_platform field assumptionField missing or wrong type on some modelsNot all hardware versions expose this field
Network alerts/IPS API version incompatibility404 or schema error on known endpointEndpoint path changed between controller firmware versions
Access CODE_UNAUTHORIZED ambiguitySame error code for expired token vs. wrong credentialsCannot distinguish root cause without inspecting response body detail

When you see a live smoke failure with no corresponding unit test failure, assume API contract mismatch first. Inspect the full summary body before looking at tool logic.

Procedure E: Extend the Harness for New Tools

When a new tool is scaffolded and registered in the server's tools_manifest.json, extend the harness as follows:

  1. Run inventory to see current classification:
    uv run python scripts/live_smoke.py --server network --phase inventory | grep unifi_new_thing
    Confirm safety_tier matches your intent. Classification is driven automatically by manifest annotations — check the tool's ToolAnnotations in the tool module.
  2. If the tool should be read_only: Ensure readOnlyHint=True is set on ToolAnnotations in the tool function. The harness will auto-include it in readonly phase. No harness edits needed.
  3. If the tool has a confirm param (preview/lifecycle): The harness auto-includes it in preview phase with confirm=False. For safe lifecycle testing (create+delete pair), add a new lifecycle method to the LiveSmokeRunner class in scripts/live_smoke.py and call it from run_lifecycles() or run_approved().

    Building preview args from live values: When constructing confirm=False preview args for a new capability tool, reuse the device-inventory cache already seeded by prior read-only list tools in the same run (device/client lists fetched earlier) to source live current values (device IDs, MACs) instead of hardcoding hardware identifiers. Hardcoded IDs go stale as soon as lab hardware changes; cached live values stay valid across runs.

    Lifecycle completeness checklist — required for every new lifecycle method:

    • Follows create → update → get → delete order (NOT create → delete only)
    • The update step asserts field preservation via a subsequent get call
    • Non-default fields are tested with explicit targeted values (not just defaults)
    • The lifecycle method lands in the harness permanently, not a throwaway script

    Throwaway vs. permanent: One-off validation scripts (for enum-hint PRs, new optional parameters, or targeted edge-case verification) belong under scripts/ and must be deleted after verification — they are NOT lifecycle methods and must NOT be committed to the harness permanently. Only full create→update→get→delete lifecycle flows should be added as permanent harness methods.

    The DNS lifecycle (lifecycle_network_dns) is the canonical reference implementation: create a record, update one field, get it back to assert the update landed, then delete. WLAN and AP-group lifecycles were extended to follow the same pattern.

  4. If the tool is risky/destructive: Add it to RISKY_OPERATION_NAMES (the set at line ~90 in scripts/live_smoke.py) or set destructiveHint=True on ToolAnnotations. This moves it to pending_approval and excludes it from automated phases.
  5. Run read-only phase first, inspect the artifact:
    uv run python scripts/live_smoke.py --server network --phase readonly
    cat live-smoke-results/network-*.json | python -m json.tool | grep -A5 unifi_new_thing
    Confirm status: "ok" and success: true and that summary has the expected shape.
  6. Advance to safe/approved phase after readonly passes cleanly.
  7. Document the tier classification in the PR description — reviewers need to know the blast-radius classification to sign off on the smoke evidence.

Procedure F: Probe Script Workflow and Image-Level Docker Smoke

Live hardware smoke catches API contract mismatches but requires real hardware access. Two additional regression layers run without hardware and catch regressions in the CI pipeline.

Probe-script layer (scripts/probe_*.py utilities):

Smaller-scope smoke scripts run against development builds without requiring full live hardware setup. These probe scripts verify:

  • Tool registration (manifest entries are syntactically valid)
  • Schema validation (schemas load and validators register)
  • Manager instantiation (DI/bootstrap sequence succeeds)
  • Tool function signatures (decorators and parameters match manifest)

Run probe scripts in any PR that touches tool registration or schema changes:

python scripts/probe_tools.py --server network
python scripts/probe_schemas.py

Probe failures are non-fatal for local development but become CI gates to catch early regressions before a full hardware run.

Image-level Docker smoke (release gate requirement):

The release build pipeline runs image-level smoke tests on generated Docker images before they're pushed to GHCR. This tests:

  • All three app servers start cleanly inside their respective images
  • All tools are discoverable in each image's tools_manifest.json
  • Basic connectivity to a mock controller (localhost loopback) succeeds

Image-level smoke does not execute tool logic (no live hardware), but it catches import errors, missing dependencies, manifest corruption, and startup failures that only appear in the final release image.

This layer lives in CI/CD pipeline (GitHub Actions), not in developer workflows. Local equivalents can be tested with:

docker build -t unifi-network:dev -f Dockerfile.network . && \
  docker run --rm unifi-network:dev python -c "from unifi_network_mcp import *; print('OK')"

Four-layer regression model:

  1. Unit/fixture layer — mock data, schema validation, bootstrap (fast, pre-commit)
  2. Probe-script layer — tool registration, manifest, schema instantiation (minutes, pre-push)
  3. Live smoke layer — API contract verification on real hardware (manual gate, code review)
  4. Image-level layer — Docker build, startup, manifest integrity (release gate, CI pipeline)

Each layer adds cost but catches distinct classes of regressions. The first three run in developer workflows; the fourth is automated in the release pipeline.

Cross-Cutting Gotchas

  • UniFi Network 429 login-lockout — stop on first 429, do not retry through it. A 429 response from the Network controller's login endpoint means the account is rate-limited or locked out. Retrying immediately produces a cascade of misleading "Not-connected" failures across every subsequent tool call in the run, obscuring the real cause. On the first 429, stop the run immediately, wait for the lockout window to clear (do not hot-loop retries), and re-run once — do not interpret the cascading failures as tool bugs.
  • Write-verification standard — mutations report WriteVerificationResult separately from mutation_applied. Lifecycle/mutation tool results classify each written field as persisted, dropped, or coerced by comparing the request payload to a follow-up get. mutation_applied (did the API accept the write) is reported as a distinct field from field-level verification (did each value actually stick) — a write can have mutation_applied: true while individual fields show dropped or coerced. Guest network purpose changes are rejected pre-mutation (validated before the write is even attempted). The harness's disabled-VLAN-only lifecycle exercises this verification path; when adding new lifecycle methods for mutating tools, follow the same persisted/dropped/ coerced classification instead of only checking mutation_applied.
  • Mock + golden fixtures are insufficient by design. Live smoke is the only mechanism that catches auth token expiry, real payload shapes, hardware-specific fields, and API version skew. Treat live smoke as a required quality gate, not optional extra validation.
  • .env is gitignored — never commit credentials. If you see UNIFI_HOST or UNIFI_PASSWORD in a diff, abort the commit immediately and rotate the credentials.
  • --server is required for all MCP-direct phases. Omitting it causes a parse error. api-actions, api-resources, and api-streams phases use a different runner and do not require --server.
  • api-actions and api-resources use curated subsets, not auto-discovery. API_ACTIONS_SAMPLE and API_RESOURCES_SAMPLE in scripts/live_smoke.py are hardcoded lists. New tools are NOT automatically included in --phase api-actions or --phase api-resources coverage: append them explicitly. Do not assume successful MCP-direct smoke implies API coverage. A read that needs a live id goes in API_ACTION_DERIVED_READS (actions) or uses an API_RESOURCE_SEEDS placeholder (resources); with nothing listed it is recorded as skipped. A seed taken from a field other than a listed item's id, or from a collection inside a detail, names it as collection.field (API_ACTION_DERIVED_SEED_KEYS, or the key in API_RESOURCE_SEEDS). A resource that is not a cursor page declares its shape (list or detail) in API_RESOURCE_SHAPES; a detail names the fields it compares with its action in API_RESOURCE_DETAIL_PARITY_FIELDS, or an empty tuple to compare field names only when every value moves between the two calls.
  • Drive is registered only with a complete local login. The API phases register a Drive controller (product_kinds: ["drive"]) when UNIFI_DRIVE_HOST, UNIFI_DRIVE_USERNAME and UNIFI_DRIVE_PASSWORD are all set, and skip every Drive entry otherwise. They exercise every Drive read plus one request-only write preview, which never reaches the NAS; no API phase applies a Drive write.
  • --phase safe exercises default args only — it is a regression detector, not full coverage. The harness calls every tool with its default argument values. New optional parameters added to existing tools are not exercised by the safe phase. After a PR that adds optional parameters, run a targeted second pass: write a short script under scripts/ that calls the tool with each new non-default value and asserts on the response shape. Delete after verification.
  • HA/shadow mode transient failures are environment issues, not code bugs. If live smoke fails with "resource temporarily unavailable," "sync in progress," or similar, verify the HA cluster has stabilized before investigating the tool. Retry after 30–60 seconds. Do not block merge on HA transient failures — note them in the PR with a re-run confirmation.
  • Credential rotation invalidates prior artifacts. If credentials changed between runs, artifacts from prior runs cannot be used as PR evidence. Re-run from scratch.
  • api-resources parity check can show a false MISMATCH from ID-key preference or the action endpoint's 100-row default. _items_id_set() (in scripts/live_smoke.py) walks ("id", "_id", "mac", "uuid") in order and uses the first key present on each item; if the resource-endpoint item and the matching action-endpoint item expose different first-matching keys, the comparison can pick non-corresponding values for what is actually the same item. Separately, most parity_args entries in API_RESOURCES_SAMPLE call the action tool with default args, and several list tools default to limit: 100 — on a site with more than 100 items, resource_subset_of_action can go false purely from action-side truncation, not a real API contract break. Before treating parity_mismatches > 0 as a bug, check the site's item count against 100 and confirm which id key populated on each side.
  • Phase scope expands with each new domain. Each new tool category must be classified and added — do not assume prior phases cover new domains.
  • tools_manifest.json is the source of truth for auto-discovery. Manifest annotation correctness (readOnlyHint, destructiveHint) and harness registration (for lifecycle methods) are both required. Wrong annotations silently misclassify tools.
  • AlarmRulesFacade fallback silently masks SuperAdmin credential failures. If the account lacks SuperAdmin on the Protect console, AlarmManagerPermissionError is caught by AlarmRulesFacade and it silently falls back to the legacy automations API. The smoke record shows status: ok — but the v2 code path was never exercised. The complete flag in the MCP _meta block distinguishes v2 success (complete: true) from legacy fallback (complete: false). When smoke-testing alarm rules, inspect the summary._meta block and confirm complete: true; a passing run with complete: false means v2 was never reached.
  • HTTP 404 from Access API-key endpoints confirms auth is working. When using API-key-authenticated Access endpoints, a 404 on a valid-format resource path means the key was accepted but the resource doesn't exist — this is a green credential signal. A 401/403 means the key was rejected. Use this to validate Access API key configuration: deliberately query a known-missing resource ID and expect 404, not 401.
  • HTTP 401 on the uiprotect bootstrap/WebSocket path during Protect smoke is expected and benign. The uiprotect library opens a WebSocket channel for real-time events using a cookie-based auth path that the MCP API key does not cover. A 401 on that WebSocket/bootstrap path does not indicate a problem with the REST API key — the REST path used by all MCP tool calls is healthy. When you see a 401 in Protect smoke output, check whether it's on the WebSocket bootstrap path before treating it as a real auth failure.
  • access_get_activity_summary CODE_SYSTEM_ERROR -3 on the Access activities histogram endpoint is a pre-existing controller issue, not a code bug. This error reproduces consistently across branches and controller firmware versions on affected controllers. It is a known upstream Access controller issue unrelated to MCP code changes. When this error appears in smoke results, treat it as an environment/controller issue: note it in the PR, re-run on a different controller if available, and do not block merge solely on this error.
  • macOS local-network privacy gate — Homebrew Python/uv gets [Errno 65] No route to host on RFC1918 addresses. macOS 15/26.x enforces a per-binary local-network entitlement. Homebrew Python, uv, and other ad-hoc-signed (non-Apple-signed) binaries are denied LAN access by the system firewall even when macOS Privacy & Security shows them as approved — the entitlement check is per binary and resets on Homebrew upgrades. Symptoms: [Errno 65] No route to host for any 192.168.x.x / 10.x.x.x connection while ping succeeds. Workaround: run the smoke harness inside Docker (docker run --rm ...) where the container inherits the LAN entitlement from Docker Desktop. Per-binary macOS approval is also possible but resets on the next brew upgrade.
  • UNIFI_NETWORK_HOST vs UNIFI_HOST — write them the same way, or give Network its own credentials. MCP-direct smoke (--server all) and the REST API phases both bootstrap the Network server with UNIFI_NETWORK_HOST when it is set, else UNIFI_HOST. Newer server releases send the shared UNIFI_USERNAME, UNIFI_PASSWORD and UNIFI_API_KEY only when the Network host names the UNIFI_HOST console as written apart from letter case, on the same port: an IP in one and a hostname in the other, a scheme, a slash or a different port cuts them, the server logs UNIFI_PASSWORD is set but not used, and the first login fails. Either set UNIFI_NETWORK_HOST exactly as UNIFI_HOST, or set UNIFI_NETWORK_USERNAME/UNIFI_NETWORK_PASSWORD (or UNIFI_NETWORK_API_KEY) too.
  • Enum-hint PRs require explicit non-default MCP tool calls — --phase safe alone is insufficient evidence. The default --phase safe run exercises every tool with its default argument values only. A PR that modifies enum hints or filter descriptions on tool arguments is never exercised by the harness defaults — the modified annotation paths are simply not invoked. Required evidence: make an explicit targeted call (e.g., via Docker Compose MCP or a short probe script) that passes the newly-documented enum value and confirms the correct filtered response. --phase safe output is necessary background but not sufficient smoke evidence for enum-hint changes.
  • Nonzero harness exit from a pre-existing unrelated tool failure — document and proceed. A live smoke run may exit nonzero because a tool unrelated to the PR's changes fails (e.g., a known upstream controller issue or pre-existing API regression). This is NOT a merge blocker for the PR's code path. Required steps: (a) identify the failing tool and confirm it fails identically on main independent of the PR; (b) confirm all tools in the PR's exercised code path show status: ok in the artifact; (c) document the pre-existing failure with the tool name and error message in the PR description. Never treat every nonzero harness exit as a merge block — only failures in the PR's exercised code path are blocking.
  • Mutation-widening PRs require safe-apply/revert smoke OR documented confirm=false preview. When a PR widens a mutation tool's accepted parameters (e.g., adding updateable fields to unifi_update_traffic_route), unit tests alone are insufficient — mocks cannot catch API-side field rejection or payload normalization failures. Required: either (a) a live smoke run that applies the mutation with confirm=True against a disposable resource, asserts the result, and reverts idempotently (net-zero), OR (b) documented deferral: run with confirm=False preview and embed the returned preview payload showing the would-be request shape in the PR evidence block. Omitting both for mutation-widening PRs is a merge blocker.
  • Bootstrap.doorlocks may be absent in newer uiprotect versions — access via getattr fallback only. The doorlocks attribute was removed from the uiprotect Bootstrap dataclass in a library upgrade. Direct attribute access (bootstrap.doorlocks) raises AttributeError at runtime on affected versions with no deprecation warning. Fix: replace all bootstrap.doorlocks accesses with getattr(bootstrap, "doorlocks", []). Live smoke against a controller running an upgraded uiprotect surfaces this as an exception status in Protect smoke records; mock-based unit tests and golden fixtures cannot catch it.
  • Singleton config resources use an apply → verify → revert lifecycle, not create → delete. Some device/config tools have no create or delete counterpart — they mutate one existing singleton resource. For these, model the lifecycle method as: read current state, apply the new value, verify via a follow-up get, then revert to the original captured value. Do not force a create/delete pair onto singleton-shaped tools.
  • access_update_device_config has no confirm/preview argument — it does not get the Stage 1 preview safety net. Because the harness's preview gate only applies to tools with a confirm param, this tool is not automatically protected by Procedure C. Treat it as mutating_requires_review: verify its classification manually and require explicit human review of arguments before any live call, since there is no preview payload to inspect first.
  • Lab hardware strategy: production controllers are discovery/read-only only — mutation testing uses a dedicated Gateway Ultra. Never run safe/approved-phase mutations against a production controller. Point mutation-phase runs at a dedicated lab Gateway Ultra (or equivalent disposable hardware) reserved for this purpose; reserve production hardware for readonly/inventory discovery passes only.
  • --server all is unsafe as evidence that an installed wheel (not repo source) is under test. --server all invokes uv run --package per app, which resolves the repo workspace and can silently substitute the published wheel with local source. To verify a published-package version is actually what's running, invoke --server network / --server protect / --server access separately using the isolated env's Python, and assert both importlib.metadata.version(...) and the module's __file__ path resolve under site-packages (not the repo checkout). Also run uv pip install --refresh first — a freshly published PyPI version can be absent from cached index metadata, so a stale cache silently keeps resolving the prior version.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.