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
mcpforge/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Public MCPForge package interface."""
2
+
3
+ from mcpforge.config.models import ProjectConfig
4
+ from mcpforge.domain.models import ApiDocument, Endpoint
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = ["ApiDocument", "Endpoint", "ProjectConfig", "__version__"]
mcpforge/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Run MCPForge with ``python -m mcpforge``."""
2
+
3
+ from mcpforge.cli.app import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,28 @@
1
+ """Runtime authentication and redaction."""
2
+
3
+ from mcpforge.auth.models import ResolvedAuth
4
+ from mcpforge.auth.providers import (
5
+ ApiKeyAuthProvider,
6
+ AuthProvider,
7
+ BasicAuthProvider,
8
+ BearerAuthProvider,
9
+ NoAuthProvider,
10
+ StaticHeadersAuthProvider,
11
+ )
12
+ from mcpforge.auth.redaction import REDACTED, SENSITIVE_NAMES, redact
13
+ from mcpforge.auth.resolver import provider_for, resolve_auth
14
+
15
+ __all__ = [
16
+ "ApiKeyAuthProvider",
17
+ "AuthProvider",
18
+ "BasicAuthProvider",
19
+ "BearerAuthProvider",
20
+ "NoAuthProvider",
21
+ "REDACTED",
22
+ "ResolvedAuth",
23
+ "SENSITIVE_NAMES",
24
+ "StaticHeadersAuthProvider",
25
+ "provider_for",
26
+ "redact",
27
+ "resolve_auth",
28
+ ]
@@ -0,0 +1,25 @@
1
+ """Authentication request material contracts."""
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, field
5
+
6
+
7
+ @dataclass(frozen=True, slots=True)
8
+ class ResolvedAuth:
9
+ """Resolved request authentication material."""
10
+
11
+ headers: Mapping[str, str] = field(default_factory=dict)
12
+ query: Mapping[str, str] = field(default_factory=dict)
13
+ username: str | None = None
14
+ password: str | None = None
15
+
16
+ def redacted(self) -> "ResolvedAuth":
17
+ """Return a copy with all sensitive values masked."""
18
+
19
+ mask = "***REDACTED***"
20
+ return ResolvedAuth(
21
+ headers={key: mask for key in self.headers},
22
+ query={key: mask for key in self.query},
23
+ username=mask if self.username is not None else None,
24
+ password=mask if self.password is not None else None,
25
+ )
@@ -0,0 +1,72 @@
1
+ """Environment-backed authentication providers."""
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from mcpforge.auth.models import ResolvedAuth
6
+ from mcpforge.config.models import (
7
+ ApiKeyAuthConfig,
8
+ BasicAuthConfig,
9
+ BearerAuthConfig,
10
+ NoAuthConfig,
11
+ StaticHeadersAuthConfig,
12
+ )
13
+ from mcpforge.config.secrets import resolve_env
14
+
15
+
16
+ class AuthProvider(ABC):
17
+ """Provider interface for runtime authentication resolution."""
18
+
19
+ @abstractmethod
20
+ def resolve(self) -> ResolvedAuth:
21
+ """Resolve authentication material from the environment."""
22
+ raise NotImplementedError
23
+
24
+
25
+ class NoAuthProvider(AuthProvider):
26
+ def __init__(self, config: NoAuthConfig) -> None:
27
+ self.config = config
28
+
29
+ def resolve(self) -> ResolvedAuth:
30
+ return ResolvedAuth()
31
+
32
+
33
+ class BearerAuthProvider(AuthProvider):
34
+ def __init__(self, config: BearerAuthConfig) -> None:
35
+ self.config = config
36
+
37
+ def resolve(self) -> ResolvedAuth:
38
+ return ResolvedAuth(headers={"Authorization": f"Bearer {resolve_env(self.config.token)}"})
39
+
40
+
41
+ class ApiKeyAuthProvider(AuthProvider):
42
+ def __init__(self, config: ApiKeyAuthConfig) -> None:
43
+ self.config = config
44
+
45
+ def resolve(self) -> ResolvedAuth:
46
+ value = resolve_env(self.config.value)
47
+ if self.config.location == "query":
48
+ return ResolvedAuth(query={self.config.name: value})
49
+ return ResolvedAuth(headers={self.config.name: value})
50
+
51
+
52
+ class BasicAuthProvider(AuthProvider):
53
+ def __init__(self, config: BasicAuthConfig) -> None:
54
+ self.config = config
55
+
56
+ def resolve(self) -> ResolvedAuth:
57
+ return ResolvedAuth(
58
+ username=resolve_env(self.config.username),
59
+ password=resolve_env(self.config.password),
60
+ )
61
+
62
+
63
+ class StaticHeadersAuthProvider(AuthProvider):
64
+ def __init__(self, config: StaticHeadersAuthConfig) -> None:
65
+ self.config = config
66
+
67
+ def resolve(self) -> ResolvedAuth:
68
+ return ResolvedAuth(
69
+ headers={
70
+ name: resolve_env(reference) for name, reference in self.config.headers.items()
71
+ }
72
+ )
@@ -0,0 +1,47 @@
1
+ """Recursive credential redaction."""
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from typing import Any
5
+
6
+ SENSITIVE_NAMES = frozenset(
7
+ {
8
+ "authorization",
9
+ "proxy-authorization",
10
+ "cookie",
11
+ "set-cookie",
12
+ "token",
13
+ "password",
14
+ "secret",
15
+ "api_key",
16
+ "api-key",
17
+ "access_token",
18
+ "client_secret",
19
+ }
20
+ )
21
+ REDACTED = "***REDACTED***"
22
+
23
+
24
+ def redact(value: Any, extra_secrets: Sequence[str] = ()) -> Any:
25
+ """Return a recursively redacted copy of arbitrary diagnostic data."""
26
+
27
+ secret_values = tuple(secret for secret in extra_secrets if secret)
28
+
29
+ if isinstance(value, Mapping):
30
+ return {
31
+ str(key): (
32
+ REDACTED
33
+ if str(key).lower().replace("-", "_") in SENSITIVE_NAMES
34
+ else redact(child, secret_values)
35
+ )
36
+ for key, child in value.items()
37
+ }
38
+ if isinstance(value, list):
39
+ return [redact(item, secret_values) for item in value]
40
+ if isinstance(value, tuple):
41
+ return tuple(redact(item, secret_values) for item in value)
42
+ if isinstance(value, str):
43
+ result = value
44
+ for secret in secret_values:
45
+ result = result.replace(secret, REDACTED)
46
+ return result
47
+ return value
@@ -0,0 +1,42 @@
1
+ """Authentication provider selection."""
2
+
3
+ from mcpforge.auth.models import ResolvedAuth
4
+ from mcpforge.auth.providers import (
5
+ ApiKeyAuthProvider,
6
+ AuthProvider,
7
+ BasicAuthProvider,
8
+ BearerAuthProvider,
9
+ NoAuthProvider,
10
+ StaticHeadersAuthProvider,
11
+ )
12
+ from mcpforge.config.models import (
13
+ ApiKeyAuthConfig,
14
+ BasicAuthConfig,
15
+ BearerAuthConfig,
16
+ NoAuthConfig,
17
+ ProjectConfig,
18
+ StaticHeadersAuthConfig,
19
+ )
20
+
21
+
22
+ def provider_for(config: ProjectConfig) -> AuthProvider:
23
+ """Create the provider matching project authentication configuration."""
24
+
25
+ auth = config.auth
26
+ if isinstance(auth, NoAuthConfig):
27
+ return NoAuthProvider(auth)
28
+ if isinstance(auth, BearerAuthConfig):
29
+ return BearerAuthProvider(auth)
30
+ if isinstance(auth, ApiKeyAuthConfig):
31
+ return ApiKeyAuthProvider(auth)
32
+ if isinstance(auth, BasicAuthConfig):
33
+ return BasicAuthProvider(auth)
34
+ if isinstance(auth, StaticHeadersAuthConfig):
35
+ return StaticHeadersAuthProvider(auth)
36
+ raise TypeError(f"unsupported authentication configuration: {type(auth).__name__}")
37
+
38
+
39
+ def resolve_auth(config: ProjectConfig) -> ResolvedAuth:
40
+ """Resolve project authentication at request time."""
41
+
42
+ return provider_for(config).resolve()
@@ -0,0 +1 @@
1
+ """MCPForge command-line interface."""
mcpforge/cli/app.py ADDED
@@ -0,0 +1,45 @@
1
+ """Typer application entry point."""
2
+
3
+ from typing import Annotated
4
+
5
+ import typer
6
+
7
+ from mcpforge import __version__
8
+ from mcpforge.cli.commands import import_spec, init, inspect, run, serve, test, validate
9
+ from mcpforge.cli.output import console
10
+
11
+ app = typer.Typer(
12
+ name="mcpforge",
13
+ help="Turn any REST API into an AI-ready MCP server.",
14
+ no_args_is_help=False,
15
+ invoke_without_command=True,
16
+ add_completion=False,
17
+ )
18
+
19
+ app.add_typer(init.app)
20
+ app.add_typer(import_spec.app)
21
+ app.add_typer(inspect.app)
22
+ app.add_typer(validate.app)
23
+ app.add_typer(test.app)
24
+ app.add_typer(serve.app)
25
+ app.add_typer(run.app)
26
+
27
+
28
+ @app.callback()
29
+ def callback(
30
+ version: Annotated[
31
+ bool,
32
+ typer.Option("--version", help="Show the MCPForge version.", is_eager=True),
33
+ ] = False,
34
+ ) -> None:
35
+ """MCPForge command-line interface."""
36
+
37
+ if version:
38
+ console.print(f"MCPForge {__version__}")
39
+ raise typer.Exit()
40
+
41
+
42
+ def main() -> None:
43
+ """Run the command-line application."""
44
+
45
+ app()
@@ -0,0 +1,13 @@
1
+ """MCPForge CLI command modules."""
2
+
3
+ from mcpforge.cli.commands import import_spec, init, inspect, run, serve, test, validate
4
+
5
+ __all__ = [
6
+ "import_spec",
7
+ "init",
8
+ "inspect",
9
+ "run",
10
+ "serve",
11
+ "test",
12
+ "validate",
13
+ ]
@@ -0,0 +1,41 @@
1
+ """The import command."""
2
+
3
+ from typing import Annotated
4
+
5
+ import typer
6
+
7
+ from mcpforge.ingestion.service import ingest_path
8
+
9
+ app = typer.Typer(
10
+ name="import",
11
+ help="Load and normalize an API specification.",
12
+ )
13
+
14
+
15
+ @app.command()
16
+ def import_spec(
17
+ source: Annotated[str, typer.Argument(help="Local path or HTTP(S) URL.")],
18
+ format: Annotated[
19
+ str | None,
20
+ typer.Option("--format", help="openapi, swagger, or manual."),
21
+ ] = None,
22
+ timeout: Annotated[
23
+ float,
24
+ typer.Option("--timeout", min=0.1, max=300.0),
25
+ ] = 30.0,
26
+ ) -> None:
27
+ """Parse a source and display its normalized endpoint count."""
28
+
29
+ try:
30
+ document = ingest_path(
31
+ source,
32
+ format=format,
33
+ timeout_seconds=timeout,
34
+ )
35
+ except Exception as exc:
36
+ raise typer.BadParameter(str(exc)) from exc
37
+
38
+ typer.echo(
39
+ f"Imported {document.source_format or 'unknown'} specification: "
40
+ f"{len(document.endpoints)} endpoint(s)"
41
+ )
@@ -0,0 +1,42 @@
1
+ """The init command."""
2
+
3
+ from pathlib import Path
4
+ from typing import Annotated
5
+
6
+ import typer
7
+
8
+ from mcpforge.cli.output import print_success
9
+ from mcpforge.cli.scaffold import scaffold_project
10
+
11
+ app = typer.Typer(name="init", help="Create a new MCPForge project.")
12
+
13
+
14
+ @app.callback(invoke_without_command=True)
15
+ def init(
16
+ directory: Annotated[
17
+ Path,
18
+ typer.Argument(help="Project directory.", exists=False),
19
+ ] = Path("."),
20
+ force: Annotated[
21
+ bool,
22
+ typer.Option("--force", help="Overwrite existing generated files."),
23
+ ] = False,
24
+ with_example: Annotated[
25
+ bool,
26
+ typer.Option("--with-example/--without-example"),
27
+ ] = True,
28
+ ) -> None:
29
+ """Scaffold a configuration and optional example specification."""
30
+
31
+ try:
32
+ files = scaffold_project(
33
+ directory,
34
+ force=force,
35
+ with_example=with_example,
36
+ )
37
+ except FileExistsError as exc:
38
+ typer.echo(str(exc))
39
+ raise typer.Exit(code=1) from exc
40
+
41
+ for path in files:
42
+ print_success(f"Created {path}")
@@ -0,0 +1,56 @@
1
+ """The inspect command."""
2
+
3
+ from pathlib import Path
4
+ from typing import Annotated
5
+
6
+ import typer
7
+ from rich.table import Table
8
+
9
+ from mcpforge.cli.output import console
10
+ from mcpforge.config.loader import load_config
11
+ from mcpforge.filtering.evaluator import filter_document
12
+ from mcpforge.generation.service import generate_tools
13
+ from mcpforge.ingestion.service import ingest_path
14
+
15
+ app = typer.Typer(name="inspect", help="Inspect endpoints and generated tools.")
16
+
17
+
18
+ @app.callback(invoke_without_command=True)
19
+ def inspect(
20
+ config: Annotated[Path, typer.Option("--config")] = Path("mcpforge.yaml"),
21
+ output: Annotated[str, typer.Option("--format")] = "table",
22
+ ) -> None:
23
+ """Display the filtered endpoint and tool inventory."""
24
+
25
+ try:
26
+ project = load_config(config)
27
+ document = ingest_path(
28
+ project.source.location,
29
+ format=project.source.format,
30
+ timeout_seconds=project.source.timeout_seconds,
31
+ )
32
+ document = filter_document(document, project.filters, project.security)
33
+ tools = generate_tools(document)
34
+ except Exception as exc:
35
+ raise typer.BadParameter(str(exc)) from exc
36
+
37
+ rows = [
38
+ {
39
+ "method": endpoint.method.value,
40
+ "path": endpoint.path,
41
+ "tool": tool.name,
42
+ "safety": (endpoint.safety.value if endpoint.safety else "read"),
43
+ }
44
+ for endpoint, tool in zip(document.endpoints, tools, strict=True)
45
+ ]
46
+
47
+ if output.lower() == "json":
48
+ import json
49
+
50
+ typer.echo(json.dumps(rows, indent=2))
51
+ return
52
+
53
+ table = Table("Method", "Path", "Tool", "Safety")
54
+ for row in rows:
55
+ table.add_row(row["method"], row["path"], row["tool"], row["safety"])
56
+ console.print(table)
@@ -0,0 +1,44 @@
1
+ """The run command."""
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import typer
8
+
9
+ from mcpforge.config.loader import DEFAULT_CONFIG_FILENAME
10
+ from mcpforge.config.models import ProjectConfig
11
+ from mcpforge.mcp.transports import Transport
12
+ from mcpforge.runtime.application import RuntimeApplication
13
+ from mcpforge.runtime.dependencies import build_dependencies
14
+
15
+ app = typer.Typer(name="run", help="Import, validate, generate, and serve.")
16
+
17
+
18
+ @app.callback(invoke_without_command=True)
19
+ def run(
20
+ source: Annotated[str | None, typer.Argument(help="Specification path or URL.")] = None,
21
+ config: Annotated[Path, typer.Option("--config")] = Path(DEFAULT_CONFIG_FILENAME),
22
+ transport: Annotated[Transport, typer.Option("--transport")] = Transport.STDIO,
23
+ host: Annotated[str, typer.Option("--host")] = "127.0.0.1",
24
+ port: Annotated[int, typer.Option("--port", min=1, max=65535)] = 8000,
25
+ ) -> None:
26
+ """Run an existing project or replace its source for this invocation."""
27
+
28
+ if source is not None:
29
+ project = ProjectConfig.model_validate(
30
+ {
31
+ "source": {"location": source},
32
+ }
33
+ )
34
+ dependencies = build_dependencies(config)
35
+ dependencies.config = project # type: ignore[misc]
36
+ application = RuntimeApplication(dependencies)
37
+ else:
38
+ application = RuntimeApplication.from_config(config)
39
+
40
+ async def serve() -> None:
41
+ async with application:
42
+ application.serve(transport, host=host, port=port)
43
+
44
+ asyncio.run(serve())
@@ -0,0 +1,31 @@
1
+ """The serve command."""
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import typer
8
+
9
+ from mcpforge.mcp.transports import Transport
10
+ from mcpforge.runtime.application import RuntimeApplication
11
+
12
+ app = typer.Typer(name="serve", help="Start the MCP server.")
13
+
14
+
15
+ @app.callback(invoke_without_command=True)
16
+ def serve(
17
+ config: Annotated[Path, typer.Option("--config")] = Path("mcpforge.yaml"),
18
+ transport: Annotated[
19
+ Transport,
20
+ typer.Option("--transport"),
21
+ ] = Transport.STDIO,
22
+ host: Annotated[str, typer.Option("--host")] = "127.0.0.1",
23
+ port: Annotated[int, typer.Option("--port", min=1, max=65535)] = 8000,
24
+ ) -> None:
25
+ """Start an MCP server over stdio or streamable HTTP."""
26
+
27
+ async def run() -> None:
28
+ async with RuntimeApplication.from_config(config) as application:
29
+ application.serve(transport, host=host, port=port)
30
+
31
+ asyncio.run(run())
@@ -0,0 +1,60 @@
1
+ """The test command."""
2
+
3
+ import asyncio
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import typer
8
+
9
+ from mcpforge.cli.output import print_success
10
+ from mcpforge.config.loader import load_config
11
+ from mcpforge.execution.client import HTTPClient
12
+ from mcpforge.execution.engine import ExecutionEngine
13
+ from mcpforge.filtering.evaluator import filter_document
14
+ from mcpforge.ingestion.service import ingest_path
15
+
16
+ app = typer.Typer(name="test", help="Test API connectivity and authentication.")
17
+
18
+
19
+ @app.callback(invoke_without_command=True)
20
+ def test(
21
+ config: Annotated[Path, typer.Option("--config")] = Path("mcpforge.yaml"),
22
+ operation: Annotated[str | None, typer.Option("--operation")] = None,
23
+ dry_run: Annotated[bool, typer.Option("--dry-run")] = False,
24
+ ) -> None:
25
+ """Execute a selected safe endpoint or perform a dry run."""
26
+
27
+ try:
28
+ project = load_config(config)
29
+ document = ingest_path(
30
+ project.source.location,
31
+ format=project.source.format,
32
+ timeout_seconds=project.source.timeout_seconds,
33
+ )
34
+ document = filter_document(document, project.filters, project.security)
35
+ endpoint = next(
36
+ (
37
+ item
38
+ for item in document.endpoints
39
+ if operation is None or item.operation_id == operation or item.path == operation
40
+ ),
41
+ None,
42
+ )
43
+ if endpoint is None:
44
+ raise ValueError("no matching enabled operation found")
45
+
46
+ if dry_run:
47
+ print_success(f"Dry run valid for {endpoint.method.value} {endpoint.path}")
48
+ return
49
+
50
+ async def execute() -> dict[str, object]:
51
+ async with HTTPClient(
52
+ timeout_seconds=project.http.timeout_seconds,
53
+ verify_tls=project.http.verify_tls,
54
+ ).lifecycle() as client:
55
+ return await ExecutionEngine(project, client).execute(endpoint, {})
56
+
57
+ result = asyncio.run(execute())
58
+ print_success(f"Connectivity successful: status {result.get('status_code')}")
59
+ except Exception as exc:
60
+ raise typer.BadParameter(str(exc)) from exc
@@ -0,0 +1,41 @@
1
+ """The validate command."""
2
+
3
+ from pathlib import Path
4
+ from typing import Annotated
5
+
6
+ import typer
7
+
8
+ from mcpforge.cli.output import print_success
9
+ from mcpforge.config.loader import load_config
10
+ from mcpforge.filtering.evaluator import filter_document
11
+ from mcpforge.generation.service import generate_tools
12
+ from mcpforge.ingestion.service import ingest_path
13
+
14
+ app = typer.Typer(name="validate", help="Validate project configuration and source.")
15
+
16
+
17
+ @app.callback(invoke_without_command=True)
18
+ def validate(
19
+ config: Annotated[Path, typer.Option("--config")] = Path("mcpforge.yaml"),
20
+ strict: Annotated[bool, typer.Option("--strict")] = False,
21
+ ) -> None:
22
+ """Validate configuration, ingestion, filtering, and tool generation."""
23
+
24
+ try:
25
+ project = load_config(config)
26
+ document = ingest_path(
27
+ project.source.location,
28
+ format=project.source.format,
29
+ timeout_seconds=project.source.timeout_seconds,
30
+ )
31
+ filtered = filter_document(document, project.filters, project.security)
32
+ tools = generate_tools(filtered)
33
+ except Exception as exc:
34
+ raise typer.BadParameter(str(exc)) from exc
35
+
36
+ if strict and not tools:
37
+ raise typer.BadParameter("strict validation produced no enabled tools")
38
+
39
+ print_success(
40
+ f"Configuration valid: {len(filtered.endpoints)} endpoint(s), {len(tools)} tool(s)"
41
+ )
@@ -0,0 +1,14 @@
1
+ """Shared command-line context."""
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ from mcpforge.config.models import ProjectConfig
7
+
8
+
9
+ @dataclass(slots=True)
10
+ class CLIContext:
11
+ """Explicit state shared by command handlers."""
12
+
13
+ config_path: Path = Path("mcpforge.yaml")
14
+ config: ProjectConfig | None = None
mcpforge/cli/output.py ADDED
@@ -0,0 +1,31 @@
1
+ """Rich-based terminal output helpers."""
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from rich.console import Console
6
+ from rich.table import Table
7
+
8
+ console = Console()
9
+
10
+
11
+ def print_success(message: str) -> None:
12
+ """Print a successful operation message."""
13
+
14
+ console.print(f"[green]✓[/green] {message}")
15
+
16
+
17
+ def print_error(message: str) -> None:
18
+ """Print an error message."""
19
+
20
+ console.print(f"[red]Error:[/red] {message}")
21
+
22
+
23
+ def print_key_values(values: Iterable[tuple[str, str]]) -> None:
24
+ """Render key-value data as a compact table."""
25
+
26
+ table = Table(show_header=False, box=None)
27
+ table.add_column("Key", style="cyan")
28
+ table.add_column("Value")
29
+ for key, value in values:
30
+ table.add_row(key, value)
31
+ console.print(table)