dcert-mcp 4.0.3__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dcert_mcp/__init__.py +161 -0
- dcert_mcp/auth.py +189 -0
- dcert_mcp/binary.py +107 -0
- dcert_mcp/cli.py +241 -0
- dcert_mcp/client.py +28 -0
- dcert_mcp/config.py +225 -0
- dcert_mcp/config.yaml +120 -0
- dcert_mcp/middleware.py +195 -0
- dcert_mcp/proxy.py +28 -0
- dcert_mcp/py.typed +0 -0
- dcert_mcp/resilience.py +686 -0
- dcert_mcp/server.py +84 -0
- dcert_mcp/tools.py +938 -0
- dcert_mcp-4.0.3.data/scripts/dcert-mcp.exe +0 -0
- dcert_mcp-4.0.3.dist-info/METADATA +211 -0
- dcert_mcp-4.0.3.dist-info/RECORD +19 -0
- dcert_mcp-4.0.3.dist-info/WHEEL +4 -0
- dcert_mcp-4.0.3.dist-info/entry_points.txt +2 -0
- dcert_mcp-4.0.3.dist-info/licenses/LICENSE +21 -0
dcert_mcp/__init__.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""dcert_mcp: Python proxy and typed client for the dcert-mcp TLS certificate server.
|
|
2
|
+
|
|
3
|
+
The package runs a FastMCP proxy around the ``dcert-mcp`` Rust binary and
|
|
4
|
+
exposes every TLS certificate tool over the Model Context Protocol. Tools
|
|
5
|
+
added to the Rust binary are discovered at runtime, so no Python changes
|
|
6
|
+
are needed when the server grows.
|
|
7
|
+
|
|
8
|
+
Usage as a server::
|
|
9
|
+
|
|
10
|
+
from dcert_mcp import create_server
|
|
11
|
+
create_server().run()
|
|
12
|
+
|
|
13
|
+
Usage as a client::
|
|
14
|
+
|
|
15
|
+
from dcert_mcp import create_client
|
|
16
|
+
async with create_client() as client:
|
|
17
|
+
result = await client.call_tool("analyze_certificate", {"target": "example.com"})
|
|
18
|
+
|
|
19
|
+
Usage with the typed async wrappers::
|
|
20
|
+
|
|
21
|
+
from dcert_mcp import analyze_certificate, create_session
|
|
22
|
+
async with create_session() as session:
|
|
23
|
+
result = await analyze_certificate(target="example.com", session=session)
|
|
24
|
+
|
|
25
|
+
The helpers need the ``proxy`` extra: ``pip install "dcert-mcp[proxy]"``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import importlib
|
|
31
|
+
|
|
32
|
+
__version__ = "4.0.3"
|
|
33
|
+
|
|
34
|
+
#: Names whose absence means the ``proxy`` extra is not installed.
|
|
35
|
+
PROXY_EXTRA_MODULES = frozenset({"fastmcp", "click", "yaml", "starlette", "mcp", "anyio"})
|
|
36
|
+
PROXY_EXTRA_HINT = 'pip install "dcert-mcp[proxy]"'
|
|
37
|
+
|
|
38
|
+
_EXPORTS = {
|
|
39
|
+
"CircuitBreaker": "resilience",
|
|
40
|
+
"CircuitBreakerOpen": "resilience",
|
|
41
|
+
"Config": "config",
|
|
42
|
+
"load_config": "config",
|
|
43
|
+
"DcertConnectionError": "tools",
|
|
44
|
+
"DcertError": "tools",
|
|
45
|
+
"DcertTimeoutError": "tools",
|
|
46
|
+
"DcertToolError": "tools",
|
|
47
|
+
"Guard": "resilience",
|
|
48
|
+
"OTelConfig": "resilience",
|
|
49
|
+
"RateLimiter": "resilience",
|
|
50
|
+
"ResilienceConfig": "resilience",
|
|
51
|
+
"Session": "tools",
|
|
52
|
+
"analyze_certificate": "tools",
|
|
53
|
+
"backoff_delays": "resilience",
|
|
54
|
+
"build_guard": "resilience",
|
|
55
|
+
"check_expiry": "tools",
|
|
56
|
+
"check_revocation": "tools",
|
|
57
|
+
"close_default_session": "tools",
|
|
58
|
+
"compare_certificates": "tools",
|
|
59
|
+
"convert_pem_to_pfx": "tools",
|
|
60
|
+
"convert_pfx_to_pem": "tools",
|
|
61
|
+
"create_circuit_breaker": "resilience",
|
|
62
|
+
"create_client": "client",
|
|
63
|
+
"create_keystore": "tools",
|
|
64
|
+
"create_rate_limiter": "resilience",
|
|
65
|
+
"create_server": "server",
|
|
66
|
+
"create_session": "tools",
|
|
67
|
+
"create_truststore": "tools",
|
|
68
|
+
"explain_cipher_suite": "tools",
|
|
69
|
+
"export_pem": "tools",
|
|
70
|
+
"list_cipher_suites": "tools",
|
|
71
|
+
"list_tls_policies": "tools",
|
|
72
|
+
"otel_config_from_env": "resilience",
|
|
73
|
+
"resilience_config_from_env": "resilience",
|
|
74
|
+
"setup_otel": "resilience",
|
|
75
|
+
"show_tls_policy": "tools",
|
|
76
|
+
"tls_connection_info": "tools",
|
|
77
|
+
"tls_policy_test": "tools",
|
|
78
|
+
"tls_scan": "tools",
|
|
79
|
+
"truncate_response": "resilience",
|
|
80
|
+
"verify_key_match": "tools",
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
__all__ = [
|
|
84
|
+
"create_server",
|
|
85
|
+
"create_client",
|
|
86
|
+
"__version__",
|
|
87
|
+
"Config",
|
|
88
|
+
"load_config",
|
|
89
|
+
"Session",
|
|
90
|
+
"create_session",
|
|
91
|
+
"close_default_session",
|
|
92
|
+
"DcertError",
|
|
93
|
+
"DcertTimeoutError",
|
|
94
|
+
"DcertConnectionError",
|
|
95
|
+
"DcertToolError",
|
|
96
|
+
"ResilienceConfig",
|
|
97
|
+
"resilience_config_from_env",
|
|
98
|
+
"OTelConfig",
|
|
99
|
+
"otel_config_from_env",
|
|
100
|
+
"CircuitBreaker",
|
|
101
|
+
"CircuitBreakerOpen",
|
|
102
|
+
"create_circuit_breaker",
|
|
103
|
+
"Guard",
|
|
104
|
+
"build_guard",
|
|
105
|
+
"RateLimiter",
|
|
106
|
+
"create_rate_limiter",
|
|
107
|
+
"backoff_delays",
|
|
108
|
+
"setup_otel",
|
|
109
|
+
"truncate_response",
|
|
110
|
+
"analyze_certificate",
|
|
111
|
+
"check_expiry",
|
|
112
|
+
"check_revocation",
|
|
113
|
+
"compare_certificates",
|
|
114
|
+
"tls_connection_info",
|
|
115
|
+
"export_pem",
|
|
116
|
+
"verify_key_match",
|
|
117
|
+
"convert_pfx_to_pem",
|
|
118
|
+
"convert_pem_to_pfx",
|
|
119
|
+
"create_keystore",
|
|
120
|
+
"create_truststore",
|
|
121
|
+
"list_cipher_suites",
|
|
122
|
+
"explain_cipher_suite",
|
|
123
|
+
"tls_scan",
|
|
124
|
+
"list_tls_policies",
|
|
125
|
+
"show_tls_policy",
|
|
126
|
+
"tls_policy_test",
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def missing_extra_message(module: str) -> str:
|
|
131
|
+
"""Return the one line shown when the ``proxy`` extra is not installed."""
|
|
132
|
+
return f"dcert_mcp needs the optional package '{module}'. Install it with: {PROXY_EXTRA_HINT}"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def __getattr__(name: str) -> object:
|
|
136
|
+
"""Import the module that defines *name* on first use.
|
|
137
|
+
|
|
138
|
+
``import dcert_mcp`` stays cheap and works without the ``proxy`` extra;
|
|
139
|
+
only touching a helper that needs FastMCP imports it.
|
|
140
|
+
|
|
141
|
+
Raises:
|
|
142
|
+
ImportError: With one line naming the extra when a proxy dependency is missing.
|
|
143
|
+
AttributeError: When *name* is not part of the public API.
|
|
144
|
+
"""
|
|
145
|
+
module_name = _EXPORTS.get(name)
|
|
146
|
+
if module_name is None:
|
|
147
|
+
raise AttributeError(f"module 'dcert_mcp' has no attribute {name!r}")
|
|
148
|
+
try:
|
|
149
|
+
module = importlib.import_module(f"dcert_mcp.{module_name}")
|
|
150
|
+
except ModuleNotFoundError as exc:
|
|
151
|
+
root = (exc.name or "").split(".")[0]
|
|
152
|
+
if root in PROXY_EXTRA_MODULES:
|
|
153
|
+
raise ImportError(missing_extra_message(root)) from exc
|
|
154
|
+
raise
|
|
155
|
+
value = getattr(module, name)
|
|
156
|
+
globals()[name] = value
|
|
157
|
+
return value
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def __dir__() -> list[str]:
|
|
161
|
+
return sorted([*globals(), *_EXPORTS])
|
dcert_mcp/auth.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Authentication and Host header checks for the HTTP and SSE transports.
|
|
2
|
+
|
|
3
|
+
``dcert-mcp-proxy --transport http|sse`` exposes every dcert tool over the
|
|
4
|
+
network, so it refuses to start without either a static bearer token or an
|
|
5
|
+
OIDC configuration, and it only answers requests whose ``Host`` header names
|
|
6
|
+
a loopback address, the bind address or an entry from ``--allowed-hosts``
|
|
7
|
+
(which defeats DNS rebinding from a browser).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hmac
|
|
13
|
+
import os
|
|
14
|
+
from collections.abc import Awaitable, Callable, Iterable, Mapping, MutableMapping
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from fastmcp.server.auth import AccessToken, AuthProvider, TokenVerifier
|
|
19
|
+
from fastmcp.server.auth.providers.jwt import JWTVerifier
|
|
20
|
+
|
|
21
|
+
from dcert_mcp.config import AuthConfig
|
|
22
|
+
|
|
23
|
+
#: Client id reported for requests authenticated with the static token.
|
|
24
|
+
STATIC_TOKEN_CLIENT_ID = "dcert-static-token" # noqa: S105 (an identifier, not a secret)
|
|
25
|
+
|
|
26
|
+
#: Bind addresses that mean "every interface" and so name no host.
|
|
27
|
+
WILDCARD_BINDS = frozenset({"0.0.0.0", "::", ""}) # noqa: S104
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class AuthSettings:
|
|
32
|
+
"""Authentication settings resolved from flags and the environment."""
|
|
33
|
+
|
|
34
|
+
token: str | None = None
|
|
35
|
+
oidc_issuer: str | None = None
|
|
36
|
+
oidc_audience: str | None = None
|
|
37
|
+
oidc_jwks_uri: str | None = None
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def oidc_configured(self) -> bool:
|
|
41
|
+
"""Whether any OIDC setting is present."""
|
|
42
|
+
return any((self.oidc_issuer, self.oidc_audience, self.oidc_jwks_uri))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def settings_from_env(config: AuthConfig, env: Mapping[str, str] | None = None) -> AuthSettings:
|
|
46
|
+
"""Read :class:`AuthSettings` from the variables named in *config*."""
|
|
47
|
+
source = os.environ if env is None else env
|
|
48
|
+
|
|
49
|
+
def read(name: str) -> str | None:
|
|
50
|
+
return source.get(name, "").strip() or None
|
|
51
|
+
|
|
52
|
+
return AuthSettings(
|
|
53
|
+
token=read(config.token_env),
|
|
54
|
+
oidc_issuer=read(config.oidc_issuer_env),
|
|
55
|
+
oidc_audience=read(config.oidc_audience_env),
|
|
56
|
+
oidc_jwks_uri=read(config.oidc_jwks_env),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class BearerTokenVerifier(TokenVerifier):
|
|
61
|
+
"""Accept exactly one static bearer token, compared in constant time."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, token: str) -> None:
|
|
64
|
+
super().__init__()
|
|
65
|
+
self._token = token.encode()
|
|
66
|
+
|
|
67
|
+
async def verify_token(self, token: str) -> AccessToken | None:
|
|
68
|
+
"""Return an access token when *token* matches, otherwise ``None``."""
|
|
69
|
+
if not hmac.compare_digest(token.encode(), self._token):
|
|
70
|
+
return None
|
|
71
|
+
return AccessToken(token=token, client_id=STATIC_TOKEN_CLIENT_ID, scopes=[])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def build_auth(settings: AuthSettings, config: AuthConfig) -> AuthProvider:
|
|
75
|
+
"""Return the auth provider for *settings*.
|
|
76
|
+
|
|
77
|
+
OIDC needs the issuer, the audience and the JWKS URL, all over https; a
|
|
78
|
+
static token must be at least ``config.min_token_length`` characters.
|
|
79
|
+
|
|
80
|
+
Raises:
|
|
81
|
+
ValueError: If nothing is configured, or the configuration is
|
|
82
|
+
incomplete or unsafe. The message names the variables to set.
|
|
83
|
+
"""
|
|
84
|
+
if settings.oidc_configured:
|
|
85
|
+
return _oidc_verifier(settings, config)
|
|
86
|
+
if settings.token is not None:
|
|
87
|
+
if len(settings.token) < config.min_token_length:
|
|
88
|
+
raise ValueError(
|
|
89
|
+
f"the auth token must be at least {config.min_token_length} characters "
|
|
90
|
+
f"(--auth-token or {config.token_env})"
|
|
91
|
+
)
|
|
92
|
+
return BearerTokenVerifier(settings.token)
|
|
93
|
+
raise ValueError(
|
|
94
|
+
"HTTP and SSE transports need authentication: set --auth-token "
|
|
95
|
+
f"(or {config.token_env}) or an OIDC issuer, audience and JWKS URL "
|
|
96
|
+
f"({config.oidc_issuer_env}, {config.oidc_audience_env}, {config.oidc_jwks_env})"
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _oidc_verifier(settings: AuthSettings, config: AuthConfig) -> JWTVerifier:
|
|
101
|
+
"""Return a JWT verifier for a complete, https only OIDC configuration."""
|
|
102
|
+
required = {
|
|
103
|
+
config.oidc_issuer_env: settings.oidc_issuer,
|
|
104
|
+
config.oidc_audience_env: settings.oidc_audience,
|
|
105
|
+
config.oidc_jwks_env: settings.oidc_jwks_uri,
|
|
106
|
+
}
|
|
107
|
+
missing = [name for name, value in required.items() if not value]
|
|
108
|
+
if missing:
|
|
109
|
+
raise ValueError(f"incomplete OIDC configuration: set {', '.join(missing)}")
|
|
110
|
+
for name in (config.oidc_issuer_env, config.oidc_jwks_env):
|
|
111
|
+
value = required[name] or ""
|
|
112
|
+
if not value.startswith("https://"):
|
|
113
|
+
raise ValueError(f"{name} must be an https:// URL, got {value!r}")
|
|
114
|
+
return JWTVerifier(
|
|
115
|
+
jwks_uri=settings.oidc_jwks_uri,
|
|
116
|
+
issuer=settings.oidc_issuer,
|
|
117
|
+
audience=settings.oidc_audience,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def parse_host_header(value: str) -> str:
|
|
122
|
+
"""Return the host part of a ``Host`` header, lower cased, without port or brackets."""
|
|
123
|
+
host = value.strip().lower()
|
|
124
|
+
if host.startswith("["):
|
|
125
|
+
return host[1:].split("]", 1)[0]
|
|
126
|
+
if host.count(":") == 1:
|
|
127
|
+
return host.split(":", 1)[0]
|
|
128
|
+
return host
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def allowed_hosts(loopback: Iterable[str], bind_host: str, extra: Iterable[str]) -> frozenset[str]:
|
|
132
|
+
"""Return the ``Host`` header values to accept.
|
|
133
|
+
|
|
134
|
+
Loopback names are always accepted. A concrete bind address is accepted
|
|
135
|
+
too; a wildcard bind (``0.0.0.0``) names no host, so remote names must
|
|
136
|
+
come from *extra* (``--allowed-hosts``, comma separated or repeated).
|
|
137
|
+
"""
|
|
138
|
+
hosts = {parse_host_header(h) for h in loopback}
|
|
139
|
+
if bind_host.strip() not in WILDCARD_BINDS:
|
|
140
|
+
hosts.add(parse_host_header(bind_host))
|
|
141
|
+
for entry in extra:
|
|
142
|
+
hosts.update(parse_host_header(h) for h in entry.split(",") if h.strip())
|
|
143
|
+
return frozenset(hosts)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
Scope = MutableMapping[str, Any]
|
|
147
|
+
Message = MutableMapping[str, Any]
|
|
148
|
+
Receive = Callable[[], Awaitable[Message]]
|
|
149
|
+
Send = Callable[[Message], Awaitable[None]]
|
|
150
|
+
ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class HostHeaderGuard:
|
|
154
|
+
"""ASGI middleware that answers 400 unless the ``Host`` header is allowed.
|
|
155
|
+
|
|
156
|
+
Starlette's own ``TrustedHostMiddleware`` cannot parse bracketed IPv6
|
|
157
|
+
hosts, hence this small replacement.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
def __init__(self, app: ASGIApp, hosts: frozenset[str]) -> None:
|
|
161
|
+
self.app = app
|
|
162
|
+
self.hosts = hosts
|
|
163
|
+
|
|
164
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
165
|
+
"""Pass allowed requests through and refuse the rest."""
|
|
166
|
+
if scope.get("type") not in {"http", "websocket"} or host_allowed(scope, self.hosts):
|
|
167
|
+
await self.app(scope, receive, send)
|
|
168
|
+
return
|
|
169
|
+
body = b"Invalid Host header"
|
|
170
|
+
await send(
|
|
171
|
+
{
|
|
172
|
+
"type": "http.response.start",
|
|
173
|
+
"status": 400,
|
|
174
|
+
"headers": [
|
|
175
|
+
(b"content-type", b"text/plain; charset=utf-8"),
|
|
176
|
+
(b"content-length", str(len(body)).encode()),
|
|
177
|
+
],
|
|
178
|
+
}
|
|
179
|
+
)
|
|
180
|
+
await send({"type": "http.response.body", "body": body})
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def host_allowed(scope: Scope, hosts: frozenset[str]) -> bool:
|
|
184
|
+
"""Return whether the request in *scope* carries an allowed ``Host`` header."""
|
|
185
|
+
headers: Iterable[tuple[bytes, bytes]] = scope.get("headers", [])
|
|
186
|
+
for name, value in headers:
|
|
187
|
+
if name.lower() == b"host":
|
|
188
|
+
return parse_host_header(value.decode("latin-1")) in hosts
|
|
189
|
+
return False
|
dcert_mcp/binary.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Locate the Rust ``dcert-mcp`` binary.
|
|
2
|
+
|
|
3
|
+
The search order for :func:`find_binary` is:
|
|
4
|
+
|
|
5
|
+
1. An explicit path from the environment (``DCERT_MCP_BINARY``; see
|
|
6
|
+
``config.yaml``).
|
|
7
|
+
2. A compiled binary on ``PATH``. The ``dcert-mcp`` wheel installs it there, as
|
|
8
|
+
a script that is the Rust executable itself, so no Python wrapper is in the
|
|
9
|
+
way. Pip generated console script wrappers are skipped so the proxy can
|
|
10
|
+
never exec itself in a loop.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from dcert_mcp.config import load_config
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def is_python_script(path: str) -> bool:
|
|
27
|
+
"""Return ``True`` when *path* is a Python console-script wrapper.
|
|
28
|
+
|
|
29
|
+
Reads the configured number of leading bytes; a file starting with
|
|
30
|
+
``#!`` whose first line mentions ``python`` is a pip generated wrapper,
|
|
31
|
+
not a compiled binary.
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
with open(path, "rb") as handle:
|
|
35
|
+
head = handle.read(load_config().binaries.wrapper_probe_bytes)
|
|
36
|
+
except OSError:
|
|
37
|
+
return False
|
|
38
|
+
first_line = head.split(b"\n", 1)[0].lower()
|
|
39
|
+
return head[:2] == b"#!" and b"python" in first_line
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_running_script(path: str) -> bool:
|
|
43
|
+
"""Return ``True`` when *path* is the script the interpreter is running.
|
|
44
|
+
|
|
45
|
+
On Windows pip installs a native ``.exe`` launcher that runs Python on
|
|
46
|
+
itself, so ``sys.argv[0]`` is that launcher; comparing by file identity
|
|
47
|
+
catches it where :func:`is_python_script` cannot.
|
|
48
|
+
"""
|
|
49
|
+
argv0 = sys.argv[0] if sys.argv else ""
|
|
50
|
+
if not argv0:
|
|
51
|
+
return False
|
|
52
|
+
try:
|
|
53
|
+
return os.path.samefile(path, argv0)
|
|
54
|
+
except (OSError, ValueError):
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def is_wrapper(path: str) -> bool:
|
|
59
|
+
"""Return ``True`` when *path* is a console script wrapper rather than a binary."""
|
|
60
|
+
return is_python_script(path) or is_running_script(path)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _explicit_binary(name: str) -> str | None:
|
|
64
|
+
"""Return the binary named by its environment variable, if any is set.
|
|
65
|
+
|
|
66
|
+
The value is made absolute so it can never be resolved through ``PATH``.
|
|
67
|
+
"""
|
|
68
|
+
variable = load_config().binaries.env.get(name)
|
|
69
|
+
value = os.environ.get(variable, "") if variable else ""
|
|
70
|
+
if not value:
|
|
71
|
+
return None
|
|
72
|
+
candidate = Path(value).expanduser().resolve()
|
|
73
|
+
if candidate.is_file() and os.access(candidate, os.X_OK):
|
|
74
|
+
logger.debug("Using %s from %s: %s", name, variable, candidate)
|
|
75
|
+
return str(candidate)
|
|
76
|
+
raise FileNotFoundError(f"{variable}={value} does not exist or is not executable")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _path_binary(name: str) -> str | None:
|
|
80
|
+
"""Return a compiled *name* on ``PATH``, skipping console script wrappers."""
|
|
81
|
+
found = shutil.which(name)
|
|
82
|
+
if found and not is_wrapper(found):
|
|
83
|
+
return found
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def find_binary(name: str) -> str:
|
|
88
|
+
"""Return the absolute path to the Rust binary *name*.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
name: ``dcert`` or ``dcert-mcp``.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
FileNotFoundError: If no usable binary can be located.
|
|
95
|
+
"""
|
|
96
|
+
for locate in (_explicit_binary, _path_binary):
|
|
97
|
+
found = locate(name)
|
|
98
|
+
if found:
|
|
99
|
+
logger.debug("Resolved %s to %s", name, found)
|
|
100
|
+
return found
|
|
101
|
+
binaries = load_config().binaries
|
|
102
|
+
variable = binaries.env.get(name, binaries.fallback_env)
|
|
103
|
+
raise FileNotFoundError(
|
|
104
|
+
f"{name} binary not found. Either:\n"
|
|
105
|
+
f" 1. Set {variable}=/path/to/{name}\n"
|
|
106
|
+
f" 2. Reinstall the package: pip install --force-reinstall dcert-mcp"
|
|
107
|
+
)
|
dcert_mcp/cli.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Command line entry point of the FastMCP proxy (``dcert-mcp-proxy``).
|
|
2
|
+
|
|
3
|
+
The ``dcert`` and ``dcert-mcp`` commands are the Rust executables themselves,
|
|
4
|
+
installed as wheel scripts, so no Python runs for them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import replace
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
import click
|
|
14
|
+
from starlette.middleware import Middleware
|
|
15
|
+
|
|
16
|
+
from dcert_mcp.auth import AuthSettings, HostHeaderGuard, build_auth
|
|
17
|
+
from dcert_mcp.auth import allowed_hosts as build_allowed_hosts
|
|
18
|
+
from dcert_mcp.config import load_config
|
|
19
|
+
from dcert_mcp.resilience import OTelConfig, ResilienceConfig
|
|
20
|
+
|
|
21
|
+
_CONFIG = load_config()
|
|
22
|
+
|
|
23
|
+
#: The ``dcert-mcp`` setting that refuses private, loopback and metadata
|
|
24
|
+
#: destinations (``src/mcp/config.rs``).
|
|
25
|
+
DENY_PRIVATE_TARGETS_ENV = "DCERT_MCP_DENY_PRIVATE_TARGETS"
|
|
26
|
+
#: Transports FastMCP's ``run`` accepts; ``config.yaml`` lists the subset offered.
|
|
27
|
+
Transport = Literal["stdio", "http", "sse"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resilience_overrides(
|
|
31
|
+
config: ResilienceConfig,
|
|
32
|
+
*,
|
|
33
|
+
no_retry: bool,
|
|
34
|
+
no_circuit_breaker: bool,
|
|
35
|
+
rate_limit: float | None,
|
|
36
|
+
cache: bool,
|
|
37
|
+
bulkhead_max: int | None,
|
|
38
|
+
) -> ResilienceConfig:
|
|
39
|
+
"""Return *config* with the CLI flags applied.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
ValueError: If a flag sets a value outside its valid range.
|
|
43
|
+
"""
|
|
44
|
+
return replace(
|
|
45
|
+
config,
|
|
46
|
+
retry_enabled=config.retry_enabled and not no_retry,
|
|
47
|
+
circuit_breaker_enabled=config.circuit_breaker_enabled and not no_circuit_breaker,
|
|
48
|
+
rate_limit_enabled=config.rate_limit_enabled or rate_limit is not None,
|
|
49
|
+
rate_limit_rps=config.rate_limit_rps if rate_limit is None else rate_limit,
|
|
50
|
+
cache_enabled=config.cache_enabled or cache,
|
|
51
|
+
bulkhead_max=config.bulkhead_max if bulkhead_max is None else bulkhead_max,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def otel_overrides(config: OTelConfig, *, otel: bool, otel_exporter: str | None) -> OTelConfig:
|
|
56
|
+
"""Return *config* with the CLI flags applied."""
|
|
57
|
+
return replace(
|
|
58
|
+
config,
|
|
59
|
+
enabled=config.enabled or otel,
|
|
60
|
+
exporter=config.exporter if otel_exporter is None else otel_exporter,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@click.command(name="dcert-mcp-proxy", context_settings={"help_option_names": ["-h", "--help"]})
|
|
65
|
+
@click.option(
|
|
66
|
+
"--transport",
|
|
67
|
+
type=click.Choice(_CONFIG.server.transports),
|
|
68
|
+
default=_CONFIG.server.default_transport,
|
|
69
|
+
show_default=True,
|
|
70
|
+
help="Transport mode.",
|
|
71
|
+
)
|
|
72
|
+
@click.option(
|
|
73
|
+
"--host",
|
|
74
|
+
default=_CONFIG.server.host,
|
|
75
|
+
show_default=True,
|
|
76
|
+
help="Bind address for HTTP/SSE mode.",
|
|
77
|
+
)
|
|
78
|
+
@click.option(
|
|
79
|
+
"--auth-token",
|
|
80
|
+
envvar=_CONFIG.server.auth.token_env,
|
|
81
|
+
show_envvar=True,
|
|
82
|
+
default=None,
|
|
83
|
+
help=(
|
|
84
|
+
"Static bearer token required by HTTP/SSE mode "
|
|
85
|
+
f"(at least {_CONFIG.server.auth.min_token_length} characters). "
|
|
86
|
+
"Prefer the environment variable: a flag value is visible in process listings."
|
|
87
|
+
),
|
|
88
|
+
)
|
|
89
|
+
@click.option(
|
|
90
|
+
"--oidc-issuer",
|
|
91
|
+
envvar=_CONFIG.server.auth.oidc_issuer_env,
|
|
92
|
+
show_envvar=True,
|
|
93
|
+
default=None,
|
|
94
|
+
help="OIDC issuer (https) whose access tokens HTTP/SSE mode accepts.",
|
|
95
|
+
)
|
|
96
|
+
@click.option(
|
|
97
|
+
"--oidc-audience",
|
|
98
|
+
envvar=_CONFIG.server.auth.oidc_audience_env,
|
|
99
|
+
show_envvar=True,
|
|
100
|
+
default=None,
|
|
101
|
+
help="Audience the OIDC access tokens must carry.",
|
|
102
|
+
)
|
|
103
|
+
@click.option(
|
|
104
|
+
"--oidc-jwks-uri",
|
|
105
|
+
envvar=_CONFIG.server.auth.oidc_jwks_env,
|
|
106
|
+
show_envvar=True,
|
|
107
|
+
default=None,
|
|
108
|
+
help="JWKS URL (https) with the OIDC signing keys.",
|
|
109
|
+
)
|
|
110
|
+
@click.option(
|
|
111
|
+
"--allowed-hosts",
|
|
112
|
+
multiple=True,
|
|
113
|
+
metavar="HOST[,HOST...]",
|
|
114
|
+
help=(
|
|
115
|
+
"Extra Host header values HTTP/SSE mode accepts besides loopback and the "
|
|
116
|
+
"bind address (repeatable or comma separated)."
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
@click.option(
|
|
120
|
+
"--port",
|
|
121
|
+
type=click.IntRange(1, 65535),
|
|
122
|
+
default=_CONFIG.server.port,
|
|
123
|
+
show_default=True,
|
|
124
|
+
help="Port for HTTP/SSE mode.",
|
|
125
|
+
)
|
|
126
|
+
@click.option(
|
|
127
|
+
"--binary",
|
|
128
|
+
type=click.Path(exists=True, dir_okay=False, executable=True),
|
|
129
|
+
default=None,
|
|
130
|
+
help="Path to the dcert-mcp binary (found on PATH if not set).",
|
|
131
|
+
)
|
|
132
|
+
@click.option("--no-retry", is_flag=True, help="Disable automatic retry on connection errors.")
|
|
133
|
+
@click.option("--no-circuit-breaker", is_flag=True, help="Disable the circuit breaker.")
|
|
134
|
+
@click.option(
|
|
135
|
+
"--rate-limit",
|
|
136
|
+
type=click.FloatRange(min=0, min_open=True),
|
|
137
|
+
default=None,
|
|
138
|
+
metavar="RPS",
|
|
139
|
+
help="Enable rate limiting at RPS requests per second (must be positive).",
|
|
140
|
+
)
|
|
141
|
+
@click.option("--cache", is_flag=True, help="Enable response caching.")
|
|
142
|
+
@click.option(
|
|
143
|
+
"--bulkhead-max",
|
|
144
|
+
type=click.IntRange(min=1),
|
|
145
|
+
default=None,
|
|
146
|
+
metavar="N",
|
|
147
|
+
help=f"Maximum concurrent tool calls (default: {_CONFIG.resilience.bulkhead_max}).",
|
|
148
|
+
)
|
|
149
|
+
@click.option("--otel", is_flag=True, help="Enable OpenTelemetry tracing.")
|
|
150
|
+
@click.option(
|
|
151
|
+
"--otel-exporter",
|
|
152
|
+
type=click.Choice(_CONFIG.otel.exporters),
|
|
153
|
+
default=None,
|
|
154
|
+
help=f"OpenTelemetry exporter (default: {_CONFIG.otel.exporter}).",
|
|
155
|
+
)
|
|
156
|
+
def main(
|
|
157
|
+
transport: Transport,
|
|
158
|
+
host: str,
|
|
159
|
+
auth_token: str | None,
|
|
160
|
+
oidc_issuer: str | None,
|
|
161
|
+
oidc_audience: str | None,
|
|
162
|
+
oidc_jwks_uri: str | None,
|
|
163
|
+
allowed_hosts: tuple[str, ...],
|
|
164
|
+
port: int,
|
|
165
|
+
binary: str | None,
|
|
166
|
+
no_retry: bool,
|
|
167
|
+
no_circuit_breaker: bool,
|
|
168
|
+
rate_limit: float | None,
|
|
169
|
+
cache: bool,
|
|
170
|
+
bulkhead_max: int | None,
|
|
171
|
+
otel: bool,
|
|
172
|
+
otel_exporter: str | None,
|
|
173
|
+
) -> None:
|
|
174
|
+
"""Run the dcert MCP proxy server for TLS certificate analysis."""
|
|
175
|
+
from dcert_mcp.resilience import otel_config_from_env, resilience_config_from_env, setup_otel
|
|
176
|
+
from dcert_mcp.server import create_server
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
resilience = resilience_overrides(
|
|
180
|
+
resilience_config_from_env(),
|
|
181
|
+
no_retry=no_retry,
|
|
182
|
+
no_circuit_breaker=no_circuit_breaker,
|
|
183
|
+
rate_limit=rate_limit,
|
|
184
|
+
cache=cache,
|
|
185
|
+
bulkhead_max=bulkhead_max,
|
|
186
|
+
)
|
|
187
|
+
except ValueError as exc:
|
|
188
|
+
raise click.ClickException(f"invalid resilience setting: {exc}") from exc
|
|
189
|
+
|
|
190
|
+
auth = None
|
|
191
|
+
if transport != "stdio":
|
|
192
|
+
settings = AuthSettings(
|
|
193
|
+
token=auth_token or None,
|
|
194
|
+
oidc_issuer=oidc_issuer or None,
|
|
195
|
+
oidc_audience=oidc_audience or None,
|
|
196
|
+
oidc_jwks_uri=oidc_jwks_uri or None,
|
|
197
|
+
)
|
|
198
|
+
try:
|
|
199
|
+
auth = build_auth(settings, _CONFIG.server.auth)
|
|
200
|
+
except ValueError as exc:
|
|
201
|
+
raise click.ClickException(f"refusing to start: {exc}") from exc
|
|
202
|
+
|
|
203
|
+
setup_otel(otel_overrides(otel_config_from_env(), otel=otel, otel_exporter=otel_exporter))
|
|
204
|
+
try:
|
|
205
|
+
server = create_server(
|
|
206
|
+
binary_path=binary,
|
|
207
|
+
env=child_policy_env(transport),
|
|
208
|
+
resilience=resilience,
|
|
209
|
+
auth=auth,
|
|
210
|
+
)
|
|
211
|
+
except (FileNotFoundError, RuntimeError) as exc:
|
|
212
|
+
raise click.ClickException(str(exc)) from exc
|
|
213
|
+
|
|
214
|
+
if transport == "stdio":
|
|
215
|
+
server.run()
|
|
216
|
+
else:
|
|
217
|
+
hosts = build_allowed_hosts(_CONFIG.server.loopback_hosts, host, allowed_hosts)
|
|
218
|
+
server.run(
|
|
219
|
+
transport=transport,
|
|
220
|
+
host=host,
|
|
221
|
+
port=port,
|
|
222
|
+
middleware=[Middleware(HostHeaderGuard, hosts=hosts)],
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def child_policy_env(transport: str) -> dict[str, str]:
|
|
227
|
+
"""Return the destination policy defaults for the ``dcert-mcp`` child.
|
|
228
|
+
|
|
229
|
+
The child always speaks stdio to this proxy, so it would choose its stdio
|
|
230
|
+
default and allow private destinations. Served over HTTP or SSE, the
|
|
231
|
+
proxy takes requests from the network, so private, loopback and metadata
|
|
232
|
+
addresses are refused unless the operator set the variable themselves,
|
|
233
|
+
as ``dcert-mcp --mode http`` does.
|
|
234
|
+
"""
|
|
235
|
+
if transport == "stdio" or DENY_PRIVATE_TARGETS_ENV in os.environ:
|
|
236
|
+
return {}
|
|
237
|
+
return {DENY_PRIVATE_TARGETS_ENV: "1"}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
if __name__ == "__main__":
|
|
241
|
+
main()
|