0.1.0 (Fork): Zertifikate löschen/erneuern, Domains ändern, Redirects, Streams, 404-Hosts
Build and Push Docker Image / build (push) Canceled after 0s
Tests / test (push) Canceled after 0s

- delete_certificate (Vorschau + confirm, verweigert bei Nutzung ohne force),
  renew_certificate, list_unused_certificates
- update_proxy_host: domain_names, hsts_enabled, hsts_subdomains, http2_support,
  caching_enabled; create_proxy_host: dieselben vier Schalter
- find_proxy_host (auch Umlaute/Punycode)
- Redirection-Hosts, TCP/UDP-Streams, 404-Hosts (auflisten, anlegen, löschen)
- delete_proxy_host und alle neuen Löschwerkzeuge nur mit confirm=true
- Fehler als MCP-ToolError statt Text

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michael RollandClaude Opus 5.5 committed 2026-11-23 14:49:56 +01:00
1 parent 92ad9a9f32
commit bfcf5c2e25
7 files changed
+870 -28

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Changelog
## [0.1.0] - 2026-11-23 (fork of upstream v0.0.7)
### Added
- `delete_certificate` (preview + `confirm`, refuses while in use unless `force`),
`renew_certificate`, `list_unused_certificates` (unused + expiring soon).
- `update_proxy_host`: `domain_names`, `hsts_enabled`, `hsts_subdomains`, `http2_support`,
`caching_enabled`; `create_proxy_host`: the same four flags.
- `find_proxy_host` (partial and Unicode/punycode-aware domain search).
- Redirection hosts: `list_redirection_hosts`, `create_redirection_host`, `delete_redirection_host`.
- Streams: `list_streams`, `create_stream` (port-collision check), `delete_stream`.
- 404 hosts: `list_404_hosts`, `delete_404_host`.
### Changed
- `delete_proxy_host` and all new delete tools only preview unless `confirm=true`.
- Failures are raised as MCP tool errors (`isError: true`) instead of returned as text.
+21 -1
View File
@@ -2,6 +2,13 @@
MCP server for [Nginx Proxy Manager](https://nginxproxymanager.com/) - manage your reverse proxy through AI assistants.
> **Fork:** This is a fork of [b3nw/nginx-proxy-manager-mcp](https://github.com/b3nw/nginx-proxy-manager-mcp)
> (MIT, see License) based on upstream v0.0.7. Additions: certificate housekeeping
> (find unused/expiring, delete, renew), changing domain names / HSTS / HTTP/2 / caching
> of proxy hosts, redirection hosts, TCP/UDP streams, 404 hosts, a domain search, a
> `confirm=true` preview step for every delete, and MCP tool errors (`isError`) instead of
> plain-text errors. See [CHANGELOG.md](CHANGELOG.md).
## Quick Start (Docker)
The easiest way to run the NPM MCP server - no cloning required!
@@ -156,6 +163,18 @@ Add to your `claude_desktop_config.json`:
| `enable_proxy_host` | Enable (bring online) a disabled proxy host (v0.0.4+) |
| `disable_proxy_host` | Disable (take offline) a proxy host without deleting it (v0.0.4+) |
| `create_certificate` | Provision a new Let's Encrypt SSL certificate (v0.0.3+, NPM 2.x compatible) |
| `find_proxy_host` | *(fork)* Find proxy hosts by (partial, also Unicode) domain name |
| `list_unused_certificates` | *(fork)* Certificates no host uses, and used ones expiring soon |
| `delete_certificate` | *(fork)* Delete a certificate; refuses while hosts use it unless `force=true` |
| `renew_certificate` | *(fork)* Renew a Let's Encrypt certificate now |
| `list_redirection_hosts` / `create_redirection_host` / `delete_redirection_host` | *(fork)* Domain redirects (301/302/307/308) |
| `list_streams` / `create_stream` / `delete_stream` | *(fork)* TCP/UDP port forwards |
| `list_404_hosts` / `delete_404_host` | *(fork)* 404 hosts |
*(fork)* `update_proxy_host` additionally accepts `domain_names` (full replacement list),
`hsts_enabled`, `hsts_subdomains`, `http2_support` and `caching_enabled`; `create_proxy_host`
accepts the same four flags. Every `delete_*` tool only previews unless `confirm=true`, and
all write tools still require `NPM_MCP_ENABLE_DESTRUCTIVE_TOOLS=true`.
## Managing Proxy Host Lifecycle
@@ -320,4 +339,5 @@ See [CONTRIBUTORS.md](CONTRIBUTORS.md) for the list of individuals who have cont
## License
MIT
MIT - original work by the upstream author ([b3nw](https://github.com/b3nw/nginx-proxy-manager-mcp));
fork additions under the same license.
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "npm-mcp"
version = "0.0.7"
version = "0.1.0"
description = "MCP server for Nginx Proxy Manager"
readme = "README.md"
requires-python = ">=3.11"
+75
View File
@@ -474,3 +474,78 @@ class NpmClient:
response = await self._request("POST", "/nginx/certificates", json=payload)
return Certificate(**response.json())
# -------------------------------------------------------------------------
# Certificates: delete / renew
# -------------------------------------------------------------------------
async def delete_certificate(self, cert_id: int) -> bool:
"""Delete a certificate (``DELETE /nginx/certificates/{id}``). Irreversible."""
response = await self._request("DELETE", f"/nginx/certificates/{cert_id}")
return bool(response.json())
async def renew_certificate(self, cert_id: int) -> Certificate:
"""Renew a Let's Encrypt certificate now (``POST /nginx/certificates/{id}/renew``)."""
response = await self._request("POST", f"/nginx/certificates/{cert_id}/renew")
return Certificate(**response.json())
# -------------------------------------------------------------------------
# Redirection hosts, streams and 404 hosts (raw dict responses)
# -------------------------------------------------------------------------
async def _list(self, endpoint: str) -> list[dict]:
response = await self._request("GET", endpoint, params={"expand": "certificate"})
data = response.json()
return data if isinstance(data, list) else []
async def get_redirection_hosts(self) -> list[dict]:
return await self._list("/nginx/redirection-hosts")
async def create_redirection_host(self, payload: dict) -> dict:
response = await self._request("POST", "/nginx/redirection-hosts", json=payload)
return response.json()
async def delete_redirection_host(self, host_id: int) -> bool:
response = await self._request("DELETE", f"/nginx/redirection-hosts/{host_id}")
return bool(response.json())
async def get_streams(self) -> list[dict]:
return await self._list("/nginx/streams")
async def create_stream(self, payload: dict) -> dict:
response = await self._request("POST", "/nginx/streams", json=payload)
return response.json()
async def delete_stream(self, stream_id: int) -> bool:
response = await self._request("DELETE", f"/nginx/streams/{stream_id}")
return bool(response.json())
async def get_dead_hosts(self) -> list[dict]:
return await self._list("/nginx/dead-hosts")
async def delete_dead_host(self, host_id: int) -> bool:
response = await self._request("DELETE", f"/nginx/dead-hosts/{host_id}")
return bool(response.json())
async def certificate_usage(self) -> dict[int, list[str]]:
"""Map certificate id -> list of 'kind #id (domains)' that use it."""
usage: dict[int, list[str]] = {}
proxy = await self.get_proxy_hosts(expand="")
for host in proxy:
if host.certificate_id:
usage.setdefault(host.certificate_id, []).append(
f"proxy host #{host.id} ({', '.join(host.domain_names)})"
)
for kind, items in (
("redirection host", await self.get_redirection_hosts()),
("404 host", await self.get_dead_hosts()),
("stream", await self.get_streams()),
):
for item in items:
cert_id = item.get("certificate_id") or 0
if cert_id:
label = ", ".join(item.get("domain_names") or []) or (
f"port {item.get('incoming_port')}"
)
usage.setdefault(int(cert_id), []).append(f"{kind} #{item.get('id')} ({label})")
return usage
+478 -24
View File
@@ -6,6 +6,7 @@ from contextlib import asynccontextmanager
from typing import Any
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from pydantic import BaseModel, Field
from .client import NpmClient
@@ -154,7 +155,7 @@ async def list_proxy_hosts(instance: str | None = None) -> str:
return f"Found {len(hosts)} proxy host(s):\n\n" + "\n\n".join(result)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -217,7 +218,7 @@ async def get_proxy_host_details(host_id: int, instance: str | None = None) -> s
return json.dumps(details, indent=2)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -258,7 +259,7 @@ async def get_system_health(instance: str | None = None) -> str:
return "\n".join(result)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -290,7 +291,7 @@ async def search_audit_logs(limit: int = 50, offset: int = 0, instance: str | No
return header + "\n".join(result)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -322,7 +323,7 @@ async def list_certificates(instance: str | None = None) -> str:
return f"Found {len(certs)} certificate(s):\n\n" + "\n\n".join(result)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -346,7 +347,7 @@ async def list_access_lists(instance: str | None = None) -> str:
return f"Found {len(access_lists)} access list(s):\n\n" + "\n".join(result)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -362,6 +363,10 @@ async def create_proxy_host(
access_list_id: int | None = None,
advanced_config: str | None = None,
locations: list[ProxyHostLocationInput] | None = None,
hsts_enabled: bool | None = None,
hsts_subdomains: bool | None = None,
http2_support: bool | None = None,
caching_enabled: bool | None = None,
instance: str | None = None,
) -> str:
"""Create a new proxy host in Nginx Proxy Manager.
@@ -380,6 +385,10 @@ async def create_proxy_host(
locations: Custom location blocks. Each dict accepts path,
forward_scheme, forward_host, forward_port, forward_path,
advanced_config, and access_list_id.
hsts_enabled: Send HSTS header (default from config)
hsts_subdomains: Include subdomains in HSTS (default from config)
http2_support: Enable HTTP/2 (default from config)
caching_enabled: Enable asset caching (default from config)
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
@@ -398,11 +407,23 @@ async def create_proxy_host(
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),
hsts_enabled=hsts_enabled
if hsts_enabled is not None
else defaults.get("hsts_enabled", True),
hsts_subdomains=(
hsts_subdomains
if hsts_subdomains is not None
else defaults.get("hsts_subdomains", False)
),
http2_support=http2_support
if http2_support is not None
else defaults.get("http2_support", True),
block_exploits=_or(block_exploits, "block_exploits"),
caching_enabled=defaults.get("caching_enabled", False),
caching_enabled=(
caching_enabled
if caching_enabled is not None
else defaults.get("caching_enabled", False)
),
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"),
@@ -424,12 +445,13 @@ async def create_proxy_host(
)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def update_proxy_host(
host_id: int,
domain_names: list[str] | None = None,
forward_host: str | None = None,
forward_port: int | None = None,
forward_scheme: str | None = None,
@@ -440,6 +462,10 @@ async def update_proxy_host(
access_list_id: int | None = None,
advanced_config: str | None = None,
locations: list[ProxyHostLocationInput] | None = None,
hsts_enabled: bool | None = None,
hsts_subdomains: bool | None = None,
http2_support: bool | None = None,
caching_enabled: bool | None = None,
instance: str | None = None,
) -> str:
"""Update an existing proxy host in Nginx Proxy Manager.
@@ -450,6 +476,8 @@ async def update_proxy_host(
Args:
host_id: The ID of the proxy host to update
domain_names: Full replacement list of domain names (e.g. add a second name).
The certificate must cover every name, otherwise HTTPS fails for the new ones.
forward_host: Backend host/IP to forward to
forward_port: Backend port to forward to
forward_scheme: Backend protocol - "http" or "https"
@@ -463,6 +491,10 @@ async def update_proxy_host(
(each: path, forward_scheme, forward_host, forward_port,
forward_path, advanced_config, access_list_id). Omit to
leave existing locations unchanged.
hsts_enabled: Send HSTS header
hsts_subdomains: Include subdomains in HSTS
http2_support: Enable HTTP/2
caching_enabled: Enable asset caching
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
@@ -470,6 +502,19 @@ async def update_proxy_host(
try:
client, _ = _resolve(instance)
kwargs = {}
if domain_names is not None:
cleaned = [d.strip().lower() for d in domain_names if d.strip()]
if not cleaned:
raise ValueError("domain_names must not be empty")
kwargs["domain_names"] = cleaned
for key, value in (
("hsts_enabled", hsts_enabled),
("hsts_subdomains", hsts_subdomains),
("http2_support", http2_support),
("caching_enabled", caching_enabled),
):
if value is not None:
kwargs[key] = value
if forward_host is not None:
kwargs["forward_host"] = forward_host
if forward_port is not None:
@@ -504,34 +549,42 @@ async def update_proxy_host(
)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def delete_proxy_host(host_id: int, instance: str | None = None) -> str:
async def delete_proxy_host(
host_id: int, confirm: bool = False, instance: str | None = None
) -> str:
"""Delete a proxy host from Nginx Proxy Manager. This cannot be undone.
Without confirm=true only shows what would be deleted.
Args:
host_id: The ID of the proxy host to delete
confirm: Must be true after the user approved deleting exactly this host
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
client, _ = _resolve(instance)
domains: str | None = None
try:
host = await client.get_proxy_host(host_id)
domains = ", ".join(host.domain_names)
except Exception:
pass
host = await client.get_proxy_host(host_id)
domains = ", ".join(host.domain_names)
if not confirm:
return (
f"Preview only - nothing deleted.\n\nWould delete proxy host [{host_id}] "
f"({domains}) -> {host.forward_scheme}://{host.forward_host}:{host.forward_port}"
f", certificate {host.certificate_id or 'none'}.\n"
"Call again with confirm=true after the user approved it."
)
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}]."
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -555,7 +608,7 @@ async def enable_proxy_host(host_id: int, instance: str | None = None) -> str:
return f"Successfully enabled proxy host [{host_id}]."
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -582,7 +635,7 @@ async def disable_proxy_host(host_id: int, instance: str | None = None) -> str:
return f"Successfully disabled proxy host [{host_id}]."
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -639,7 +692,7 @@ async def get_proxy_host_logs(
return f"{header}\n\n{log_output}"
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
@mcp.tool()
@@ -679,4 +732,405 @@ async def create_certificate(
)
except Exception as e:
return _format_error(e)
raise ToolError(_format_error(e)) from None
# =============================================================================
# Fork additions: search, certificates, redirection hosts, streams, 404 hosts
# =============================================================================
def _preview(text: str) -> str:
return (
f"Preview only - nothing changed.\n\n{text}\n"
"Call again with confirm=true after the user approved it."
)
@mcp.tool()
async def find_proxy_host(domain: str, instance: str | None = None) -> str:
"""Find proxy hosts whose domain names contain the given text (e.g. 'git' or 'hörbuch').
Unicode names are matched in their punycode form too.
Args:
domain: Full or partial domain name
instance: NPM instance name (omit for default)
"""
try:
client, _ = _resolve(instance)
needle = domain.strip().lower()
if not needle:
raise ValueError("domain must not be empty")
try:
puny = ".".join(label.encode("idna").decode("ascii") for label in needle.split("."))
except UnicodeError:
puny = needle
hosts = await client.get_proxy_hosts()
hits = [h for h in hosts if any(needle in d or puny in d for d in h.domain_names)]
if not hits:
return f"No proxy host matches '{domain}'."
lines = [
f"[{h.id}] {', '.join(h.domain_names)} -> "
f"{h.forward_scheme}://{h.forward_host}:{h.forward_port} "
f"({'enabled' if h.enabled else 'disabled'}, certificate {h.certificate_id or 'none'})"
for h in hits
]
return f"Found {len(hits)} proxy host(s):\n" + "\n".join(lines)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def list_unused_certificates(
expiring_within_days: int = 30, instance: str | None = None
) -> str:
"""Certificate housekeeping: certificates no host uses, and certificates that expire soon.
Unused certificates can usually be deleted with delete_certificate. READ ONLY.
Args:
expiring_within_days: Also list used certificates expiring within this many days
instance: NPM instance name (omit for default)
"""
try:
from datetime import UTC, datetime, timedelta
client, _ = _resolve(instance)
certs = await client.get_certificates()
usage = await client.certificate_usage()
soon = datetime.now(UTC) + timedelta(days=expiring_within_days)
unused, expiring = [], []
for cert in certs:
expires = cert.expires_on.strftime("%Y-%m-%d") if cert.expires_on else "unknown"
line = f"[{cert.id}] {', '.join(cert.domain_names)} (expires {expires})"
if cert.id not in usage:
unused.append(line)
elif cert.expires_on and cert.expires_on < soon:
expiring.append(f"{line} - used by {'; '.join(usage[cert.id])}")
parts = [f"Unused certificates ({len(unused)}):"] + (unused or [" none"])
parts += [
"",
f"Used certificates expiring within {expiring_within_days} days ({len(expiring)}):",
]
parts += expiring or [" none"]
return "\n".join(parts)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def delete_certificate(
cert_id: int, confirm: bool = False, force: bool = False, instance: str | None = None
) -> str:
"""Delete an SSL certificate. This cannot be undone.
Refuses while a proxy/redirection/404 host or stream still uses the certificate
(those hosts would lose HTTPS) unless force=true. Without confirm=true only previews.
Args:
cert_id: Certificate ID (see list_certificates / list_unused_certificates)
confirm: Must be true after the user approved deleting exactly this certificate
force: Delete even though hosts still use it (they lose HTTPS)
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
client, _ = _resolve(instance)
cert = await client.get_certificate(cert_id)
users = (await client.certificate_usage()).get(cert_id, [])
expires = cert.expires_on.strftime("%Y-%m-%d") if cert.expires_on else "unknown"
names = ", ".join(cert.domain_names)
summary = f"Certificate [{cert_id}] {names} ({cert.provider}, expires {expires})"
if users and not force:
return (
f"Refused - {summary} is still used by: {'; '.join(users)}.\n"
"Switch those hosts to another certificate first, or pass force=true."
)
if not confirm:
note = f"\nStill used by: {'; '.join(users)} (they would lose HTTPS)." if users else ""
return _preview(f"Would delete {summary}.{note}")
await client.delete_certificate(cert_id)
return f"Successfully deleted {summary}."
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def renew_certificate(cert_id: int, instance: str | None = None) -> str:
"""Renew a Let's Encrypt certificate now (NPM also renews automatically before expiry).
Args:
cert_id: Certificate ID
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
client, _ = _resolve(instance)
cert = await client.renew_certificate(cert_id)
expires = cert.expires_on.strftime("%Y-%m-%d") if cert.expires_on else "unknown"
names = ", ".join(cert.domain_names)
return f"Renewed certificate [{cert_id}] {names}; now expires {expires}."
except Exception as e:
raise ToolError(_format_error(e)) from None
def _host_line(item: dict, target: str) -> str:
state = "enabled" if item.get("enabled", True) else "disabled"
cert = item.get("certificate_id") or "none"
names = ", ".join(item.get("domain_names") or [])
return f"[{item.get('id')}] {names} -> {target} ({state}, certificate {cert})"
@mcp.tool()
async def list_redirection_hosts(instance: str | None = None) -> str:
"""List redirection hosts (domains that redirect to another URL). READ ONLY.
Args:
instance: NPM instance name (omit for default)
"""
try:
client, _ = _resolve(instance)
items = await client.get_redirection_hosts()
if not items:
return "No redirection hosts configured."
lines = [
_host_line(
i,
f"{i.get('forward_http_code')} {i.get('forward_scheme')}://{i.get('forward_domain_name')}"
f"{' (path kept)' if i.get('preserve_path') else ''}",
)
for i in items
]
return f"Found {len(items)} redirection host(s):\n" + "\n".join(lines)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def create_redirection_host(
domain_names: list[str],
forward_domain_name: str,
forward_http_code: int = 301,
forward_scheme: str = "auto",
preserve_path: bool = True,
certificate_id: int = 0,
ssl_forced: bool = True,
block_exploits: bool = True,
instance: str | None = None,
) -> str:
"""Create a redirection host, e.g. old.example.com -> new.example.com.
Args:
domain_names: Domains that should redirect
forward_domain_name: Target domain (optionally with path)
forward_http_code: 301 (permanent), 302, 307 or 308
forward_scheme: "auto" (same as request), "http" or "https"
preserve_path: Append the requested path to the target
certificate_id: Certificate for HTTPS on the source domains (0 for none)
ssl_forced: Force HTTPS on the source domains (needs a certificate)
block_exploits: Enable common exploit blocking
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
if forward_http_code not in (300, 301, 302, 303, 307, 308):
raise ValueError("forward_http_code must be 300, 301, 302, 303, 307 or 308")
if forward_scheme not in ("auto", "http", "https"):
raise ValueError("forward_scheme must be auto, http or https")
client, _ = _resolve(instance)
item = await client.create_redirection_host(
{
"domain_names": [d.strip().lower() for d in domain_names if d.strip()],
"forward_domain_name": forward_domain_name.strip(),
"forward_http_code": forward_http_code,
"forward_scheme": forward_scheme,
"preserve_path": preserve_path,
"certificate_id": certificate_id,
"ssl_forced": ssl_forced and bool(certificate_id),
"block_exploits": block_exploits,
"hsts_enabled": False,
"hsts_subdomains": False,
"http2_support": bool(certificate_id),
"advanced_config": "",
"meta": {},
}
)
return "Successfully created redirection host!\n\n" + _host_line(
item, f"{forward_http_code} {forward_scheme}://{forward_domain_name}"
)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def delete_redirection_host(
host_id: int, confirm: bool = False, instance: str | None = None
) -> str:
"""Delete a redirection host. This cannot be undone. Without confirm=true only previews.
Args:
host_id: Redirection host ID
confirm: Must be true after the user approved deleting exactly this host
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
client, _ = _resolve(instance)
match = [i for i in await client.get_redirection_hosts() if i.get("id") == host_id]
if not match:
raise ValueError(f"Redirection host {host_id} not found")
line = _host_line(match[0], str(match[0].get("forward_domain_name")))
if not confirm:
return _preview(f"Would delete redirection host {line}.")
await client.delete_redirection_host(host_id)
return f"Successfully deleted redirection host {line}."
except Exception as e:
raise ToolError(_format_error(e)) from None
def _stream_line(item: dict) -> str:
proto = "+".join(
p
for p, on in (("tcp", item.get("tcp_forwarding")), ("udp", item.get("udp_forwarding")))
if on
)
state = "enabled" if item.get("enabled", True) else "disabled"
return (
f"[{item.get('id')}] :{item.get('incoming_port')} -> "
f"{item.get('forwarding_host')}:{item.get('forwarding_port')} ({proto or 'none'}, {state})"
)
@mcp.tool()
async def list_streams(instance: str | None = None) -> str:
"""List TCP/UDP streams (port forwards handled by NPM). READ ONLY.
Args:
instance: NPM instance name (omit for default)
"""
try:
client, _ = _resolve(instance)
items = await client.get_streams()
if not items:
return "No streams configured."
return f"Found {len(items)} stream(s):\n" + "\n".join(_stream_line(i) for i in items)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def create_stream(
incoming_port: int,
forwarding_host: str,
forwarding_port: int,
tcp_forwarding: bool = True,
udp_forwarding: bool = False,
instance: str | None = None,
) -> str:
"""Create a TCP/UDP stream: NPM listens on incoming_port and forwards to host:port.
Args:
incoming_port: Port NPM listens on (must be free and published by the NPM container)
forwarding_host: Target host/IP
forwarding_port: Target port
tcp_forwarding: Forward TCP
udp_forwarding: Forward UDP
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
if not (tcp_forwarding or udp_forwarding):
raise ValueError("enable tcp_forwarding and/or udp_forwarding")
for port in (incoming_port, forwarding_port):
if not 1 <= port <= 65535:
raise ValueError("ports must be between 1 and 65535")
client, _ = _resolve(instance)
taken = [i for i in await client.get_streams() if i.get("incoming_port") == incoming_port]
if taken:
raise ValueError(
f"Port {incoming_port} is already used by stream {_stream_line(taken[0])}"
)
item = await client.create_stream(
{
"incoming_port": incoming_port,
"forwarding_host": forwarding_host.strip(),
"forwarding_port": forwarding_port,
"tcp_forwarding": tcp_forwarding,
"udp_forwarding": udp_forwarding,
"meta": {},
}
)
return "Successfully created stream!\n\n" + _stream_line(item)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def delete_stream(stream_id: int, confirm: bool = False, instance: str | None = None) -> str:
"""Delete a TCP/UDP stream. This cannot be undone. Without confirm=true only previews.
Args:
stream_id: Stream ID
confirm: Must be true after the user approved deleting exactly this stream
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
client, _ = _resolve(instance)
match = [i for i in await client.get_streams() if i.get("id") == stream_id]
if not match:
raise ValueError(f"Stream {stream_id} not found")
if not confirm:
return _preview(f"Would delete stream {_stream_line(match[0])}.")
await client.delete_stream(stream_id)
return f"Successfully deleted stream {_stream_line(match[0])}."
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def list_404_hosts(instance: str | None = None) -> str:
"""List 404 hosts (domains NPM answers with "not found"). READ ONLY.
Args:
instance: NPM instance name (omit for default)
"""
try:
client, _ = _resolve(instance)
items = await client.get_dead_hosts()
if not items:
return "No 404 hosts configured."
return f"Found {len(items)} 404 host(s):\n" + "\n".join(_host_line(i, "404") for i in items)
except Exception as e:
raise ToolError(_format_error(e)) from None
@mcp.tool()
async def delete_404_host(host_id: int, confirm: bool = False, instance: str | None = None) -> str:
"""Delete a 404 host. This cannot be undone. Without confirm=true only previews.
Args:
host_id: 404 host ID
confirm: Must be true after the user approved deleting exactly this host
instance: NPM instance name (omit for default)
"""
if msg := _check_destructive():
return msg
try:
client, _ = _resolve(instance)
match = [i for i in await client.get_dead_hosts() if i.get("id") == host_id]
if not match:
raise ValueError(f"404 host {host_id} not found")
if not confirm:
return _preview(f"Would delete 404 host {_host_line(match[0], '404')}.")
await client.delete_dead_host(host_id)
return f"Successfully deleted 404 host {_host_line(match[0], '404')}."
except Exception as e:
raise ToolError(_format_error(e)) from None
+276
View File
@@ -0,0 +1,276 @@
"""Tests for the fork additions: certificates, domains, redirects, streams, 404 hosts, confirm."""
from datetime import UTC, datetime, timedelta
import pytest
from fastmcp.exceptions import ToolError
from npm_mcp import server
from npm_mcp.client import NpmClient
from npm_mcp.exceptions import NpmApiError
from npm_mcp.models import Certificate, ProxyHost
BASE = "http://npm.test/api"
NOW = datetime.now(UTC)
def host(host_id: int, domains: list[str], cert: int = 0, **extra) -> ProxyHost:
return ProxyHost(
id=host_id,
created_on=NOW,
modified_on=NOW,
owner_user_id=1,
domain_names=domains,
forward_host="10.0.0.5",
forward_port=8080,
certificate_id=cert,
**extra,
)
def cert(cert_id: int, domains: list[str], days: int = 60) -> Certificate:
return Certificate(
id=cert_id,
provider="letsencrypt",
domain_names=domains,
expires_on=NOW + timedelta(days=days),
)
class FakeClient:
def __init__(self):
self.hosts = [
host(1, ["git.example.de"], cert=10),
host(2, ["xn--hrbuch-wxa.example.de"], cert=11),
]
self.certs = [
cert(10, ["git.example.de"]),
cert(11, ["xn--hrbuch-wxa.example.de"], days=5),
cert(12, ["old.example.de"]),
]
self.redirects = [
{
"id": 5,
"domain_names": ["www.example.de"],
"forward_domain_name": "example.de",
"forward_http_code": 301,
"forward_scheme": "auto",
"certificate_id": 0,
}
]
self.streams = [
{
"id": 7,
"incoming_port": 2222,
"forwarding_host": "10.0.0.9",
"forwarding_port": 22,
"tcp_forwarding": True,
"udp_forwarding": False,
}
]
self.dead = [{"id": 9, "domain_names": ["gone.example.de"], "certificate_id": 0}]
self.calls: list[tuple] = []
async def get_proxy_hosts(self, expand="owner,certificate"):
return self.hosts
async def get_proxy_host(self, host_id, expand="owner,certificate"):
return next(h for h in self.hosts if h.id == host_id)
async def delete_proxy_host(self, host_id):
self.calls.append(("delete_proxy_host", host_id))
return True
async def update_proxy_host(self, host_id, **kwargs):
self.calls.append(("update_proxy_host", host_id, kwargs))
current = await self.get_proxy_host(host_id)
return current.model_copy(update=kwargs)
async def get_certificates(self):
return self.certs
async def get_certificate(self, cert_id):
return next(c for c in self.certs if c.id == cert_id)
async def delete_certificate(self, cert_id):
self.calls.append(("delete_certificate", cert_id))
return True
async def renew_certificate(self, cert_id):
self.calls.append(("renew_certificate", cert_id))
return cert(cert_id, ["git.example.de"], days=90)
async def certificate_usage(self):
return await NpmClient.certificate_usage(self)
async def get_redirection_hosts(self):
return self.redirects
async def create_redirection_host(self, payload):
self.calls.append(("create_redirection_host", payload))
return {"id": 6, **payload}
async def delete_redirection_host(self, host_id):
self.calls.append(("delete_redirection_host", host_id))
return True
async def get_streams(self):
return self.streams
async def create_stream(self, payload):
self.calls.append(("create_stream", payload))
return {"id": 8, **payload}
async def delete_stream(self, stream_id):
self.calls.append(("delete_stream", stream_id))
return True
async def get_dead_hosts(self):
return self.dead
async def delete_dead_host(self, host_id):
self.calls.append(("delete_dead_host", host_id))
return True
@pytest.fixture
def fake(monkeypatch):
client = FakeClient()
monkeypatch.setattr(server, "_resolve", lambda instance=None: (client, None))
monkeypatch.setattr(server.settings, "mcp_enable_destructive_tools", True)
return client
async def test_find_proxy_host_matches_unicode(fake):
out = await server.find_proxy_host("hörbuch")
assert "[2]" in out and "[1]" not in out
assert "No proxy host" in await server.find_proxy_host("nothing")
async def test_update_proxy_host_can_change_domain_names(fake):
out = await server.update_proxy_host(
1, domain_names=["Git.example.de", "code.example.de "], hsts_enabled=False
)
assert (
"update_proxy_host",
1,
{"domain_names": ["git.example.de", "code.example.de"], "hsts_enabled": False},
) in fake.calls
assert "code.example.de" in out
async def test_update_proxy_host_rejects_empty_domains(fake):
with pytest.raises(ToolError, match="must not be empty"):
await server.update_proxy_host(1, domain_names=[" "])
async def test_delete_proxy_host_needs_confirm(fake):
preview = await server.delete_proxy_host(1)
assert preview.startswith("Preview only") and "git.example.de" in preview
assert fake.calls == []
await server.delete_proxy_host(1, confirm=True)
assert fake.calls == [("delete_proxy_host", 1)]
async def test_unused_and_expiring_certificates(fake):
out = await server.list_unused_certificates(expiring_within_days=30)
unused, _, expiring = out.partition("Used certificates")
assert "[12] old.example.de" in unused and "[10]" not in unused
assert "[11]" in expiring and "proxy host #2" in expiring
async def test_delete_certificate_refuses_when_in_use(fake):
out = await server.delete_certificate(10, confirm=True)
assert out.startswith("Refused") and "proxy host #1" in out
assert fake.calls == []
async def test_delete_unused_certificate_preview_then_delete(fake):
assert (await server.delete_certificate(12)).startswith("Preview only")
assert fake.calls == []
out = await server.delete_certificate(12, confirm=True)
assert "Successfully deleted" in out
assert fake.calls == [("delete_certificate", 12)]
async def test_force_delete_used_certificate_warns_in_preview(fake):
out = await server.delete_certificate(10, force=True)
assert "would lose HTTPS" in out
async def test_renew_certificate(fake):
out = await server.renew_certificate(10)
assert "Renewed certificate [10]" in out
async def test_redirection_hosts(fake):
assert "301 auto://example.de" in await server.list_redirection_hosts()
out = await server.create_redirection_host(
["old.example.de"], "new.example.de/path", 308, "https"
)
payload = fake.calls[-1][1]
assert payload["forward_http_code"] == 308 and payload["ssl_forced"] is False
assert "Successfully created" in out
with pytest.raises(ToolError, match="forward_http_code"):
await server.create_redirection_host(["x.example.de"], "y.example.de", 200)
assert (await server.delete_redirection_host(5)).startswith("Preview only")
await server.delete_redirection_host(5, confirm=True)
assert fake.calls[-1] == ("delete_redirection_host", 5)
async def test_streams(fake):
assert ":2222 -> 10.0.0.9:22 (tcp" in await server.list_streams()
with pytest.raises(ToolError, match="already used"):
await server.create_stream(2222, "10.0.0.1", 22)
with pytest.raises(ToolError, match="tcp_forwarding"):
await server.create_stream(3333, "10.0.0.1", 22, tcp_forwarding=False)
await server.create_stream(3333, "10.0.0.1", 53, udp_forwarding=True)
assert fake.calls[-1][1]["udp_forwarding"] is True
await server.delete_stream(7, confirm=True)
assert fake.calls[-1] == ("delete_stream", 7)
async def test_404_hosts(fake):
assert "gone.example.de" in await server.list_404_hosts()
assert (await server.delete_404_host(9)).startswith("Preview only")
await server.delete_404_host(9, confirm=True)
assert fake.calls[-1] == ("delete_dead_host", 9)
with pytest.raises(ToolError, match="not found"):
await server.delete_404_host(99, confirm=True)
async def test_destructive_gate_still_applies(fake, monkeypatch):
monkeypatch.setattr(server.settings, "mcp_enable_destructive_tools", False)
for call in (
server.delete_certificate(12, confirm=True),
server.create_stream(3333, "h", 1),
server.delete_404_host(9, confirm=True),
server.renew_certificate(10),
):
assert await call == server.DESTRUCTIVE_DISABLED_MSG
assert fake.calls == []
async def test_api_errors_are_tool_errors(fake, monkeypatch):
async def boom(*_args, **_kwargs):
raise NpmApiError("internal", status_code=500)
monkeypatch.setattr(fake, "get_streams", boom)
with pytest.raises(ToolError, match="API error"):
await server.list_streams()
async def test_client_certificate_endpoints(httpx_mock):
httpx_mock.add_response(
method="POST", url=f"{BASE}/tokens", json={"token": "t", "expires": "2099-01-01T00:00:00Z"}
)
httpx_mock.add_response(method="DELETE", url=f"{BASE}/nginx/certificates/12", json=True)
httpx_mock.add_response(
method="POST",
url=f"{BASE}/nginx/certificates/10/renew",
json={"id": 10, "provider": "letsencrypt", "domain_names": ["a.de"]},
)
async with NpmClient(base_url=BASE, identity="i", secret="s") as client:
assert await client.delete_certificate(12) is True
renewed = await client.renew_certificate(10)
assert renewed.id == 10
Generated
+2 -2
View File
@@ -1,5 +1,5 @@
version = 1
revision = 3
revision = 5
requires-python = ">=3.11"
resolution-markers = [
"python_full_version >= '3.15'",
@@ -734,7 +734,7 @@ wheels = [
[[package]]
name = "npm-mcp"
version = "0.0.7"
version = "0.1.0"
source = { editable = "." }
dependencies = [
{ name = "fastmcp" },