bizteamai-smcp-biz 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_biz-1.13.1.dist-info/METADATA +119 -0
- bizteamai_smcp_biz-1.13.1.dist-info/RECORD +21 -0
- bizteamai_smcp_biz-1.13.1.dist-info/WHEEL +5 -0
- bizteamai_smcp_biz-1.13.1.dist-info/entry_points.txt +5 -0
- bizteamai_smcp_biz-1.13.1.dist-info/top_level.txt +1 -0
- smcp/__init__.py +53 -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 +76 -0
- smcp/confirm.py +262 -0
- smcp/cpu.py +67 -0
- smcp/decorators.py +97 -0
- smcp/enforce.py +132 -0
- smcp/filters.py +176 -0
- smcp/license.py +232 -0
- smcp/logchain.py +270 -0
- smcp/tls.py +160 -0
@@ -0,0 +1,119 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: bizteamai-smcp-biz
|
3
|
+
Version: 1.13.1
|
4
|
+
Summary: SMCP Business Edition - Secure Model Context Protocol with advanced licensing
|
5
|
+
Author-email: BizTeam AI <support@bizteamai.com>
|
6
|
+
License: Commercial
|
7
|
+
Project-URL: Homepage, https://github.com/bizteamai
|
8
|
+
Project-URL: Documentation, https://github.com/bizteamai/smcp-biz
|
9
|
+
Project-URL: Repository, https://github.com/bizteamai/smcp-biz
|
10
|
+
Project-URL: Bug Tracker, https://github.com/bizteamai/smcp-biz/issues
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
12
|
+
Classifier: Intended Audience :: Developers
|
13
|
+
Classifier: License :: Other/Proprietary License
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
18
|
+
Requires-Python: >=3.10
|
19
|
+
Description-Content-Type: text/markdown
|
20
|
+
Requires-Dist: mcp
|
21
|
+
Requires-Dist: fastmcp
|
22
|
+
Requires-Dist: cryptography
|
23
|
+
Requires-Dist: pyyaml
|
24
|
+
Requires-Dist: psutil>=5.8.0
|
25
|
+
Requires-Dist: requests>=2.25.0
|
26
|
+
Provides-Extra: support
|
27
|
+
Requires-Dist: psutil>=5.8.0; extra == "support"
|
28
|
+
Requires-Dist: requests>=2.25.0; extra == "support"
|
29
|
+
|
30
|
+
# SMCP Business Edition
|
31
|
+
|
32
|
+
Professional secure MCP server implementation with advanced licensing and enterprise features.
|
33
|
+
|
34
|
+
## Key Features
|
35
|
+
|
36
|
+
- **Core-based Licensing**: License validation based on CPU core usage
|
37
|
+
- **Runtime Enforcement**: Graceful enforcement with 15-minute grace period
|
38
|
+
- **Automatic Renewal**: Hot-reload license keys without restarts
|
39
|
+
- **Revocation Support**: Remote revocation list checking
|
40
|
+
- **Enterprise Security**: All community features plus advanced compliance
|
41
|
+
- **Professional Support**: Priority support and SLA guarantees
|
42
|
+
- **Seamless Upgrade**: Same import (`import smcp`) as community edition
|
43
|
+
|
44
|
+
## Installation
|
45
|
+
|
46
|
+
### Business Edition
|
47
|
+
#### From Private PyPI Server
|
48
|
+
```bash
|
49
|
+
pip install --extra-index-url https://bizteamai.com/pypi/simple/ smcp-biz
|
50
|
+
```
|
51
|
+
|
52
|
+
#### With Upload Authentication (for contributors)
|
53
|
+
```bash
|
54
|
+
# For uploading packages (requires token authentication)
|
55
|
+
pip install --extra-index-url https://<upload-token>@bizteamai.com/pypi/simple/ bizteam-smcp-biz
|
56
|
+
```
|
57
|
+
|
58
|
+
**Note**:
|
59
|
+
- Package name is `smcp-biz` but imports as `smcp` for seamless upgrade from community edition
|
60
|
+
- Public downloads don't require authentication
|
61
|
+
- Upload operations require a valid token
|
62
|
+
- Private PyPI server hosted at `https://bizteamai.com/pypi/`
|
63
|
+
|
64
|
+
### Community Edition
|
65
|
+
|
66
|
+
The community edition (`bizteam-smcp`) is available on PyPI.org:
|
67
|
+
```bash
|
68
|
+
# Community edition from PyPI.org
|
69
|
+
pip install bizteam-smcp
|
70
|
+
|
71
|
+
# Or from private PyPI
|
72
|
+
pip install --extra-index-url https://bizteamai.com/pypi/simple/ bizteam-smcp
|
73
|
+
```
|
74
|
+
|
75
|
+
## License Configuration
|
76
|
+
|
77
|
+
Set your license file path:
|
78
|
+
```bash
|
79
|
+
export BIZTEAM_LICENSE_FILE=/etc/bizteam/license.txt
|
80
|
+
```
|
81
|
+
|
82
|
+
Or set the license key directly:
|
83
|
+
```bash
|
84
|
+
export BIZTEAM_LICENSE_KEY="BZT.customer.cores.expiry.nonce.signature"
|
85
|
+
```
|
86
|
+
|
87
|
+
## Development Mode
|
88
|
+
|
89
|
+
For development and testing:
|
90
|
+
```bash
|
91
|
+
export BIZTEAM_DEV_MODE=1 # Disables license checking
|
92
|
+
```
|
93
|
+
|
94
|
+
## Usage
|
95
|
+
|
96
|
+
```python
|
97
|
+
import smcp # Same import as community edition
|
98
|
+
# Business edition will be used if installed
|
99
|
+
```
|
100
|
+
|
101
|
+
## CLI Tools
|
102
|
+
|
103
|
+
Enhanced CLI tools included:
|
104
|
+
```bash
|
105
|
+
smcp-gen-key # Generate license keys
|
106
|
+
smcp-approve # Approve pending actions
|
107
|
+
smcp-mkcert # Certificate generation
|
108
|
+
smcp-revoke # License revocation
|
109
|
+
```
|
110
|
+
|
111
|
+
## Support
|
112
|
+
|
113
|
+
- **Technical Support**: support@bizteamai.com
|
114
|
+
- **Sales Inquiries**: sales@bizteamai.com
|
115
|
+
- **GitHub**: https://github.com/bizteamai/smcp-biz
|
116
|
+
|
117
|
+
## License
|
118
|
+
|
119
|
+
This is commercial software distributed under a proprietary license. A valid license key is required for production use.
|
@@ -0,0 +1,21 @@
|
|
1
|
+
smcp/__init__.py,sha256=wjnXjqkSQubRo5P70GzH39N4DI9saRJfpso4AYqsN2Y,1674
|
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=idntYvXFmATIt5eKlYGVxvtH0TMANpNU9FZtSCrpCVY,2127
|
6
|
+
smcp/decorators.py,sha256=8kAHBch9trJEsRXcCl2AlolUYmyM5MZG1QB1wsRZ1tc,3426
|
7
|
+
smcp/enforce.py,sha256=kiymcEvdXAA1SweSpOYywS9Gfvfa1zPeWhUdJ9Ek6GY,4642
|
8
|
+
smcp/filters.py,sha256=8YHWUj-pYoFZyNrQymyGcoL9TUyPz_YyXcuWa3zPhvg,6054
|
9
|
+
smcp/license.py,sha256=ksCwsZMw57SOU9E9uhskyyHc-oHY2C273wdox49KXvw,6841
|
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=bmD8x9l8-opmVqPvVKEnO84QsQ7k_pztw-HvCmREe8Y,2559
|
15
|
+
smcp/cli/mkcert.py,sha256=JI12e3OJGa_HwkVBfzDAxTarUV_bAujOfSj1TPd_Tqw,10161
|
16
|
+
smcp/cli/revoke.py,sha256=rERtBhqdcmUxLBsWmEI6sp1vlZRjIeVHSIj2T-yzs_k,2675
|
17
|
+
bizteamai_smcp_biz-1.13.1.dist-info/METADATA,sha256=TnKQoF28MhosO-vIWQRC8UcOL5RBN0MGHEkfrDYybOQ,3645
|
18
|
+
bizteamai_smcp_biz-1.13.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
19
|
+
bizteamai_smcp_biz-1.13.1.dist-info/entry_points.txt,sha256=vSlSkuuQ5SX83RZnSkL5uR7rI61crto6b9FLwSEYtxo,162
|
20
|
+
bizteamai_smcp_biz-1.13.1.dist-info/top_level.txt,sha256=NC_CT8OBJEqtDZkUDD9oM8UTD_COXbkff6feQ3E82hw,5
|
21
|
+
bizteamai_smcp_biz-1.13.1.dist-info/RECORD,,
|
@@ -0,0 +1 @@
|
|
1
|
+
smcp
|
smcp/__init__.py
ADDED
@@ -0,0 +1,53 @@
|
|
1
|
+
"""
|
2
|
+
SMCP Business Edition - Secure Model Context Protocol
|
3
|
+
|
4
|
+
Professional secure MCP server implementation with core-based licensing.
|
5
|
+
"""
|
6
|
+
|
7
|
+
import logging
|
8
|
+
import atexit
|
9
|
+
import os
|
10
|
+
|
11
|
+
from .license import verify_license, get_licensed_cores
|
12
|
+
from .enforce import start_enforcement
|
13
|
+
|
14
|
+
# Import core SMCP functionality
|
15
|
+
from .app_wrapper import FastSMCP
|
16
|
+
from .decorators import tool, prompt, retrieval
|
17
|
+
|
18
|
+
__version__ = "0.1.0"
|
19
|
+
__all__ = ["FastSMCP", "tool", "prompt", "retrieval"]
|
20
|
+
|
21
|
+
# Initialize licensing system
|
22
|
+
logger = logging.getLogger(__name__)
|
23
|
+
|
24
|
+
def _initialize_licensing():
|
25
|
+
"""Initialize the licensing system on module import."""
|
26
|
+
try:
|
27
|
+
# Check if we're in development/testing mode
|
28
|
+
if os.getenv('BIZTEAM_DEV_MODE') == '1':
|
29
|
+
logger.info("SMCP Business Edition - Development mode (license checking disabled)")
|
30
|
+
return
|
31
|
+
|
32
|
+
# Verify license on import
|
33
|
+
license_info = verify_license()
|
34
|
+
if license_info:
|
35
|
+
licensed_cores = get_licensed_cores()
|
36
|
+
logger.info(f"SMCP Business Edition - Licensed for {licensed_cores} cores")
|
37
|
+
|
38
|
+
# Start enforcement monitoring
|
39
|
+
start_enforcement()
|
40
|
+
else:
|
41
|
+
logger.error("SMCP Business Edition - Invalid or missing license")
|
42
|
+
raise RuntimeError("Valid license required for SMCP Business Edition")
|
43
|
+
|
44
|
+
except Exception as e:
|
45
|
+
logger.error(f"License initialization failed: {e}")
|
46
|
+
if os.getenv('BIZTEAM_DEV_MODE') != '1':
|
47
|
+
raise
|
48
|
+
|
49
|
+
# Initialize on import
|
50
|
+
_initialize_licensing()
|
51
|
+
|
52
|
+
# Clean up on exit
|
53
|
+
atexit.register(lambda: logger.debug("SMCP Business Edition - Shutting down"))
|
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