From 1dd2292383df1cb46e2a061040f43c160a75a4c9 Mon Sep 17 00:00:00 2001 From: b3nw Date: Tue, 11 Aug 2026 21:11:05 -0400 Subject: [PATCH] feat: multi-instance NPM configuration (#13) * feat: multi-instance NPM configuration Adds NPM_INSTANCES env var (JSON map) to manage multiple NPM servers from a single MCP instance. Every tool gains an optional 'instance' parameter. Legacy single-instance config (NPM_API_URL/IDENTITY/SECRET) still works unchanged. Includes list_instances tool, per-instance proxy_defaults and log_dir, and full backward compatibility. * fix(config): add explicit type validation for NPM_INSTANCES fields * fix(multi-instance): fix cross-instance log leakage and order-dependent default selection * chore(multi-instance): document NPM_DEFAULT_INSTANCE and harden logs fallback logic against cross-instance leakage --------- Co-authored-by: b3nw <189466+b3nw@users.noreply.github.com> --- README.md | 16 ++ env.example | 5 + src/npm_mcp/config.py | 154 ++++++++++++++-- src/npm_mcp/logs.py | 48 +++-- src/npm_mcp/server.py | 348 +++++++++++++++-------------------- tests/test_logs.py | 4 +- tests/test_multi_instance.py | 132 +++++++++++++ 7 files changed, 461 insertions(+), 246 deletions(-) create mode 100644 tests/test_multi_instance.py diff --git a/README.md b/README.md index 66773c3..90ae897 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ NPM_PROXY_DEFAULTS='{"certificate_id": 24, "ssl_forced": true}' | `NPM_MCP_AUTH_TOKEN` | No | - | Bearer token required for HTTP transport clients | | `NPM_LOG_DIR` | No | - | Path to mounted NPM log directory (enables `get_proxy_host_logs`) | | `NPM_PROXY_DEFAULTS` | No | `{}` | JSON defaults for `create_proxy_host` | +| `NPM_INSTANCES` | No | - | JSON map of named NPM instances for multi-instance mode (see below) | +| `NPM_DEFAULT_INSTANCE` | No | - | Name of the default instance for unnamed tool calls (defaults to the first instance in `NPM_INSTANCES`) | ### NPM_PROXY_DEFAULTS Keys @@ -87,6 +89,20 @@ NPM_PROXY_DEFAULTS='{"certificate_id": 24, "ssl_forced": true, "block_exploits": | `access_list_id` | int | `0` | Access list ID (use `list_access_lists` to find) | | `advanced_config` | string | `""` | Custom nginx configuration block | +### Multi-Instance Mode + +Manage multiple NPM servers from a single MCP instance by setting `NPM_INSTANCES`: + +```bash +NPM_INSTANCES='{"prod":{"api_url":"http://npm-prod:81/api","identity":"admin@prod.com","secret":"x","log_dir":"/data/prod-logs"},"staging":{"api_url":"http://npm-staging:81/api","identity":"admin@staging.com","secret":"y"}}' +``` + +Each instance object supports: `api_url` (required), `identity` (required), `secret` (required), `log_dir` (optional), `proxy_defaults` (optional). + +When `NPM_INSTANCES` is set, single-instance settings (`NPM_API_URL`, `NPM_IDENTITY`, `NPM_SECRET`) are ignored. Every tool gains an optional `instance` parameter - omit it to target the explicit `NPM_DEFAULT_INSTANCE` (or the first configured instance in `NPM_INSTANCES` if unset). + +Use the `list_instances` tool to see all available instances. + ## Usage ### Stdio Mode (for Claude Desktop, etc.) diff --git a/env.example b/env.example index 120f878..4ddcd69 100644 --- a/env.example +++ b/env.example @@ -1,8 +1,13 @@ # NPM MCP Configuration +# --- Single instance mode (default) --- NPM_API_URL=http://localhost:81/api NPM_IDENTITY=admin@example.com NPM_SECRET=changeme +# --- Multi-instance mode (overrides single instance settings above) --- +# NPM_INSTANCES='{"prod":{"api_url":"http://npm-prod:81/api","identity":"admin@example.com","secret":"x"},"staging":{"api_url":"http://npm-staging:81/api","identity":"admin@example.com","secret":"y"}}' +# NPM_DEFAULT_INSTANCE=prod + # Server Configuration NPM_MCP_HOST=0.0.0.0 NPM_MCP_PORT=8000 diff --git a/src/npm_mcp/config.py b/src/npm_mcp/config.py index 1e3dc2e..6729b31 100644 --- a/src/npm_mcp/config.py +++ b/src/npm_mcp/config.py @@ -1,11 +1,11 @@ """Configuration management using pydantic-settings.""" +import json as _json from typing import Any -from pydantic import field_validator +from pydantic import field_validator, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict -# Default values for proxy host creation DEFAULT_PROXY_SETTINGS: dict[str, Any] = { "forward_scheme": "http", "certificate_id": 0, @@ -22,6 +22,33 @@ DEFAULT_PROXY_SETTINGS: dict[str, Any] = { } +class NpmInstance: + """Connection details for a single NPM instance.""" + + __slots__ = ("name", "api_url", "identity", "secret", "log_dir", "proxy_defaults") + + def __init__( + self, + name: str, + api_url: str, + identity: str, + secret: str, + log_dir: str = "", + proxy_defaults: dict[str, Any] | None = None, + ): + self.name = name + self.api_url = api_url.rstrip("/") + self.identity = identity + self.secret = secret + self.log_dir = log_dir + self.proxy_defaults = proxy_defaults or {} + + def get_proxy_defaults(self) -> dict[str, Any]: + merged = DEFAULT_PROXY_SETTINGS.copy() + merged.update(self.proxy_defaults) + return merged + + class Settings(BaseSettings): """Application settings loaded from environment variables.""" @@ -30,51 +57,144 @@ class Settings(BaseSettings): env_file=".env", env_file_encoding="utf-8", extra="ignore", + arbitrary_types_allowed=True, ) - # NPM API Configuration api_url: str = "http://localhost:81/api" identity: str = "" secret: str = "" - - # MCP Server Configuration mcp_host: str = "0.0.0.0" mcp_port: int = 8000 - mcp_transport: str = "stdio" # "stdio" or "http" + mcp_transport: str = "stdio" # Runtime guard for destructive/write operations mcp_enable_destructive_tools: bool = False # Optional bearer token for authenticating MCP clients over HTTP mcp_auth_token: str = "" - - # Path to NPM log directory (mount NPM's /data/logs here) log_dir: str = "" - - # Proxy host creation defaults (JSON string) - # Example: '{"certificate_id": 24, "ssl_forced": true}' proxy_defaults: dict[str, Any] = {} + instances: dict[str, dict[str, Any]] = {} + default_instance: str | None = None + + # Private attrs — runtime cache, not pydantic fields + _instances_parsed: dict[str, NpmInstance] = {} + _default_instance_name: str = "" @field_validator("proxy_defaults", mode="before") @classmethod def parse_proxy_defaults(cls, v: Any) -> dict[str, Any]: - """Parse JSON string to dict, or pass through if already dict.""" if isinstance(v, dict): return v if isinstance(v, str) and v.strip(): - import json - try: - return json.loads(v) - except json.JSONDecodeError as e: + return _json.loads(v) + except _json.JSONDecodeError as e: raise ValueError(f"Invalid JSON in NPM_PROXY_DEFAULTS: {e}") from e return {} + @field_validator("instances", mode="before") + @classmethod + def parse_instances(cls, v: Any) -> dict[str, dict[str, Any]]: + if isinstance(v, dict): + return v + if isinstance(v, str) and v.strip(): + try: + return _json.loads(v) + except _json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in NPM_INSTANCES: {e}") from e + return {} + + @model_validator(mode="after") + def build_instances(self) -> "Settings": + parsed: dict[str, NpmInstance] = {} + if self.instances: + for name, cfg in self.instances.items(): + if not isinstance(cfg, dict): + raise ValueError( + f"NPM_INSTANCES['{name}'] must be an object, " + f"got {type(cfg).__name__}" + ) + missing = [ + k for k in ("api_url", "identity", "secret") if not cfg.get(k) + ] + if missing: + raise ValueError( + f"NPM_INSTANCES['{name}'] missing required field(s): " + f"{missing}" + ) + for field in ("api_url", "identity", "secret"): + val = cfg[field] + if not isinstance(val, str): + raise ValueError( + f"NPM_INSTANCES['{name}']['{field}'] must be a string, " + f"got {type(val).__name__}" + ) + log_dir = cfg.get("log_dir", "") + if not isinstance(log_dir, str): + raise ValueError( + f"NPM_INSTANCES['{name}']['log_dir'] must be a string, " + f"got {type(log_dir).__name__}" + ) + proxy_defaults = cfg.get("proxy_defaults", {}) + if not isinstance(proxy_defaults, dict): + raise ValueError( + f"NPM_INSTANCES['{name}']['proxy_defaults'] must be an object, " + f"got {type(proxy_defaults).__name__}" + ) + parsed[name] = NpmInstance( + name=name, + api_url=cfg["api_url"], + identity=cfg["identity"], + secret=cfg["secret"], + log_dir=log_dir, + proxy_defaults=proxy_defaults, + ) + if self.default_instance: + if self.default_instance not in parsed: + available = ", ".join(parsed) + raise ValueError( + f"NPM_DEFAULT_INSTANCE '{self.default_instance}' is not in configured instances. " + f"Available: {available}" + ) + self._default_instance_name = self.default_instance + else: + self._default_instance_name = next(iter(parsed)) + elif self.identity and self.secret: + parsed["default"] = NpmInstance( + name="default", + api_url=self.api_url, + identity=self.identity, + secret=self.secret, + log_dir=self.log_dir, + proxy_defaults=self.proxy_defaults, + ) + self._default_instance_name = "default" + self._instances_parsed = parsed + return self + def get_proxy_defaults(self) -> dict[str, Any]: - """Get merged proxy defaults (base defaults + user overrides).""" merged = DEFAULT_PROXY_SETTINGS.copy() merged.update(self.proxy_defaults) return merged + def get_instance(self, name: str | None = None) -> NpmInstance: + if not self._instances_parsed: + raise ValueError( + "No NPM instances configured. Set NPM_IDENTITY/NPM_SECRET or NPM_INSTANCES." + ) + key = name or self._default_instance_name + if key not in self._instances_parsed: + available = ", ".join(self._instances_parsed) + raise ValueError(f"Unknown instance '{key}'. Available: {available}") + return self._instances_parsed[key] + + @property + def default_instance_name(self) -> str: + return self._default_instance_name + + def list_instances(self) -> list[str]: + return list(self._instances_parsed.keys()) + settings = Settings() diff --git a/src/npm_mcp/logs.py b/src/npm_mcp/logs.py index 2d09764..015059f 100644 --- a/src/npm_mcp/logs.py +++ b/src/npm_mcp/logs.py @@ -14,25 +14,26 @@ MAX_LINES = 500 MAX_FILE_SIZE = 50 * 1024 * 1024 # 50 MB safety cap -def _get_log_dir() -> Path: +def _get_log_dir(log_dir: str | None = None) -> Path: """Resolve and validate the configured log directory.""" - log_dir = settings.log_dir - if not log_dir: + # Prevent falling back to global settings.log_dir when multi-instance mode is active. + d = log_dir if settings.instances else (log_dir or settings.log_dir) + if not d: raise NpmLogError( - "NPM_LOG_DIR is not configured. Mount NPM's /data/logs volume " - "and set NPM_LOG_DIR to the mount path. See README for details." + "Log directory is not configured. Mount NPM's /data/logs volume " + "and set NPM_LOG_DIR (or instance log_dir). See README for details." ) - path = Path(log_dir) + path = Path(d) if not path.is_dir(): - raise NpmLogError(f"Log directory does not exist: {log_dir}") + raise NpmLogError(f"Log directory does not exist: {d}") return path -def _log_file_path(host_id: int, log_type: str) -> Path: +def _log_file_path(host_id: int, log_type: str, log_dir: str | None = None) -> Path: if log_type not in ("access", "error"): raise NpmLogError(f"Invalid log type: {log_type!r} (must be 'access' or 'error')") - log_dir = _get_log_dir() - return log_dir / f"proxy-host-{host_id}_{log_type}.log" + d = _get_log_dir(log_dir) + return d / f"proxy-host-{host_id}_{log_type}.log" def read_log_lines( @@ -40,6 +41,7 @@ def read_log_lines( log_type: str = "access", lines: int = 100, search: str | None = None, + log_dir: str | None = None, ) -> dict: """Read the last N lines from a proxy host log file. @@ -48,12 +50,10 @@ def read_log_lines( log_type: "access" or "error". lines: Number of most recent lines to return (capped at MAX_LINES). search: Optional substring filter applied to each line. - - Returns: - Dict with host_id, log_type, file name, line count, and the lines themselves. + log_dir: Override log directory (for multi-instance support). """ lines = max(1, min(lines, MAX_LINES)) - log_path = _log_file_path(host_id, log_type) + log_path = _log_file_path(host_id, log_type, log_dir) if not log_path.is_file(): raise NpmLogError( @@ -89,22 +89,20 @@ def read_log_lines( } -def is_log_dir_configured() -> bool: +def is_log_dir_configured(log_dir: str | None = None) -> bool: """Check whether the log directory is configured and accessible.""" - if not settings.log_dir: + # Prevent falling back to global settings.log_dir when multi-instance mode is active. + d = log_dir if settings.instances else (log_dir or settings.log_dir) + if not d: return False - return Path(settings.log_dir).is_dir() + return Path(d).is_dir() -def list_available_logs() -> list[dict]: - """List all proxy-host log files present in the log directory. - - Returns: - List of dicts with host_id, log_type, file name, and size. - """ - log_dir = _get_log_dir() +def list_available_logs(log_dir: str | None = None) -> list[dict]: + """List all proxy-host log files present in the log directory.""" + d = _get_log_dir(log_dir) results = [] - for entry in sorted(log_dir.iterdir()): + for entry in sorted(d.iterdir()): match = LOG_FILE_PATTERN.match(entry.name) if match and entry.is_file(): results.append( diff --git a/src/npm_mcp/server.py b/src/npm_mcp/server.py index 1ad7346..1db0cb9 100644 --- a/src/npm_mcp/server.py +++ b/src/npm_mcp/server.py @@ -8,40 +8,51 @@ from typing import Any from mcp.server.fastmcp import FastMCP from .client import NpmClient -from .config import settings +from .config import NpmInstance, settings from .exceptions import NpmApiError, NpmAuthenticationError, NpmConnectionError, NpmLogError from .logs import is_log_dir_configured, list_available_logs, read_log_lines logger = logging.getLogger(__name__) -# Create global client instance (lazy initialization) -_client: NpmClient | None = None +_clients: dict[str, NpmClient] = {} -def get_client() -> NpmClient: - """Get or create the NPM client instance.""" - global _client - if _client is None: - _client = NpmClient() - return _client +def _get_client(instance: NpmInstance) -> NpmClient: + """Get or create a client for the given instance.""" + if instance.name not in _clients: + _clients[instance.name] = NpmClient( + base_url=instance.api_url, + identity=instance.identity, + secret=instance.secret, + ) + return _clients[instance.name] + + +def _resolve(instance: str | None) -> tuple[NpmClient, NpmInstance]: + """Resolve instance name to (client, instance_config). Raises ValueError for bad names.""" + inst = settings.get_instance(instance) + return _get_client(inst), inst @asynccontextmanager async def lifespan(server: FastMCP): """Manage client lifecycle.""" - global _client - _client = NpmClient() - logger.info(f"NPM MCP Server starting, connecting to {settings.api_url}") + logger.info("NPM MCP Server starting") + for name in settings.list_instances(): + inst = settings.get_instance(name) + _clients[name] = NpmClient( + base_url=inst.api_url, identity=inst.identity, secret=inst.secret + ) + logger.info(f" instance '{name}' -> {inst.api_url}") try: yield finally: - if _client: - await _client.close() - _client = None + for c in _clients.values(): + await c.close() + _clients.clear() logger.info("NPM MCP Server stopped") -# Initialize FastMCP server mcp = FastMCP( "npm-mcp", instructions="MCP server for Nginx Proxy Manager - manage reverse proxy configurations", @@ -65,7 +76,6 @@ def _check_destructive() -> str | None: def _format_error(e: Exception) -> str: - """Format exception for tool response.""" if isinstance(e, NpmAuthenticationError): return f"Authentication failed: {e}" elif isinstance(e, NpmConnectionError): @@ -83,14 +93,33 @@ def _format_error(e: Exception) -> str: @mcp.tool() -async def list_proxy_hosts() -> str: +async def list_instances() -> str: + """List all configured NPM instances. + + Returns the names of all NPM instances available to this MCP server. + Use these names with the 'instance' parameter on other tools. + """ + names = settings.list_instances() + if not names: + return "No NPM instances configured." + default = settings.default_instance_name + lines = [] + for n in names: + inst = settings.get_instance(n) + marker = " (default)" if n == default else "" + lines.append(f" {n}{marker} -> {inst.api_url}") + return f"Configured NPM instances ({len(names)}):\n" + "\n".join(lines) + + +@mcp.tool() +async def list_proxy_hosts(instance: str | None = None) -> str: """List all proxy hosts configured in Nginx Proxy Manager. - Returns a summary of all proxy hosts including their domains, - forward destinations, and SSL status. + Args: + instance: NPM instance name (omit for default) """ try: - client = get_client() + client, _ = _resolve(instance) hosts = await client.get_proxy_hosts() if not hosts: @@ -100,11 +129,11 @@ async def list_proxy_hosts() -> str: for host in hosts: domains = ", ".join(host.domain_names) ssl_status = "\U0001f512 SSL" if host.ssl_forced else "\U0001f513 HTTP" - enabled_status = "✅" if host.enabled else "❌" - + enabled_status = "\u2705" if host.enabled else "\u274c" + fwd = f"{host.forward_scheme}://{host.forward_host}:{host.forward_port}" result.append( f"{enabled_status} [{host.id}] {domains}\n" - f" → {host.forward_scheme}://{host.forward_host}:{host.forward_port} {ssl_status}" + f" \u2192 {fwd} {ssl_status}" ) return f"Found {len(hosts)} proxy host(s):\n\n" + "\n\n".join(result) @@ -114,17 +143,15 @@ async def list_proxy_hosts() -> str: @mcp.tool() -async def get_proxy_host_details(host_id: int) -> str: +async def get_proxy_host_details(host_id: int, instance: str | None = None) -> str: """Get detailed configuration for a specific proxy host. Args: host_id: The ID of the proxy host to retrieve - - Returns full configuration including SSL settings, locations, - and advanced configuration. + instance: NPM instance name (omit for default) """ try: - client = get_client() + client, _ = _resolve(instance) host = await client.get_proxy_host(host_id) details: dict[str, Any] = { @@ -156,7 +183,6 @@ async def get_proxy_host_details(host_id: int) -> str: if host.advanced_config: details["advanced_config"] = host.advanced_config - if host.locations: details["locations"] = [ { @@ -166,7 +192,6 @@ async def get_proxy_host_details(host_id: int) -> str: } for loc in host.locations ] - if host.owner: details["owner"] = host.owner.name @@ -177,40 +202,39 @@ async def get_proxy_host_details(host_id: int) -> str: @mcp.tool() -async def get_system_health() -> str: +async def get_system_health(instance: str | None = None) -> str: """Check the health and status of the Nginx Proxy Manager instance. - Returns system status, version information, and connectivity status. + Args: + instance: NPM instance name (omit for default) """ try: - client = get_client() + client, inst = _resolve(instance) status = await client.get_status() - result = [f"Status: {status.status}"] - + result = [f"Instance: {inst.name}", f"Status: {status.status}"] if status.version: result.append(f"Version: {status.version}") - # Test authentication by getting proxy hosts (lower permission requirement) try: await client._ensure_authenticated() - result.append("Authenticated: ✅") - - # Try to get settings (admin only) + result.append("Authenticated: \u2705") try: settings_list = await client.get_settings() - result.append(f"Admin access: ✅ ({len(settings_list)} settings)") + result.append(f"Admin access: \u2705 ({len(settings_list)} settings)") except NpmApiError: - result.append("Admin access: ❌ (limited permissions)") + result.append("Admin access: \u274c (limited permissions)") except NpmAuthenticationError: - result.append("Authenticated: ❌ (check credentials)") + result.append("Authenticated: \u274c (check credentials)") - if is_log_dir_configured(): - logs = list_available_logs() - result.append(f"Log directory: ✅ ({len(logs)} log files found)") + log_dir = inst.log_dir + if log_dir and is_log_dir_configured(log_dir): + logs = list_available_logs(log_dir) + result.append(f"Log directory: \u2705 ({len(logs)} log files found)") else: result.append( - "Log directory: ❌ (not configured — set NPM_LOG_DIR to enable get_proxy_host_logs)" + "Log directory: \u274c " + "(not configured \u2014 set NPM_LOG_DIR or instance log_dir)" ) return "\n".join(result) @@ -220,18 +244,19 @@ async def get_system_health() -> str: @mcp.tool() -async def search_audit_logs(limit: int = 50, offset: int = 0) -> str: +async def search_audit_logs( + limit: int = 50, offset: int = 0, instance: str | None = None +) -> str: """Search the audit log for recent actions in Nginx Proxy Manager. Args: limit: Maximum number of entries to return (default: 50, max: 100) offset: Number of entries to skip for pagination (default: 0) - - Returns recent audit log entries showing user actions and changes. + instance: NPM instance name (omit for default) """ try: - client = get_client() - limit = min(limit, 100) # Cap at 100 + client, _ = _resolve(instance) + limit = min(limit, 100) entries = await client.get_audit_log(limit=limit, offset=offset) if not entries: @@ -253,14 +278,14 @@ async def search_audit_logs(limit: int = 50, offset: int = 0) -> str: @mcp.tool() -async def list_certificates() -> str: +async def list_certificates(instance: str | None = None) -> str: """List all SSL certificates managed by Nginx Proxy Manager. - Returns a summary of all certificates including their domains, - provider, and expiration dates. + Args: + instance: NPM instance name (omit for default) """ try: - client = get_client() + client, _ = _resolve(instance) certs = await client.get_certificates() if not certs: @@ -271,11 +296,9 @@ async def list_certificates() -> str: domains = ", ".join(cert.domain_names[:3]) if len(cert.domain_names) > 3: domains += f" (+{len(cert.domain_names) - 3} more)" - expiry = "" if cert.expires_on: expiry = f" (expires: {cert.expires_on.strftime('%Y-%m-%d')})" - result.append( f"[{cert.id}] {cert.nice_name} ({cert.provider})\n Domains: {domains}{expiry}" ) @@ -287,14 +310,14 @@ async def list_certificates() -> str: @mcp.tool() -async def list_access_lists() -> str: +async def list_access_lists(instance: str | None = None) -> str: """List all access lists configured in Nginx Proxy Manager. - Returns a summary of all access lists including their IDs and names. - Use these IDs when creating proxy hosts that require access control. + Args: + instance: NPM instance name (omit for default) """ try: - client = get_client() + client, _ = _resolve(instance) access_lists = await client.get_access_lists() if not access_lists: @@ -322,72 +345,49 @@ async def create_proxy_host( allow_websocket_upgrade: bool | None = None, access_list_id: int | None = None, advanced_config: str | None = None, + instance: str | None = None, ) -> str: """Create a new proxy host in Nginx Proxy Manager. Args: domain_names: List of domain names (e.g., ["app.example.com"]) - forward_host: Backend host/IP to forward to (e.g., "10.0.0.50" or "container-name") - forward_port: Backend port to forward to (e.g., 8080) + forward_host: Backend host/IP to forward to + forward_port: Backend port to forward to forward_scheme: Backend protocol - "http" or "https" (default from config) - certificate_id: SSL certificate ID. Use list_certificates to find available certs. - Use 0 for no SSL, or the ID of a wildcard cert. (default from config) + certificate_id: SSL certificate ID (0 for none) ssl_forced: Force HTTPS redirect (default from config) block_exploits: Enable common exploit blocking (default from config) allow_websocket_upgrade: Allow WebSocket connections (default from config) - access_list_id: Access list ID for authentication. Use list_access_lists to find. - Use 0 for no access restrictions. (default from config) - advanced_config: Custom nginx configuration block (default from config) - - Returns: - Details of the created proxy host including the new host ID. - - Note: - Default values can be configured via NPM_PROXY_DEFAULTS environment variable. - Example: NPM_PROXY_DEFAULTS='{"certificate_id": 24, "ssl_forced": true}' - - Example: - create_proxy_host( - domain_names=["myapp.example.com"], - forward_host="10.0.0.50", - forward_port=3000, - certificate_id=24, # *.example.com wildcard - ) + access_list_id: Access list ID (0 for no restrictions) + advanced_config: Custom nginx configuration block + instance: NPM instance name (omit for default) """ if msg := _check_destructive(): return msg try: - # Get defaults from config, then override with provided values - defaults = settings.get_proxy_defaults() + client, inst = _resolve(instance) + defaults = inst.get_proxy_defaults() + + def _or(val, key): + return val if val is not None else defaults[key] - client = get_client() host = await client.create_proxy_host( domain_names=domain_names, forward_host=forward_host, forward_port=forward_port, - forward_scheme=forward_scheme - if forward_scheme is not None - else defaults["forward_scheme"], - certificate_id=certificate_id - if certificate_id is not None - else defaults["certificate_id"], - ssl_forced=ssl_forced if ssl_forced is not None else defaults["ssl_forced"], + forward_scheme=_or(forward_scheme, "forward_scheme"), + certificate_id=_or(certificate_id, "certificate_id"), + ssl_forced=_or(ssl_forced, "ssl_forced"), hsts_enabled=defaults.get("hsts_enabled", True), hsts_subdomains=defaults.get("hsts_subdomains", False), http2_support=defaults.get("http2_support", True), - block_exploits=block_exploits - if block_exploits is not None - else defaults["block_exploits"], + block_exploits=_or(block_exploits, "block_exploits"), caching_enabled=defaults.get("caching_enabled", False), - allow_websocket_upgrade=allow_websocket_upgrade - if allow_websocket_upgrade is not None - else defaults["allow_websocket_upgrade"], - access_list_id=access_list_id - if access_list_id is not None - else defaults["access_list_id"], - advanced_config=advanced_config - if advanced_config is not None - else defaults["advanced_config"], + allow_websocket_upgrade=_or( + allow_websocket_upgrade, "allow_websocket_upgrade" + ), + access_list_id=_or(access_list_id, "access_list_id"), + advanced_config=_or(advanced_config, "advanced_config"), meta=defaults.get("meta", {}), ) @@ -416,6 +416,7 @@ async def update_proxy_host( allow_websocket_upgrade: bool | None = None, access_list_id: int | None = None, advanced_config: str | None = None, + instance: str | None = None, ) -> str: """Update an existing proxy host in Nginx Proxy Manager. @@ -426,20 +427,18 @@ async def update_proxy_host( forward_host: Backend host/IP to forward to forward_port: Backend port to forward to forward_scheme: Backend protocol - "http" or "https" - certificate_id: SSL certificate ID (use list_certificates to find, 0 for none) + certificate_id: SSL certificate ID (0 for none) ssl_forced: Force HTTPS redirect block_exploits: Enable common exploit blocking allow_websocket_upgrade: Allow WebSocket connections access_list_id: Access list ID (0 for no restrictions) advanced_config: Custom nginx configuration block - - Returns: - Details of the updated proxy host. + instance: NPM instance name (omit for default) """ if msg := _check_destructive(): return msg try: - client = get_client() + client, _ = _resolve(instance) kwargs = {} if forward_host is not None: kwargs["forward_host"] = forward_host @@ -477,38 +476,24 @@ async def update_proxy_host( @mcp.tool() -async def delete_proxy_host(host_id: int) -> str: - """Delete a proxy host from Nginx Proxy Manager. - - Permanently removes the proxy host configuration via - DELETE /nginx/proxy-hosts/{id}. The reverse proxy stops serving the - host's domains immediately. This action cannot be undone — recreate the - host with create_proxy_host if you need it back. +async def delete_proxy_host(host_id: int, instance: str | None = None) -> str: + """Delete a proxy host from Nginx Proxy Manager. This cannot be undone. Args: - host_id: The ID of the proxy host to delete (use list_proxy_hosts to find IDs) - - Returns: - Confirmation that the proxy host was deleted. - - Example: - delete_proxy_host(42) # permanently remove proxy host 42 + host_id: The ID of the proxy host to delete + instance: NPM instance name (omit for default) """ if msg := _check_destructive(): return msg try: - client = get_client() - - # Resolve the domains first so the confirmation message is meaningful. + client, _ = _resolve(instance) domains: str | None = None try: host = await client.get_proxy_host(host_id) domains = ", ".join(host.domain_names) except Exception: - domains = None - + pass await client.delete_proxy_host(host_id) - if domains: return f"Successfully deleted proxy host [{host_id}] ({domains})." return f"Successfully deleted proxy host [{host_id}]." @@ -518,29 +503,18 @@ async def delete_proxy_host(host_id: int) -> str: @mcp.tool() -async def enable_proxy_host(host_id: int) -> str: +async def enable_proxy_host(host_id: int, instance: str | None = None) -> str: """Enable a proxy host in Nginx Proxy Manager. - Brings a previously disabled proxy host back online via - POST /nginx/proxy-hosts/{id}/enable, so the reverse proxy serves its - domains again. If the host is already enabled, NPM returns an HTTP 400 - error ("Host is already enabled"), which is surfaced as an API error. - Args: - host_id: The ID of the proxy host to enable (use list_proxy_hosts to find IDs) - - Returns: - Confirmation that the proxy host was enabled. - - Example: - enable_proxy_host(42) # bring proxy host 42 back online + host_id: The ID of the proxy host to enable + instance: NPM instance name (omit for default) """ if msg := _check_destructive(): return msg try: - client = get_client() + client, _ = _resolve(instance) await client.enable_proxy_host(host_id) - try: host = await client.get_proxy_host(host_id) domains = ", ".join(host.domain_names) @@ -553,39 +527,24 @@ async def enable_proxy_host(host_id: int) -> str: @mcp.tool() -async def disable_proxy_host(host_id: int) -> str: - """Disable a proxy host in Nginx Proxy Manager. - - Takes a proxy host offline via POST /nginx/proxy-hosts/{id}/disable - without deleting it. The reverse proxy stops serving the host's domains - until it is re-enabled with enable_proxy_host; the configuration is - preserved. If the host is already disabled, NPM returns an HTTP 400 - error ("Host is already disabled"), which is surfaced as an API error. +async def disable_proxy_host(host_id: int, instance: str | None = None) -> str: + """Disable a proxy host in Nginx Proxy Manager without deleting it. Args: - host_id: The ID of the proxy host to disable (use list_proxy_hosts to find IDs) - - Returns: - Confirmation that the proxy host was disabled. - - Example: - disable_proxy_host(42) # take proxy host 42 offline, keep its config + host_id: The ID of the proxy host to disable + instance: NPM instance name (omit for default) """ if msg := _check_destructive(): return msg try: - client = get_client() - - # Resolve domains before disabling (host stays readable while disabled). + client, _ = _resolve(instance) domains: str | None = None try: host = await client.get_proxy_host(host_id) domains = ", ".join(host.domain_names) except Exception: - domains = None - + pass await client.disable_proxy_host(host_id) - if domains: return f"Successfully disabled proxy host [{host_id}] ({domains})." return f"Successfully disabled proxy host [{host_id}]." @@ -600,44 +559,35 @@ async def get_proxy_host_logs( log_type: str = "access", lines: int = 100, search: str | None = None, + instance: str | None = None, ) -> str: """Retrieve recent nginx log entries for a specific proxy host. - Reads the raw nginx access or error log file for the given host. - Requires the NPM log directory to be mounted (see NPM_LOG_DIR config). - Args: - host_id: The ID of the proxy host (use list_proxy_hosts to find IDs) - log_type: Log type - "access" for HTTP traffic or "error" - for nginx errors (default: "access") - lines: Number of most recent lines to return - (default: 100, max: 500) - search: Optional filter string - only lines containing this - text are returned (case-insensitive) - - Returns: - The most recent log lines for the proxy host, with metadata. - - Examples: - - get_proxy_host_logs(5) — last 100 access log lines for host 5 - - get_proxy_host_logs(5, log_type="error") — recent error log - - get_proxy_host_logs(5, lines=50, search="404") — last 50 lines containing "404" - - get_proxy_host_logs(5, search="10.0.0.1") — filter by client IP + host_id: The ID of the proxy host + log_type: "access" or "error" (default: "access") + lines: Number of most recent lines (default: 100, max: 500) + search: Optional case-insensitive filter string + instance: NPM instance name (omit for default) """ try: - client = get_client() + client, inst = _resolve(instance) host = await client.get_proxy_host(host_id) domains = ", ".join(host.domain_names) + log_dir = inst.log_dir + if not log_dir: + return ( + "Log directory not configured for this instance. " + "Set log_dir in the instance config or NPM_LOG_DIR." + ) + result = read_log_lines( - host_id=host_id, - log_type=log_type, - lines=lines, - search=search, + host_id=host_id, log_type=log_type, lines=lines, search=search, log_dir=log_dir, ) header_parts = [ - f"Proxy host [{host_id}] {domains} — {log_type} log", + f"Proxy host [{host_id}] {domains} - {log_type} log", f"File: {result['file']}", ] if result["total_lines_in_file"] is not None: @@ -647,10 +597,8 @@ async def get_proxy_host_logs( header_parts.append(f"Showing last {result['returned_lines']} lines:") header = "\n".join(header_parts) - if not result["lines"]: return f"{header}\n\n(no log entries found)" - log_output = "\n".join(result["lines"]) return f"{header}\n\n{log_output}" @@ -663,6 +611,7 @@ async def create_certificate( domain_names: list[str], email: str, dns_challenge: bool = False, + instance: str | None = None, ) -> str: """Provision a new Let's Encrypt SSL certificate. @@ -670,19 +619,14 @@ async def create_certificate( domain_names: List of domain names for the certificate email: Email address for Let's Encrypt notifications dns_challenge: Use DNS challenge instead of HTTP (default: False) - - Returns: - Details of the created certificate including its ID. - Use the returned ID with create_proxy_host or update_proxy_host. + instance: NPM instance name (omit for default) """ if msg := _check_destructive(): return msg try: - client = get_client() + client, _ = _resolve(instance) cert = await client.create_certificate( - domain_names=domain_names, - email=email, - dns_challenge=dns_challenge, + domain_names=domain_names, email=email, dns_challenge=dns_challenge, ) domains = ", ".join(cert.domain_names) diff --git a/tests/test_logs.py b/tests/test_logs.py index 2c3efcc..b527894 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -104,7 +104,7 @@ class TestReadLogLines: read_log_lines(host_id=5, log_type="combined") def test_no_log_dir_configured(self, no_log_dir): - with pytest.raises(NpmLogError, match="NPM_LOG_DIR is not configured"): + with pytest.raises(NpmLogError, match="not configured"): read_log_lines(host_id=5, log_type="access") def test_nonexistent_log_dir(self, monkeypatch): @@ -142,5 +142,5 @@ class TestListAvailableLogs: assert access_5["size_bytes"] > 0 def test_not_configured(self, no_log_dir): - with pytest.raises(NpmLogError, match="NPM_LOG_DIR is not configured"): + with pytest.raises(NpmLogError, match="not configured"): list_available_logs() diff --git a/tests/test_multi_instance.py b/tests/test_multi_instance.py new file mode 100644 index 0000000..17bd3b9 --- /dev/null +++ b/tests/test_multi_instance.py @@ -0,0 +1,132 @@ +"""Tests for multi-instance configuration.""" + +import pytest + +from npm_mcp.config import Settings + + +class TestMultiInstance: + def test_single_instance_legacy(self): + """Legacy single-instance config creates a 'default' instance.""" + s = Settings(api_url="http://npm:81/api", identity="a@b", secret="x") + assert s.list_instances() == ["default"] + inst = s.get_instance() + assert inst.api_url == "http://npm:81/api" + assert inst.identity == "a@b" + + def test_multi_instance_from_dict(self): + s = Settings( + identity="ignored", secret="ignored", + instances={ + "prod": {"api_url": "http://prod:81/api", "identity": "a@b", "secret": "p"}, + "staging": {"api_url": "http://staging:81/api", "identity": "c@d", "secret": "s"}, + }, + ) + assert set(s.list_instances()) == {"prod", "staging"} + assert s.get_instance("prod").api_url == "http://prod:81/api" + assert s.get_instance("staging").identity == "c@d" + + def test_default_instance_is_first(self): + s = Settings( + identity="i", secret="s", + instances={ + "alpha": {"api_url": "http://a:81/api", "identity": "x", "secret": "y"}, + "beta": {"api_url": "http://b:81/api", "identity": "x", "secret": "y"}, + }, + ) + default = s.get_instance() + assert default.name == "alpha" + + def test_unknown_instance_raises(self): + s = Settings(identity="a", secret="b") + with pytest.raises(ValueError, match="Unknown instance"): + s.get_instance("nonexistent") + + def test_no_instances_raises(self): + s = Settings(identity="", secret="") + with pytest.raises(ValueError, match="No NPM instances configured"): + s.get_instance() + + def test_instance_proxy_defaults(self): + s = Settings( + identity="i", secret="s", + instances={ + "prod": { + "api_url": "http://p:81/api", + "identity": "x", + "secret": "y", + "proxy_defaults": {"certificate_id": 42}, + }, + }, + ) + defaults = s.get_instance("prod").get_proxy_defaults() + assert defaults["certificate_id"] == 42 + assert defaults["ssl_forced"] is True # base default preserved + + def test_instances_json_env(self, monkeypatch): + monkeypatch.setenv("NPM_IDENTITY", "x") + monkeypatch.setenv("NPM_SECRET", "y") + monkeypatch.setenv( + "NPM_INSTANCES", + '{"site1":{"api_url":"http://s1:81/api","identity":"a","secret":"b"}}', + ) + s = Settings() + assert s.list_instances() == ["site1"] + + def test_missing_required_field_raises(self): + with pytest.raises(ValueError, match="missing required field"): + Settings( + identity="i", secret="s", + instances={"bad": {"identity": "a", "secret": "b"}}, + ) + + def test_default_instance_name_property(self): + s = Settings(identity="a", secret="b") + assert s.default_instance_name == "default" + + def test_instances_invalid_types_raise(self): + # Invalid api_url type (int) + with pytest.raises(ValueError, match="must be a string"): + Settings( + identity="i", secret="s", + instances={"site1": {"api_url": 123, "identity": "a", "secret": "b"}} + ) + + # Invalid log_dir type (list) + with pytest.raises(ValueError, match="must be a string"): + Settings( + identity="i", secret="s", + instances={"site1": {"api_url": "http://npm:81/api", "identity": "a", "secret": "b", "log_dir": []}} + ) + + # Invalid proxy_defaults type (str) + with pytest.raises(ValueError, match="must be an object"): + Settings( + identity="i", secret="s", + instances={"site1": {"api_url": "http://npm:81/api", "identity": "a", "secret": "b", "proxy_defaults": "invalid"}} + ) + + def test_default_instance_selection(self): + # Explicit default instance configuration + s = Settings( + identity="i", secret="s", + default_instance="beta", + instances={ + "alpha": {"api_url": "http://a:81/api", "identity": "x", "secret": "y"}, + "beta": {"api_url": "http://b:81/api", "identity": "x", "secret": "y"}, + }, + ) + assert s.default_instance_name == "beta" + assert s.get_instance().name == "beta" + + def test_default_instance_missing_raises(self): + # Explicit default instance configured but not present in instances list + with pytest.raises(ValueError, match="is not in configured instances"): + Settings( + identity="i", secret="s", + default_instance="gamma", + instances={ + "alpha": {"api_url": "http://a:81/api", "identity": "x", "secret": "y"}, + "beta": {"api_url": "http://b:81/api", "identity": "x", "secret": "y"}, + }, + )