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,119 @@
1
+ """Normalization of endpoint parameters, bodies, and responses."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+
6
+ from mcpforge.domain.enums import ParameterLocation
7
+ from mcpforge.domain.models import Parameter, RequestBody, ResponseDefinition
8
+ from mcpforge.ingestion.errors import SpecificationError
9
+ from mcpforge.ingestion.normalization.references import ReferenceResolver
10
+ from mcpforge.ingestion.normalization.schemas import normalize_schema
11
+
12
+
13
+ def _location(value: str) -> ParameterLocation:
14
+ try:
15
+ return ParameterLocation(value)
16
+ except ValueError as exc:
17
+ raise SpecificationError(f"unsupported parameter location: {value!r}") from exc
18
+
19
+
20
+ def normalize_parameter(
21
+ raw: Mapping[str, Any],
22
+ resolver: ReferenceResolver,
23
+ ) -> Parameter:
24
+ """Normalize an OpenAPI or manual parameter."""
25
+
26
+ name = raw.get("name")
27
+ location = raw.get("in", raw.get("location"))
28
+ if not isinstance(name, str) or not isinstance(location, str):
29
+ raise SpecificationError("parameter requires string name and location")
30
+
31
+ schema_raw = raw.get("schema")
32
+ if schema_raw is None and isinstance(raw.get("type"), str):
33
+ schema_raw = {
34
+ key: raw[key]
35
+ for key in ("type", "format", "items", "enum", "default", "minimum", "maximum")
36
+ if key in raw
37
+ }
38
+
39
+ return Parameter(
40
+ name=name,
41
+ location=_location(location),
42
+ required=bool(raw.get("required", False)),
43
+ description=raw.get("description"),
44
+ schema=normalize_schema(schema_raw or {}, resolver),
45
+ deprecated=bool(raw.get("deprecated", False)),
46
+ example=raw.get("example"),
47
+ )
48
+
49
+
50
+ def normalize_request_body(
51
+ raw: Mapping[str, Any] | None,
52
+ resolver: ReferenceResolver,
53
+ ) -> RequestBody | None:
54
+ """Normalize an OpenAPI request body or Swagger body parameter."""
55
+
56
+ if raw is None:
57
+ return None
58
+
59
+ if raw.get("in") == "body":
60
+ schema_raw = raw.get("schema", {})
61
+ return RequestBody(
62
+ required=bool(raw.get("required", False)),
63
+ content_type="application/json",
64
+ schema=normalize_schema(schema_raw, resolver),
65
+ description=raw.get("description"),
66
+ )
67
+
68
+ content = raw.get("content")
69
+ if isinstance(content, Mapping) and content:
70
+ content_type, media = next(iter(content.items()))
71
+ media_mapping = media if isinstance(media, Mapping) else {}
72
+ return RequestBody(
73
+ required=bool(raw.get("required", False)),
74
+ content_type=str(content_type),
75
+ schema=normalize_schema(media_mapping.get("schema", {}), resolver),
76
+ description=raw.get("description"),
77
+ )
78
+
79
+ raise SpecificationError("request body must define content or a body schema")
80
+
81
+
82
+ def normalize_response(
83
+ status_code: str | int,
84
+ raw: Mapping[str, Any],
85
+ resolver: ReferenceResolver,
86
+ swagger: bool = False,
87
+ ) -> ResponseDefinition:
88
+ """Normalize one OpenAPI or Swagger response."""
89
+
90
+ try:
91
+ status = int(status_code)
92
+ except (TypeError, ValueError) as exc:
93
+ raise SpecificationError(f"invalid response status code: {status_code!r}") from exc
94
+
95
+ if swagger:
96
+ schema = raw.get("schema")
97
+ return ResponseDefinition(
98
+ status_code=status,
99
+ description=raw.get("description"),
100
+ content_type="application/json" if schema else None,
101
+ schema=normalize_schema(schema, resolver) if schema is not None else None,
102
+ )
103
+
104
+ content = raw.get("content")
105
+ if isinstance(content, Mapping) and content:
106
+ content_type, media = next(iter(content.items()))
107
+ media_mapping = media if isinstance(media, Mapping) else {}
108
+ schema = media_mapping.get("schema")
109
+ return ResponseDefinition(
110
+ status_code=status,
111
+ description=raw.get("description"),
112
+ content_type=str(content_type),
113
+ schema=normalize_schema(schema, resolver) if schema is not None else None,
114
+ )
115
+
116
+ return ResponseDefinition(
117
+ status_code=status,
118
+ description=raw.get("description"),
119
+ )
@@ -0,0 +1,57 @@
1
+ """Local JSON Pointer reference resolution with cycle detection."""
2
+
3
+ from collections.abc import Mapping
4
+ from copy import deepcopy
5
+ from typing import Any
6
+
7
+ from mcpforge.ingestion.errors import ReferenceResolutionError
8
+
9
+
10
+ class ReferenceResolver:
11
+ """Resolve local JSON references against one specification document."""
12
+
13
+ def __init__(self, document: Mapping[str, Any]) -> None:
14
+ self._document = document
15
+
16
+ def resolve(self, value: Any, stack: tuple[str, ...] = ()) -> Any:
17
+ """Resolve references recursively while preserving non-reference values."""
18
+
19
+ if isinstance(value, list):
20
+ return [self.resolve(item, stack) for item in value]
21
+
22
+ if not isinstance(value, Mapping):
23
+ return deepcopy(value)
24
+
25
+ if "$ref" in value:
26
+ reference = value["$ref"]
27
+ if not isinstance(reference, str) or not reference.startswith("#/"):
28
+ raise ReferenceResolutionError(
29
+ f"only local references are supported: {reference!r}"
30
+ )
31
+ if reference in stack:
32
+ chain = " -> ".join((*stack, reference))
33
+ raise ReferenceResolutionError(f"cyclic reference detected: {chain}")
34
+
35
+ target = self._lookup(reference)
36
+ resolved = self.resolve(target, (*stack, reference))
37
+
38
+ siblings = {key: item for key, item in value.items() if key != "$ref"}
39
+ if siblings and isinstance(resolved, Mapping):
40
+ merged = dict(resolved)
41
+ merged.update(
42
+ {key: self.resolve(item, (*stack, reference)) for key, item in siblings.items()}
43
+ )
44
+ return merged
45
+ return resolved
46
+
47
+ return {str(key): self.resolve(item, stack) for key, item in value.items()}
48
+
49
+ def _lookup(self, reference: str) -> Any:
50
+ current: Any = self._document
51
+ for token in reference[2:].split("/"):
52
+ token = token.replace("~1", "/").replace("~0", "~")
53
+ if isinstance(current, Mapping) and token in current:
54
+ current = current[token]
55
+ else:
56
+ raise ReferenceResolutionError(f"unresolved local reference: {reference}")
57
+ return current
@@ -0,0 +1,76 @@
1
+ """Conversion of OpenAPI, Swagger, and manual schemas."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+
6
+ from mcpforge.domain.models import JsonSchema
7
+ from mcpforge.ingestion.normalization.references import ReferenceResolver
8
+
9
+
10
+ def normalize_schema(
11
+ raw: Any,
12
+ resolver: ReferenceResolver | None = None,
13
+ ) -> JsonSchema:
14
+ """Convert an arbitrary JSON Schema-like object into ``JsonSchema``."""
15
+
16
+ if raw is None:
17
+ return JsonSchema()
18
+
19
+ if isinstance(raw, bool):
20
+ return JsonSchema(type="boolean" if raw else None)
21
+
22
+ if not isinstance(raw, Mapping):
23
+ raise ValueError("schema must be a mapping")
24
+
25
+ resolved: Mapping[str, Any]
26
+ if resolver is not None:
27
+ resolved_value = resolver.resolve(raw)
28
+ if not isinstance(resolved_value, Mapping):
29
+ raise ValueError("resolved schema must be a mapping")
30
+ resolved = resolved_value
31
+ else:
32
+ resolved = raw
33
+
34
+ properties_raw = resolved.get("properties", {})
35
+ properties = (
36
+ {str(name): normalize_schema(value, resolver) for name, value in properties_raw.items()}
37
+ if isinstance(properties_raw, Mapping)
38
+ else {}
39
+ )
40
+
41
+ items_raw = resolved.get("items")
42
+ items = normalize_schema(items_raw, resolver) if items_raw is not None else None
43
+
44
+ known = {
45
+ "type",
46
+ "title",
47
+ "description",
48
+ "format",
49
+ "enum",
50
+ "default",
51
+ "required",
52
+ "properties",
53
+ "items",
54
+ "additionalProperties",
55
+ }
56
+ extras = {
57
+ str(key): value for key, value in resolved.items() if key not in known and key != "$ref"
58
+ }
59
+
60
+ return JsonSchema(
61
+ type=resolved.get("type"),
62
+ title=resolved.get("title"),
63
+ description=resolved.get("description"),
64
+ format=resolved.get("format"),
65
+ enum=list(resolved["enum"]) if isinstance(resolved.get("enum"), list) else None,
66
+ default=resolved.get("default"),
67
+ required=list(resolved.get("required", [])),
68
+ properties=properties,
69
+ items=items,
70
+ additional_properties=(
71
+ normalize_schema(resolved["additionalProperties"], resolver)
72
+ if isinstance(resolved.get("additionalProperties"), Mapping)
73
+ else resolved.get("additionalProperties")
74
+ ),
75
+ **extras,
76
+ )
@@ -0,0 +1,8 @@
1
+ """Specification parsers."""
2
+
3
+ from mcpforge.ingestion.parsers.base import Parser
4
+ from mcpforge.ingestion.parsers.manual import ManualParser
5
+ from mcpforge.ingestion.parsers.openapi import OpenAPIParser
6
+ from mcpforge.ingestion.parsers.swagger import SwaggerParser
7
+
8
+ __all__ = ["ManualParser", "OpenAPIParser", "Parser", "SwaggerParser"]
@@ -0,0 +1,14 @@
1
+ """Parser protocol."""
2
+
3
+ from typing import Protocol
4
+
5
+ from mcpforge.domain.models import ApiDocument
6
+ from mcpforge.ingestion.source import LoadedDocument
7
+
8
+
9
+ class Parser(Protocol):
10
+ """Contract implemented by all specification parsers."""
11
+
12
+ def parse(self, loaded: LoadedDocument) -> ApiDocument:
13
+ """Convert a loaded document to the normalized domain model."""
14
+ ...
@@ -0,0 +1,82 @@
1
+ """Parser for the developer-friendly manual MCPForge YAML format."""
2
+
3
+ from collections.abc import Mapping
4
+
5
+ from mcpforge.domain.models import ApiDocument
6
+ from mcpforge.ingestion.errors import SpecificationError
7
+ from mcpforge.ingestion.normalization.operation import endpoint_from_operation
8
+ from mcpforge.ingestion.normalization.references import ReferenceResolver
9
+ from mcpforge.ingestion.source import LoadedDocument
10
+
11
+
12
+ class ManualParser:
13
+ """Parse manual MCPForge endpoint configuration."""
14
+
15
+ def parse(self, loaded: LoadedDocument) -> ApiDocument:
16
+ """Parse a manual specification."""
17
+
18
+ document = loaded.document
19
+ endpoints_raw = document.get("endpoints")
20
+ if not isinstance(endpoints_raw, list):
21
+ raise SpecificationError("manual specification requires an endpoints list")
22
+
23
+ resolver = ReferenceResolver(document)
24
+ endpoints = []
25
+
26
+ for index, raw in enumerate(endpoints_raw):
27
+ if not isinstance(raw, Mapping):
28
+ raise SpecificationError(f"manual endpoint {index} must be a mapping")
29
+
30
+ path = raw.get("path")
31
+ method = raw.get("method")
32
+ if not isinstance(path, str) or not isinstance(method, str):
33
+ raise SpecificationError(f"manual endpoint {index} requires string path and method")
34
+
35
+ endpoint_raw = dict(raw)
36
+ if "operation_id" in endpoint_raw and "operationId" not in endpoint_raw:
37
+ endpoint_raw["operationId"] = endpoint_raw.pop("operation_id")
38
+ if "request_body" in endpoint_raw and "requestBody" not in endpoint_raw:
39
+ endpoint_raw["requestBody"] = endpoint_raw.pop("request_body")
40
+
41
+ parameters = endpoint_raw.get("parameters", [])
42
+ if not isinstance(parameters, list):
43
+ raise SpecificationError(f"manual endpoint {index} parameters must be a list")
44
+
45
+ converted_parameters = []
46
+ for parameter in parameters:
47
+ if not isinstance(parameter, Mapping):
48
+ raise SpecificationError(
49
+ f"manual endpoint {index} contains an invalid parameter"
50
+ )
51
+ item = dict(parameter)
52
+ if "location" in item and "in" not in item:
53
+ item["in"] = item.pop("location")
54
+ converted_parameters.append(item)
55
+ endpoint_raw["parameters"] = converted_parameters
56
+
57
+ responses = endpoint_raw.get("responses", {})
58
+ if isinstance(responses, list):
59
+ endpoint_raw["responses"] = {
60
+ str(item.get("status_code")): item
61
+ for item in responses
62
+ if isinstance(item, Mapping)
63
+ }
64
+
65
+ endpoints.append(
66
+ endpoint_from_operation(
67
+ path=path,
68
+ method=method,
69
+ raw=endpoint_raw,
70
+ resolver=resolver,
71
+ )
72
+ )
73
+
74
+ return ApiDocument(
75
+ title=str(document.get("name", document.get("title", "Manual API"))),
76
+ version=str(document.get("version", "0.0.0")),
77
+ base_url=document.get("base_url"),
78
+ description=document.get("description"),
79
+ endpoints=endpoints,
80
+ source_format="manual",
81
+ source_name=loaded.source.location,
82
+ )
@@ -0,0 +1,87 @@
1
+ """OpenAPI 3.0 and 3.1 parser."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+
6
+ from mcpforge.domain.models import ApiDocument
7
+ from mcpforge.ingestion.errors import SpecificationError
8
+ from mcpforge.ingestion.normalization.operation import endpoint_from_operation
9
+ from mcpforge.ingestion.normalization.references import ReferenceResolver
10
+ from mcpforge.ingestion.source import LoadedDocument
11
+
12
+
13
+ class OpenAPIParser:
14
+ """Parse OpenAPI 3.0 and 3.1 documents."""
15
+
16
+ def parse(self, loaded: LoadedDocument) -> ApiDocument:
17
+ """Parse one loaded OpenAPI document."""
18
+
19
+ document = loaded.document
20
+ version = document.get("openapi")
21
+ if not isinstance(version, str) or not version.startswith(("3.0", "3.1")):
22
+ raise SpecificationError("document is not an OpenAPI 3.0 or 3.1 specification")
23
+
24
+ paths = document.get("paths", {})
25
+ if not isinstance(paths, Mapping):
26
+ raise SpecificationError("OpenAPI paths must be a mapping")
27
+
28
+ resolver = ReferenceResolver(document)
29
+ endpoints = []
30
+
31
+ for path, path_item in paths.items():
32
+ if not isinstance(path, str) or not isinstance(path_item, Mapping):
33
+ continue
34
+
35
+ common_parameters = path_item.get("parameters", [])
36
+ if not isinstance(common_parameters, list):
37
+ common_parameters = []
38
+
39
+ for method, operation in path_item.items():
40
+ if method.lower() not in {
41
+ "get",
42
+ "post",
43
+ "put",
44
+ "patch",
45
+ "delete",
46
+ "head",
47
+ "options",
48
+ }:
49
+ continue
50
+ if not isinstance(operation, Mapping):
51
+ raise SpecificationError(f"operation {method} {path} must be a mapping")
52
+
53
+ endpoints.append(
54
+ endpoint_from_operation(
55
+ path=path,
56
+ method=method,
57
+ raw=operation,
58
+ resolver=resolver,
59
+ path_parameters=common_parameters,
60
+ )
61
+ )
62
+
63
+ info = document.get("info", {})
64
+ if not isinstance(info, Mapping):
65
+ info = {}
66
+
67
+ return ApiDocument(
68
+ title=str(info.get("title", "Untitled API")),
69
+ version=str(info.get("version", version)),
70
+ base_url=self._base_url(document),
71
+ description=(
72
+ str(info["description"]) if isinstance(info.get("description"), str) else None
73
+ ),
74
+ endpoints=endpoints,
75
+ source_format="openapi",
76
+ source_name=loaded.source.location,
77
+ )
78
+
79
+ @staticmethod
80
+ def _base_url(document: Mapping[str, Any]) -> str | None:
81
+ servers = document.get("servers")
82
+ if isinstance(servers, list) and servers:
83
+ first = servers[0]
84
+ if isinstance(first, Mapping) and isinstance(first.get("url"), str):
85
+ return str(first["url"])
86
+
87
+ return None
@@ -0,0 +1,95 @@
1
+ """Swagger 2.0 parser."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+ from urllib.parse import urlunsplit
6
+
7
+ from mcpforge.domain.models import ApiDocument
8
+ from mcpforge.ingestion.errors import SpecificationError
9
+ from mcpforge.ingestion.normalization.operation import endpoint_from_operation
10
+ from mcpforge.ingestion.normalization.references import ReferenceResolver
11
+ from mcpforge.ingestion.source import LoadedDocument
12
+
13
+
14
+ class SwaggerParser:
15
+ """Parse Swagger 2.0 documents."""
16
+
17
+ def parse(self, loaded: LoadedDocument) -> ApiDocument:
18
+ """Parse one loaded Swagger 2.0 document."""
19
+
20
+ document = loaded.document
21
+ if document.get("swagger") != "2.0":
22
+ raise SpecificationError("document is not a Swagger 2.0 specification")
23
+
24
+ paths = document.get("paths", {})
25
+ if not isinstance(paths, Mapping):
26
+ raise SpecificationError("Swagger paths must be a mapping")
27
+
28
+ resolver = ReferenceResolver(document)
29
+ endpoints = []
30
+
31
+ for path, path_item in paths.items():
32
+ if not isinstance(path, str) or not isinstance(path_item, Mapping):
33
+ continue
34
+
35
+ common_parameters = path_item.get("parameters", [])
36
+ if not isinstance(common_parameters, list):
37
+ common_parameters = []
38
+
39
+ for method, operation in path_item.items():
40
+ if method.lower() not in {
41
+ "get",
42
+ "post",
43
+ "put",
44
+ "patch",
45
+ "delete",
46
+ "head",
47
+ "options",
48
+ }:
49
+ continue
50
+ if not isinstance(operation, Mapping):
51
+ raise SpecificationError(f"operation {method} {path} must be a mapping")
52
+
53
+ endpoints.append(
54
+ endpoint_from_operation(
55
+ path=path,
56
+ method=method,
57
+ raw=operation,
58
+ resolver=resolver,
59
+ path_parameters=common_parameters,
60
+ swagger=True,
61
+ )
62
+ )
63
+
64
+ info = document.get("info", {})
65
+ info = info if isinstance(info, Mapping) else {}
66
+
67
+ return ApiDocument(
68
+ title=str(info.get("title", "Untitled API")),
69
+ version=str(info.get("version", "2.0.0")),
70
+ base_url=self._base_url(document),
71
+ description=info.get("description"),
72
+ endpoints=endpoints,
73
+ source_format="swagger",
74
+ source_name=loaded.source.location,
75
+ extensions={
76
+ "security_definitions": document.get("securityDefinitions", {}),
77
+ },
78
+ )
79
+
80
+ @staticmethod
81
+ def _base_url(document: Mapping[str, Any]) -> str | None:
82
+ host = document.get("host")
83
+ if not isinstance(host, str) or not host:
84
+ return None
85
+
86
+ schemes = document.get("schemes")
87
+ scheme = "https"
88
+ if isinstance(schemes, list) and schemes and isinstance(schemes[0], str):
89
+ scheme = schemes[0]
90
+
91
+ base_path = document.get("basePath", "")
92
+ if not isinstance(base_path, str):
93
+ base_path = ""
94
+
95
+ return urlunsplit((scheme, host, base_path.rstrip("/"), "", ""))
@@ -0,0 +1,84 @@
1
+ """High-level source ingestion service."""
2
+
3
+ from collections.abc import Mapping
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from mcpforge.domain.models import ApiDocument
8
+ from mcpforge.ingestion.errors import SpecificationError, UnsupportedFormatError
9
+ from mcpforge.ingestion.loaders.file import load_file
10
+ from mcpforge.ingestion.loaders.remote import load_remote
11
+ from mcpforge.ingestion.parsers.base import Parser
12
+ from mcpforge.ingestion.parsers.manual import ManualParser
13
+ from mcpforge.ingestion.parsers.openapi import OpenAPIParser
14
+ from mcpforge.ingestion.parsers.swagger import SwaggerParser
15
+ from mcpforge.ingestion.source import LoadedDocument, Source
16
+
17
+
18
+ def detect_format(document: Mapping[str, Any]) -> str:
19
+ """Detect the specification format from its top-level marker."""
20
+
21
+ if isinstance(document.get("openapi"), str):
22
+ version = document["openapi"]
23
+ if version.startswith(("3.0", "3.1")):
24
+ return "openapi"
25
+ if document.get("swagger") == "2.0":
26
+ return "swagger"
27
+ if isinstance(document.get("endpoints"), list):
28
+ return "manual"
29
+ raise UnsupportedFormatError(
30
+ "unable to detect format; expected OpenAPI, Swagger 2.0, or manual endpoints"
31
+ )
32
+
33
+
34
+ def parser_for(format_name: str) -> Parser:
35
+ """Return a parser for a normalized format name."""
36
+
37
+ parsers: dict[str, Parser] = {
38
+ "openapi": OpenAPIParser(),
39
+ "swagger": SwaggerParser(),
40
+ "manual": ManualParser(),
41
+ }
42
+ try:
43
+ return parsers[format_name.lower()]
44
+ except KeyError as exc:
45
+ raise UnsupportedFormatError(f"unsupported specification format: {format_name}") from exc
46
+
47
+
48
+ def _loaded_source(source: Source) -> LoadedDocument:
49
+ if source.kind.value == "file":
50
+ return load_file(source)
51
+ return load_remote(source)
52
+
53
+
54
+ def ingest(source: Source) -> ApiDocument:
55
+ """Load, detect, parse, and validate one API source."""
56
+
57
+ loaded = _loaded_source(source)
58
+ format_name = source.format.lower() if source.format else detect_format(loaded.document)
59
+ parser = parser_for(format_name)
60
+
61
+ try:
62
+ return parser.parse(loaded)
63
+ except (SpecificationError, ValueError) as exc:
64
+ if isinstance(exc, SpecificationError):
65
+ raise
66
+ raise SpecificationError(f"failed to normalize {source.location} as {format_name}") from exc
67
+
68
+
69
+ def ingest_path(
70
+ location: str | Path,
71
+ *,
72
+ format: str | None = None,
73
+ timeout_seconds: float = 30.0,
74
+ max_bytes: int = 10_000_000,
75
+ ) -> ApiDocument:
76
+ """Convenience wrapper for ingesting a string or path location."""
77
+
78
+ source = Source(
79
+ location=str(location),
80
+ format=format,
81
+ timeout_seconds=timeout_seconds,
82
+ max_bytes=max_bytes,
83
+ )
84
+ return ingest(source)
@@ -0,0 +1,50 @@
1
+ """Source and loaded-document contracts."""
2
+
3
+ from dataclasses import dataclass
4
+ from enum import StrEnum
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from urllib.parse import urlparse
8
+
9
+
10
+ class SourceKind(StrEnum):
11
+ """Supported source locations."""
12
+
13
+ FILE = "file"
14
+ URL = "url"
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class Source:
19
+ """A local or remote API specification source."""
20
+
21
+ location: str
22
+ format: str | None = None
23
+ timeout_seconds: float = 30.0
24
+ max_bytes: int = 10_000_000
25
+
26
+ @property
27
+ def kind(self) -> SourceKind:
28
+ """Return whether the source is local or remote."""
29
+
30
+ parsed = urlparse(self.location)
31
+ if parsed.scheme in {"http", "https"}:
32
+ return SourceKind.URL
33
+ return SourceKind.FILE
34
+
35
+ @property
36
+ def path(self) -> Path:
37
+ """Return the local path representation."""
38
+
39
+ if self.kind is not SourceKind.FILE:
40
+ raise ValueError("remote sources do not have a local path")
41
+ return Path(self.location)
42
+
43
+
44
+ @dataclass(frozen=True, slots=True)
45
+ class LoadedDocument:
46
+ """Raw parsed source content and loading metadata."""
47
+
48
+ document: dict[str, Any]
49
+ source: Source
50
+ media_type: str | None = None