modmex-lambda 0.7.0__py3-none-any.whl → 0.7.2__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.
- modmex_lambda/__init__.py +2 -0
- modmex_lambda/logging.py +1 -1
- modmex_lambda/mcp/__init__.py +8 -2
- modmex_lambda/mcp/middleware.py +46 -0
- modmex_lambda/mcp/server.py +13 -3
- modmex_lambda/mcp/tool.py +8 -4
- modmex_lambda/mcp/transport.py +131 -1
- modmex_lambda/mcp/web_adapter.py +155 -0
- modmex_lambda/mcp/web_adapter_launcher.py +34 -0
- {modmex_lambda-0.7.0.dist-info → modmex_lambda-0.7.2.dist-info}/METADATA +78 -6
- {modmex_lambda-0.7.0.dist-info → modmex_lambda-0.7.2.dist-info}/RECORD +13 -11
- {modmex_lambda-0.7.0.dist-info → modmex_lambda-0.7.2.dist-info}/WHEEL +0 -0
- {modmex_lambda-0.7.0.dist-info → modmex_lambda-0.7.2.dist-info}/licenses/LICENSE +0 -0
modmex_lambda/__init__.py
CHANGED
|
@@ -19,6 +19,7 @@ __all__ = [
|
|
|
19
19
|
"Tracer",
|
|
20
20
|
"ModmexValidator",
|
|
21
21
|
"ValidationError",
|
|
22
|
+
"LambdaWebAdapterResolver",
|
|
22
23
|
]
|
|
23
24
|
|
|
24
25
|
|
|
@@ -42,6 +43,7 @@ def __getattr__(name):
|
|
|
42
43
|
"Tracer": ("modmex_lambda.tracing", "Tracer"),
|
|
43
44
|
"ModmexValidator": ("modmex_lambda.validation", "ModmexValidator"),
|
|
44
45
|
"ValidationError": ("modmex_lambda.validation", "ValidationError"),
|
|
46
|
+
"LambdaWebAdapterResolver": ("modmex_lambda.mcp.web_adapter", "LambdaWebAdapterResolver"),
|
|
45
47
|
}.get(name)
|
|
46
48
|
if target is None:
|
|
47
49
|
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
modmex_lambda/logging.py
CHANGED
|
@@ -44,7 +44,7 @@ class Logger:
|
|
|
44
44
|
correlation_id_header: str = "x-correlation-id",
|
|
45
45
|
level: str | int | None = None,
|
|
46
46
|
) -> None:
|
|
47
|
-
self._service = service or os.getenv("SERVICE_NAME") or os.getenv("AWS_LAMBDA_FUNCTION_NAME") or "service"
|
|
47
|
+
self._service = service or os.getenv("SERVICE_NAME") or os.getenv("SERVICE") or os.getenv("AWS_LAMBDA_FUNCTION_NAME") or "service"
|
|
48
48
|
self._stream = stream or sys.stdout
|
|
49
49
|
self._serialize = json_serializer or self._serialize_payload
|
|
50
50
|
self._correlation_id_header = correlation_id_header.lower()
|
modmex_lambda/mcp/__init__.py
CHANGED
|
@@ -11,8 +11,9 @@ from modmex_lambda.mcp.server import MCPError, MCPServer
|
|
|
11
11
|
from modmex_lambda.mcp.tool import MCPTool
|
|
12
12
|
from modmex_lambda.mcp.resource import MCPResource
|
|
13
13
|
from modmex_lambda.mcp.prompt import MCPPrompt
|
|
14
|
-
from modmex_lambda.mcp.transport import MCPHttpTransport, SSEEvent, encode_sse, encode_sse_stream, MCP_JSON_CONTENT_TYPE, MCP_SSE_CONTENT_TYPE
|
|
15
|
-
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware, MCPNextMiddleware
|
|
14
|
+
from modmex_lambda.mcp.transport import MCPHttpTransport, MCPStreamingHttpTransport, StreamingHTTPResponse, SSEEvent, encode_sse, encode_sse_stream, MCP_JSON_CONTENT_TYPE, MCP_SSE_CONTENT_TYPE
|
|
15
|
+
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware, MCPNextMiddleware, MCPProgressReporter, MCPCancellationToken
|
|
16
|
+
from modmex_lambda.mcp.web_adapter import LambdaWebAdapterResolver
|
|
16
17
|
|
|
17
18
|
__all__ = [
|
|
18
19
|
"JSONRPCError",
|
|
@@ -23,6 +24,8 @@ __all__ = [
|
|
|
23
24
|
"MCPServer",
|
|
24
25
|
"MCPError",
|
|
25
26
|
"MCPHttpTransport",
|
|
27
|
+
"MCPStreamingHttpTransport",
|
|
28
|
+
"StreamingHTTPResponse",
|
|
26
29
|
"MCPTool",
|
|
27
30
|
"MCPResource",
|
|
28
31
|
"MCPPrompt",
|
|
@@ -34,4 +37,7 @@ __all__ = [
|
|
|
34
37
|
"MCPContext",
|
|
35
38
|
"MCPMiddleware",
|
|
36
39
|
"MCPNextMiddleware",
|
|
40
|
+
"MCPProgressReporter",
|
|
41
|
+
"MCPCancellationToken",
|
|
42
|
+
"LambdaWebAdapterResolver",
|
|
37
43
|
]
|
modmex_lambda/mcp/middleware.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import inspect
|
|
6
|
+
import threading
|
|
6
7
|
from dataclasses import dataclass, field
|
|
7
8
|
from typing import TYPE_CHECKING, Callable, Protocol, TypeAlias, Union, Any
|
|
8
9
|
|
|
@@ -22,6 +23,35 @@ JSONValue: TypeAlias = Union[
|
|
|
22
23
|
]
|
|
23
24
|
|
|
24
25
|
|
|
26
|
+
@dataclass
|
|
27
|
+
class MCPCancellationToken:
|
|
28
|
+
"""Cooperative cancellation state for a streaming MCP operation."""
|
|
29
|
+
|
|
30
|
+
_event: threading.Event = field(default_factory=threading.Event)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def cancelled(self) -> bool:
|
|
34
|
+
return self._event.is_set()
|
|
35
|
+
|
|
36
|
+
def cancel(self) -> None:
|
|
37
|
+
self._event.set()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class MCPProgressReporter:
|
|
42
|
+
"""Cooperative progress publisher available to a running MCP operation."""
|
|
43
|
+
|
|
44
|
+
publish: Callable[[dict[str, JSONValue]], None]
|
|
45
|
+
|
|
46
|
+
def report(self, progress: float, *, total: float | None = None, message: str | None = None) -> None:
|
|
47
|
+
event: dict[str, JSONValue] = {"progress": progress}
|
|
48
|
+
if total is not None:
|
|
49
|
+
event["total"] = total
|
|
50
|
+
if message is not None:
|
|
51
|
+
event["message"] = message
|
|
52
|
+
self.publish(event)
|
|
53
|
+
|
|
54
|
+
|
|
25
55
|
@dataclass
|
|
26
56
|
class MCPContext:
|
|
27
57
|
request: "Request | None"
|
|
@@ -29,8 +59,24 @@ class MCPContext:
|
|
|
29
59
|
capability: str
|
|
30
60
|
name: str
|
|
31
61
|
arguments: dict[str, JSONValue]
|
|
62
|
+
context: dict[str, Any] = field(default_factory=dict)
|
|
32
63
|
state: dict[str, object] = field(default_factory=dict)
|
|
33
64
|
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
request_context = getattr(self.request, "context", None)
|
|
67
|
+
if isinstance(request_context, dict):
|
|
68
|
+
self.context = request_context
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def progress(self) -> MCPProgressReporter | None:
|
|
72
|
+
value = self.state.get("progress_reporter")
|
|
73
|
+
return value if isinstance(value, MCPProgressReporter) else None
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def cancelled(self) -> bool:
|
|
77
|
+
value = self.state.get("cancellation_token")
|
|
78
|
+
return isinstance(value, MCPCancellationToken) and value.cancelled
|
|
79
|
+
|
|
34
80
|
|
|
35
81
|
class MCPNextMiddleware(Protocol):
|
|
36
82
|
def __call__(self, context: MCPContext) -> object: ...
|
modmex_lambda/mcp/server.py
CHANGED
|
@@ -17,7 +17,7 @@ from modmex_lambda.mcp.registry import MCPPromptRegistry, MCPResourceRegistry
|
|
|
17
17
|
from modmex_lambda.mcp.prompt import MCPPrompt
|
|
18
18
|
from modmex_lambda.mcp.resource import MCPResource
|
|
19
19
|
from modmex_lambda.mcp.tool import MCPTool
|
|
20
|
-
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware
|
|
20
|
+
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware, MCPProgressReporter, MCPCancellationToken
|
|
21
21
|
|
|
22
22
|
from modmex_lambda.mcp.protocol import MCP_PROTOCOL_VERSION
|
|
23
23
|
|
|
@@ -314,7 +314,7 @@ class MCPServer:
|
|
|
314
314
|
arguments = params.get("arguments", {})
|
|
315
315
|
if not isinstance(arguments, dict):
|
|
316
316
|
raise ValueError("tools/call 'arguments' must be an object")
|
|
317
|
-
output = tool.invoke(arguments, request=context, middlewares=self.middlewares, middleware_context=
|
|
317
|
+
output = tool.invoke(arguments, request=context, middlewares=self.middlewares, middleware_context=self._tool_context(context, name, arguments))
|
|
318
318
|
return _tool_result(output)
|
|
319
319
|
|
|
320
320
|
def _resources_list(self, params: dict[str, Any], *, context: Any = None) -> dict[str, Any]:
|
|
@@ -361,7 +361,7 @@ class MCPServer:
|
|
|
361
361
|
arguments = params.get("arguments", {})
|
|
362
362
|
if not isinstance(arguments, dict):
|
|
363
363
|
raise ValueError("tools/call 'arguments' must be an object")
|
|
364
|
-
output = await tool.ainvoke(arguments, request=context, middlewares=self.middlewares, middleware_context=
|
|
364
|
+
output = await tool.ainvoke(arguments, request=context, middlewares=self.middlewares, middleware_context=self._tool_context(context, name, arguments))
|
|
365
365
|
return _tool_result(output)
|
|
366
366
|
|
|
367
367
|
async def _resources_read_async(self, params: dict[str, Any], *, context: Any = None) -> dict[str, Any]:
|
|
@@ -386,6 +386,16 @@ class MCPServer:
|
|
|
386
386
|
raise ValueError("prompts/get 'arguments' must be an object")
|
|
387
387
|
return {"resultType": "complete", **await prompt.aget(arguments, context=context, server=self, middlewares=self.middlewares), "ttlMs": 300000, "cacheScope": "private"}
|
|
388
388
|
|
|
389
|
+
def _tool_context(self, request: Any, name: str, arguments: dict[str, Any]) -> MCPContext:
|
|
390
|
+
state: dict[str, object] = {}
|
|
391
|
+
reporter = getattr(request, "progress_reporter", None)
|
|
392
|
+
if isinstance(reporter, MCPProgressReporter):
|
|
393
|
+
state["progress_reporter"] = reporter
|
|
394
|
+
token = getattr(request, "cancellation_token", None)
|
|
395
|
+
if isinstance(token, MCPCancellationToken):
|
|
396
|
+
state["cancellation_token"] = token
|
|
397
|
+
return MCPContext(request=request, server=self, capability="tools", name=name, arguments=arguments, state=state)
|
|
398
|
+
|
|
389
399
|
|
|
390
400
|
def _json_text(value: Any) -> str:
|
|
391
401
|
if isinstance(value, str):
|
modmex_lambda/mcp/tool.py
CHANGED
|
@@ -91,9 +91,11 @@ class MCPTool:
|
|
|
91
91
|
dependency_overrides=dependency_overrides,
|
|
92
92
|
dependency_resolver=dependency_resolver,
|
|
93
93
|
)
|
|
94
|
-
|
|
94
|
+
if "request" in parameters and "request" not in values:
|
|
95
|
+
values["request"] = request
|
|
96
|
+
for name in ("context", "ctx"):
|
|
95
97
|
if name in parameters and name not in values:
|
|
96
|
-
values[name] =
|
|
98
|
+
values[name] = ctx
|
|
97
99
|
values.update(arguments)
|
|
98
100
|
return self.handler(**values)
|
|
99
101
|
|
|
@@ -120,9 +122,11 @@ class MCPTool:
|
|
|
120
122
|
|
|
121
123
|
def endpoint(ctx: MCPContext) -> Any:
|
|
122
124
|
values = solve_dependencies(dependant=self.dependant, request=request, dependency_overrides=kwargs.get("dependency_overrides"), dependency_resolver=kwargs.get("dependency_resolver"))
|
|
123
|
-
|
|
125
|
+
if "request" in parameters and "request" not in values:
|
|
126
|
+
values["request"] = request
|
|
127
|
+
for name in ("context", "ctx"):
|
|
124
128
|
if name in parameters and name not in values:
|
|
125
|
-
values[name] =
|
|
129
|
+
values[name] = ctx
|
|
126
130
|
values.update(arguments)
|
|
127
131
|
return self.handler(**values)
|
|
128
132
|
|
modmex_lambda/mcp/transport.py
CHANGED
|
@@ -4,9 +4,11 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import json
|
|
6
6
|
import base64
|
|
7
|
+
import queue
|
|
8
|
+
import threading
|
|
7
9
|
from dataclasses import dataclass
|
|
8
10
|
from http import HTTPStatus
|
|
9
|
-
from typing import Any, Iterable
|
|
11
|
+
from typing import Any, Iterable, Iterator
|
|
10
12
|
|
|
11
13
|
|
|
12
14
|
MCP_JSON_CONTENT_TYPE = "application/json"
|
|
@@ -21,6 +23,17 @@ class SSEEvent:
|
|
|
21
23
|
retry: int | None = None
|
|
22
24
|
|
|
23
25
|
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class StreamingHTTPResponse:
|
|
28
|
+
"""HTTP metadata plus a lazily-produced body for streaming adapters."""
|
|
29
|
+
|
|
30
|
+
status_code: int
|
|
31
|
+
content_type: str
|
|
32
|
+
headers: dict[str, str]
|
|
33
|
+
body: Iterator[str]
|
|
34
|
+
cancellation_token: Any = None
|
|
35
|
+
|
|
36
|
+
|
|
24
37
|
def encode_sse(event: SSEEvent | Any) -> str:
|
|
25
38
|
"""Encode one event according to the SSE wire format."""
|
|
26
39
|
if not isinstance(event, SSEEvent):
|
|
@@ -120,6 +133,45 @@ class MCPHttpTransport:
|
|
|
120
133
|
if "io.modelcontextprotocol/clientCapabilities" not in metadata:
|
|
121
134
|
response = JSONRPCResponse.failure(payload.get("id"), JSONRPCErrorCode.INVALID_PARAMS, "Missing clientCapabilities")
|
|
122
135
|
return Response(body=self._model_dict(response), status_code=HTTPStatus.BAD_REQUEST, content_type=content_types.APPLICATION_JSON)
|
|
136
|
+
if method == "tools/call":
|
|
137
|
+
mismatch = self._validate_tool_parameter_headers(payload, headers)
|
|
138
|
+
if mismatch is not None:
|
|
139
|
+
return self._header_mismatch(payload, mismatch)
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
def _validate_tool_parameter_headers(self, payload: dict[str, Any], headers: Any) -> str | None:
|
|
143
|
+
params = payload.get("params") or {}
|
|
144
|
+
tool = self.server.tools.get(params.get("name")) if isinstance(params.get("name"), str) else None
|
|
145
|
+
if tool is None:
|
|
146
|
+
return None
|
|
147
|
+
schema = tool.definition().get("inputSchema")
|
|
148
|
+
arguments = params.get("arguments") or {}
|
|
149
|
+
expected: dict[str, str] = {}
|
|
150
|
+
|
|
151
|
+
def visit(node: Any, value: Any) -> None:
|
|
152
|
+
if not isinstance(node, dict) or not isinstance(value, dict):
|
|
153
|
+
return
|
|
154
|
+
for name, property_schema in (node.get("properties") or {}).items():
|
|
155
|
+
if not isinstance(property_schema, dict):
|
|
156
|
+
continue
|
|
157
|
+
header_name = property_schema.get("x-mcp-header")
|
|
158
|
+
if isinstance(header_name, str) and name in value:
|
|
159
|
+
item = value[name]
|
|
160
|
+
serialized = str(item).lower() if isinstance(item, bool) else str(item)
|
|
161
|
+
expected[f"mcp-param-{header_name}".lower()] = serialized
|
|
162
|
+
if property_schema.get("type") == "object":
|
|
163
|
+
visit(property_schema, value.get(name))
|
|
164
|
+
|
|
165
|
+
visit(schema, arguments)
|
|
166
|
+
actual = {str(key).lower(): value for key, value in headers.items()}
|
|
167
|
+
for header_name, expected_value in expected.items():
|
|
168
|
+
if header_name not in actual:
|
|
169
|
+
return f"Missing {header_name} header"
|
|
170
|
+
if self._decode_header(actual[header_name]) != expected_value:
|
|
171
|
+
return f"{header_name} does not match tool argument"
|
|
172
|
+
for header_name in actual:
|
|
173
|
+
if header_name.startswith("mcp-param-") and header_name not in expected:
|
|
174
|
+
return f"Unexpected {header_name} header"
|
|
123
175
|
return None
|
|
124
176
|
|
|
125
177
|
def _header_mismatch(self, payload: dict[str, Any], message: str) -> Any:
|
|
@@ -157,6 +209,84 @@ class MCPHttpTransport:
|
|
|
157
209
|
)
|
|
158
210
|
|
|
159
211
|
|
|
212
|
+
class MCPStreamingHttpTransport:
|
|
213
|
+
"""Produce MCP responses through an incremental SSE HTTP body.
|
|
214
|
+
|
|
215
|
+
The transport is adapter-neutral. A web server owns the socket and
|
|
216
|
+
consumes ``StreamingHTTPResponse.body``; a disconnected writer should
|
|
217
|
+
propagate its socket exception so the generator stops immediately.
|
|
218
|
+
"""
|
|
219
|
+
|
|
220
|
+
def __init__(self, server: Any, *, allowed_origins: list[str] | None = None) -> None:
|
|
221
|
+
self.server = server
|
|
222
|
+
self._http = MCPHttpTransport(server, allowed_origins=allowed_origins)
|
|
223
|
+
|
|
224
|
+
def handle(self, request: Any) -> StreamingHTTPResponse:
|
|
225
|
+
"""Return a lazy SSE response for one MCP HTTP request."""
|
|
226
|
+
validation = self._http._validate_headers(request.json_body, request.headers)
|
|
227
|
+
if validation is not None:
|
|
228
|
+
body = validation.body
|
|
229
|
+
status = validation.status_code
|
|
230
|
+
content_type = validation.content_type
|
|
231
|
+
return StreamingHTTPResponse(status, content_type, {}, iter((encode_sse(body),)))
|
|
232
|
+
|
|
233
|
+
payload = request.json_body
|
|
234
|
+
if payload.get("method") == "tools/call":
|
|
235
|
+
return self._handle_tool_call(request, payload)
|
|
236
|
+
response = self.server.handle(payload, context=request)
|
|
237
|
+
|
|
238
|
+
def body() -> Iterator[str]:
|
|
239
|
+
if response is not None:
|
|
240
|
+
yield encode_sse(self._http._model_dict(response))
|
|
241
|
+
|
|
242
|
+
return StreamingHTTPResponse(
|
|
243
|
+
status_code=202 if response is None else 200,
|
|
244
|
+
content_type=MCP_SSE_CONTENT_TYPE,
|
|
245
|
+
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
|
|
246
|
+
body=body(),
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
def _handle_tool_call(self, request: Any, payload: dict[str, Any]) -> StreamingHTTPResponse:
|
|
250
|
+
from modmex_lambda.mcp.middleware import MCPProgressReporter
|
|
251
|
+
from modmex_lambda.mcp.middleware import MCPCancellationToken
|
|
252
|
+
|
|
253
|
+
events: queue.Queue[tuple[str, Any]] = queue.Queue()
|
|
254
|
+
cancellation_token = MCPCancellationToken()
|
|
255
|
+
request.cancellation_token = cancellation_token
|
|
256
|
+
request.progress_reporter = MCPProgressReporter(lambda value: events.put(("progress", value)))
|
|
257
|
+
|
|
258
|
+
def run() -> None:
|
|
259
|
+
try:
|
|
260
|
+
events.put(("result", self.server.handle(payload, context=request)))
|
|
261
|
+
except BaseException as exc:
|
|
262
|
+
events.put(("exception", exc))
|
|
263
|
+
finally:
|
|
264
|
+
events.put(("done", None))
|
|
265
|
+
|
|
266
|
+
threading.Thread(target=run, daemon=True).start()
|
|
267
|
+
|
|
268
|
+
def body() -> Iterator[str]:
|
|
269
|
+
while True:
|
|
270
|
+
kind, value = events.get()
|
|
271
|
+
if kind == "progress":
|
|
272
|
+
yield encode_sse(SSEEvent(data=value, event="progress"))
|
|
273
|
+
elif kind == "result":
|
|
274
|
+
if value is not None:
|
|
275
|
+
yield encode_sse(self._http._model_dict(value))
|
|
276
|
+
elif kind == "exception":
|
|
277
|
+
raise value
|
|
278
|
+
elif kind == "done":
|
|
279
|
+
return
|
|
280
|
+
|
|
281
|
+
return StreamingHTTPResponse(
|
|
282
|
+
status_code=200,
|
|
283
|
+
content_type=MCP_SSE_CONTENT_TYPE,
|
|
284
|
+
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
|
|
285
|
+
body=body(),
|
|
286
|
+
cancellation_token=cancellation_token,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
160
290
|
def _serialize(value: Any) -> Any:
|
|
161
291
|
if hasattr(value, "model_dump"):
|
|
162
292
|
return value.model_dump()
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Lambda Web Adapter resolver for MCP streaming applications."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
from typing import Any, Callable
|
|
10
|
+
|
|
11
|
+
from modmex_lambda.logging import Logger
|
|
12
|
+
from modmex_lambda.mcp.transport import MCPStreamingHttpTransport
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class LambdaWebAdapterResolver:
|
|
16
|
+
"""Expose an MCP server through Lambda Web Adapter's HTTP port.
|
|
17
|
+
|
|
18
|
+
Application code only registers capabilities and calls ``include_mcp``;
|
|
19
|
+
HTTP parsing, streaming, and disconnect handling remain in the library.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, *, host: str = "0.0.0.0", port: int | None = None, health_path: str = "/health", max_body_bytes: int = 1_048_576, allowed_origins: list[str] | None = None, logger: Logger | None = None) -> None:
|
|
23
|
+
if max_body_bytes <= 0:
|
|
24
|
+
raise ValueError("max_body_bytes must be positive")
|
|
25
|
+
self.host = host
|
|
26
|
+
self.port = port or int(os.environ.get("PORT", "8080"))
|
|
27
|
+
self.health_path = health_path
|
|
28
|
+
self.max_body_bytes = max_body_bytes
|
|
29
|
+
self.allowed_origins = allowed_origins
|
|
30
|
+
self.logger = logger or Logger(service=os.getenv('SERVICE', 'lambda-web-adapter'))
|
|
31
|
+
self._routes: dict[str, Any] = {}
|
|
32
|
+
self._middlewares: list[Callable[..., Any]] = []
|
|
33
|
+
|
|
34
|
+
def middleware(self, func: Callable[..., Any] | None = None) -> Any:
|
|
35
|
+
"""Register HTTP middleware with ``middleware(request, next)``."""
|
|
36
|
+
if func is None:
|
|
37
|
+
def decorator(middleware: Callable[..., Any]) -> Callable[..., Any]:
|
|
38
|
+
self._middlewares.append(middleware)
|
|
39
|
+
return middleware
|
|
40
|
+
return decorator
|
|
41
|
+
self._middlewares.append(func)
|
|
42
|
+
return func
|
|
43
|
+
|
|
44
|
+
def include_mcp(self, server: Any, *, path: str = "/mcp") -> None:
|
|
45
|
+
self._routes[path] = MCPStreamingHttpTransport(server, allowed_origins=self.allowed_origins)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def handler(self) -> "LambdaWebAdapterHandler":
|
|
49
|
+
"""Return the unified application entrypoint.
|
|
50
|
+
|
|
51
|
+
The returned object is consumed by the generated Lambda Web Adapter
|
|
52
|
+
launcher in streaming deployments. Keeping the public value named
|
|
53
|
+
``handler`` makes the application contract identical to a regular
|
|
54
|
+
Lambda application while the launcher remains an implementation
|
|
55
|
+
detail of the deployment plugin.
|
|
56
|
+
"""
|
|
57
|
+
return LambdaWebAdapterHandler(self)
|
|
58
|
+
|
|
59
|
+
def run(self) -> None:
|
|
60
|
+
resolver = self
|
|
61
|
+
|
|
62
|
+
class Handler(BaseHTTPRequestHandler):
|
|
63
|
+
def do_POST(self) -> None:
|
|
64
|
+
resolver._handle(self)
|
|
65
|
+
|
|
66
|
+
def do_GET(self) -> None:
|
|
67
|
+
if self.path == resolver.health_path:
|
|
68
|
+
resolver._write_json(self, 200, {"status": "ok"})
|
|
69
|
+
else:
|
|
70
|
+
self.send_error(404)
|
|
71
|
+
|
|
72
|
+
def log_message(self, format: str, *args: object) -> None:
|
|
73
|
+
resolver.logger.debug("http request", request=format % args)
|
|
74
|
+
|
|
75
|
+
server = ThreadingHTTPServer((self.host, self.port), Handler)
|
|
76
|
+
server.daemon_threads = True
|
|
77
|
+
self.logger.info("Lambda Web Adapter server listening", host=self.host, port=self.port)
|
|
78
|
+
try:
|
|
79
|
+
server.serve_forever()
|
|
80
|
+
finally:
|
|
81
|
+
server.server_close()
|
|
82
|
+
|
|
83
|
+
def _handle(self, handler: BaseHTTPRequestHandler) -> None:
|
|
84
|
+
transport = self._routes.get(handler.path)
|
|
85
|
+
if transport is None:
|
|
86
|
+
handler.send_error(404)
|
|
87
|
+
return
|
|
88
|
+
try:
|
|
89
|
+
length = int(handler.headers.get("Content-Length", "0"))
|
|
90
|
+
if length < 0 or length > self.max_body_bytes:
|
|
91
|
+
self._write_json(handler, 413, {"error": "Request body is too large"})
|
|
92
|
+
return
|
|
93
|
+
payload = json.loads(handler.rfile.read(length))
|
|
94
|
+
request = SimpleNamespace(
|
|
95
|
+
json_body=payload,
|
|
96
|
+
headers={key.lower(): value for key, value in handler.headers.items()},
|
|
97
|
+
context={},
|
|
98
|
+
)
|
|
99
|
+
response = self._run_middlewares(request, lambda: transport.handle(request))
|
|
100
|
+
handler.send_response(response.status_code)
|
|
101
|
+
handler.send_header("Content-Type", response.content_type)
|
|
102
|
+
for name, value in response.headers.items():
|
|
103
|
+
handler.send_header(name, value)
|
|
104
|
+
handler.end_headers()
|
|
105
|
+
for event in response.body:
|
|
106
|
+
handler.wfile.write(event.encode())
|
|
107
|
+
handler.wfile.flush()
|
|
108
|
+
handler.close_connection = True
|
|
109
|
+
except (BrokenPipeError, ConnectionResetError, OSError) as exc:
|
|
110
|
+
if "response" in locals() and response.cancellation_token is not None:
|
|
111
|
+
response.cancellation_token.cancel()
|
|
112
|
+
self.logger.info("MCP stream cancelled", error=str(exc))
|
|
113
|
+
except (ValueError, json.JSONDecodeError) as exc:
|
|
114
|
+
self._write_json(handler, 400, {"error": str(exc)})
|
|
115
|
+
|
|
116
|
+
def _run_middlewares(self, request: Any, endpoint: Callable[[], Any]) -> Any:
|
|
117
|
+
def invoke(index: int) -> Any:
|
|
118
|
+
if index == len(self._middlewares):
|
|
119
|
+
return endpoint()
|
|
120
|
+
middleware = self._middlewares[index]
|
|
121
|
+
return middleware(request, lambda: invoke(index + 1))
|
|
122
|
+
return invoke(0)
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
def _write_json(handler: BaseHTTPRequestHandler, status: int, body: dict[str, str]) -> None:
|
|
126
|
+
encoded = json.dumps(body).encode()
|
|
127
|
+
handler.send_response(status)
|
|
128
|
+
handler.send_header("Content-Type", "application/json")
|
|
129
|
+
handler.send_header("Content-Length", str(len(encoded)))
|
|
130
|
+
handler.end_headers()
|
|
131
|
+
handler.wfile.write(encoded)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class LambdaWebAdapterHandler:
|
|
135
|
+
"""Callable application entrypoint used by Lambda Web Adapter."""
|
|
136
|
+
|
|
137
|
+
def __init__(self, resolver: LambdaWebAdapterResolver) -> None:
|
|
138
|
+
self._resolver = resolver
|
|
139
|
+
|
|
140
|
+
def run(self) -> None:
|
|
141
|
+
"""Start the HTTP application consumed by Lambda Web Adapter."""
|
|
142
|
+
self._resolver.run()
|
|
143
|
+
|
|
144
|
+
def __call__(self, event: dict[str, Any], context: object) -> Any:
|
|
145
|
+
"""Fail clearly when used as a normal Lambda handler.
|
|
146
|
+
|
|
147
|
+
Lambda Web Adapter applications are HTTP processes, not API Gateway
|
|
148
|
+
event handlers. The callable shape is intentionally present so the
|
|
149
|
+
same ``handler = app.handler`` contract can be shared with regular
|
|
150
|
+
Modmex applications; the streaming launcher calls ``run()``.
|
|
151
|
+
"""
|
|
152
|
+
raise RuntimeError(
|
|
153
|
+
"LambdaWebAdapterResolver.handler must be started with handler.run(); "
|
|
154
|
+
"it cannot process a Lambda event directly"
|
|
155
|
+
)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Launch a configured Modmex Lambda Web Adapter application."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from modmex_lambda.mcp.web_adapter import LambdaWebAdapterHandler
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main() -> None:
|
|
12
|
+
module_name = os.environ.get("MCP_HANDLER_MODULE")
|
|
13
|
+
attribute_name = os.environ.get("MCP_HANDLER_ATTRIBUTE", "handler")
|
|
14
|
+
if not module_name:
|
|
15
|
+
raise RuntimeError("MCP_HANDLER_MODULE is required")
|
|
16
|
+
|
|
17
|
+
module = importlib.import_module(module_name)
|
|
18
|
+
try:
|
|
19
|
+
handler = getattr(module, attribute_name)
|
|
20
|
+
except AttributeError as exc:
|
|
21
|
+
raise RuntimeError(
|
|
22
|
+
f"MCP handler '{module_name}.{attribute_name}' was not found"
|
|
23
|
+
) from exc
|
|
24
|
+
|
|
25
|
+
if not isinstance(handler, LambdaWebAdapterHandler):
|
|
26
|
+
raise TypeError(
|
|
27
|
+
f"MCP handler '{module_name}.{attribute_name}' must be a "
|
|
28
|
+
"LambdaWebAdapterHandler for streaming deployments"
|
|
29
|
+
)
|
|
30
|
+
handler.run()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
if __name__ == "__main__":
|
|
34
|
+
main()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: modmex-lambda
|
|
3
|
-
Version: 0.7.
|
|
3
|
+
Version: 0.7.2
|
|
4
4
|
Summary: Ultra-lightweight AWS Lambda utilities for API Gateway routing and event handling.
|
|
5
5
|
Author: Modmex
|
|
6
6
|
License: MIT
|
|
@@ -1367,9 +1367,81 @@ def create_order(order: Order):
|
|
|
1367
1367
|
enforce an Origin allowlist itself. Leaving it as `None` explicitly delegates
|
|
1368
1368
|
Origin validation to API Gateway, WAF, or application middleware.
|
|
1369
1369
|
|
|
1370
|
-
###
|
|
1370
|
+
### Buffered transport boundary
|
|
1371
1371
|
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1372
|
+
This section applies to `APIGatewayRestResolver` and
|
|
1373
|
+
`APIGatewayHttpResolver`. JSON is the normal response mode, and the MCP HTTP
|
|
1374
|
+
transport can return a buffered SSE representation when the client requests
|
|
1375
|
+
`text/event-stream`. These resolvers do not provide incremental Lambda
|
|
1376
|
+
response streaming or a long-lived bidirectional connection.
|
|
1377
|
+
|
|
1378
|
+
For incremental response streaming, use `LambdaWebAdapterResolver` together
|
|
1379
|
+
with the `serverless-python-mcp` deployment plugin described below. That is a
|
|
1380
|
+
separate runtime path because Lambda Web Adapter owns the HTTP process and
|
|
1381
|
+
the response stream.
|
|
1382
|
+
|
|
1383
|
+
MCP request/response features such as pagination, `structuredContent`, MRTR
|
|
1384
|
+
result handling, resources and prompts are part of the protocol implementation
|
|
1385
|
+
and are independent of whether the response is buffered or streamed. Long-
|
|
1386
|
+
lived subscriptions and server-push notification sessions are not provided by
|
|
1387
|
+
these Lambda integrations.
|
|
1388
|
+
|
|
1389
|
+
### Serverless deployment and response streaming
|
|
1390
|
+
|
|
1391
|
+
For Serverless Framework deployments, use the companion npm plugin
|
|
1392
|
+
[`serverless-python-mcp`](https://www.npmjs.com/package/serverless-python-mcp).
|
|
1393
|
+
The plugin synthesizes the Lambda functions and transport resources from
|
|
1394
|
+
`custom.pythonMcp`; the application still owns the resolver and middleware:
|
|
1395
|
+
|
|
1396
|
+
```yaml
|
|
1397
|
+
plugins:
|
|
1398
|
+
- serverless-python-mcp
|
|
1399
|
+
|
|
1400
|
+
custom:
|
|
1401
|
+
pythonMcp:
|
|
1402
|
+
servers:
|
|
1403
|
+
orders:
|
|
1404
|
+
handler: app.handler
|
|
1405
|
+
transport: url # url, http, or httpApi
|
|
1406
|
+
streaming: true
|
|
1407
|
+
path: /mcp # optional; defaults to /mcp
|
|
1408
|
+
```
|
|
1409
|
+
|
|
1410
|
+
The application entrypoint is deliberately the same shape as a regular
|
|
1411
|
+
Serverless Lambda handler:
|
|
1412
|
+
|
|
1413
|
+
```python
|
|
1414
|
+
from modmex_lambda import LambdaWebAdapterResolver
|
|
1415
|
+
|
|
1416
|
+
from server import mcp
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
app = LambdaWebAdapterResolver()
|
|
1420
|
+
app.include_mcp(mcp, path="/mcp")
|
|
1421
|
+
handler = app.handler
|
|
1422
|
+
```
|
|
1423
|
+
|
|
1424
|
+
The configured value is `module.attribute`, such as `app.handler`. For
|
|
1425
|
+
buffered deployments Serverless invokes `handler(event, context)` directly.
|
|
1426
|
+
For streaming deployments the plugin stages a temporary launcher that imports
|
|
1427
|
+
the configured `LambdaWebAdapterHandler` and calls `handler.run()`; the
|
|
1428
|
+
launcher is removed after packaging. Application code never needs an
|
|
1429
|
+
`if __name__ == "__main__"` block or a permanent `run.sh` file.
|
|
1430
|
+
|
|
1431
|
+
Transport mapping:
|
|
1432
|
+
|
|
1433
|
+
- `url`: Lambda Function URL;
|
|
1434
|
+
- `http`: API Gateway REST API (v1);
|
|
1435
|
+
- `httpApi`: API Gateway HTTP API (v2).
|
|
1436
|
+
|
|
1437
|
+
`streaming: true` is supported by `url` and `http`; `httpApi` is buffered-only.
|
|
1438
|
+
With `streaming: false`, all three transports are supported. Function URL
|
|
1439
|
+
authorizers are limited to `aws_iam` or public access. HTTP API authorizers can
|
|
1440
|
+
be declared globally under `provider.httpApi.authorizers` and referenced by
|
|
1441
|
+
name, or declared inline on an individual MCP server using Serverless'
|
|
1442
|
+
compatible authorizer configuration.
|
|
1443
|
+
|
|
1444
|
+
The Lambda Web Adapter layer is attached only to streaming MCP functions and
|
|
1445
|
+
is selected by the function architecture (`x86_64` or `arm64`). The plugin
|
|
1446
|
+
uses the regional layer ARN through `AWS::Region`; it does not require a layer
|
|
1447
|
+
entry in the service's global `provider` configuration.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
modmex_lambda/__init__.py,sha256=
|
|
1
|
+
modmex_lambda/__init__.py,sha256=pa6666Ha3us8fhuzc-znAEvHuMLvcbrgu1T9jcvwr8c,2427
|
|
2
2
|
modmex_lambda/dependencies.py,sha256=vjBU3LMBJeAI96vCgwE5SnhAzSViFIaylvaJ15IKwOU,2827
|
|
3
3
|
modmex_lambda/event_sources.py,sha256=eLTEN1g9JF2Nk09fMcJn43dBz8BKwCOrtxmZkzr99sM,1714
|
|
4
4
|
modmex_lambda/exceptions.py,sha256=GL6ZZKhXr0BqfCsGwzookBrUJ1M7JIU2Ju3vWdyna_s,128
|
|
5
|
-
modmex_lambda/logging.py,sha256=
|
|
5
|
+
modmex_lambda/logging.py,sha256=Nf3MlYTUzoELgjfUcxoD2MCJuXvfTkT0YwMvfmoYNwc,6879
|
|
6
6
|
modmex_lambda/params.py,sha256=s7cnrW2NSCwWyQ_odn0b_uQJJn_aDR0JO6XUAFKI3PY,131
|
|
7
7
|
modmex_lambda/parser.py,sha256=BO2PG1YHZsRbHxqcd4rKehJDkBoipAQjAgXi-E7mysM,1544
|
|
8
8
|
modmex_lambda/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
@@ -58,16 +58,18 @@ modmex_lambda/event_handler/dependencies/dependency_middleware.py,sha256=c_N7Ugt
|
|
|
58
58
|
modmex_lambda/event_handler/dependencies/depends.py,sha256=pJ1rcMoA99vSaQTPxJ0zkYppPDKU0-lm9URc9Gifmdw,7110
|
|
59
59
|
modmex_lambda/event_handler/dependencies/params.py,sha256=eTQf_HWRZHEGtk5RnE2HSPqZ6ZMdVMvxOD_fm_pIpbg,9948
|
|
60
60
|
modmex_lambda/event_handler/dependencies/types.py,sha256=5VA8zl-EjQDNKXOrNT7sRv_vNs40Lz8aMP-sf-lf8sk,376
|
|
61
|
-
modmex_lambda/mcp/__init__.py,sha256=
|
|
62
|
-
modmex_lambda/mcp/middleware.py,sha256=
|
|
61
|
+
modmex_lambda/mcp/__init__.py,sha256=V8owTgDQ4K8ktcZu64KLAmOrNfICK_NWSEe35COHCN8,1366
|
|
62
|
+
modmex_lambda/mcp/middleware.py,sha256=ddLLAZRkppKXpOVYDBS43D2L1gQFPg7syrtysDsPfeQ,3464
|
|
63
63
|
modmex_lambda/mcp/prompt.py,sha256=FiWS-b5WbCZV6HJwdclM4q5cXok5J3v_n3XSz6ha96E,2403
|
|
64
64
|
modmex_lambda/mcp/protocol.py,sha256=MiG2rHcJuN9so_TjtVArIL5ROMpHJoPtHTYzX8D6o2Y,1562
|
|
65
65
|
modmex_lambda/mcp/registry.py,sha256=p68lShojJv8eL0gYj4CjpvDE8mJy0UyhqzRsJcVooFk,3471
|
|
66
66
|
modmex_lambda/mcp/resource.py,sha256=X_U0om1-nsuv8WwJ_ydUrFQL3k4aRqwp502aAs7KP3o,3694
|
|
67
67
|
modmex_lambda/mcp/schema.py,sha256=TjHBV4rlavJxIrGA2g3g_PS00gXxEIw-t2uxOJtBn9Q,3300
|
|
68
|
-
modmex_lambda/mcp/server.py,sha256=
|
|
69
|
-
modmex_lambda/mcp/tool.py,sha256=
|
|
70
|
-
modmex_lambda/mcp/transport.py,sha256=
|
|
68
|
+
modmex_lambda/mcp/server.py,sha256=tdeA_X6EkcOCJzYxD9t-W9-Gv7lUMwJ_SNdA69RBA8s,18872
|
|
69
|
+
modmex_lambda/mcp/tool.py,sha256=dCNxT8GzKJzsdOkWINk2kI6RSMCYIi4EI8N_iK67Hmg,7740
|
|
70
|
+
modmex_lambda/mcp/transport.py,sha256=QFz5isnrktDL2GQdg2aNzKzz-sqIB0Y5wZpjTaw-4wA,13738
|
|
71
|
+
modmex_lambda/mcp/web_adapter.py,sha256=gi8MPIGMjYEZr8ntrj1DAADyUoWcvyp_bqyUTo3vT2c,6674
|
|
72
|
+
modmex_lambda/mcp/web_adapter_launcher.py,sha256=CEo_nCcYkNLifkgXFG0_rdKq6DzZcqXWbdCEFE_fcPE,981
|
|
71
73
|
modmex_lambda/persistence/__init__.py,sha256=oa4FHCvitEkoagJ059jGATj6GSm-maazzf_QNi4WdQs,74
|
|
72
74
|
modmex_lambda/persistence/dynamodb/__init__.py,sha256=f_R3NHWfHvTWkCYfBHqY-z75r7pESsUv5FmFf05Glgg,1026
|
|
73
75
|
modmex_lambda/persistence/dynamodb/expressions.py,sha256=E_FDebLgROv63DBRQXKuO1hXjTt9g1kGzbgH2YBNu-Y,1694
|
|
@@ -154,7 +156,7 @@ modmex_lambda/stream/utils/time.py,sha256=dnsL2xeWpa1FXm2p8y9rWXtICMBlCBkgLaJ_en
|
|
|
154
156
|
modmex_lambda/stream/utils/uow.py,sha256=8WSPVE7AiHInkFDfBEeKOvdirY6GAgBoS7qkF1f1JVM,3207
|
|
155
157
|
modmex_lambda/stream/utils/data_classes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
156
158
|
modmex_lambda/stream/utils/data_classes/dynamodb.py,sha256=h_7MtUyRkvvV1r2QECrRDu7RR4Hh94SwSjc_8K2_XGM,363
|
|
157
|
-
modmex_lambda-0.7.
|
|
158
|
-
modmex_lambda-0.7.
|
|
159
|
-
modmex_lambda-0.7.
|
|
160
|
-
modmex_lambda-0.7.
|
|
159
|
+
modmex_lambda-0.7.2.dist-info/METADATA,sha256=N39W51pJr7mmvvXIiCfn72N4xMFqguv_D505i5D-Dkw,41354
|
|
160
|
+
modmex_lambda-0.7.2.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
161
|
+
modmex_lambda-0.7.2.dist-info/licenses/LICENSE,sha256=_C2TDTOsYeJvE4vn9VB51laKvleBKbdNnn96wJVtXhQ,1063
|
|
162
|
+
modmex_lambda-0.7.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|