melodee icon indicating copy to clipboard operation
melodee copied to clipboard

Add Remote Server Mode via Melodee REST API (No Remote Execution)

Open sphildreth opened this issue 10 months ago • 0 comments

Background

Today, mcli runs commands locally against a Melodee installation using local configuration and local services.

Operators need the ability to run mcli against a remote Melodee server (for example https://demo.melodee.org) from any workstation.

User Story

As a Melodee server operator/admin, I want mcli to support a --server option that targets a remote Melodee server over HTTPS using the existing REST API, so I can query and administer the server from any machine.

Non-Goals / Out of Scope

  • No server-side "execute CLI command" endpoints.
  • No SSH-based command execution.
  • No requirement to have access to the server filesystem.
  • No new authentication scheme: Remote mode uses the existing API key model.

Definitions

  • Remote Server Mode: mcli operates as an HTTP client to https://<host>/api/v1/* endpoints.
  • Local Mode: existing behavior; mcli runs against local configuration/services.
  • API Token: user API key that is sent as Authorization: Bearer <token>.

Functional Requirements

FR1 — Remote Mode Selection

  • If --server is supplied, mcli MUST operate in Remote Server Mode.
  • If --server is not supplied, mcli MUST operate in Local Mode (unchanged existing behavior).

FR2 — Global Options

Add the following global options:

  • --server <baseUrl> (example: https://demo.melodee.org)
  • --token <apiToken> (GUID/token string; passed as Bearer token)
  • --profile <name> (optional; loads server/token defaults from config)

FR3 — Environment Variable Support

Support environment variables as an alternative to command line flags:

  • MELODEE_SERVER
  • MELODEE_TOKEN
  • MELODEE_PROFILE

FR4 — Configuration File (Profiles)

Implement a config file that can store one or more named profiles.

Config file location:

  • Linux/macOS: ~/.config/melodee/mcli.json
  • Windows: %APPDATA%\\melodee\\mcli.json

Config schema (exact JSON keys):

{
  "profiles": {
    "demo": {
      "server": "https://demo.melodee.org",
      "token": "<token here>"
    },
    "prod": {
      "server": "https://melodee.example.com",
      "token": "<token here>"
    }
  },
  "defaults": {
    "profile": "demo"
  }
}

FR5 — Precedence Rules

Remote mode options MUST be resolved in this order (highest wins):

  1. Command line flags (--server, --token, --profile)
  2. Environment variables (MELODEE_SERVER, MELODEE_TOKEN, MELODEE_PROFILE)
  3. Config file profile (defaults.profile, then profile section)

FR6 — Token Safety

  • mcli MUST NOT print tokens to stdout/stderr.
  • For any command that echoes configuration (e.g., mcli config show), tokens MUST be masked like: ********-****-****-****-************.
  • When --token is provided on the command line, the tool MUST print a one-time warning:
    • WARNING: Passing tokens on the command line can leak secrets via shell history. Prefer MELODEE_TOKEN or config profiles.

FR7 — Base URL Normalization

  • --server may be passed with or without trailing /.
  • mcli MUST normalize base URLs such that API calls use:
    • <server>/api/v1/... Examples:
  • https://demo.melodee.org -> https://demo.melodee.org/api/v1/...
  • https://demo.melodee.org/ -> https://demo.melodee.org/api/v1/...

FR8 — HTTP Authentication

In Remote Server Mode, every request MUST include:

  • Header: Authorization: Bearer <token>
  • Header: Accept: application/json

If no token is available after applying precedence rules, mcli MUST fail with exit code 2 and message:

  • ERROR: Missing API token. Provide --token, MELODEE_TOKEN, or a config profile token.

FR9 — HTTP Client Defaults

mcli Remote Server Mode MUST use these HttpClient settings:

  • Timeout: 30 seconds
  • User-Agent: mcli/<version>
  • Automatic decompression: enabled if supported by platform
  • TLS: use platform defaults (do not weaken certificate validation)

FR10 — Error Handling (Remote)

Remote mode MUST map errors to deterministic exit codes and user-friendly messages.

Exit codes:

  • 0 success
  • 2 usage/config error (missing server/token/profile)
  • 10 network/connectivity error (DNS, refused connection, TLS handshake)
  • 11 timeout
  • 12 unauthorized/forbidden (HTTP 401/403)
  • 13 not found (HTTP 404)
  • 14 server error (HTTP 5xx)
  • 15 unexpected/serialization error

Output rules:

  • stdout: command results only
  • stderr: errors, warnings, diagnostics
  • include HTTP status code and short reason phrase for non-2xx

Examples:

  • ERROR (401 Unauthorized): API token invalid or expired.
  • ERROR (403 Forbidden): Token does not have permission to perform this action.
  • ERROR (404 Not Found): Endpoint not available on server version 1.7.4.

FR11 — Minimal Remote Commands (MVP)

The following commands MUST work in Remote Server Mode using REST API calls:

  1. mcli system info
  • Calls: GET /api/v1/system/info
  • Prints the JSON response as-is (pretty printed if --json is not specified; see FR12).
  1. mcli user me
  • Calls: GET /api/v1/user/me
  • Prints the JSON response as-is.
  1. mcli search <query>
  • Calls: POST /api/v1/search OR existing search endpoint used by UI (use the server OpenAPI if already defined).
  • Accepts --limit <n> default 25.

NOTE: If mcli already has local equivalents for these commands, remote mode MUST match existing CLI output shape as closely as possible.

FR12 — Output Formatting

Add a global output option:

  • --json (default false)

Rules:

  • If --json is true, output MUST be compact JSON on stdout.
  • If --json is false, output MUST be pretty printed JSON (indent 2 spaces) for JSON responses.

FR13 — Admin Command: user list

Remote mode MUST support:

  • mcli user list

If the server does not currently expose a users listing API, implement a new Admin API (see FR14).

FR14 — Admin API: List Users Endpoint

Add the following endpoint to Melodee API:

  • Method: GET
  • Route: /api/v1/admin/users
  • Auth: required
  • Authorization: MUST require "admin" privileges (use your existing role/claim system)
  • Response: JSON array of users with minimal safe fields

Response DTO (exact fields):

[
  {
    "id": "<guid>",
    "username": "<string>",
    "email": "<string|null>",
    "isAdmin": true,
    "isEnabled": true,
    "createdAt": "<iso8601>",
    "lastLoginAt": "<iso8601|null>"
  }
]

Security rules:

  • Do NOT return password hashes, salts, tokens, refresh tokens, or any secret material.
  • For non-admin tokens, return 403 Forbidden.

FR15 — mcli Mapping for Admin Users

In Remote Server Mode, mcli user list MUST:

  • Call GET /api/v1/admin/users
  • Print the JSON response (obeying --json)

FR16 — Backwards Compatibility

  • Existing Local Mode behavior MUST remain unchanged.
  • Existing command syntax MUST remain valid.
  • Remote mode MUST not require any new dependencies in the server beyond the Admin endpoint in FR14.

Implementation Requirements (No Decisions Left to Agent)

IR1 — Abstraction Layer

Introduce a single interface used by commands:

  • IMelodeeClient
    • Task<SystemInfoDto> GetSystemInfoAsync(CancellationToken ct)
    • Task<UserMeDto> GetCurrentUserAsync(CancellationToken ct)
    • Task<IReadOnlyList<AdminUserDto>> GetAdminUsersAsync(CancellationToken ct)
    • Task<SearchResultsDto> SearchAsync(SearchRequestDto request, CancellationToken ct)

Provide two implementations:

  • LocalMelodeeClient (wrap existing local services)
  • RemoteMelodeeClient (HttpClient to REST API)

IR2 — Client Selection

At startup, resolve mode:

  • If --server resolved -> instantiate RemoteMelodeeClient
  • Else -> instantiate LocalMelodeeClient

IR3 — Remote Client Construction

RemoteMelodeeClient MUST:

  • Accept normalized baseUrl (FR7)
  • Accept token (FR8)
  • Use a single HttpClient instance
  • Set default headers once in constructor
  • Use System.Text.Json for serialization
  • Use JsonSerializerOptions with:
    • PropertyNameCaseInsensitive = true
    • WriteIndented = !--json

IR4 — OpenAPI Alignment

If the server exposes /openapi/v1.json, the endpoint paths and DTO field names MUST match the spec. If there is a mismatch, update the spec and server DTOs to match the exact routes/fields listed in this story.

IR5 — Unit and Integration Tests

Implement the following tests:

mcli unit tests

  • Resolving precedence order (FR5)
  • Base URL normalization (FR7)
  • Token masking (FR6)
  • Exit code mapping (FR10)

Server integration tests (API)

  • /api/v1/admin/users returns 401 without token
  • /api/v1/admin/users returns 403 with non-admin token
  • /api/v1/admin/users returns 200 for admin token
  • Response does not include any sensitive fields

IR6 — Documentation Updates

Update CLI docs (README or docs site):

  • Remote mode usage examples
  • Env var usage
  • Profile config file location and schema
  • Security warning about command-line token usage

Acceptance Criteria

AC1 — Remote system info works

Command:

mcli --server https://demo.melodee.org --token <token> system info

Expected:

  • exits 0
  • prints server system info JSON

AC2 — Remote current user works

Command:

mcli --server https://demo.melodee.org --token <token> user me

Expected:

  • exits 0
  • prints current user JSON

AC3 — Remote admin user listing works

Command:

mcli --server https://demo.melodee.org --token <admin-token> user list

Expected:

  • exits 0
  • prints JSON array of users

AC4 — Missing token fails with correct exit code

Command:

mcli --server https://demo.melodee.org user list

Expected:

  • exits 2
  • prints ERROR: Missing API token... to stderr

AC5 — Unauthorized token fails cleanly

Command:

mcli --server https://demo.melodee.org --token <bad-token> system info

Expected:

  • exits 12
  • stderr contains 401 Unauthorized

AC6 — Local mode unchanged

Command:

mcli system info

Expected:

  • behaves exactly as before this change

Deliverables

  • mcli updated with Remote Server Mode support (FR1-FR13)
  • Server updated with /api/v1/admin/users endpoint (FR14)
  • Tests implemented and passing (IR5)
  • Documentation updated (IR6)

sphildreth avatar Jan 10 '26 15:01 sphildreth