View a markdown version of this page

示例 - Amazon Bedrock AgentCore

示例

以下示例显示了一个可以同时处理请求和响应拦截器类型的 Python Lambda 函数。REQUEST 拦截器记录 MCP 方法并原封不动地传递请求,而 RESPONSE 拦截器则原封不动地传递响应。

Pass-through 拦截器

此示例演示了一个简单的拦截器,该拦截器记录请求拦截器的 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 函数配置为请求和响应拦截器。当配置为请求拦截器时,它将记录来自传入请求的 MCP 方法。当配置为 RESPONSE 拦截器时,它只会原封不动地传递响应。两种拦截器类型均不加修改地返回原始数据,这使其成为 “直通” 拦截器。