modmex-lambda 0.7.1__py3-none-any.whl → 0.7.3__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 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()
@@ -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
  ]
@@ -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: ...
@@ -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=MCPContext(request=context, server=self, capability="tools", name=name, arguments=arguments))
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=MCPContext(request=context, server=self, capability="tools", name=name, arguments=arguments))
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
- for name in ("request", "context", "ctx"):
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] = request
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
- for name in ("request", "context", "ctx"):
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] = request
129
+ values[name] = ctx
126
130
  values.update(arguments)
127
131
  return self.handler(**values)
128
132
 
@@ -4,9 +4,12 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import base64
7
+ import asyncio
8
+ import queue
9
+ import threading
7
10
  from dataclasses import dataclass
8
11
  from http import HTTPStatus
9
- from typing import Any, Iterable
12
+ from typing import Any, Iterable, Iterator
10
13
 
11
14
 
12
15
  MCP_JSON_CONTENT_TYPE = "application/json"
@@ -21,6 +24,17 @@ class SSEEvent:
21
24
  retry: int | None = None
22
25
 
23
26
 
27
+ @dataclass(frozen=True)
28
+ class StreamingHTTPResponse:
29
+ """HTTP metadata plus a lazily-produced body for streaming adapters."""
30
+
31
+ status_code: int
32
+ content_type: str
33
+ headers: dict[str, str]
34
+ body: Iterator[str]
35
+ cancellation_token: Any = None
36
+
37
+
24
38
  def encode_sse(event: SSEEvent | Any) -> str:
25
39
  """Encode one event according to the SSE wire format."""
26
40
  if not isinstance(event, SSEEvent):
@@ -67,9 +81,9 @@ class MCPHttpTransport:
67
81
  response = JSONRPCResponse.failure(None, JSONRPCErrorCode.PARSE_ERROR, str(exc))
68
82
  return Response(body=self._model_dict(response), status_code=HTTPStatus.OK, content_type=MCP_JSON_CONTENT_TYPE)
69
83
 
70
- origin = request.headers.get("origin")
71
- if origin and self.allowed_origins is not None and origin not in self.allowed_origins:
72
- return Response(body={"error": "Origin is not allowed"}, status_code=HTTPStatus.FORBIDDEN, content_type=content_types.APPLICATION_JSON)
84
+ origin_error = self._validate_origin(request)
85
+ if origin_error is not None:
86
+ return Response(body=origin_error, status_code=HTTPStatus.FORBIDDEN, content_type=content_types.APPLICATION_JSON)
73
87
  if isinstance(payload, list):
74
88
  return Response(body={"error": "Batch requests are not supported by Streamable HTTP"}, status_code=HTTPStatus.BAD_REQUEST, content_type=content_types.APPLICATION_JSON)
75
89
  if isinstance(payload, dict):
@@ -86,9 +100,7 @@ class MCPHttpTransport:
86
100
  response_headers.update({"Cache-Control": "no-cache", "Connection": "keep-alive"})
87
101
  if body is not None:
88
102
  body = encode_sse(body)
89
- status_code = HTTPStatus.ACCEPTED if response is None else HTTPStatus.OK
90
- if response is not None and response.error is not None and response.error.code == JSONRPCErrorCode.METHOD_NOT_FOUND:
91
- status_code = HTTPStatus.NOT_FOUND
103
+ status_code = _http_status_for_response(response)
92
104
  return Response(
93
105
  body=body,
94
106
  status_code=status_code,
@@ -96,6 +108,12 @@ class MCPHttpTransport:
96
108
  headers=response_headers,
97
109
  )
98
110
 
111
+ def _validate_origin(self, request: Any) -> dict[str, str] | None:
112
+ origin = request.headers.get("origin")
113
+ if origin and self.allowed_origins is not None and origin not in self.allowed_origins:
114
+ return {"error": "Origin is not allowed"}
115
+ return None
116
+
99
117
  def _validate_headers(self, payload: dict[str, Any], headers: Any) -> Any:
100
118
  from modmex_lambda.event_handler import content_types
101
119
  from modmex_lambda.event_handler.response import Response
@@ -196,7 +214,116 @@ class MCPHttpTransport:
196
214
  )
197
215
 
198
216
 
217
+ class MCPStreamingHttpTransport:
218
+ """Produce MCP responses through an incremental SSE HTTP body.
219
+
220
+ The transport is adapter-neutral. A web server owns the socket and
221
+ consumes ``StreamingHTTPResponse.body``; a disconnected writer should
222
+ propagate its socket exception so the generator stops immediately.
223
+ """
224
+
225
+ def __init__(self, server: Any, *, allowed_origins: list[str] | None = None) -> None:
226
+ self.server = server
227
+ self._http = MCPHttpTransport(server, allowed_origins=allowed_origins)
228
+
229
+ def handle(self, request: Any) -> StreamingHTTPResponse:
230
+ """Return a lazy SSE response for one MCP HTTP request."""
231
+ payload = request.json_body
232
+ if not isinstance(payload, dict):
233
+ return StreamingHTTPResponse(
234
+ 400,
235
+ MCP_JSON_CONTENT_TYPE,
236
+ {},
237
+ iter((json.dumps({"error": "Streamable HTTP request must be a JSON object"}),)),
238
+ )
239
+ origin_error = self._http._validate_origin(request)
240
+ if origin_error is not None:
241
+ return StreamingHTTPResponse(403, MCP_JSON_CONTENT_TYPE, {}, iter((json.dumps(origin_error),)))
242
+ validation = self._http._validate_headers(payload, request.headers)
243
+ if validation is not None:
244
+ return StreamingHTTPResponse(validation.status_code, MCP_JSON_CONTENT_TYPE, {}, iter((json.dumps(validation.body),)))
245
+
246
+ if payload.get("method") == "tools/call":
247
+ return self._handle_tool_call(request, payload)
248
+ # The adapter has a synchronous boundary, but dispatch through the
249
+ # async server path so resources and prompts support async handlers too.
250
+ response = asyncio.run(self.server.handle_async(payload, context=request))
251
+
252
+ def body() -> Iterator[str]:
253
+ if response is not None:
254
+ yield encode_sse(self._http._model_dict(response))
255
+
256
+ return StreamingHTTPResponse(
257
+ status_code=_http_status_for_response(response),
258
+ content_type=MCP_SSE_CONTENT_TYPE,
259
+ headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
260
+ body=body(),
261
+ )
262
+
263
+ def _handle_tool_call(self, request: Any, payload: dict[str, Any]) -> StreamingHTTPResponse:
264
+ from modmex_lambda.mcp.middleware import MCPProgressReporter
265
+ from modmex_lambda.mcp.middleware import MCPCancellationToken
266
+
267
+ events: queue.Queue[tuple[str, Any]] = queue.Queue()
268
+ cancellation_token = MCPCancellationToken()
269
+ request.cancellation_token = cancellation_token
270
+ progress_token = (payload.get("params") or {}).get("_meta", {}).get("progressToken")
271
+ request.progress_reporter = (
272
+ MCPProgressReporter(
273
+ lambda value: events.put(("progress", {
274
+ "jsonrpc": "2.0",
275
+ "method": "notifications/progress",
276
+ "params": {"progressToken": progress_token, **value},
277
+ }))
278
+ )
279
+ if progress_token is not None else None
280
+ )
281
+
282
+ def run() -> None:
283
+ try:
284
+ events.put(("result", asyncio.run(self.server.handle_async(payload, context=request))))
285
+ except BaseException as exc:
286
+ events.put(("exception", exc))
287
+ finally:
288
+ events.put(("done", None))
289
+
290
+ threading.Thread(target=run, daemon=True).start()
291
+
292
+ def body() -> Iterator[str]:
293
+ while True:
294
+ kind, value = events.get()
295
+ if kind == "progress":
296
+ yield encode_sse(value)
297
+ elif kind == "result":
298
+ if value is not None:
299
+ yield encode_sse(self._http._model_dict(value))
300
+ elif kind == "exception":
301
+ raise value
302
+ elif kind == "done":
303
+ return
304
+
305
+ return StreamingHTTPResponse(
306
+ status_code=200,
307
+ content_type=MCP_SSE_CONTENT_TYPE,
308
+ headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
309
+ body=body(),
310
+ cancellation_token=cancellation_token,
311
+ )
312
+
313
+
199
314
  def _serialize(value: Any) -> Any:
200
315
  if hasattr(value, "model_dump"):
201
316
  return value.model_dump()
202
317
  return str(value)
318
+
319
+
320
+ def _http_status_for_response(response: Any) -> int:
321
+ """Map a completed MCP response to its HTTP status consistently."""
322
+ if response is None:
323
+ return HTTPStatus.ACCEPTED
324
+
325
+ from modmex_lambda.mcp import JSONRPCErrorCode
326
+
327
+ if response.error is not None and response.error.code == JSONRPCErrorCode.METHOD_NOT_FOUND:
328
+ return HTTPStatus.NOT_FOUND
329
+ return HTTPStatus.OK
@@ -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.1
3
+ Version: 0.7.3
4
4
  Summary: Ultra-lightweight AWS Lambda utilities for API Gateway routing and event handling.
5
5
  Author: Modmex
6
6
  License: MIT
@@ -1269,9 +1269,10 @@ handler = KinesisSource(registry, concurrency=False).handle
1269
1269
 
1270
1270
  ## Model Context Protocol (MCP) Server
1271
1271
 
1272
- `modmex-lambda` exposes MCP `2026-07-28` through the existing
1273
- `APIGatewayHttpResolver`. MCP is an optional adapter; it does not introduce a
1274
- second HTTP resolver, DI system, or application lifecycle.
1272
+ `modmex-lambda` implements the MCP `2026-07-28` server runtime and adapts it to
1273
+ the existing Lambda HTTP resolvers or to Lambda Web Adapter. MCP is an
1274
+ optional adapter; it reuses the existing dependency injection, middleware and
1275
+ application lifecycle rather than introducing a parallel web framework.
1275
1276
 
1276
1277
  ### Basic server
1277
1278
 
@@ -1303,6 +1304,60 @@ app.include_mcp(mcp, path="/mcp")
1303
1304
  handler = app.handler
1304
1305
  ```
1305
1306
 
1307
+ ### Choosing the resolver
1308
+
1309
+ Choose the resolver from the AWS transport and whether the function must
1310
+ stream the HTTP response:
1311
+
1312
+ | AWS transport | Response mode | Resolver | Entrypoint behavior |
1313
+ |---|---|---|---|
1314
+ | API Gateway HTTP API v2 | buffered | `APIGatewayHttpResolver` | `handler(event, context)` |
1315
+ | API Gateway REST API v1 | buffered | `APIGatewayRestResolver` | `handler(event, context)` |
1316
+ | Lambda Function URL | buffered | `APIGatewayHttpResolver` | `handler(event, context)` |
1317
+ | API Gateway REST API v1 | incremental streaming | `LambdaWebAdapterResolver` | `handler.run()` |
1318
+ | Lambda Function URL | incremental streaming | `LambdaWebAdapterResolver` | `handler.run()` |
1319
+
1320
+ Function URLs use the API Gateway HTTP API payload format version 2.0, which is
1321
+ why `APIGatewayHttpResolver` is the correct buffered resolver for both HTTP API
1322
+ and Function URL invocations. The AWS event shape is not used in streaming:
1323
+ Lambda Web Adapter starts the resolver as an HTTP process and forwards HTTP
1324
+ requests to its listening port.
1325
+
1326
+ Buffered HTTP API example:
1327
+
1328
+ ```python
1329
+ from modmex_lambda import APIGatewayHttpResolver
1330
+
1331
+ app = APIGatewayHttpResolver()
1332
+ app.include_mcp(mcp, path="/mcp")
1333
+ handler = app.handler
1334
+ ```
1335
+
1336
+ Buffered REST API example:
1337
+
1338
+ ```python
1339
+ from modmex_lambda import APIGatewayRestResolver
1340
+
1341
+ app = APIGatewayRestResolver()
1342
+ app.include_mcp(mcp, path="/mcp")
1343
+ handler = app.handler
1344
+ ```
1345
+
1346
+ Streaming example:
1347
+
1348
+ ```python
1349
+ from modmex_lambda import LambdaWebAdapterResolver
1350
+
1351
+ app = LambdaWebAdapterResolver()
1352
+ app.include_mcp(mcp, path="/mcp")
1353
+ handler = app.handler
1354
+ ```
1355
+
1356
+ For the streaming example, the deployment must start the Web Adapter process;
1357
+ the `serverless-python-mcp` plugin generates that launcher automatically.
1358
+ Without the plugin, the application can start the HTTP process explicitly by
1359
+ calling `handler.run()`.
1360
+
1306
1361
  ### Capabilities
1307
1362
 
1308
1363
  The server supports:
@@ -1314,7 +1369,12 @@ The server supports:
1314
1369
  - pagination through the opaque `nextCursor` field;
1315
1370
  - `structuredContent` in tool results;
1316
1371
  - `resultType`, `ttlMs` and `cacheScope` metadata;
1317
- - JSON responses and buffered `text/event-stream` responses.
1372
+ - JSON responses and buffered `text/event-stream` responses through the API
1373
+ Gateway resolvers;
1374
+ - incremental SSE response streaming through `LambdaWebAdapterResolver`;
1375
+ - async handlers for tools, resources and prompts in the streaming transport;
1376
+ - MCP `notifications/progress` events when the client supplies a
1377
+ `progressToken`.
1318
1378
 
1319
1379
  Resources and prompts are registered explicitly:
1320
1380
 
@@ -1346,10 +1406,11 @@ Mcp-Method: tools/call
1346
1406
  Mcp-Name: create_order
1347
1407
  ```
1348
1408
 
1349
- The server does not use `initialize`, `ping` or `Mcp-Session-Id`. Requests are
1350
- independent and may be routed to any Lambda instance. If the application needs
1351
- state, it must pass an explicit handle in tool arguments or persist that state
1352
- in its own services.
1409
+ The server implements the stateless `2026-07-28` HTTP contract and does not
1410
+ use `initialize`, `ping` or `Mcp-Session-Id`. Requests are independent and may
1411
+ be routed to any Lambda instance. If the application needs state, it must pass
1412
+ an explicit handle in tool arguments or persist that state in its own
1413
+ services. The runtime does not provide a session store.
1353
1414
 
1354
1415
  ### Middleware and authorization
1355
1416
 
@@ -1369,7 +1430,97 @@ Origin validation to API Gateway, WAF, or application middleware.
1369
1430
 
1370
1431
  ### Transport boundary
1371
1432
 
1372
- JSON is the required response mode. Buffered SSE is available when the client
1373
- requests `text/event-stream`, but this integration does not provide a
1374
- long-lived bidirectional stream or incremental Lambda response streaming.
1375
- Tasks, MRTR, subscriptions and real-time notifications are future extensions.
1433
+ This section applies to `APIGatewayRestResolver` and
1434
+ `APIGatewayHttpResolver`. JSON is the normal response mode, and the MCP HTTP
1435
+ transport can return a buffered SSE representation when the client requests
1436
+ `text/event-stream`. These resolvers do not provide incremental Lambda
1437
+ response streaming or a long-lived bidirectional connection.
1438
+
1439
+ For incremental response streaming, use `LambdaWebAdapterResolver` together
1440
+ with the `serverless-python-mcp` deployment plugin described below. This is a
1441
+ separate host adapter because Lambda Web Adapter owns the HTTP process and the
1442
+ response stream; the MCP server and capabilities remain the same. The
1443
+ streaming transport executes tools, resources and prompts through the async
1444
+ dispatcher, so all three capability types may use `async def` handlers.
1445
+
1446
+ When a tool reports progress, the client must send a `progressToken` in
1447
+ `params._meta`. The server emits standard MCP JSON-RPC progress notifications
1448
+ before the final result. Without a token, progress reports are not emitted to
1449
+ the client.
1450
+
1451
+ Streaming responses include `Cache-Control: no-cache`,
1452
+ `Connection: keep-alive`, and `X-Accel-Buffering: no`. The Lambda Web Adapter
1453
+ and the upstream client still control the lifetime of the connection; this
1454
+ integration does not provide a durable session or bidirectional subscription.
1455
+ Malformed requests and protocol/header validation failures are returned as
1456
+ ordinary JSON error responses, even when the client advertises SSE. Successful
1457
+ streaming responses use SSE framing, with the final JSON-RPC response as the
1458
+ last event.
1459
+
1460
+ MCP request/response features such as pagination, `structuredContent`, MRTR
1461
+ result handling, resources and prompts are part of the protocol implementation
1462
+ and are independent of whether the response is buffered or streamed. Long-
1463
+ lived subscriptions and server-push notification sessions are not provided by
1464
+ these Lambda integrations.
1465
+
1466
+ ### Serverless deployment and response streaming
1467
+
1468
+ For Serverless Framework deployments, use the companion npm plugin
1469
+ [`serverless-python-mcp`](https://www.npmjs.com/package/serverless-python-mcp).
1470
+ The plugin synthesizes the Lambda functions and transport resources from
1471
+ `custom.pythonMcp`; the application still owns the resolver and middleware:
1472
+
1473
+ ```yaml
1474
+ plugins:
1475
+ - serverless-python-mcp
1476
+
1477
+ custom:
1478
+ pythonMcp:
1479
+ servers:
1480
+ orders:
1481
+ handler: app.handler
1482
+ transport: url # url, http, or httpApi
1483
+ streaming: true
1484
+ path: /mcp # optional; defaults to /mcp
1485
+ ```
1486
+
1487
+ The application entrypoint is deliberately the same shape as a regular
1488
+ Serverless Lambda handler:
1489
+
1490
+ ```python
1491
+ from modmex_lambda import LambdaWebAdapterResolver
1492
+
1493
+ from server import mcp
1494
+
1495
+
1496
+ app = LambdaWebAdapterResolver()
1497
+ app.include_mcp(mcp, path="/mcp")
1498
+ handler = app.handler
1499
+ ```
1500
+
1501
+ The configured value is `module.attribute`, such as `app.handler`. For
1502
+ buffered deployments Serverless invokes `handler(event, context)` directly.
1503
+ For streaming deployments the plugin stages a temporary launcher that imports
1504
+ the configured handler returned by `LambdaWebAdapterResolver.handler` and calls
1505
+ `handler.run()`; the
1506
+ launcher is removed after packaging. Application code never needs an
1507
+ `if __name__ == "__main__"` block or a permanent `run.sh` file.
1508
+
1509
+ Transport mapping:
1510
+
1511
+ - `url`: Lambda Function URL;
1512
+ - `http`: API Gateway REST API (v1);
1513
+ - `httpApi`: API Gateway HTTP API (v2).
1514
+
1515
+ `streaming: true` is supported by `url` and `http`; `httpApi` is buffered-only.
1516
+ With `streaming: false`, all three transports are supported. Function URL
1517
+ authorizers are limited to `aws_iam` or public access. HTTP API authorizers can
1518
+ be declared globally under `provider.httpApi.authorizers` and referenced by
1519
+ name, or declared inline on an individual MCP server using Serverless'
1520
+ compatible authorizer configuration. For `http`, authorizers are passed to the
1521
+ native REST API event compiler.
1522
+
1523
+ The Lambda Web Adapter layer is attached only to streaming MCP functions and
1524
+ is selected by the function architecture (`x86_64` or `arm64`). The plugin
1525
+ uses the regional layer ARN through `AWS::Region`; it does not require a layer
1526
+ entry in the service's global `provider` configuration.
@@ -1,8 +1,8 @@
1
- modmex_lambda/__init__.py,sha256=7_Ja7fgLqR4RgEHRj2wpjndlh4P2TCdpfT05TZu6EnY,2296
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=FdFYT4Vih6XVKV6GOZfukltByyig6iSLbzKaWwJPZLA,6855
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=_moQqhKN_GN5XB7AtbDtvMTqQzBPEfIA34gDYxKwmH4,1057
62
- modmex_lambda/mcp/middleware.py,sha256=ZFTLAmj2J8XEPy3e7O3OC1gT2jMBM_YMJTFeQVjUIvI,1999
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=Wsm9G_rVzMUOurbn_VuATqKlnQnAWoKmKQ7JqTWoTb0,18342
69
- modmex_lambda/mcp/tool.py,sha256=rYeTFo9kVDm6VyYNzzO0SWEu9WtGSpXZuX3Cvhev6yw,7546
70
- modmex_lambda/mcp/transport.py,sha256=SOMwUv2hXEn6ZUuuCj39cZqk6SC8RR2qCTF7XHA7gwk,10181
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=LqyYsnRWxRtrswksh1HLYzB1iYoJP8U_nG40IqtHobg,15145
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.1.dist-info/METADATA,sha256=f6HaOnWQm-pLWAY79LlGjPa9kjBlUUUA5FBrT1hwDfc,38565
158
- modmex_lambda-0.7.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
159
- modmex_lambda-0.7.1.dist-info/licenses/LICENSE,sha256=_C2TDTOsYeJvE4vn9VB51laKvleBKbdNnn96wJVtXhQ,1063
160
- modmex_lambda-0.7.1.dist-info/RECORD,,
159
+ modmex_lambda-0.7.3.dist-info/METADATA,sha256=gqbfRSRhicrsXDz__jZF5slCCQciHDaQUjGN6S3hT2A,44716
160
+ modmex_lambda-0.7.3.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
161
+ modmex_lambda-0.7.3.dist-info/licenses/LICENSE,sha256=_C2TDTOsYeJvE4vn9VB51laKvleBKbdNnn96wJVtXhQ,1063
162
+ modmex_lambda-0.7.3.dist-info/RECORD,,