51 Commits
Author SHA1 Message Date
flan b3632375af Merge pull request 'Close redaction gaps + honor the poll-attempt cap' (#1) from fix/audit-redaction-poller into main
Build and Package / Build Binaries (push) Canceled after 0s
2026-07-19 16:07:34 -04:00
flan a775b23283 Close redaction gaps + honor the poll-attempt cap
Build and Package / Build Binaries (pull_request) Canceled after 0s
- redact.go: scan the interior of string values for secret-keyed
  key:value / key=value assignments, so a POSTGRES_PASSWORD embedded in a
  custom app's compose YAML (returned by get_app_config as one blob) is
  masked instead of reaching the model context. Non-secret lines and
  ordinary prose are left byte-for-byte unchanged.
- registry.go: run the raw pool.query response through RedactJSON before
  embedding it in handleQueryPools' parse-error string; handler errors are
  returned unredacted, bypassing the normal choke point.
- poller.go/types.go: honor PollerConfig.MaxPollAttempts. It was declared
  ("0 = unlimited") but never read, so it read as a safety cap that wasn't
  enforced. A task now fails once it exhausts the cap; 0 stays unlimited,
  so default behavior is unchanged.

Flips the redact_gaps compose-blob test from asserting the gap to
asserting it is closed.
2026-07-19 19:38:40 +00:00
flan 26d5eda1c7 Close the audit's findings: key leaked via the API-error path; redaction gaps
Build and Package / Build Binaries (push) Has been cancelled
An independent audit of this fork found the headline claim -- 'the API key never
reaches a log line' -- was broken on a path I had not covered.

formatAPIErrorWithContext serialized the request params into the error string, and
for auth.login_ex those params ARE the plaintext key. Not debug-gated, not
redacted. Any middleware error frame on authentication (bad key, or a reconnect
that re-authenticates and fails mid-session) put the key into log.Fatalf at startup
AND, through CallTool's error return, into the model's context and the transcript.
My redaction test only covered the debug request-log frame, which is precisely why
this survived.

Worse, the deprecated auth.login_with_api_key passes the key as a bare positional
param -- a naked string with no key name -- so key-based redaction was structurally
incapable of masking it. redactParamsForError now masks every scalar param of any
auth.* method outright, leaving maps to key-based redaction so username/mechanism
still show up in the error.

Redaction gaps also closed: env vars come back as [{name:DB_PASSWORD,value:
...}], where the secret sits under the generic key value and no key rule could
see it; bindpw/keytab/bare-key were absent from the hints (upstream's
maskCredentials only masks those at the top level, so a nested one bypassed both);
and the float64 round-trip silently corrupted 64-bit integers like ZFS guids.

-insecure was a no-op: verification was always off while the flag claimed to be
what turned it off. That undercuts the ws:// rejection entirely -- refusing
plaintext to protect the key is hollow if the wss:// connection trusts any cert.
Verification is now on by default; -insecure genuinely disables it and warns.
TrueNAS is self-signed, so -insecure is required against a stock box -- but as an
explicit choice, not a silent default.

Remaining limit is documented, not hidden: redaction is key-name-based, so a secret
inside an opaque string blob (a custom app's compose YAML) is not caught. A test
pins that behaviour so it can't be mistaken for safety.

Read-only gate audited clean: gate before dispatch, fail-closed for unknown tools,
no mutating middleware method reachable from an allowlisted tool.
2026-07-13 16:03:03 +00:00
flan 2da1d6ab51 Keep the /websocket endpoint; document why /api/current needs a rewrite
Build and Package / Build Binaries (push) Has been cancelled
I briefly switched the default endpoint to the modern /api/current, but live
testing on 25.10.4 showed it hangs: the client speaks the legacy DDP-style
protocol ({msg:connect}, {msg:method}), which /api/current (pure JSON-RPC 2.0)
does not accept. The TCP connection opens, the handshake is ignored, and the
read blocks forever with no fallback.

So /websocket is the correct path for this protocol layer, and it works on
25.10 and through Fangtooth. Moving to /api/current -- the endpoint that
survives the REST removal in TrueNAS 26 -- is a rewrite of the connect/method
framing, not a URL swap. Documented as a known issue. The port de-hardcoding
from the previous commit stands.
2026-07-12 22:58:09 +00:00
flan 7938600a7a Migrate auth to login_ex, honour explicit port, stop logging credentials
Build and Package / Build Binaries (push) Has been cancelled
Verified end-to-end against TrueNAS 25.10.4 over the br2 bridge.

auth.login_ex: auth.login_with_api_key is deprecated in TrueNAS 26 and removed
in 27. Switch to auth.login_ex (API_KEY_PLAIN), which needs the key's owning
username; add -username / TRUENAS_USERNAME, and fall back to the old call when
it is absent. API keys themselves are unaffected -- only the login method
changed.

Connection port: buildConnectionURLs discarded any port on the endpoint and
forced 443, breaking every install whose UI moved off the default (TrueNAS
ui_httpsport, or a reverse proxy holding 443 -- both true here: the UI is on
444). Honour an explicit host:port via net.SplitHostPort; default to 443 only
when none is given.

Credential logging: the client logged every request frame unconditionally --
including the auth.login_ex params, i.e. the plaintext API key -- with no
-debug guard. Thread -debug through to the client, gate all wire logging behind
it, and redact credential-shaped fields even then. A key must never reach a log
file, debug or not.

-api-key-file: read the key from a file so it stays out of argv (world-readable
via /proc) and out of the environment.

Tests cover port selection incl. IPv6 and ws:// rejection, and that the API key
is redacted from a logged auth frame while non-secret fields survive.
2026-07-12 22:19:28 +00:00
flan aaed22785b Add read-only mode and unconditional secret redaction
Build and Package / Build Binaries (push) Has been cancelled
Upstream is unsafe to point at a NAS that hosts anything of consequence:

- system_reboot is registered with an empty input schema and a handler that
  calls system.reboot immediately, so a model can take the host down in one
  unconfirmed tool call. The README's claim of dry-run on 'all write
  operations' is not accurate: dry-run is opt-in per call, and
  ExecuteWithDryRun() falls through to real execution when the argument is
  omitted.
- get_app_config returns app.config verbatim, putting database passwords,
  encryption keys and API tokens into the model's context and into any
  transcript that persists it.

-read-only is a fail-closed allowlist: 31 non-mutating tools are served, the
other 21 are refused, and anything not explicitly reviewed -- including tools
upstream adds later -- is refused by default. A denylist would silently admit
the next system_reboot. Refused tools are hidden from tools/list and rejected
at dispatch.

Redaction is unconditional, read-write mode included. A credential has no
business reaching the model, and relying on the operator to field-filter is
not a control.

Tests assert the mutating-tool list against the live registry, so an upstream
rename breaks the build instead of quietly widening the boundary.
2026-07-12 21:45:32 +00:00
Zack Welch 9acb432768 Remove release workflow, add forgejo deployment workflow 2026-07-04 11:50:28 -04:00
Zack Welch 1c2397acdd Update dependencies 2026-07-03 12:30:19 -04:00
Kris MooreandClaude Sonnet 4.6 fc9fded024 Add get_app_config and update_app tools
Enables the full read-modify-write workflow for app configuration:
- get_app_config: calls app.config to retrieve current user-specified values
- update_app: job-based call to app.update with dry_run support and
  host_path storage validation (reuses enforceHostPathStorage)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 19:46:30 -05:00
Kris MooreandClaude Sonnet 4.6 05447c5be5 Add extended reporting metrics: cputemp, uptime, disktemp, ARC, UPS
- get_system_metrics: add cputemp and uptime graph options
- get_disk_metrics: add type parameter to support disktemp in addition to disk I/O
- get_arc_metrics: new tool for ZFS ARC metrics (25 graph types including size, demand hit/miss rates, L2ARC stats)
- get_ups_metrics: new tool for UPS metrics (charge, runtime, voltage, current, frequency, load, temperature)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-20 16:15:22 -05:00
Kris MooreandClaude Sonnet 4.6 e05a49fc29 Add start_app and stop_app tools
Adds two new job-based MCP tools for controlling app lifecycle:
- start_app: starts a stopped app via app.start, 10-minute job TTL
- stop_app: stops a running app via app.stop, 5-minute job TTL

Both tools follow the upgrade_app pattern: return a task_id and job_id
for async tracking via tasks_get, and support dry_run mode to preview
the operation without executing it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-18 13:23:36 -05:00
Kris MooreandClaude Sonnet 4.6 d5861a2df6 Fix job ID parsing and WebSocket buffer overflow issues
- Handle both int and array job ID responses from app.create/upgrade/delete
- Increase WebSocket buffer sizes to 64KB to prevent buffer overflow panics
- Rewrite WebSocket client with proper concurrent request multiplexing:
  - Read loop goroutine routes responses by ID to the correct waiting caller
  - Write mutex prevents concurrent writes from corrupting WebSocket frames
  - Per-request response channels eliminate cross-delivered responses
  - Connection snapshot pattern prevents nil pointer dereferences
  - failAllPending propagates disconnect errors to all in-flight callers

Fixes: "cannot unmarshal object into int" (wrong response cross-delivered)
Fixes: "RSV1 set, bad opcode 14" (concurrent write frame corruption)
Fixes: nil pointer dereference on startup before connection established

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-17 15:06:22 -05:00
Kris MooreandClaude Sonnet 4.5 a42334fa43 Fix job ID parsing and WebSocket buffer overflow issues
This commit addresses two critical bugs:

1. Job ID Parsing: Handle both integer and array responses
   - TrueNAS API inconsistently returns job IDs as either int (123) or array ([123])
   - Updated app.create, app.delete, and app.upgrade handlers to try parsing as int first
   - If int parsing fails, parse as array and extract first element
   - Fixes: "json: cannot unmarshal array into Go value of type int" error

2. WebSocket Buffer Overflow: Increase buffer sizes to 64KB
   - Default 4KB buffers caused panic: "slice bounds out of range [:8192] with capacity 4096"
   - Set ReadBufferSize and WriteBufferSize to 65536 bytes (64KB)
   - Complements existing 10MB message limit for large API responses
   - Prevents buffer overflow when TrueNAS sends large upgrade summaries

Files modified:
- tools/apps.go: handleInstallApp and handleDeleteApp job ID parsing
- tools/registry.go: handleUpgradeApp job ID parsing
- truenas/client.go: WebSocket dialer buffer configuration

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-17 13:58:17 -05:00
Kris MooreandClaude Sonnet 4.5 3b39f46e1f Update documentation for app installation wizard and catalog features
Add comprehensive documentation for the new guided app installation wizard
and catalog search capabilities.

Changes:
- README: Update Applications section to mention catalog search and guided
  installation with storage setup
- examples.md: Add extensive examples for:
  * App catalog search and browsing
  * Guided installation workflow with multi-step wizard
  * Storage requirement planning and dataset creation
  * App management operations (delete, upgrade)
- full-features.md: Document new tools:
  * search_app_catalog - Search apps by name/category/keyword
  * get_app_catalog_details - Get app details, storage hints, and README
  * install_app - Complete wizard guidance with 8-step process
  * delete_app - Safe removal preserving data in host-path datasets

The guided installation wizard automatically:
- Queries available pools
- Plans dataset structure
- Creates missing datasets
- Validates configuration
- Tracks installation progress

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-13 21:00:19 -05:00
Kris MooreandClaude Sonnet 4.5 42b8db9d85 Enhance app installation wizard with schema optimization and error reporting
This commit introduces major improvements to the TrueNAS app installation
wizard, making it more efficient and easier to debug.

Schema Optimization (96% size reduction):
- Summarize large enums (600+ timezones) to show count + 3 examples instead of
  listing all values, reducing schema output from 158KB to ~6KB
- Preserve small enums (≤10 items) completely for full visibility
- Extract only essential fields (variable, type, required, default, min/max)
- Recursively handle nested schemas and attributes
- Add formatSchemaForWizard() and summarizeQuestion() functions

Proactive Wizard Guidance:
- Enhanced storage_workflow with explicit step-by-step instructions
- Auto-query available pools instead of asking user to type pool names
- Present pool options or auto-select if only one pool exists
- Clear guidance: "NEVER ask user to type pool name - always query and present"
- Updated generateWizardGuidance() with 10-step workflow (was 9)

Auto-Create Dataset Ancestors:
- Change create_ancestors default from false to true in both registry and Go code
- Automatically creates parent datasets (e.g., tank/apps, tank/apps/syncthing)
- Prevents "parent dataset does not exist" errors
- Works like mkdir -p for ZFS datasets

Generic API Error Reporting:
- Add formatAPIErrorWithContext() to include request details in all API errors
- Show method name, complete params/payload, and full trace in every error
- Format trace as readable JSON when it's an object
- Enables instant debugging without checking logs or adding debug code

Testing:
- Add comprehensive tests for schema summarization and wizard guidance
- All 27+ test suites pass
- Successfully tested with Syncthing installation on TrueNAS 31

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-13 20:58:51 -05:00
Kris MooreandClaude Sonnet 4.5 0794ddd2c9 Add directory services support for TrueNAS MCP
Implements comprehensive Active Directory, LDAP, and FreeIPA integration:
- 7 new tools: status, query, configure, leave, refresh cache, list certificates
- Integration with system_health for automatic DS status monitoring
- Share creation tools now show directory service warnings
- Full credential masking for security (passwords/keytabs)
- Dry-run support for all write operations with safety warnings
- Task tracking for long-running join/leave operations

Uses unified directoryservices.* API methods for all operations.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 13:48:37 -05:00
Kris MooreandClaude Sonnet 4.5 92aff4cf84 Simplify README documentation
Remove full WebSocket URL configuration options:
- Remove Option 2 (full WebSocket URL) from Claude Desktop config
- Remove "Add with full WebSocket URL" from Claude Code section
- Simplify --truenas-url flag description to only mention hostname
- Remove full WebSocket URL example from command-line examples

Remove Limitations section:
- Remove "Pool Capacity Historical Data" limitations section
- Remove from table of contents

These changes simplify the documentation by focusing on the recommended
hostname-based configuration approach and removing API limitation details
that are better tracked in issue trackers or release notes.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 11:11:33 -05:00
Kris MooreandClaude Sonnet 4.5 40e346e58e Refactor README.md for improved navigation
- Create docs/full-features.md with complete feature documentation
- Create docs/examples.md with all example queries organized by category
- Condense README features section to brief overview with link
- Condense README examples section to quick start with link
- Remove verbose "Storage Maintenance Best Practices" section
- Remove "Next Steps" section
- Reduce README from 817 to 431 lines for easier navigation

This improves maintainability and makes it easier for users to find
information without overwhelming the main README.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 11:05:52 -05:00
Kris MooreandClaude Sonnet 4.5 77b0c8c9ca Add boot environment cleanup guidance to apply_update tool
Enhance apply_update tool description to include best practice
guidance for post-update maintenance:

- Recommends checking boot environments after successful update
- Suggests using query_boot_environments to identify old versions
- Advises keeping 2-3 recent boot environments for rollback safety
- Provides clear workflow: update → reboot → check → prune

This helps LLM proactively suggest boot environment cleanup after
system updates, preventing storage bloat from accumulated boot
environments over time.

Validated workflow:
- Updated truenas31 from 20260209 to 20260210 build
- Checked boot environments (5 found, 19.75 GiB total)
- Deleted 2 old environments (freed 7.33 GiB)
- Kept current, previous, and stable release (12.42 GiB)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 10:58:45 -05:00
Kris MooreandClaude Sonnet 4.5 941cc6565c Add ZFS pool scrub management tools for TrueNAS MCP
Implements comprehensive scrub management capabilities:

Tools added (5):
- query_scrub_schedules: List all scrub schedules with filtering
- get_scrub_status: Aggregated status with current scrub progress
- create_scrub_schedule: Schedule automated scrubs (weekly/monthly/custom)
- run_scrub: Manually trigger scrub with task tracking
- delete_scrub_schedule: Remove scrub schedules with warnings

Features:
- Dry-run support for all write operations
- Task manager integration for run_scrub progress tracking
- Human-readable cron schedule formatting
- Next run time calculation
- Scrub duration estimation based on pool size
- Safety checks (duplicate schedules, running scrubs)
- Comprehensive error handling
- LLM guidance embedded in tool descriptions

Documentation:
- Complete tool descriptions in README
- Storage maintenance best practices section
- 11 example queries for natural language interaction
- Scheduling recommendations (home vs production)
- Performance impact details

Implementation:
- tools/scrub_handlers.go: 1056 lines (handlers, dry-run, helpers)
- tools/scrub_test.go: 221 lines (unit tests, all passing)
- tools/registry.go: +153 lines (tool registrations)
- README.md: +116 lines (documentation)

Fixed API call formatting:
- Removed extra array nesting in query filters
- Corrected pool.query, pool.scrub.query, and core.get_jobs calls
- Validated against TrueNAS 26.04 API documentation

Testing:
- All unit tests pass
- Validated on live TrueNAS 31 system
- Successfully started scrub and verified task tracking

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 17:01:45 -05:00
Kris MooreandClaude Sonnet 4.5 f305d7b52b Fix boot environment deletion API parameter format
The boot.environment.destroy API expects parameters as a map/object
rather than a bare string. Updated the delete handler to pass the ID
as {"id": "name"} format, which resolves the "API error (code 0)" when
attempting to delete boot environments.

Tested successfully: deletion now works and correctly frees space.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 16:10:12 -05:00
Kris MooreandClaude Sonnet 4.5 9dc782c305 Add boot environment management tools for TrueNAS
Adds three new MCP tools for managing ZFS boot environments:
- query_boot_environments: List and filter boot environments with sorting
- delete_boot_environment: Safely delete old boot environments with dry-run
- get_current_boot_environment: Quick reference for active/activated environments

Features:
- Multi-layer safety checks prevent deleting active/activated/protected environments
- Dry-run support shows warnings and space to be freed
- Filtering by name, protected status, and deletable status
- Sorting by name, creation date, or size
- Human-readable size formatting and storage summaries
- Comprehensive test suite with 4 test functions

Updates system update workflow documentation to include boot environment
cleanup as part of the recommended maintenance process.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 15:59:02 -05:00
Kris MooreandClaude Sonnet 4.5 69e2a93c38 Remove non-working environment variable examples for Claude Code
- Remove -e flag examples from Claude Code installation section
- Keep only command-line argument approach (--truenas-url, --api-key)
- Update all three examples to use args instead of env vars
- Environment variable support can be added in future update

Users reported environment variables don't work with claude mcp add.
Sticking to proven command-line argument approach for now.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 11:28:32 -05:00
Kris MooreandClaude Sonnet 4.5 724d3e25fb Add table of contents and Claude Code installation instructions
Table of Contents:
- Add comprehensive linked TOC at top of README
- Links to all major sections with proper anchor links
- Include subsections for installation steps and advanced features
- Improves navigation for long README document

Claude Code Installation:
- Add new "Claude Code" subsection under Step 3
- Document `claude mcp add` command with examples
- Show three configuration methods:
  - Environment variables (recommended)
  - Command-line arguments
  - Full WebSocket URL
- Include verification and management commands (list, get, remove)
- Update Step 4 and Step 5 to cover both Claude Desktop and Claude Code

Additional Improvements:
- Restructure Step 3 with Claude Desktop and Claude Code subsections
- Generalize Step 4/5 headers to "MCP Client" instead of just Claude Desktop
- Replace example API key with placeholder for better security
- Maintain consistent formatting throughout

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-09 10:18:04 -05:00
Kris MooreandClaude Sonnet 4.5 20d89c256f Add documentation for system update and maintenance tools
Features Section:
- Add "System update and maintenance operations" section
- Document check_updates - check for available system updates
- Document download_update - download updates with task tracking
- Document apply_update - apply updates with optional reboot
- Document update_status - monitor update progress
- Document system_reboot - reboot system after updates
- Include safety warnings for destructive operations

Example Queries:
- Add "System Updates" section with 7 example queries
- Cover checking, downloading, applying, and monitoring updates
- Include system reboot examples

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 12:40:27 -05:00
Kris MooreandClaude Sonnet 4.5 9e9bcd01b0 Add comprehensive test suite with coverage reporting
Test Suite:
- Add table-driven tests for validation functions
- tools/dataset_test.go - validateDatasetName, validateEncryptionOptions
- tools/smb_test.go - validateShareName, validateSharePath
- tools/nfs_test.go - validateCIDR, validateNFSHost
- 100% coverage on all validation functions
- 122 test cases covering valid inputs, edge cases, and error conditions

Test Infrastructure:
- Use Go table-driven test pattern for maintainability
- Clear test names describing each scenario
- Comprehensive error message validation
- Edge case coverage (empty strings, boundary values, special characters)

Coverage Reporting:
- Updated GitHub Actions workflow to generate coverage reports
- Run tests with -coverprofile and -covermode=atomic
- Upload coverage artifacts for review
- Display coverage summary in GitHub Actions output
- Add coverage files to .gitignore

Overall project coverage: 3.8% (validation functions: 100%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 12:39:07 -05:00
Kris MooreandClaude Sonnet 4.5 90d9cc0c7b Add research preview status to README
- Add prominent warning notice at top of README
- Clarify project is in active development
- Note APIs and features may change
- Advise against production use

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 12:30:45 -05:00
Kris Moore 6a112d27a8 Relicense to GPLv3 2026-02-08 12:28:43 -05:00
Kris MooreandClaude Sonnet 4.5 f19c860d82 Add GitHub Actions workflows for build and release
- Add build.yml workflow that runs on push to main
  - Runs linters and tests
  - Builds binaries for macOS ARM64, Windows AMD64, Linux AMD64
  - Uploads binaries as artifacts (30 day retention)

- Add release.yml workflow that runs on version tags (v*.*.*)
  - Builds and packages binaries (tar.gz for Unix, zip for Windows)
  - Generates SHA256 checksums
  - Creates GitHub release with attached binary packages

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 12:25:15 -05:00
Kris MooreandClaude Sonnet 4.5 313fd23549 Add NFS share creation with wizard-style guidance
Implements NFS share creation following the same pattern as SMB shares, with interactive wizard flow for Unix/Linux file sharing.

**NFS Share Creation (create_nfs_share):**
- Network/host access restrictions (CIDR notation, IP/hostname)
- User mapping for security (maproot_user/group, mapall_user/group)
- Read-only or read-write access
- Security level selection (SYS, Kerberos)
- Comprehensive validation (CIDR format, host format)
- Security warnings for unrestricted access
- Dry-run mode with security analysis
- Mount command examples

**Wizard Guidance:**
Embedded in tool description to guide LLM through:
- Dataset selection (new with share_type=NFS, acltype=POSIX)
- Access control (read-only vs read-write)
- Network/host restrictions (CIDR and hostname validation)
- User mapping recommendations (maproot_user='nobody' for security)
- Security level selection (SYS default, Kerberos optional)
- Security warnings and confirmation flow
- Best practices for NFS security

**Validation:**
- CIDR notation validation for network restrictions
- Host format validation (no quotes or spaces)
- Path validation (must start with /mnt/, child datasets only)

**Security Features:**
- Warns if no network/host restrictions (accessible from anywhere)
- Warns if no maproot_user (root clients get root access)
- Recommends maproot_user='nobody' and maproot_group='nogroup'
- Highlights read-write + unrestricted as high risk

Reuses create_dataset tool for consistent dataset creation across SMB/NFS/iSCSI protocols.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 10:09:54 -05:00
Kris Moore a33a10368d Fix SMB share wizard guidance to use proper ZFS terminology
Changed from 'existing directory' to 'existing ZFS dataset' with proper warnings:
- Query datasets first when using existing
- Never suggest pool root (e.g., tank, flash)
- Always use child datasets
- Clarified path description to show proper dataset mountpoints

This ensures users follow ZFS best practices and don't accidentally share pool roots or arbitrary directories.
2026-02-08 09:58:54 -05:00
Kris MooreandClaude Sonnet 4.5 cfe5427563 Add dataset and SMB share creation with wizard-style guidance
Implements Phase 1 & 2 of SMB share creation plan with interactive wizard flow guided by comprehensive tool descriptions. The LLM naturally walks users through configuration by following embedded guidance in tool descriptions.

**Dataset Creation (create_dataset):**
- Reusable for SMB, NFS, iSCSI, and apps
- Supports FILESYSTEM and VOLUME types
- Encryption with auto-key or passphrase
- Compression (LZ4, ZSTD, GZIP), quotas, ACLs
- Share type optimization (SMB, NFS, MULTIPROTOCOL, APPS)
- Comprehensive validation and error handling
- Dry-run mode for previewing changes

**SMB Share Creation (create_smb_share):**
- Purpose-based configuration (standard, Time Machine, multi-protocol, etc.)
- Access control (IP restrictions, read-only, browsability)
- Audit logging support
- Security warnings for public shares
- Network path generation
- Dry-run with security analysis

**Wizard Guidance:**
Embedded in tool descriptions to guide LLM through:
- Pool and dataset name selection
- Encryption recommendations
- Compression and quota configuration
- Share purpose and access control
- Security warnings and confirmation flow
- Best practices for each use case

Both tools support dry-run mode and require explicit user confirmation before write operations, with comprehensive previews showing exactly what will be created.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-08 09:48:14 -05:00
Kris MooreandClaude Sonnet 4.5 b54425a497 Add query_vms tool with filtering, sorting, and security
Enables natural language queries for virtual machines with intelligent filtering by name/state/autostart, sorting by name/memory/status, and simplified device summaries. Automatically excludes sensitive data like display passwords for security. Returns clean VM information with CPU/memory config, bootloader, devices (disks, NICs, displays), and current state.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 20:23:24 -05:00
Kris MooreandClaude Sonnet 4.5 a1dcc5e0d8 Add query_snapshots tool with filtering, sorting, and date parsing
Enables natural language queries for ZFS snapshots with intelligent filtering by dataset/pool/holds, sorting by name/dataset/created date, and automatic parsing of common snapshot naming patterns (auto-YYYY-MM-DD format). Returns simplified response with essential fields and metadata, following the same pattern as query_datasets to keep responses manageable.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 20:19:36 -05:00
Kris MooreandClaude Sonnet 4.5 a29bcd0079 Enhance query_datasets with filtering, sorting, and response simplification
- Add intelligent filtering: pool name, encryption status
- Add sorting: by space usage (default), available space, or name
- Add configurable limit (default 50) to prevent overwhelming responses
- Simplify dataset output: ~15 relevant fields instead of 40+ nested properties
- Show human-readable sizes alongside bytes for calculations
- Fix API call to pass required options parameter (was causing API errors)
- Update README with enhanced dataset query examples and capabilities

This reduces typical query responses from 75KB (138 datasets × 200 lines) to
manageable sizes while preserving all critical information for capacity
planning and space analysis queries.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 20:09:23 -05:00
Kris MooreandClaude Sonnet 4.5 6033b86ad9 Fix system_reboot to pass required reason parameter
The TrueNAS system.reboot API requires a reason parameter.
Updated the call to pass "System reboot requested via MCP" as the reason.

This fixes the issue where reboot commands were not executing.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 19:46:49 -05:00
Kris MooreandClaude Sonnet 4.5 b3d3efe6d5 Add system_reboot tool for TrueNAS reboot control
Implements system reboot functionality via MCP:

New Tool:
- system_reboot: Reboot the TrueNAS system

Features:
- Simple parameter-less reboot trigger
- Clear warnings about connection loss
- Designed for use after system updates (EREBOOTREQUIRED state)
- Enables LLM to prompt user for reboot after update completion

Usage:
After applying system updates, the LLM can detect EREBOOTREQUIRED
status and offer to reboot the system to complete the update process.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 19:35:51 -05:00
Kris MooreandClaude Sonnet 4.5 955d28b256 Add TrueNAS system update tools with task tracking
Implements comprehensive system update management for TrueNAS via MCP:

New Tools:
- check_updates: Query available TrueNAS system updates
- download_update: Download updates with graceful "already downloaded" detection
- apply_update: Apply updates with job-based task tracking
- update_status: Get current update status and progress

Features:
- Automatic detection of pre-staged updates (TrueNAS auto-downloads)
- Job-based task tracking for long-running update operations
- Dry-run support for both download and apply operations
- LLM orchestration support for multi-step update workflows
- Proper status codes (EREBOOTREQUIRED after update applied)

Testing:
- Full update workflow tested on TrueNAS 26.04.0-MASTER
- Successfully downloaded and applied updates with task tracking
- Gracefully handles already-downloaded updates
- Task polling tracked all update stages (verify, extract, migrate, etc.)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 19:33:17 -05:00
Kris MooreandClaude Sonnet 4.5 f6a162ad09 Add MCP Tasks system and dry-run pattern for long-running operations
Implements MCP Tasks specification for tracking long-running operations
like app upgrades, and adds a reusable dry-run pattern for previewing
write operations before execution.

New features:
- MCP Tasks system with background polling and automatic status updates
- tasks_list and tasks_get tools for querying task status
- upgrade_app now returns task IDs instead of raw job IDs
- Dry-run support for upgrade_app to preview changes
- Increased WebSocket read limit to handle large TrueNAS responses
- Fixed upgrade_summary parsing to handle both array and object responses
- Fixed MCP capabilities to properly advertise tool support

Architecture:
- New tasks/ package with Manager, Store, and Poller
- Reusable DryRunnable interface for write operations
- Task TTL and automatic cleanup
- Supports both job-based and status-based operations

Testing:
- Successfully upgraded 4 apps on production TrueNAS
- Task tracking verified working end-to-end
- All linters passing

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 19:06:01 -05:00
Kris MooreandClaude Sonnet 4.5 0ef7d776e5 Add capacity planning and utilization analysis tools
- Add analyze_capacity tool for comprehensive capacity analysis
  - CPU, memory, network, and disk I/O utilization trends
  - Current, average, and peak utilization percentages
  - Trend detection using linear regression
  - Conservative thresholds: 70% warning, 85% critical
  - Growth projections for increasing trends
  - Overall recommendations and status

- Add get_pool_capacity_details tool
  - Current pool and dataset capacity snapshots
  - Utilization percentages with status warnings
  - Per-dataset capacity breakdown
  - Documents API limitation: no historical pool capacity data

- Enhance system_health tool with capacity warnings
  - Automatic checks for CPU, memory, and pool capacity
  - Integrates capacity status into overall health

- Add helper functions for capacity analysis
  - Data extraction, statistical calculations
  - Linear regression for trend analysis
  - Projection calculations for growth forecasting

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 13:47:30 -05:00
Kris MooreandClaude Sonnet 4.5 7cb09154b0 Update README to reflect wss:// only security requirement
Changes:
- Architecture diagram now shows only wss:// (not ws://)
- Update port references to only mention 443 (not 80)
- Clarify that ws:// is not allowed (not just "not recommended")
- Update security section to emphasize wss:// is enforced
- Remove any suggestions that ws:// is supported

This aligns documentation with the actual implementation which
rejects ws:// connections to protect API keys from revocation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 13:56:11 -05:00
Kris MooreandClaude Sonnet 4.5 2e96f458d7 Remove unused SSE dependencies from go.mod
After removing SSE server/client code, clean up:
- github.com/r3labs/sse/v2 (no longer used)
- Related test dependencies

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 13:54:16 -05:00
Kris MooreandClaude Sonnet 4.5 6cf556bf85 Remove old two-binary architecture files
- Delete PROXY.md documentation
- Remove cmd/truenas-mcp-proxy/ directory
- Remove SSE server and client code (mcp/sse_*.go)
- Remove old proxy.go bridge code
- Update .gitignore to remove proxy binary patterns

All functionality now consolidated into single truenas-mcp binary.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 13:53:28 -05:00
Kris Moore 6b9effae32 Update .gitignore to exclude cross-platform binaries 2026-02-05 13:00:50 -05:00
Kris MooreandClaude Sonnet 4.5 0499a536be Fix app.upgrade to properly handle job ID return value
The app.upgrade API method returns a job ID (integer) since upgrading an app
is a long-running operation, but the code was trying to parse it as an object.

Changes:
- Parse result as integer job ID instead of map
- Return job ID to user so they can track upgrade progress
- Add helpful message to use query_jobs to monitor the upgrade
- Remove incorrect upgrade_result field that was causing unmarshal error

Users can now use query_jobs with the returned job ID to track the upgrade
status and see when it completes.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 12:58:37 -05:00
Kris MooreandClaude Sonnet 4.5 b0a8716760 Add automatic retry logic for connection errors
Transparently handles connection drops without exposing errors to the caller.
When a connection error occurs (broken pipe, EOF, etc.), the client now:
1. Detects it's a connection error
2. Automatically reconnects and re-authenticates
3. Retries the request
4. Only returns error if retry also fails

This eliminates the "broken pipe" errors that users were seeing after idle
connections, providing a seamless experience where reconnection happens
transparently in the background.

Connection errors handled:
- Broken pipe
- Connection reset
- EOF
- Closed network connection
- Connection refused
- I/O timeout

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 11:57:30 -05:00
Kris MooreandClaude Sonnet 4.5 9e1ee098b8 Add job monitoring capabilities to track long-running tasks
Implements query_jobs tool and enhances system_health with active jobs tracking.
This allows the AI agent to see if replication, snapshots, scrubs, or other
long-running tasks are in progress.

New features:
- query_jobs tool: Query system jobs with state filtering (RUNNING, WAITING, SUCCESS, FAILED)
- Enhanced system_health: Now includes active jobs summary and job count
- Support for all job states and configurable result limits
- Job details include: id, method, state, progress, timestamps, errors

Uses core.get_jobs API with proper query filters and options.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 11:55:49 -05:00
Kris MooreandClaude Sonnet 4.5 37a75dc39c Refactor to single-binary architecture with direct TrueNAS WebSocket connection
Major architectural change from two-binary (server + proxy) to single native
binary that runs entirely on desktop and connects directly to TrueNAS.

Key changes:
- Single binary eliminates need for TrueNAS server deployment
- Direct WebSocket connection to TrueNAS middleware over wss://
- Security: Only allow wss:// connections (TrueNAS revokes API keys over ws://)
- Self-signed certificate support enabled by default
- MCP notification support (handles notifications/initialized)
- Simplified configuration: just hostname and API key
- Cross-platform builds: macOS (ARM64/AMD64), Linux, Windows

Architecture benefits:
- No deployment to TrueNAS required
- Runs entirely on user's desktop
- Simpler setup and configuration
- Better security with mandatory encryption
- Smaller codebase (~2000 lines of SSE code removed)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-05 11:47:49 -05:00
Kris MooreandClaude Sonnet 4.5 b3ebc47885 Add app management support with query and upgrade capabilities
New read-only tool:
- query_apps: List installed applications with status, versions, and available updates
  - Shows app state, current version, upgrade availability
  - Includes web portals and active container counts
  - Optional config details retrieval

New write operation:
- upgrade_app: Upgrade applications to newer versions
  - Defaults to creating snapshots for rollback safety
  - Shows upgrade summary before proceeding
  - Supports specific version or "latest"

Also includes:
- Fix for app.query API validation (use empty array instead of null for filters)
- Updated README with new tools and categorized example usage
- Added performance metrics tools to feature list

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 12:31:17 -05:00
Kris MooreandClaude Sonnet 4.5 8daf27e85a Fix reporting metrics API calls for disk and network data
- Fix empty string vs null handling for network/disk identifiers
- Reduce response size by sampling data points (first/last 10) instead of full arrays
- Auto-discover network interfaces and disks when none specified
- Fix disk metrics by querying reporting.graphs for proper identifiers
- Use full identifier strings from reporting.graphs (e.g., "sda | Type: SSD...")

This resolves API errors when querying performance metrics and prevents
connection failures from oversized responses (122KB+ payloads).

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-04 11:29:49 -05:00