modmex-lambda 0.7.2__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.
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import json
6
6
  import base64
7
+ import asyncio
7
8
  import queue
8
9
  import threading
9
10
  from dataclasses import dataclass
@@ -80,9 +81,9 @@ class MCPHttpTransport:
80
81
  response = JSONRPCResponse.failure(None, JSONRPCErrorCode.PARSE_ERROR, str(exc))
81
82
  return Response(body=self._model_dict(response), status_code=HTTPStatus.OK, content_type=MCP_JSON_CONTENT_TYPE)
82
83
 
83
- origin = request.headers.get("origin")
84
- if origin and self.allowed_origins is not None and origin not in self.allowed_origins:
85
- 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)
86
87
  if isinstance(payload, list):
87
88
  return Response(body={"error": "Batch requests are not supported by Streamable HTTP"}, status_code=HTTPStatus.BAD_REQUEST, content_type=content_types.APPLICATION_JSON)
88
89
  if isinstance(payload, dict):
@@ -99,9 +100,7 @@ class MCPHttpTransport:
99
100
  response_headers.update({"Cache-Control": "no-cache", "Connection": "keep-alive"})
100
101
  if body is not None:
101
102
  body = encode_sse(body)
102
- status_code = HTTPStatus.ACCEPTED if response is None else HTTPStatus.OK
103
- if response is not None and response.error is not None and response.error.code == JSONRPCErrorCode.METHOD_NOT_FOUND:
104
- status_code = HTTPStatus.NOT_FOUND
103
+ status_code = _http_status_for_response(response)
105
104
  return Response(
106
105
  body=body,
107
106
  status_code=status_code,
@@ -109,6 +108,12 @@ class MCPHttpTransport:
109
108
  headers=response_headers,
110
109
  )
111
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
+
112
117
  def _validate_headers(self, payload: dict[str, Any], headers: Any) -> Any:
113
118
  from modmex_lambda.event_handler import content_types
114
119
  from modmex_lambda.event_handler.response import Response
@@ -223,26 +228,35 @@ class MCPStreamingHttpTransport:
223
228
 
224
229
  def handle(self, request: Any) -> StreamingHTTPResponse:
225
230
  """Return a lazy SSE response for one MCP HTTP request."""
226
- validation = self._http._validate_headers(request.json_body, request.headers)
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)
227
243
  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),)))
244
+ return StreamingHTTPResponse(validation.status_code, MCP_JSON_CONTENT_TYPE, {}, iter((json.dumps(validation.body),)))
232
245
 
233
- payload = request.json_body
234
246
  if payload.get("method") == "tools/call":
235
247
  return self._handle_tool_call(request, payload)
236
- response = self.server.handle(payload, context=request)
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))
237
251
 
238
252
  def body() -> Iterator[str]:
239
253
  if response is not None:
240
254
  yield encode_sse(self._http._model_dict(response))
241
255
 
242
256
  return StreamingHTTPResponse(
243
- status_code=202 if response is None else 200,
257
+ status_code=_http_status_for_response(response),
244
258
  content_type=MCP_SSE_CONTENT_TYPE,
245
- headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
259
+ headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
246
260
  body=body(),
247
261
  )
248
262
 
@@ -253,11 +267,21 @@ class MCPStreamingHttpTransport:
253
267
  events: queue.Queue[tuple[str, Any]] = queue.Queue()
254
268
  cancellation_token = MCPCancellationToken()
255
269
  request.cancellation_token = cancellation_token
256
- request.progress_reporter = MCPProgressReporter(lambda value: events.put(("progress", value)))
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
+ )
257
281
 
258
282
  def run() -> None:
259
283
  try:
260
- events.put(("result", self.server.handle(payload, context=request)))
284
+ events.put(("result", asyncio.run(self.server.handle_async(payload, context=request))))
261
285
  except BaseException as exc:
262
286
  events.put(("exception", exc))
263
287
  finally:
@@ -269,7 +293,7 @@ class MCPStreamingHttpTransport:
269
293
  while True:
270
294
  kind, value = events.get()
271
295
  if kind == "progress":
272
- yield encode_sse(SSEEvent(data=value, event="progress"))
296
+ yield encode_sse(value)
273
297
  elif kind == "result":
274
298
  if value is not None:
275
299
  yield encode_sse(self._http._model_dict(value))
@@ -281,7 +305,7 @@ class MCPStreamingHttpTransport:
281
305
  return StreamingHTTPResponse(
282
306
  status_code=200,
283
307
  content_type=MCP_SSE_CONTENT_TYPE,
284
- headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
308
+ headers={"Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no"},
285
309
  body=body(),
286
310
  cancellation_token=cancellation_token,
287
311
  )
@@ -291,3 +315,15 @@ def _serialize(value: Any) -> Any:
291
315
  if hasattr(value, "model_dump"):
292
316
  return value.model_dump()
293
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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: modmex-lambda
3
- Version: 0.7.2
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
 
@@ -1367,7 +1428,7 @@ def create_order(order: Order):
1367
1428
  enforce an Origin allowlist itself. Leaving it as `None` explicitly delegates
1368
1429
  Origin validation to API Gateway, WAF, or application middleware.
1369
1430
 
1370
- ### Buffered transport boundary
1431
+ ### Transport boundary
1371
1432
 
1372
1433
  This section applies to `APIGatewayRestResolver` and
1373
1434
  `APIGatewayHttpResolver`. JSON is the normal response mode, and the MCP HTTP
@@ -1376,9 +1437,25 @@ transport can return a buffered SSE representation when the client requests
1376
1437
  response streaming or a long-lived bidirectional connection.
1377
1438
 
1378
1439
  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.
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.
1382
1459
 
1383
1460
  MCP request/response features such as pagination, `structuredContent`, MRTR
1384
1461
  result handling, resources and prompts are part of the protocol implementation
@@ -1424,7 +1501,8 @@ handler = app.handler
1424
1501
  The configured value is `module.attribute`, such as `app.handler`. For
1425
1502
  buffered deployments Serverless invokes `handler(event, context)` directly.
1426
1503
  For streaming deployments the plugin stages a temporary launcher that imports
1427
- the configured `LambdaWebAdapterHandler` and calls `handler.run()`; the
1504
+ the configured handler returned by `LambdaWebAdapterResolver.handler` and calls
1505
+ `handler.run()`; the
1428
1506
  launcher is removed after packaging. Application code never needs an
1429
1507
  `if __name__ == "__main__"` block or a permanent `run.sh` file.
1430
1508
 
@@ -1439,7 +1517,8 @@ With `streaming: false`, all three transports are supported. Function URL
1439
1517
  authorizers are limited to `aws_iam` or public access. HTTP API authorizers can
1440
1518
  be declared globally under `provider.httpApi.authorizers` and referenced by
1441
1519
  name, or declared inline on an individual MCP server using Serverless'
1442
- compatible authorizer configuration.
1520
+ compatible authorizer configuration. For `http`, authorizers are passed to the
1521
+ native REST API event compiler.
1443
1522
 
1444
1523
  The Lambda Web Adapter layer is attached only to streaming MCP functions and
1445
1524
  is selected by the function architecture (`x86_64` or `arm64`). The plugin
@@ -67,7 +67,7 @@ modmex_lambda/mcp/resource.py,sha256=X_U0om1-nsuv8WwJ_ydUrFQL3k4aRqwp502aAs7KP3o
67
67
  modmex_lambda/mcp/schema.py,sha256=TjHBV4rlavJxIrGA2g3g_PS00gXxEIw-t2uxOJtBn9Q,3300
68
68
  modmex_lambda/mcp/server.py,sha256=tdeA_X6EkcOCJzYxD9t-W9-Gv7lUMwJ_SNdA69RBA8s,18872
69
69
  modmex_lambda/mcp/tool.py,sha256=dCNxT8GzKJzsdOkWINk2kI6RSMCYIi4EI8N_iK67Hmg,7740
70
- modmex_lambda/mcp/transport.py,sha256=QFz5isnrktDL2GQdg2aNzKzz-sqIB0Y5wZpjTaw-4wA,13738
70
+ modmex_lambda/mcp/transport.py,sha256=LqyYsnRWxRtrswksh1HLYzB1iYoJP8U_nG40IqtHobg,15145
71
71
  modmex_lambda/mcp/web_adapter.py,sha256=gi8MPIGMjYEZr8ntrj1DAADyUoWcvyp_bqyUTo3vT2c,6674
72
72
  modmex_lambda/mcp/web_adapter_launcher.py,sha256=CEo_nCcYkNLifkgXFG0_rdKq6DzZcqXWbdCEFE_fcPE,981
73
73
  modmex_lambda/persistence/__init__.py,sha256=oa4FHCvitEkoagJ059jGATj6GSm-maazzf_QNi4WdQs,74
@@ -156,7 +156,7 @@ modmex_lambda/stream/utils/time.py,sha256=dnsL2xeWpa1FXm2p8y9rWXtICMBlCBkgLaJ_en
156
156
  modmex_lambda/stream/utils/uow.py,sha256=8WSPVE7AiHInkFDfBEeKOvdirY6GAgBoS7qkF1f1JVM,3207
157
157
  modmex_lambda/stream/utils/data_classes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
158
158
  modmex_lambda/stream/utils/data_classes/dynamodb.py,sha256=h_7MtUyRkvvV1r2QECrRDu7RR4Hh94SwSjc_8K2_XGM,363
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,,
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,,