範例
下列範例顯示 Python Lambda 函數,可同時處理 REQUEST 和 RESPONSE 攔截器類型。REQUEST 攔截器會記錄 MCP 方法並傳遞請求不變,而 RESPONSE 攔截器則會傳遞回應不變。
傳遞攔截器
此範例示範一個簡單的攔截器,記錄 REQUEST 攔截器的 MCP 方法,並透過不變的方式傳遞所有請求和回應:
import json import logging # Configure logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): """ Lambda function that handles both REQUEST and RESPONSE interceptor types. For REQUEST interceptors: logs the MCP method and passes request through unchanged For RESPONSE interceptors: passes response through unchanged """ # Extract the MCP data from the event mcp_data = event.get('mcp', {}) # Check if this is a REQUEST or RESPONSE interceptor based on presence of gatewayResponse if 'gatewayResponse' in mcp_data and mcp_data['gatewayResponse'] != None: # This is a RESPONSE interceptor logger.info("Processing RESPONSE interceptor - passing through unchanged") # Pass through the original request and response unchanged response = { "interceptorOutputVersion": "1.0", "mcp": { "transformedGatewayResponse": { "body": mcp_data.get('gatewayResponse', {}).get('body', {}), "statusCode": mcp_data.get('gatewayResponse', {}).get('statusCode', 200) } } } else: # This is a REQUEST interceptor gateway_request = mcp_data.get('gatewayRequest', {}) request_body = gateway_request.get('body', {}) mcp_method = request_body.get('method', 'unknown') # Log the MCP method logger.info(f"Processing REQUEST interceptor - MCP method: {mcp_method}") # Pass through the original request unchanged response = { "interceptorOutputVersion": "1.0", "mcp": { "transformedGatewayRequest": { "body": request_body, } } } return response
此 Lambda 函數可以同時設定為 REQUEST 和 RESPONSE 攔截器。當設定為 REQUEST 攔截器時,它會記錄來自傳入請求的 MCP 方法。設定為 RESPONSE 攔截器時,只會傳遞未變更的回應。這兩種攔截器類型都會在不修改的情況下傳回原始資料,使其成為「傳遞」攔截器。