bizteamai-smcp 1.13.1__py3-none-any.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.
- bizteamai_smcp-1.13.1.dist-info/METADATA +117 -0
- bizteamai_smcp-1.13.1.dist-info/RECORD +21 -0
- bizteamai_smcp-1.13.1.dist-info/WHEEL +5 -0
- bizteamai_smcp-1.13.1.dist-info/entry_points.txt +3 -0
- bizteamai_smcp-1.13.1.dist-info/top_level.txt +1 -0
- smcp/__init__.py +29 -0
- smcp/allowlist.py +169 -0
- smcp/app_wrapper.py +216 -0
- smcp/cli/__init__.py +3 -0
- smcp/cli/approve.py +261 -0
- smcp/cli/gen_key.py +73 -0
- smcp/cli/mkcert.py +327 -0
- smcp/cli/revoke.py +73 -0
- smcp/confirm.py +262 -0
- smcp/cpu.py +67 -0
- smcp/decorators.py +97 -0
- smcp/enforce.py +100 -0
- smcp/filters.py +176 -0
- smcp/license.py +113 -0
- smcp/logchain.py +270 -0
- smcp/tls.py +160 -0
@@ -0,0 +1,117 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: bizteamai-smcp
|
3
|
+
Version: 1.13.1
|
4
|
+
Summary: Secure Model Context Protocol - Security layers for MCP servers
|
5
|
+
Author: SMCP Contributors
|
6
|
+
License: MIT
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
8
|
+
Classifier: Intended Audience :: Developers
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
16
|
+
Requires-Python: >=3.8
|
17
|
+
Description-Content-Type: text/markdown
|
18
|
+
Requires-Dist: mcp
|
19
|
+
Requires-Dist: fastmcp
|
20
|
+
Requires-Dist: cryptography
|
21
|
+
Requires-Dist: pyyaml
|
22
|
+
Provides-Extra: dev
|
23
|
+
Requires-Dist: pytest; extra == "dev"
|
24
|
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
25
|
+
Requires-Dist: black; extra == "dev"
|
26
|
+
Requires-Dist: isort; extra == "dev"
|
27
|
+
Requires-Dist: mypy; extra == "dev"
|
28
|
+
|
29
|
+
# SMCP - Secure Model Context Protocol
|
30
|
+
|
31
|
+
A security-focused wrapper library for MCP (Model Context Protocol) servers, providing multiple layers of protection through conditional guards that activate only when needed.
|
32
|
+
|
33
|
+
## Features
|
34
|
+
|
35
|
+
- **Conditional Security Guards**: Each security layer activates only when its required configuration is present
|
36
|
+
- **Mutual TLS Support**: Automatic certificate-based authentication
|
37
|
+
- **Host Allowlisting**: Outbound connection validation
|
38
|
+
- **Input Sanitization**: Prompt and parameter filtering
|
39
|
+
- **Destructive Action Confirmation**: Queue-based approval system for dangerous operations
|
40
|
+
- **Tamper-proof Logging**: SHA-chained append-only audit logs
|
41
|
+
- **Universal Coverage**: Same decorator factory works for tools, prompts, and retrieval
|
42
|
+
|
43
|
+
## Quick Start
|
44
|
+
|
45
|
+
```python
|
46
|
+
from smcp import FastSMCP as FastMCP
|
47
|
+
from smcp import tool, prompt
|
48
|
+
|
49
|
+
# Configure security features (all optional)
|
50
|
+
cfg = {
|
51
|
+
"ca_path": "ca.pem",
|
52
|
+
"cert_path": "server.pem",
|
53
|
+
"key_path": "server.key",
|
54
|
+
"ALLOWED_HOSTS": ["api.internal.local", "10.0.0.5"],
|
55
|
+
"SAFE_RE": r"^[\w\s.,:;!?-]{1,2048}$",
|
56
|
+
"LOG_PATH": "/var/log/smcp.log"
|
57
|
+
}
|
58
|
+
|
59
|
+
app = FastMCP("myserver", smcp_cfg=cfg)
|
60
|
+
|
61
|
+
@tool(confirm=True) # Requires approval
|
62
|
+
def delete_user(uid: str):
|
63
|
+
...
|
64
|
+
|
65
|
+
@prompt() # Auto-filtered if SAFE_RE present
|
66
|
+
def chat(prompt: str):
|
67
|
+
...
|
68
|
+
```
|
69
|
+
|
70
|
+
## Security Guards
|
71
|
+
|
72
|
+
| Feature | Activation Trigger | Purpose |
|
73
|
+
|---------|-------------------|---------|
|
74
|
+
| Mutual TLS | `ca_path`, `cert_path`, `key_path` in config | Certificate-based authentication |
|
75
|
+
| Host Allowlist | Non-empty `ALLOWED_HOSTS` | Outbound connection validation |
|
76
|
+
| Input Filtering | `SAFE_RE` or `MAX_LEN` defined | Sanitize prompts and parameters |
|
77
|
+
| Action Confirmation | `confirm=True` on decorator | Queue destructive operations for approval |
|
78
|
+
| Audit Logging | `LOG_PATH` set | Tamper-proof operation logging |
|
79
|
+
|
80
|
+
## CLI Tools
|
81
|
+
|
82
|
+
```bash
|
83
|
+
# Generate certificates
|
84
|
+
smcp-mkcert --ca-name "MyCA" --server-name "myserver.local"
|
85
|
+
|
86
|
+
# Approve queued actions
|
87
|
+
smcp-approve <action-id>
|
88
|
+
```
|
89
|
+
|
90
|
+
## Installation
|
91
|
+
|
92
|
+
### From PyPI.org (Public)
|
93
|
+
|
94
|
+
```bash
|
95
|
+
pip install bizteam-smcp
|
96
|
+
```
|
97
|
+
|
98
|
+
### From Private PyPI Server
|
99
|
+
|
100
|
+
```bash
|
101
|
+
# Using private PyPI server
|
102
|
+
pip install --extra-index-url https://bizteamai.com/pypi/simple/ bizteam-smcp
|
103
|
+
```
|
104
|
+
|
105
|
+
### Upgrading to Business Edition
|
106
|
+
|
107
|
+
For additional features and enterprise support, a business edition is available:
|
108
|
+
|
109
|
+
```bash
|
110
|
+
pip install --extra-index-url https://bizteamai.com/pypi/simple/ bizteam-smcp-biz
|
111
|
+
```
|
112
|
+
|
113
|
+
**Contact**: [business@bizteamai.com](mailto:business@bizteamai.com) for more information.
|
114
|
+
|
115
|
+
## License
|
116
|
+
|
117
|
+
MIT License
|
@@ -0,0 +1,21 @@
|
|
1
|
+
smcp/__init__.py,sha256=VUcL_NuIkyGPPZaqNeQLsuxd1e6SlhP9U3J5SlJ9dMA,894
|
2
|
+
smcp/allowlist.py,sha256=hitqBxRi-_I3LJm_w2a-QCLQdCllWtJVd7IIR1RSSKU,4474
|
3
|
+
smcp/app_wrapper.py,sha256=miqt_MOwQRDszwlPXyxd96XV6LUCvcZBNo8VL1GUghA,7435
|
4
|
+
smcp/confirm.py,sha256=74OluC4kyW1GIc2cGWa19m7q4wTbAOkiDtoJtoY3EXk,7725
|
5
|
+
smcp/cpu.py,sha256=0_sCaj1sixt9K7DTAcdWnmeZlCgaBIlkndwOOQ1E7UM,2126
|
6
|
+
smcp/decorators.py,sha256=8kAHBch9trJEsRXcCl2AlolUYmyM5MZG1QB1wsRZ1tc,3426
|
7
|
+
smcp/enforce.py,sha256=mZpQq7poWrQs-PHYY3jG8pPoQZn81gXDEKCQzRnRU90,3821
|
8
|
+
smcp/filters.py,sha256=8YHWUj-pYoFZyNrQymyGcoL9TUyPz_YyXcuWa3zPhvg,6054
|
9
|
+
smcp/license.py,sha256=CMrSYDAHdaC7xV7ARVupYqbf7Fk5t59mIeC_3_zvvCM,3766
|
10
|
+
smcp/logchain.py,sha256=SI-UQ5cMQuufS2-5ONdRomGuSoaMx4aNz3zE0CNRO6c,8353
|
11
|
+
smcp/tls.py,sha256=w8LtI--lHV2XMxXKRAfEL2sqQOi-1zaAPFg0RUSp-JY,4965
|
12
|
+
smcp/cli/__init__.py,sha256=D-dTgVCOE7e3QNZdPj_hoj2VOIlgNRvF728ldPQ0fKE,40
|
13
|
+
smcp/cli/approve.py,sha256=i3d-kgPX6lp-5vCZzxrhletYoZvSDx3dRLxqHeauPJ4,8815
|
14
|
+
smcp/cli/gen_key.py,sha256=WGYWfiplQgbHqTki8KxQzFsXjdVFXSmQmxYYOT4P9xQ,2558
|
15
|
+
smcp/cli/mkcert.py,sha256=JI12e3OJGa_HwkVBfzDAxTarUV_bAujOfSj1TPd_Tqw,10161
|
16
|
+
smcp/cli/revoke.py,sha256=hfTwR8tH1pH6MtBJv8EB5pZUj1cetFaZcDGENerpgm0,2413
|
17
|
+
bizteamai_smcp-1.13.1.dist-info/METADATA,sha256=5UN_JqzKKr4F72h8rrMnrXiG7ZmxmE1WROy4JH7GQbs,3584
|
18
|
+
bizteamai_smcp-1.13.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
19
|
+
bizteamai_smcp-1.13.1.dist-info/entry_points.txt,sha256=Ol5RQFBMTxosIsEfDJDA4R1MoAp0eGpysmIpvBv2cdw,90
|
20
|
+
bizteamai_smcp-1.13.1.dist-info/top_level.txt,sha256=NC_CT8OBJEqtDZkUDD9oM8UTD_COXbkff6feQ3E82hw,5
|
21
|
+
bizteamai_smcp-1.13.1.dist-info/RECORD,,
|
@@ -0,0 +1 @@
|
|
1
|
+
smcp
|
smcp/__init__.py
ADDED
@@ -0,0 +1,29 @@
|
|
1
|
+
"""
|
2
|
+
SMCP - Secure Model Context Protocol
|
3
|
+
|
4
|
+
A security-focused wrapper library for MCP servers providing conditional
|
5
|
+
security guards that activate only when their required configuration is present.
|
6
|
+
"""
|
7
|
+
|
8
|
+
import logging
|
9
|
+
|
10
|
+
from .app_wrapper import FastSMCP
|
11
|
+
from .decorators import tool, prompt, retrieval
|
12
|
+
|
13
|
+
__version__ = "0.1.0"
|
14
|
+
__all__ = ["FastSMCP", "tool", "prompt", "retrieval"]
|
15
|
+
|
16
|
+
# Non-intrusive watermark for community edition
|
17
|
+
def _show_watermark():
|
18
|
+
"""Display a subtle watermark message for the community edition."""
|
19
|
+
logger = logging.getLogger(__name__)
|
20
|
+
logger.info("SMCP Community Edition - For commercial licensing visit: https://smcp.dev/business")
|
21
|
+
|
22
|
+
# Show watermark on import (only once)
|
23
|
+
try:
|
24
|
+
if not hasattr(_show_watermark, '_shown'):
|
25
|
+
_show_watermark()
|
26
|
+
_show_watermark._shown = True
|
27
|
+
except Exception:
|
28
|
+
# Silently fail if logging isn't configured
|
29
|
+
pass
|
smcp/allowlist.py
ADDED
@@ -0,0 +1,169 @@
|
|
1
|
+
"""
|
2
|
+
Host allowlist validation for outbound connections.
|
3
|
+
"""
|
4
|
+
|
5
|
+
import ipaddress
|
6
|
+
import re
|
7
|
+
from typing import Dict, List, Union
|
8
|
+
from urllib.parse import urlparse
|
9
|
+
|
10
|
+
|
11
|
+
class HostValidationError(Exception):
|
12
|
+
"""Raised when a host fails allowlist validation."""
|
13
|
+
pass
|
14
|
+
|
15
|
+
|
16
|
+
def validate_host(target: str, cfg: Dict[str, Union[str, List[str]]]) -> None:
|
17
|
+
"""
|
18
|
+
Validate that a target host is in the allowlist.
|
19
|
+
|
20
|
+
Args:
|
21
|
+
target: Target host, URL, or IP address to validate
|
22
|
+
cfg: Configuration dictionary containing ALLOWED_HOSTS
|
23
|
+
|
24
|
+
Raises:
|
25
|
+
HostValidationError: If the host is not in the allowlist
|
26
|
+
"""
|
27
|
+
allowed_hosts = cfg.get("ALLOWED_HOSTS", [])
|
28
|
+
if not allowed_hosts:
|
29
|
+
return # No allowlist configured, allow all
|
30
|
+
|
31
|
+
# Extract hostname from URL if needed
|
32
|
+
hostname = _extract_hostname(target)
|
33
|
+
|
34
|
+
# Check against allowlist
|
35
|
+
if not _is_host_allowed(hostname, allowed_hosts):
|
36
|
+
raise HostValidationError(f"Host '{hostname}' not in allowlist")
|
37
|
+
|
38
|
+
|
39
|
+
def _extract_hostname(target: str) -> str:
|
40
|
+
"""
|
41
|
+
Extract hostname from a target string (URL, hostname, or IP).
|
42
|
+
|
43
|
+
Args:
|
44
|
+
target: Target string to parse
|
45
|
+
|
46
|
+
Returns:
|
47
|
+
Extracted hostname or IP address
|
48
|
+
"""
|
49
|
+
# If it looks like a URL, parse it
|
50
|
+
if "://" in target:
|
51
|
+
parsed = urlparse(target)
|
52
|
+
return parsed.hostname or parsed.netloc
|
53
|
+
|
54
|
+
# If it contains a port, strip it
|
55
|
+
if ":" in target and not _is_ipv6(target):
|
56
|
+
return target.split(":")[0]
|
57
|
+
|
58
|
+
return target
|
59
|
+
|
60
|
+
|
61
|
+
def _is_ipv6(address: str) -> bool:
|
62
|
+
"""Check if a string is an IPv6 address."""
|
63
|
+
try:
|
64
|
+
ipaddress.IPv6Address(address)
|
65
|
+
return True
|
66
|
+
except ipaddress.AddressValueError:
|
67
|
+
return False
|
68
|
+
|
69
|
+
|
70
|
+
def _is_host_allowed(hostname: str, allowed_hosts: List[str]) -> bool:
|
71
|
+
"""
|
72
|
+
Check if a hostname is in the allowlist.
|
73
|
+
|
74
|
+
Args:
|
75
|
+
hostname: Hostname to check
|
76
|
+
allowed_hosts: List of allowed hosts (can include patterns)
|
77
|
+
|
78
|
+
Returns:
|
79
|
+
True if the hostname is allowed
|
80
|
+
"""
|
81
|
+
for allowed in allowed_hosts:
|
82
|
+
if _host_matches(hostname, allowed):
|
83
|
+
return True
|
84
|
+
return False
|
85
|
+
|
86
|
+
|
87
|
+
def _host_matches(hostname: str, pattern: str) -> bool:
|
88
|
+
"""
|
89
|
+
Check if a hostname matches an allowlist pattern.
|
90
|
+
|
91
|
+
Supports:
|
92
|
+
- Exact matches: "api.example.com"
|
93
|
+
- Wildcard subdomains: "*.example.com"
|
94
|
+
- IP addresses: "192.168.1.1"
|
95
|
+
- IP ranges: "192.168.1.0/24"
|
96
|
+
|
97
|
+
Args:
|
98
|
+
hostname: Hostname to check
|
99
|
+
pattern: Pattern to match against
|
100
|
+
|
101
|
+
Returns:
|
102
|
+
True if the hostname matches the pattern
|
103
|
+
"""
|
104
|
+
# Exact match
|
105
|
+
if hostname == pattern:
|
106
|
+
return True
|
107
|
+
|
108
|
+
# Wildcard subdomain match
|
109
|
+
if pattern.startswith("*."):
|
110
|
+
domain = pattern[2:]
|
111
|
+
return hostname.endswith(f".{domain}") or hostname == domain
|
112
|
+
|
113
|
+
# IP range match
|
114
|
+
if "/" in pattern:
|
115
|
+
try:
|
116
|
+
network = ipaddress.ip_network(pattern, strict=False)
|
117
|
+
address = ipaddress.ip_address(hostname)
|
118
|
+
return address in network
|
119
|
+
except (ipaddress.AddressValueError, ValueError):
|
120
|
+
pass
|
121
|
+
|
122
|
+
# Regex pattern match (if pattern contains regex characters)
|
123
|
+
if any(char in pattern for char in r"[](){}+?^$|\\"):
|
124
|
+
try:
|
125
|
+
return bool(re.match(pattern, hostname))
|
126
|
+
except re.error:
|
127
|
+
pass
|
128
|
+
|
129
|
+
return False
|
130
|
+
|
131
|
+
|
132
|
+
def add_host_to_allowlist(cfg: Dict[str, List[str]], host: str) -> None:
|
133
|
+
"""
|
134
|
+
Add a host to the allowlist configuration.
|
135
|
+
|
136
|
+
Args:
|
137
|
+
cfg: Configuration dictionary to modify
|
138
|
+
host: Host to add to the allowlist
|
139
|
+
"""
|
140
|
+
if "ALLOWED_HOSTS" not in cfg:
|
141
|
+
cfg["ALLOWED_HOSTS"] = []
|
142
|
+
|
143
|
+
if host not in cfg["ALLOWED_HOSTS"]:
|
144
|
+
cfg["ALLOWED_HOSTS"].append(host)
|
145
|
+
|
146
|
+
|
147
|
+
def remove_host_from_allowlist(cfg: Dict[str, List[str]], host: str) -> None:
|
148
|
+
"""
|
149
|
+
Remove a host from the allowlist configuration.
|
150
|
+
|
151
|
+
Args:
|
152
|
+
cfg: Configuration dictionary to modify
|
153
|
+
host: Host to remove from the allowlist
|
154
|
+
"""
|
155
|
+
if "ALLOWED_HOSTS" in cfg and host in cfg["ALLOWED_HOSTS"]:
|
156
|
+
cfg["ALLOWED_HOSTS"].remove(host)
|
157
|
+
|
158
|
+
|
159
|
+
def get_allowed_hosts(cfg: Dict[str, List[str]]) -> List[str]:
|
160
|
+
"""
|
161
|
+
Get the current allowlist.
|
162
|
+
|
163
|
+
Args:
|
164
|
+
cfg: Configuration dictionary
|
165
|
+
|
166
|
+
Returns:
|
167
|
+
List of allowed hosts
|
168
|
+
"""
|
169
|
+
return cfg.get("ALLOWED_HOSTS", [])
|
smcp/app_wrapper.py
ADDED
@@ -0,0 +1,216 @@
|
|
1
|
+
"""
|
2
|
+
FastSMCP subclass with integrated security features.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from typing import Any, Dict, Optional
|
6
|
+
|
7
|
+
try:
|
8
|
+
from fastmcp import FastMCP as SDKFastMCP
|
9
|
+
except ImportError:
|
10
|
+
# Fallback for testing or when fastmcp is not available
|
11
|
+
class SDKFastMCP:
|
12
|
+
def __init__(self, *args, **kwargs):
|
13
|
+
self.name = args[0] if args else "unknown"
|
14
|
+
|
15
|
+
def run(self, **kwargs):
|
16
|
+
print(f"Running {self.name} with transport")
|
17
|
+
|
18
|
+
from .tls import TLSContextFactory, tls_configured
|
19
|
+
|
20
|
+
|
21
|
+
class FastSMCP(SDKFastMCP):
|
22
|
+
"""
|
23
|
+
Security-enhanced FastMCP server with conditional TLS and configuration injection.
|
24
|
+
|
25
|
+
Automatically enables TLS when certificates are configured and injects
|
26
|
+
security configuration into all decorated functions.
|
27
|
+
"""
|
28
|
+
|
29
|
+
def __init__(self, *args, **kwargs):
|
30
|
+
"""
|
31
|
+
Initialize FastSMCP with security configuration.
|
32
|
+
|
33
|
+
Args:
|
34
|
+
*args: Positional arguments passed to FastMCP
|
35
|
+
**kwargs: Keyword arguments, including optional smcp_cfg
|
36
|
+
"""
|
37
|
+
# Extract SMCP configuration
|
38
|
+
self.smcp_cfg = kwargs.pop("smcp_cfg", {})
|
39
|
+
|
40
|
+
# Initialize base FastMCP
|
41
|
+
super().__init__(*args, **kwargs)
|
42
|
+
|
43
|
+
# Setup TLS if configured
|
44
|
+
if tls_configured(self.smcp_cfg):
|
45
|
+
self._setup_tls()
|
46
|
+
|
47
|
+
def _setup_tls(self) -> None:
|
48
|
+
"""Setup TLS context if certificates are configured."""
|
49
|
+
try:
|
50
|
+
self._tls_context = TLSContextFactory.server_context(self.smcp_cfg)
|
51
|
+
except Exception as e:
|
52
|
+
print(f"Warning: Failed to setup TLS: {e}")
|
53
|
+
self._tls_context = None
|
54
|
+
|
55
|
+
def run(self, transport: str = "tcp", **kwargs) -> None:
|
56
|
+
"""
|
57
|
+
Run the server with security enhancements.
|
58
|
+
|
59
|
+
Args:
|
60
|
+
transport: Transport protocol to use
|
61
|
+
**kwargs: Additional keyword arguments for the server
|
62
|
+
"""
|
63
|
+
# Inject SMCP configuration for decorators
|
64
|
+
kwargs["_smcp_cfg"] = self.smcp_cfg
|
65
|
+
|
66
|
+
# Enable TLS if configured
|
67
|
+
if hasattr(self, "_tls_context") and self._tls_context:
|
68
|
+
kwargs["ssl_context"] = self._tls_context
|
69
|
+
if not transport.endswith("+tls"):
|
70
|
+
transport = f"{transport}+tls"
|
71
|
+
print(f"Starting server with TLS on {transport}")
|
72
|
+
else:
|
73
|
+
print(f"Starting server without TLS on {transport}")
|
74
|
+
|
75
|
+
# Log security configuration status
|
76
|
+
self._log_security_status()
|
77
|
+
|
78
|
+
# Run the server
|
79
|
+
super().run(transport=transport, **kwargs)
|
80
|
+
|
81
|
+
def _log_security_status(self) -> None:
|
82
|
+
"""Log the status of security features."""
|
83
|
+
from .logchain import log_security_event
|
84
|
+
|
85
|
+
features = {
|
86
|
+
"tls_enabled": hasattr(self, "_tls_context") and self._tls_context is not None,
|
87
|
+
"host_allowlist_configured": bool(self.smcp_cfg.get("ALLOWED_HOSTS")),
|
88
|
+
"input_filtering_configured": bool(self.smcp_cfg.get("SAFE_RE")),
|
89
|
+
"confirmation_enabled": self.smcp_cfg.get("CONFIRMATION_ENABLED", True),
|
90
|
+
"logging_enabled": bool(self.smcp_cfg.get("LOG_PATH")),
|
91
|
+
}
|
92
|
+
|
93
|
+
log_security_event("server_startup", features, self.smcp_cfg)
|
94
|
+
|
95
|
+
# Print security status
|
96
|
+
print("Security Features Status:")
|
97
|
+
for feature, enabled in features.items():
|
98
|
+
status = "✓" if enabled else "✗"
|
99
|
+
print(f" {status} {feature.replace('_', ' ').title()}")
|
100
|
+
|
101
|
+
def get_security_config(self) -> Dict[str, Any]:
|
102
|
+
"""
|
103
|
+
Get the current security configuration.
|
104
|
+
|
105
|
+
Returns:
|
106
|
+
Dictionary containing the current security configuration
|
107
|
+
"""
|
108
|
+
return self.smcp_cfg.copy()
|
109
|
+
|
110
|
+
def update_security_config(self, updates: Dict[str, Any]) -> None:
|
111
|
+
"""
|
112
|
+
Update the security configuration.
|
113
|
+
|
114
|
+
Args:
|
115
|
+
updates: Dictionary of configuration updates
|
116
|
+
"""
|
117
|
+
self.smcp_cfg.update(updates)
|
118
|
+
|
119
|
+
# Re-setup TLS if configuration changed
|
120
|
+
if any(key in updates for key in ["ca_path", "cert_path", "key_path"]):
|
121
|
+
if tls_configured(self.smcp_cfg):
|
122
|
+
self._setup_tls()
|
123
|
+
|
124
|
+
def add_allowed_host(self, host: str) -> None:
|
125
|
+
"""
|
126
|
+
Add a host to the allowlist.
|
127
|
+
|
128
|
+
Args:
|
129
|
+
host: Host to add to the allowlist
|
130
|
+
"""
|
131
|
+
if "ALLOWED_HOSTS" not in self.smcp_cfg:
|
132
|
+
self.smcp_cfg["ALLOWED_HOSTS"] = []
|
133
|
+
|
134
|
+
if host not in self.smcp_cfg["ALLOWED_HOSTS"]:
|
135
|
+
self.smcp_cfg["ALLOWED_HOSTS"].append(host)
|
136
|
+
|
137
|
+
def remove_allowed_host(self, host: str) -> None:
|
138
|
+
"""
|
139
|
+
Remove a host from the allowlist.
|
140
|
+
|
141
|
+
Args:
|
142
|
+
host: Host to remove from the allowlist
|
143
|
+
"""
|
144
|
+
if "ALLOWED_HOSTS" in self.smcp_cfg and host in self.smcp_cfg["ALLOWED_HOSTS"]:
|
145
|
+
self.smcp_cfg["ALLOWED_HOSTS"].remove(host)
|
146
|
+
|
147
|
+
def enable_feature(self, feature: str, **kwargs) -> None:
|
148
|
+
"""
|
149
|
+
Enable a security feature with configuration.
|
150
|
+
|
151
|
+
Args:
|
152
|
+
feature: Name of the feature to enable
|
153
|
+
**kwargs: Feature-specific configuration
|
154
|
+
"""
|
155
|
+
if feature == "input_filtering":
|
156
|
+
self.smcp_cfg["SAFE_RE"] = kwargs.get("pattern", r"^[\w\s.,:;!?-]{1,2048}$")
|
157
|
+
self.smcp_cfg["MAX_LEN"] = kwargs.get("max_length", 2048)
|
158
|
+
|
159
|
+
elif feature == "confirmation":
|
160
|
+
self.smcp_cfg["CONFIRMATION_ENABLED"] = True
|
161
|
+
if "queue_file" in kwargs:
|
162
|
+
self.smcp_cfg["QUEUE_FILE"] = kwargs["queue_file"]
|
163
|
+
|
164
|
+
elif feature == "logging":
|
165
|
+
if "log_path" not in kwargs:
|
166
|
+
raise ValueError("log_path required for logging feature")
|
167
|
+
self.smcp_cfg["LOG_PATH"] = kwargs["log_path"]
|
168
|
+
|
169
|
+
elif feature == "host_allowlist":
|
170
|
+
self.smcp_cfg["ALLOWED_HOSTS"] = kwargs.get("hosts", [])
|
171
|
+
|
172
|
+
else:
|
173
|
+
raise ValueError(f"Unknown feature: {feature}")
|
174
|
+
|
175
|
+
def disable_feature(self, feature: str) -> None:
|
176
|
+
"""
|
177
|
+
Disable a security feature.
|
178
|
+
|
179
|
+
Args:
|
180
|
+
feature: Name of the feature to disable
|
181
|
+
"""
|
182
|
+
if feature == "input_filtering":
|
183
|
+
self.smcp_cfg.pop("SAFE_RE", None)
|
184
|
+
self.smcp_cfg.pop("MAX_LEN", None)
|
185
|
+
|
186
|
+
elif feature == "confirmation":
|
187
|
+
self.smcp_cfg["CONFIRMATION_ENABLED"] = False
|
188
|
+
|
189
|
+
elif feature == "logging":
|
190
|
+
self.smcp_cfg.pop("LOG_PATH", None)
|
191
|
+
|
192
|
+
elif feature == "host_allowlist":
|
193
|
+
self.smcp_cfg.pop("ALLOWED_HOSTS", None)
|
194
|
+
|
195
|
+
elif feature == "tls":
|
196
|
+
for key in ["ca_path", "cert_path", "key_path"]:
|
197
|
+
self.smcp_cfg.pop(key, None)
|
198
|
+
if hasattr(self, "_tls_context"):
|
199
|
+
delattr(self, "_tls_context")
|
200
|
+
|
201
|
+
else:
|
202
|
+
raise ValueError(f"Unknown feature: {feature}")
|
203
|
+
|
204
|
+
|
205
|
+
def create_secure_app(name: str, **security_config) -> FastSMCP:
|
206
|
+
"""
|
207
|
+
Create a FastSMCP app with security configuration.
|
208
|
+
|
209
|
+
Args:
|
210
|
+
name: Name of the MCP server
|
211
|
+
**security_config: Security configuration options
|
212
|
+
|
213
|
+
Returns:
|
214
|
+
Configured FastSMCP instance
|
215
|
+
"""
|
216
|
+
return FastSMCP(name, smcp_cfg=security_config)
|
smcp/cli/__init__.py
ADDED