backend2mcp 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.
- backend2mcp/__init__.py +5 -0
- backend2mcp/cli/__init__.py +119 -0
- backend2mcp/core/__init__.py +38 -0
- backend2mcp/core/adapter.py +134 -0
- backend2mcp/core/auth.py +257 -0
- backend2mcp/core/exceptions.py +31 -0
- backend2mcp/core/schema.py +137 -0
- backend2mcp/core/server.py +72 -0
- backend2mcp/django/__init__.py +5 -0
- backend2mcp/django/adapter.py +356 -0
- backend2mcp/fastapi/__init__.py +5 -0
- backend2mcp/fastapi/adapter.py +298 -0
- backend2mcp/flask/__init__.py +5 -0
- backend2mcp/flask/adapter.py +315 -0
- backend2mcp-0.1.0.dist-info/METADATA +322 -0
- backend2mcp-0.1.0.dist-info/RECORD +19 -0
- backend2mcp-0.1.0.dist-info/WHEEL +4 -0
- backend2mcp-0.1.0.dist-info/entry_points.txt +2 -0
- backend2mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
backend2mcp/__init__.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""backend2mcp CLI using typer."""
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from backend2mcp.core.exceptions import AdapterConfigurationError
|
|
9
|
+
|
|
10
|
+
app = typer.Typer(
|
|
11
|
+
name="backend2mcp",
|
|
12
|
+
help="Convert Python web backends into MCP servers",
|
|
13
|
+
add_completion=False,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@app.command()
|
|
18
|
+
def run(
|
|
19
|
+
module_path: str = typer.Argument(
|
|
20
|
+
..., help="Module path to app object (e.g., 'app:app')"
|
|
21
|
+
),
|
|
22
|
+
framework: str = typer.Option(
|
|
23
|
+
None,
|
|
24
|
+
"--framework",
|
|
25
|
+
"-f",
|
|
26
|
+
help="Framework (fastapi, flask, django). Auto-detected if not provided",
|
|
27
|
+
),
|
|
28
|
+
) -> None:
|
|
29
|
+
"""Run an MCP server from a Python web backend module."""
|
|
30
|
+
typer.echo(f"Loading module from: {module_path}")
|
|
31
|
+
|
|
32
|
+
# Parse module path
|
|
33
|
+
if ":" not in module_path:
|
|
34
|
+
raise AdapterConfigurationError(
|
|
35
|
+
f"Invalid module path format. Use 'module:object' format. Got: {module_path}"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
module_name, obj_name = module_path.rsplit(":", 1)
|
|
39
|
+
|
|
40
|
+
# Import the module
|
|
41
|
+
try:
|
|
42
|
+
module = importlib.import_module(module_name)
|
|
43
|
+
except ImportError as e:
|
|
44
|
+
raise AdapterConfigurationError(
|
|
45
|
+
f"Failed to import module '{module_name}': {e}"
|
|
46
|
+
) from e
|
|
47
|
+
|
|
48
|
+
# Get the object
|
|
49
|
+
try:
|
|
50
|
+
obj = getattr(module, obj_name)
|
|
51
|
+
except AttributeError as e:
|
|
52
|
+
raise AdapterConfigurationError(
|
|
53
|
+
f"Failed to get '{obj_name}' from module '{module_name}': {e}"
|
|
54
|
+
) from e
|
|
55
|
+
|
|
56
|
+
# Detect framework and create adapter
|
|
57
|
+
adapter = _detect_and_create_adapter(obj, framework)
|
|
58
|
+
|
|
59
|
+
if adapter is None:
|
|
60
|
+
raise AdapterConfigurationError(
|
|
61
|
+
f"Could not detect framework for object type: {type(obj)}"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
typer.echo(f"Starting MCP server with {framework or 'auto-detected'} adapter...")
|
|
65
|
+
adapter.run()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _detect_and_create_adapter(obj: object, framework: str | None):
|
|
69
|
+
"""Detect framework and create appropriate adapter."""
|
|
70
|
+
# Check for FastAPI
|
|
71
|
+
if framework in (None, "fastapi"):
|
|
72
|
+
try:
|
|
73
|
+
from fastapi import FastAPI
|
|
74
|
+
from backend2mcp.fastapi import MCPAdapter as FastAPIMCPAdapter
|
|
75
|
+
|
|
76
|
+
if isinstance(obj, FastAPI):
|
|
77
|
+
return FastAPIMCPAdapter(obj)
|
|
78
|
+
except ImportError:
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
# Check for Flask
|
|
82
|
+
if framework in (None, "flask"):
|
|
83
|
+
try:
|
|
84
|
+
from flask import Flask
|
|
85
|
+
from backend2mcp.flask import MCPAdapter as FlaskMCPAdapter
|
|
86
|
+
|
|
87
|
+
if isinstance(obj, Flask):
|
|
88
|
+
return FlaskMCPAdapter(obj)
|
|
89
|
+
except ImportError:
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
# Check for Django URLs
|
|
93
|
+
if framework in (None, "django"):
|
|
94
|
+
from backend2mcp.django import MCPAdapter as DjangoMCPAdapter
|
|
95
|
+
|
|
96
|
+
if hasattr(obj, "__iter__") and not isinstance(obj, str):
|
|
97
|
+
# Likely a urlpatterns list
|
|
98
|
+
try:
|
|
99
|
+
from django.urls import URLPattern
|
|
100
|
+
|
|
101
|
+
first = next(iter(obj))
|
|
102
|
+
if isinstance(first, URLPattern):
|
|
103
|
+
return DjangoMCPAdapter(urls=list(obj))
|
|
104
|
+
except (StopIteration, TypeError):
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
if isinstance(obj, list):
|
|
108
|
+
return DjangoMCPAdapter(urls=obj)
|
|
109
|
+
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main() -> None:
|
|
114
|
+
"""Entry point for the CLI."""
|
|
115
|
+
app()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
if __name__ == "__main__":
|
|
119
|
+
main()
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""backend2mcp.core - Core abstractions and shared implementation."""
|
|
2
|
+
|
|
3
|
+
from backend2mcp.core.adapter import BaseAdapter, ToolInfo
|
|
4
|
+
from backend2mcp.core.auth import (
|
|
5
|
+
AuthContext,
|
|
6
|
+
AuthProvider,
|
|
7
|
+
APIKeyAuthProvider,
|
|
8
|
+
BearerAuthProvider,
|
|
9
|
+
HeaderInjectionAuthProvider,
|
|
10
|
+
NoAuthProvider,
|
|
11
|
+
combine_providers,
|
|
12
|
+
)
|
|
13
|
+
from backend2mcp.core.exceptions import (
|
|
14
|
+
AdapterConfigurationError,
|
|
15
|
+
RouteIntrospectionError,
|
|
16
|
+
SchemaConversionError,
|
|
17
|
+
ToolExecutionError,
|
|
18
|
+
)
|
|
19
|
+
from backend2mcp.core.server import MCPServer
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"BaseAdapter",
|
|
23
|
+
"ToolInfo",
|
|
24
|
+
"MCPServer",
|
|
25
|
+
# Auth
|
|
26
|
+
"AuthContext",
|
|
27
|
+
"AuthProvider",
|
|
28
|
+
"NoAuthProvider",
|
|
29
|
+
"BearerAuthProvider",
|
|
30
|
+
"APIKeyAuthProvider",
|
|
31
|
+
"HeaderInjectionAuthProvider",
|
|
32
|
+
"combine_providers",
|
|
33
|
+
# Exceptions
|
|
34
|
+
"AdapterConfigurationError",
|
|
35
|
+
"RouteIntrospectionError",
|
|
36
|
+
"SchemaConversionError",
|
|
37
|
+
"ToolExecutionError",
|
|
38
|
+
]
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Abstract base adapter and tool info structures."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any, Callable
|
|
6
|
+
|
|
7
|
+
from backend2mcp.core.auth import AuthContext, AuthProvider, NoAuthProvider
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class ToolInfo:
|
|
12
|
+
"""Information about an MCP tool derived from a route."""
|
|
13
|
+
|
|
14
|
+
name: str
|
|
15
|
+
description: str
|
|
16
|
+
route_path: str
|
|
17
|
+
http_method: str
|
|
18
|
+
handler: Callable[..., Any]
|
|
19
|
+
input_schema: dict[str, Any]
|
|
20
|
+
hidden: bool = False
|
|
21
|
+
required_permissions: list[str] = field(default_factory=list)
|
|
22
|
+
|
|
23
|
+
def to_mcp_tool(self) -> dict[str, Any]:
|
|
24
|
+
"""Convert to MCP tool specification."""
|
|
25
|
+
return {
|
|
26
|
+
"name": self.name,
|
|
27
|
+
"description": self.description,
|
|
28
|
+
"inputSchema": {
|
|
29
|
+
"type": "object",
|
|
30
|
+
**self.input_schema,
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BaseAdapter(ABC):
|
|
36
|
+
"""Abstract base class for framework-specific MCP adapters.
|
|
37
|
+
|
|
38
|
+
All framework adapters must implement these methods.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
auth_provider: AuthProvider | None = None,
|
|
44
|
+
):
|
|
45
|
+
"""Initialize the adapter with optional auth provider.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
auth_provider: Optional auth provider. Defaults to NoAuthProvider.
|
|
49
|
+
"""
|
|
50
|
+
self._auth_provider = auth_provider or NoAuthProvider()
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def auth_provider(self) -> AuthProvider:
|
|
54
|
+
"""Get the auth provider."""
|
|
55
|
+
return self._auth_provider
|
|
56
|
+
|
|
57
|
+
@auth_provider.setter
|
|
58
|
+
def auth_provider(self, provider: AuthProvider) -> None:
|
|
59
|
+
"""Set a custom auth provider."""
|
|
60
|
+
self._auth_provider = provider
|
|
61
|
+
|
|
62
|
+
def get_auth_context(self, request: Any = None) -> AuthContext:
|
|
63
|
+
"""Get auth context from request using the auth provider.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
request: Framework-specific request object (optional)
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
AuthContext with auth information
|
|
70
|
+
"""
|
|
71
|
+
return self._auth_provider.get_auth_context(request or {})
|
|
72
|
+
|
|
73
|
+
@abstractmethod
|
|
74
|
+
def get_routes(self) -> list[tuple[str, str, Callable[..., Any], dict[str, Any]]]:
|
|
75
|
+
"""Get all routes from the framework app.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
List of tuples: (path, http_method, handler, raw_config)
|
|
79
|
+
"""
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
@abstractmethod
|
|
83
|
+
def introspect_route(
|
|
84
|
+
self, path: str, method: str, handler: Callable[..., Any], config: Any
|
|
85
|
+
) -> ToolInfo:
|
|
86
|
+
"""Introspect a single route and return tool information.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
path: The route path (e.g., "/users/{id}")
|
|
90
|
+
method: HTTP method (GET, POST, etc.)
|
|
91
|
+
handler: The route handler function
|
|
92
|
+
config: Framework-specific route configuration
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
ToolInfo with name, description, and input_schema
|
|
96
|
+
"""
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
@abstractmethod
|
|
100
|
+
def execute_tool(
|
|
101
|
+
self,
|
|
102
|
+
handler: Callable[..., Any],
|
|
103
|
+
arguments: dict[str, Any],
|
|
104
|
+
auth_context: AuthContext | None = None,
|
|
105
|
+
) -> Any:
|
|
106
|
+
"""Execute a tool by calling its handler with resolved arguments.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
handler: The route handler function
|
|
110
|
+
arguments: Resolved arguments from MCP request
|
|
111
|
+
auth_context: AuthContext with auth information
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
The handler's return value, serialized appropriately
|
|
115
|
+
"""
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
@abstractmethod
|
|
119
|
+
def get_app(self) -> Any:
|
|
120
|
+
"""Get the underlying framework application object."""
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
@abstractmethod
|
|
124
|
+
def build_tool_name(self, http_method: str, path: str) -> str:
|
|
125
|
+
"""Build a deterministic, MCP-safe tool name from method and path.
|
|
126
|
+
|
|
127
|
+
Args:
|
|
128
|
+
http_method: HTTP method (GET, POST, etc.)
|
|
129
|
+
path: Route path
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
Sanitized tool name (alphanumeric + underscores)
|
|
133
|
+
"""
|
|
134
|
+
pass
|
backend2mcp/core/auth.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Authentication providers for backend2mcp."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class AuthContext:
|
|
12
|
+
"""Authentication context passed to tool execution.
|
|
13
|
+
|
|
14
|
+
Attributes:
|
|
15
|
+
headers: Headers to include in requests/handler calls
|
|
16
|
+
user_id: Authenticated user ID (if authenticated)
|
|
17
|
+
permissions: Set of permission strings
|
|
18
|
+
token: The bearer token (if applicable)
|
|
19
|
+
extra: Additional custom auth data
|
|
20
|
+
"""
|
|
21
|
+
headers: dict[str, str] = field(default_factory=dict)
|
|
22
|
+
user_id: str | None = None
|
|
23
|
+
permissions: set[str] = field(default_factory=set)
|
|
24
|
+
token: str | None = None
|
|
25
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
26
|
+
|
|
27
|
+
def has_permission(self, permission: str) -> bool:
|
|
28
|
+
"""Check if context has a specific permission."""
|
|
29
|
+
return permission in self.permissions
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AuthProvider(ABC):
|
|
33
|
+
"""Abstract base class for authentication providers.
|
|
34
|
+
|
|
35
|
+
Implement this to add custom auth behavior for your framework.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def get_auth_context(self, request: Any) -> AuthContext:
|
|
40
|
+
"""Extract auth context from an incoming request.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
request: Framework-specific request object
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
AuthContext with extracted auth data
|
|
47
|
+
"""
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
def validate_request(self, context: AuthContext, required_permissions: list[str]) -> bool:
|
|
51
|
+
"""Validate that request has required permissions.
|
|
52
|
+
|
|
53
|
+
Override this for custom validation logic.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
context: AuthContext from get_auth_context
|
|
57
|
+
required_permissions: List of permission strings
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
True if request is valid, False otherwise
|
|
61
|
+
"""
|
|
62
|
+
return all(context.has_permission(p) for p in required_permissions)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class NoAuthProvider(AuthProvider):
|
|
66
|
+
"""Default provider - no authentication required."""
|
|
67
|
+
|
|
68
|
+
def get_auth_context(self, request: Any) -> AuthContext:
|
|
69
|
+
"""Return empty auth context (no auth)."""
|
|
70
|
+
return AuthContext()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class BearerAuthProvider(AuthProvider):
|
|
74
|
+
"""Bearer token authentication provider.
|
|
75
|
+
|
|
76
|
+
Extracts and validates Bearer tokens from Authorization header.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(
|
|
80
|
+
self,
|
|
81
|
+
token_header: str = "Authorization",
|
|
82
|
+
token_prefix: str = "Bearer",
|
|
83
|
+
validate_tokens: list[str] | None = None,
|
|
84
|
+
):
|
|
85
|
+
"""Initialize the provider.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
token_header: Header name for token (default: Authorization)
|
|
89
|
+
token_prefix: Prefix before token (default: Bearer)
|
|
90
|
+
validate_tokens: List of valid tokens (empty = accept any)
|
|
91
|
+
"""
|
|
92
|
+
self.token_header = token_header
|
|
93
|
+
self.token_prefix = token_prefix
|
|
94
|
+
self.valid_tokens = set(validate_tokens or [])
|
|
95
|
+
|
|
96
|
+
def get_auth_context(self, request: Any) -> AuthContext:
|
|
97
|
+
"""Extract bearer token from request headers."""
|
|
98
|
+
# Try to get header from various framework request objects
|
|
99
|
+
headers = self._extract_headers(request)
|
|
100
|
+
|
|
101
|
+
auth_header = headers.get(self.token_header, "")
|
|
102
|
+
|
|
103
|
+
if not auth_header.startswith(f"{self.token_prefix} "):
|
|
104
|
+
return AuthContext()
|
|
105
|
+
|
|
106
|
+
token = auth_header[len(self.token_prefix) + 1 :]
|
|
107
|
+
|
|
108
|
+
# Validate if we have a token whitelist
|
|
109
|
+
if self.valid_tokens and token not in self.valid_tokens:
|
|
110
|
+
return AuthContext()
|
|
111
|
+
|
|
112
|
+
return AuthContext(
|
|
113
|
+
headers=headers,
|
|
114
|
+
token=token,
|
|
115
|
+
user_id=token[:8] if token else None, # Use token prefix as user ID
|
|
116
|
+
permissions={"default"},
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def _extract_headers(self, request: Any) -> dict[str, str]:
|
|
120
|
+
"""Extract headers from framework-specific request."""
|
|
121
|
+
# FastAPI/Starlette
|
|
122
|
+
if hasattr(request, "headers"):
|
|
123
|
+
return dict(request.headers)
|
|
124
|
+
|
|
125
|
+
# Flask
|
|
126
|
+
if hasattr(request, "environ"):
|
|
127
|
+
headers = {}
|
|
128
|
+
for key, value in request.environ.items():
|
|
129
|
+
if key.startswith("HTTP_"):
|
|
130
|
+
header_name = key[5:].replace("_", "-").title()
|
|
131
|
+
headers[header_name] = value
|
|
132
|
+
return headers
|
|
133
|
+
|
|
134
|
+
# Django
|
|
135
|
+
if hasattr(request, "META"):
|
|
136
|
+
headers = {}
|
|
137
|
+
for key, value in request.META.items():
|
|
138
|
+
if key.startswith("HTTP_"):
|
|
139
|
+
header_name = key[5:].replace("_", "-").title()
|
|
140
|
+
headers[header_name] = value
|
|
141
|
+
return headers
|
|
142
|
+
|
|
143
|
+
return {}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class APIKeyAuthProvider(AuthProvider):
|
|
147
|
+
"""API Key authentication provider.
|
|
148
|
+
|
|
149
|
+
Extracts API key from query parameter or header.
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
def __init__(
|
|
153
|
+
self,
|
|
154
|
+
header_name: str = "X-API-Key",
|
|
155
|
+
query_param: str = "api_key",
|
|
156
|
+
valid_keys: list[str] | None = None,
|
|
157
|
+
):
|
|
158
|
+
"""Initialize the provider.
|
|
159
|
+
|
|
160
|
+
Args:
|
|
161
|
+
header_name: Header name for API key
|
|
162
|
+
query_param: Query parameter name for API key
|
|
163
|
+
valid_keys: List of valid API keys (empty = accept any)
|
|
164
|
+
"""
|
|
165
|
+
self.header_name = header_name
|
|
166
|
+
self.query_param = query_param
|
|
167
|
+
self.valid_keys = set(valid_keys or [])
|
|
168
|
+
|
|
169
|
+
def get_auth_context(self, request: Any) -> AuthContext:
|
|
170
|
+
"""Extract API key from header or query param."""
|
|
171
|
+
# FastAPI/Starlette
|
|
172
|
+
if hasattr(request, "headers"):
|
|
173
|
+
headers = dict(request.headers)
|
|
174
|
+
api_key = headers.get(self.header_name) or request.query_params.get(self.query_param)
|
|
175
|
+
# Flask
|
|
176
|
+
elif hasattr(request, "environ"):
|
|
177
|
+
headers = {self.header_name: request.environ.get(f"HTTP_{self.header_name.upper().replace('-', '_')}", "")}
|
|
178
|
+
api_key = headers.get(self.header_name) or request.args.get(self.query_param)
|
|
179
|
+
# Django
|
|
180
|
+
elif hasattr(request, "META"):
|
|
181
|
+
headers = {self.header_name: request.META.get(f"HTTP_{self.header_name.upper().replace('-', '_')}", "")}
|
|
182
|
+
api_key = headers.get(self.header_name) or request.GET.get(self.query_param)
|
|
183
|
+
else:
|
|
184
|
+
return AuthContext()
|
|
185
|
+
|
|
186
|
+
if not api_key:
|
|
187
|
+
return AuthContext()
|
|
188
|
+
|
|
189
|
+
if self.valid_keys and api_key not in self.valid_keys:
|
|
190
|
+
return AuthContext()
|
|
191
|
+
|
|
192
|
+
return AuthContext(
|
|
193
|
+
headers=headers,
|
|
194
|
+
user_id=f"apikey-{api_key[:8]}",
|
|
195
|
+
permissions={"api"},
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class HeaderInjectionAuthProvider(AuthProvider):
|
|
200
|
+
"""Always injects custom headers into auth context.
|
|
201
|
+
|
|
202
|
+
Useful for forwarding headers to downstream services.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
def __init__(self, static_headers: dict[str, str]):
|
|
206
|
+
"""Initialize with static headers to inject.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
static_headers: Headers to inject into every request
|
|
210
|
+
"""
|
|
211
|
+
self.static_headers = static_headers
|
|
212
|
+
|
|
213
|
+
def get_auth_context(self, request: Any) -> AuthContext:
|
|
214
|
+
"""Return context with injected headers."""
|
|
215
|
+
# Extract request headers
|
|
216
|
+
if hasattr(request, "headers"):
|
|
217
|
+
request_headers = dict(request.headers)
|
|
218
|
+
elif hasattr(request, "environ"):
|
|
219
|
+
request_headers = {}
|
|
220
|
+
for key, value in request.environ.items():
|
|
221
|
+
if key.startswith("HTTP_"):
|
|
222
|
+
header_name = key[5:].replace("_", "-").title()
|
|
223
|
+
request_headers[header_name] = value
|
|
224
|
+
else:
|
|
225
|
+
request_headers = {}
|
|
226
|
+
|
|
227
|
+
# Merge static headers (static take precedence)
|
|
228
|
+
merged_headers = {**request_headers, **self.static_headers}
|
|
229
|
+
|
|
230
|
+
return AuthContext(
|
|
231
|
+
headers=merged_headers,
|
|
232
|
+
permissions={"default"},
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def combine_providers(*providers: AuthProvider) -> AuthProvider:
|
|
237
|
+
"""Combine multiple auth providers (first valid match wins).
|
|
238
|
+
|
|
239
|
+
Returns a provider that tries each provider in order.
|
|
240
|
+
"""
|
|
241
|
+
combined = _CombinedAuthProvider(providers)
|
|
242
|
+
return combined
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class _CombinedAuthProvider(AuthProvider):
|
|
246
|
+
"""Auth provider that combines multiple providers."""
|
|
247
|
+
|
|
248
|
+
def __init__(self, providers: tuple[AuthProvider, ...]):
|
|
249
|
+
self.providers = providers
|
|
250
|
+
|
|
251
|
+
def get_auth_context(self, request: Any) -> AuthContext:
|
|
252
|
+
"""Try each provider, return first non-empty context."""
|
|
253
|
+
for provider in self.providers:
|
|
254
|
+
context = provider.get_auth_context(request)
|
|
255
|
+
if context.token or context.user_id or context.permissions:
|
|
256
|
+
return context
|
|
257
|
+
return AuthContext()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Structured exceptions for backend2mcp."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Backend2MCPError(Exception):
|
|
5
|
+
"""Base exception for all backend2mcp errors."""
|
|
6
|
+
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RouteIntrospectionError(Backend2MCPError):
|
|
11
|
+
"""Raised when route introspection fails."""
|
|
12
|
+
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SchemaConversionError(Backend2MCPError):
|
|
17
|
+
"""Raised when converting route schemas to MCP format fails."""
|
|
18
|
+
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ToolExecutionError(Backend2MCPError):
|
|
23
|
+
"""Raised when executing a tool fails."""
|
|
24
|
+
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class AdapterConfigurationError(Backend2MCPError):
|
|
29
|
+
"""Raised when adapter is misconfigured."""
|
|
30
|
+
|
|
31
|
+
pass
|