openapi-mcpforge 0.1.0__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.
Files changed (92) hide show
  1. mcpforge/__init__.py +8 -0
  2. mcpforge/__main__.py +6 -0
  3. mcpforge/auth/__init__.py +28 -0
  4. mcpforge/auth/models.py +25 -0
  5. mcpforge/auth/providers.py +72 -0
  6. mcpforge/auth/redaction.py +47 -0
  7. mcpforge/auth/resolver.py +42 -0
  8. mcpforge/cli/__init__.py +1 -0
  9. mcpforge/cli/app.py +45 -0
  10. mcpforge/cli/commands/__init__.py +13 -0
  11. mcpforge/cli/commands/import_spec.py +41 -0
  12. mcpforge/cli/commands/init.py +42 -0
  13. mcpforge/cli/commands/inspect.py +56 -0
  14. mcpforge/cli/commands/run.py +44 -0
  15. mcpforge/cli/commands/serve.py +31 -0
  16. mcpforge/cli/commands/test.py +60 -0
  17. mcpforge/cli/commands/validate.py +41 -0
  18. mcpforge/cli/context.py +14 -0
  19. mcpforge/cli/output.py +31 -0
  20. mcpforge/cli/scaffold.py +71 -0
  21. mcpforge/config/__init__.py +37 -0
  22. mcpforge/config/loader.py +44 -0
  23. mcpforge/config/merger.py +25 -0
  24. mcpforge/config/models.py +182 -0
  25. mcpforge/config/secrets.py +94 -0
  26. mcpforge/domain/__init__.py +37 -0
  27. mcpforge/domain/enums.py +42 -0
  28. mcpforge/domain/errors.py +13 -0
  29. mcpforge/domain/models.py +142 -0
  30. mcpforge/domain/parameters.py +33 -0
  31. mcpforge/domain/schemas.py +6 -0
  32. mcpforge/execution/__init__.py +36 -0
  33. mcpforge/execution/client.py +55 -0
  34. mcpforge/execution/engine.py +199 -0
  35. mcpforge/execution/errors.py +83 -0
  36. mcpforge/execution/limits.py +31 -0
  37. mcpforge/execution/request_builder.py +87 -0
  38. mcpforge/execution/response.py +64 -0
  39. mcpforge/execution/retry.py +69 -0
  40. mcpforge/filtering/__init__.py +7 -0
  41. mcpforge/filtering/evaluator.py +26 -0
  42. mcpforge/filtering/policies.py +44 -0
  43. mcpforge/filtering/selectors.py +31 -0
  44. mcpforge/generation/__init__.py +19 -0
  45. mcpforge/generation/collisions.py +24 -0
  46. mcpforge/generation/descriptions.py +15 -0
  47. mcpforge/generation/input_schema.py +53 -0
  48. mcpforge/generation/models.py +32 -0
  49. mcpforge/generation/naming.py +54 -0
  50. mcpforge/generation/service.py +64 -0
  51. mcpforge/ingestion/__init__.py +26 -0
  52. mcpforge/ingestion/errors.py +23 -0
  53. mcpforge/ingestion/loaders/__init__.py +7 -0
  54. mcpforge/ingestion/loaders/file.py +48 -0
  55. mcpforge/ingestion/loaders/remote.py +83 -0
  56. mcpforge/ingestion/normalization/__init__.py +23 -0
  57. mcpforge/ingestion/normalization/operation.py +83 -0
  58. mcpforge/ingestion/normalization/parameters.py +119 -0
  59. mcpforge/ingestion/normalization/references.py +57 -0
  60. mcpforge/ingestion/normalization/schemas.py +76 -0
  61. mcpforge/ingestion/parsers/__init__.py +8 -0
  62. mcpforge/ingestion/parsers/base.py +14 -0
  63. mcpforge/ingestion/parsers/manual.py +82 -0
  64. mcpforge/ingestion/parsers/openapi.py +87 -0
  65. mcpforge/ingestion/parsers/swagger.py +95 -0
  66. mcpforge/ingestion/service.py +84 -0
  67. mcpforge/ingestion/source.py +50 -0
  68. mcpforge/mcp/__init__.py +39 -0
  69. mcpforge/mcp/adapter.py +88 -0
  70. mcpforge/mcp/errors.py +25 -0
  71. mcpforge/mcp/server.py +46 -0
  72. mcpforge/mcp/tools.py +110 -0
  73. mcpforge/mcp/transports.py +51 -0
  74. mcpforge/observability/__init__.py +23 -0
  75. mcpforge/observability/diagnostics.py +45 -0
  76. mcpforge/observability/events.py +58 -0
  77. mcpforge/observability/logging.py +45 -0
  78. mcpforge/runtime/__init__.py +15 -0
  79. mcpforge/runtime/application.py +82 -0
  80. mcpforge/runtime/dependencies.py +77 -0
  81. mcpforge/runtime/lifecycle.py +50 -0
  82. mcpforge/security/__init__.py +40 -0
  83. mcpforge/security/hosts.py +32 -0
  84. mcpforge/security/redaction.py +60 -0
  85. mcpforge/security/safety.py +39 -0
  86. mcpforge/security/ssrf.py +77 -0
  87. mcpforge/security/validation.py +36 -0
  88. openapi_mcpforge-0.1.0.dist-info/METADATA +1566 -0
  89. openapi_mcpforge-0.1.0.dist-info/RECORD +92 -0
  90. openapi_mcpforge-0.1.0.dist-info/WHEEL +4 -0
  91. openapi_mcpforge-0.1.0.dist-info/entry_points.txt +2 -0
  92. openapi_mcpforge-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,77 @@
1
+ """Runtime dependency composition."""
2
+
3
+ import logging
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ from mcpforge.config.loader import load_config
8
+ from mcpforge.config.models import ProjectConfig
9
+ from mcpforge.execution.client import HTTPClient
10
+ from mcpforge.execution.engine import ExecutionEngine
11
+ from mcpforge.filtering.evaluator import filter_document
12
+ from mcpforge.generation.models import ToolDefinition
13
+ from mcpforge.generation.service import generate_tools
14
+ from mcpforge.ingestion.service import ingest_path
15
+ from mcpforge.mcp.server import create_server
16
+ from mcpforge.observability.logging import configure_logging
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class RuntimeDependencies:
21
+ """Fully composed dependencies for a running MCP application."""
22
+
23
+ config: ProjectConfig
24
+ client: HTTPClient
25
+ engine: ExecutionEngine
26
+ tools: tuple[ToolDefinition, ...]
27
+ server: object
28
+ logger: logging.Logger
29
+
30
+
31
+ def build_dependencies(
32
+ config_path: str | Path = "mcpforge.yaml",
33
+ *,
34
+ logger_name: str = "mcpforge",
35
+ ) -> RuntimeDependencies:
36
+ """Load configuration and compose the complete runtime graph."""
37
+
38
+ config = load_config(config_path)
39
+ logger = configure_logging(logger_name=logger_name)
40
+
41
+ document = ingest_path(
42
+ config.source.location,
43
+ format=config.source.format,
44
+ timeout_seconds=config.source.timeout_seconds,
45
+ )
46
+
47
+ if config.source.base_url is not None:
48
+ document = document.model_copy(update={"base_url": str(config.source.base_url)})
49
+
50
+ filtered = filter_document(
51
+ document,
52
+ filters=config.filters,
53
+ security=config.security,
54
+ )
55
+ tools = generate_tools(filtered)
56
+
57
+ client = HTTPClient(
58
+ timeout_seconds=config.http.timeout_seconds,
59
+ verify_tls=config.http.verify_tls,
60
+ )
61
+ engine = ExecutionEngine(config, client, logger=logger)
62
+
63
+ server = create_server(
64
+ engine=engine,
65
+ endpoints=tuple(filtered.endpoints),
66
+ tools=tools,
67
+ name=config.name,
68
+ )
69
+
70
+ return RuntimeDependencies(
71
+ config=config,
72
+ client=client,
73
+ engine=engine,
74
+ tools=tools,
75
+ server=server,
76
+ logger=logger,
77
+ )
@@ -0,0 +1,50 @@
1
+ """Runtime resource lifecycle management."""
2
+
3
+ from collections.abc import AsyncIterator
4
+ from contextlib import asynccontextmanager
5
+
6
+ from mcpforge.execution.client import HTTPClient
7
+
8
+
9
+ class RuntimeLifecycle:
10
+ """Own the lifecycle of shared runtime resources."""
11
+
12
+ def __init__(self, client: HTTPClient) -> None:
13
+ self.client = client
14
+ self._started = False
15
+
16
+ async def start(self) -> None:
17
+ """Start all runtime resources."""
18
+
19
+ if not self._started:
20
+ await self.client.start()
21
+ self._started = True
22
+
23
+ async def close(self) -> None:
24
+ """Close all runtime resources."""
25
+
26
+ if self._started:
27
+ await self.client.close()
28
+ self._started = False
29
+
30
+ async def __aenter__(self) -> "RuntimeLifecycle":
31
+ await self.start()
32
+ return self
33
+
34
+ async def __aexit__(
35
+ self,
36
+ exc_type: type[BaseException] | None,
37
+ exc_value: BaseException | None,
38
+ traceback: object | None,
39
+ ) -> None:
40
+ await self.close()
41
+
42
+ @asynccontextmanager
43
+ async def context(self) -> AsyncIterator["RuntimeLifecycle"]:
44
+ """Expose the lifecycle as an async context manager."""
45
+
46
+ await self.start()
47
+ try:
48
+ yield self
49
+ finally:
50
+ await self.close()
@@ -0,0 +1,40 @@
1
+ """Security policies and network protections."""
2
+
3
+ from mcpforge.security.hosts import (
4
+ enforce_allowed_host,
5
+ host_is_allowed,
6
+ normalize_host,
7
+ )
8
+ from mcpforge.security.redaction import REDACTED, redact_secrets
9
+ from mcpforge.security.safety import (
10
+ classify_method,
11
+ enforce_operation_safety,
12
+ is_operation_allowed,
13
+ )
14
+ from mcpforge.security.ssrf import (
15
+ enforce_safe_addresses,
16
+ is_blocked_ip,
17
+ resolve_host_addresses,
18
+ validate_url_network,
19
+ )
20
+ from mcpforge.security.validation import (
21
+ validate_endpoint_request,
22
+ validate_request_target,
23
+ )
24
+
25
+ __all__ = [
26
+ "REDACTED",
27
+ "classify_method",
28
+ "enforce_allowed_host",
29
+ "enforce_operation_safety",
30
+ "enforce_safe_addresses",
31
+ "host_is_allowed",
32
+ "is_blocked_ip",
33
+ "is_operation_allowed",
34
+ "normalize_host",
35
+ "redact_secrets",
36
+ "resolve_host_addresses",
37
+ "validate_endpoint_request",
38
+ "validate_request_target",
39
+ "validate_url_network",
40
+ ]
@@ -0,0 +1,32 @@
1
+ """Allowed-host policy enforcement."""
2
+
3
+ from urllib.parse import urlparse
4
+
5
+
6
+ def normalize_host(host: str) -> str:
7
+ """Normalize a hostname for case-insensitive comparison."""
8
+
9
+ return host.strip().rstrip(".").lower()
10
+
11
+
12
+ def host_is_allowed(host: str, allowed_hosts: set[str]) -> bool:
13
+ """Check a hostname against an explicit allowlist.
14
+
15
+ Exact host matches are required. Wildcards are intentionally unsupported
16
+ to prevent accidental exposure of unrelated subdomains.
17
+ """
18
+
19
+ if not allowed_hosts:
20
+ return True
21
+ normalized = normalize_host(host)
22
+ return normalized in {normalize_host(item) for item in allowed_hosts}
23
+
24
+
25
+ def enforce_allowed_host(url: str, allowed_hosts: set[str]) -> None:
26
+ """Raise ``PermissionError`` when a URL host is not allowed."""
27
+
28
+ parsed = urlparse(url)
29
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
30
+ raise PermissionError("only HTTP and HTTPS URLs with a hostname are allowed")
31
+ if not host_is_allowed(parsed.hostname, allowed_hosts):
32
+ raise PermissionError(f"host is not allowed: {parsed.hostname}")
@@ -0,0 +1,60 @@
1
+ """Security-layer recursive secret redaction."""
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from typing import Any
5
+
6
+ REDACTED = "***REDACTED***"
7
+
8
+ _SENSITIVE_KEYS = frozenset(
9
+ {
10
+ "authorization",
11
+ "proxy-authorization",
12
+ "cookie",
13
+ "set-cookie",
14
+ "token",
15
+ "password",
16
+ "secret",
17
+ "api_key",
18
+ "api-key",
19
+ "access_token",
20
+ "refresh_token",
21
+ "client_secret",
22
+ }
23
+ )
24
+
25
+
26
+ def _normalized_key(value: object) -> str:
27
+ return str(value).strip().lower().replace("-", "_")
28
+
29
+
30
+ def redact_secrets(
31
+ value: Any,
32
+ secrets: Sequence[str] = (),
33
+ ) -> Any:
34
+ """Recursively redact sensitive keys and known secret values."""
35
+
36
+ clean_secrets = tuple(secret for secret in secrets if secret)
37
+
38
+ if isinstance(value, Mapping):
39
+ return {
40
+ key: (
41
+ REDACTED
42
+ if _normalized_key(key) in _SENSITIVE_KEYS
43
+ else redact_secrets(child, clean_secrets)
44
+ )
45
+ for key, child in value.items()
46
+ }
47
+
48
+ if isinstance(value, list):
49
+ return [redact_secrets(item, clean_secrets) for item in value]
50
+
51
+ if isinstance(value, tuple):
52
+ return tuple(redact_secrets(item, clean_secrets) for item in value)
53
+
54
+ if isinstance(value, str):
55
+ result = value
56
+ for secret in clean_secrets:
57
+ result = result.replace(secret, REDACTED)
58
+ return result
59
+
60
+ return value
@@ -0,0 +1,39 @@
1
+ """Operation safety enforcement."""
2
+
3
+ from mcpforge.config.models import SecurityConfig
4
+ from mcpforge.domain.enums import HttpMethod, OperationSafety
5
+ from mcpforge.domain.models import Endpoint
6
+
7
+
8
+ def classify_method(method: HttpMethod) -> OperationSafety:
9
+ """Classify an HTTP method by mutation risk."""
10
+
11
+ if method is HttpMethod.DELETE:
12
+ return OperationSafety.DELETE
13
+ if method in {HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH}:
14
+ return OperationSafety.WRITE
15
+ return OperationSafety.READ
16
+
17
+
18
+ def is_operation_allowed(endpoint: Endpoint, config: SecurityConfig) -> bool:
19
+ """Return whether an endpoint is permitted by the configured policy."""
20
+
21
+ safety = endpoint.safety or classify_method(endpoint.method)
22
+ if safety is OperationSafety.DELETE:
23
+ return config.allow_delete_operations
24
+ if safety is OperationSafety.WRITE:
25
+ return config.allow_write_operations
26
+ return True
27
+
28
+
29
+ def enforce_operation_safety(
30
+ endpoint: Endpoint,
31
+ config: SecurityConfig,
32
+ ) -> None:
33
+ """Raise ``PermissionError`` when an operation is not allowed."""
34
+
35
+ if not is_operation_allowed(endpoint, config):
36
+ safety = endpoint.safety or classify_method(endpoint.method)
37
+ raise PermissionError(
38
+ f"{safety.value} operation is disabled for {endpoint.method.value} {endpoint.path}"
39
+ )
@@ -0,0 +1,77 @@
1
+ """SSRF and unsafe-network protection."""
2
+
3
+ import ipaddress
4
+ import socket
5
+ from collections.abc import Iterable
6
+ from urllib.parse import urlparse
7
+
8
+
9
+ def is_blocked_ip(address: str) -> bool:
10
+ """Return whether an address belongs to an unsafe or special range."""
11
+
12
+ try:
13
+ ip = ipaddress.ip_address(address)
14
+ except ValueError:
15
+ return True
16
+
17
+ return any(
18
+ (
19
+ ip.is_private,
20
+ ip.is_loopback,
21
+ ip.is_link_local,
22
+ ip.is_multicast,
23
+ ip.is_reserved,
24
+ ip.is_unspecified,
25
+ )
26
+ )
27
+
28
+
29
+ def resolve_host_addresses(host: str, port: int) -> tuple[str, ...]:
30
+ """Resolve all IPv4 and IPv6 addresses for a hostname."""
31
+
32
+ try:
33
+ results = socket.getaddrinfo(
34
+ host,
35
+ port,
36
+ type=socket.SOCK_STREAM,
37
+ )
38
+ except socket.gaierror:
39
+ # The HTTP client will report an unreachable hostname if it is real.
40
+ # Returning no resolved addresses also lets mocked transports handle
41
+ # test hosts without weakening checks for hosts that do resolve.
42
+ return ()
43
+ addresses = {str(result[4][0]) for result in results}
44
+ return tuple(sorted(addresses))
45
+
46
+
47
+ def enforce_safe_addresses(addresses: Iterable[str]) -> None:
48
+ """Reject any unsafe resolved address."""
49
+
50
+ unsafe = [address for address in addresses if is_blocked_ip(address)]
51
+ if unsafe:
52
+ raise PermissionError(f"request resolves to blocked network address: {unsafe[0]}")
53
+
54
+
55
+ def validate_url_network(url: str) -> tuple[str, ...]:
56
+ """Validate URL syntax and resolved network addresses."""
57
+
58
+ parsed = urlparse(url)
59
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
60
+ raise PermissionError("only HTTP and HTTPS URLs are allowed")
61
+
62
+ host = parsed.hostname
63
+ if host.lower() == "localhost":
64
+ raise PermissionError("localhost requests are blocked")
65
+
66
+ try:
67
+ direct_ip = ipaddress.ip_address(host)
68
+ except ValueError:
69
+ direct_ip = None
70
+
71
+ if direct_ip is not None:
72
+ addresses: tuple[str, ...] = (str(direct_ip),)
73
+ else:
74
+ addresses = resolve_host_addresses(host, parsed.port or 443)
75
+
76
+ enforce_safe_addresses(addresses)
77
+ return addresses
@@ -0,0 +1,36 @@
1
+ """Cross-cutting request security validation."""
2
+
3
+ from urllib.parse import urlparse
4
+
5
+ from mcpforge.config.models import SecurityConfig
6
+ from mcpforge.domain.models import Endpoint
7
+ from mcpforge.security.hosts import enforce_allowed_host
8
+ from mcpforge.security.safety import enforce_operation_safety
9
+ from mcpforge.security.ssrf import validate_url_network
10
+
11
+
12
+ def validate_request_target(
13
+ url: str,
14
+ config: SecurityConfig,
15
+ ) -> None:
16
+ """Validate host allowlists, URL syntax, and SSRF protections."""
17
+
18
+ parsed = urlparse(url)
19
+ if not parsed.hostname:
20
+ raise PermissionError("request URL has no hostname")
21
+
22
+ enforce_allowed_host(url, config.allowed_hosts)
23
+
24
+ if config.block_private_networks:
25
+ validate_url_network(url)
26
+
27
+
28
+ def validate_endpoint_request(
29
+ endpoint: Endpoint,
30
+ url: str,
31
+ config: SecurityConfig,
32
+ ) -> None:
33
+ """Validate both operation safety and network target."""
34
+
35
+ enforce_operation_safety(endpoint, config)
36
+ validate_request_target(url, config)