Skip to content

Bundling assets for agentcore.CfnRuntime gives HandlerInternalFailure

0

I created an AgentCore Runtime with my assets in a .zip in a regular s3 bucket and that worked fine but it's a pain to redeploy, so I want to make it part of my stack. To do this, I built the bundle using docker. This creates a 16MB zip file that contains main.py and directories for all the dependencies (for example boto3) - in other words it created a zip file that makes sense to me.

The problem is when I go to deploy it I get this error:

SiriLlmStack: creating CloudFormation changeset...
4:09:43 PM | CREATE_FAILED        | AWS::BedrockAgentCore::Runtime | SiriRuntime
Resource handler returned message: "Internal error occurred in the handler." (RequestToken: 6964e398-7c93-8ffd-9dc2-52c5ebb4ab38, HandlerErrorCode: Handle
rInternalFailure)

❌  SiriLlmStack failed: ToolkitError: The stack named SiriLlmStack failed creation, it may need to be manually deleted from the AWS console: ROLLBACK_COMPLETE: Resource handler returned message: "Internal error occurred in the handler." (RequestToken: 6964e398-7c93-8ffd-9dc2-52c5ebb4ab38, HandlerErrorCode: HandlerInternalFailure)
error Command failed with exit code 1.

and I'm not sure how to debug this. I can't find any other logs (cloudwatch, cloudformation) that tell me what the problem could be.

Should this approach work?

        const runtimeCodeAsset = new s3assets.Asset(this, 'AgentRuntimeAsset', {
            path: path.join(__dirname, '../agent'), // folder with main.py + requirements.txt
            bundling: {
                image: DockerImage.fromRegistry('python:3.11-slim'), // <-- NOT the Lambda image
                command: [
                    'bash',
                    '-c',
                    [
                        'pip install -r requirements.txt -t /asset-output',
                        'cp -r . /asset-output',
                    ].join(' && '),
                ],
            },
        });
        runtimeCodeAsset.grantRead(runtimeRole);


        const runtime = new agentcore.CfnRuntime(this, 'SiriRuntime', {
            agentRuntimeName: 'siri_llm_runtime',
            description: 'Siri-like orchestrator agent running on AgentCore Runtime',
            roleArn: runtimeRole.roleArn,

            agentRuntimeArtifact: {
                codeConfiguration: {
                    code: {
                        s3: {
                            bucket: runtimeCodeAsset.bucket.bucketName,
                            prefix: runtimeCodeAsset.s3ObjectKey,
                        },
                    },
                    runtime: 'PYTHON_3_11',                         // or whichever you’re using
                    // entryPoint is basically ["module", "callable"] for your code
                    // e.g. main.py with app = BedrockAgentCoreApp(...)
                    entryPoint: ['main.py'],
                },
            },

            // How clients talk to your runtime
            protocolConfiguration: 'HTTP',  // clients call InvokeAgentRuntime -> your HTTP server in the container :contentReference[oaicite:6]{index=6}

            // Simplest networking: PUBLIC (no VPC). Switch to VPC later if you need internal services. :contentReference[oaicite:7]{index=7}
            networkConfiguration: {
                networkMode: 'PUBLIC',
            },

            // What your agent code needs to know at startup
            environmentVariables: {
                FOUNDATION_MODEL_ID: modelId,
                MEMORY_ARN: memory.attrMemoryArn,
                GATEWAY_ARN: gateway.attrGatewayArn,
                // You’ll probably also pass a Gateway MCP URL / target name here for your MCP client
                // e.g. GATEWAY_MCP_URL, TOOL_TARGET_NAME, etc.
            },
        });
2 Answers
0
Accepted Answer

Hello there,

I was able to successfully deploy an AgentCore Runtime using the exact same approach you described. Your CDK code structure looks correct and should work.

However, I was able to reproduce the same "Internal error occurred in the handler" error you're experiencing by introducing invalid Python syntax in my “main.py “file:

This caused the same HandlerInternalFailure

def handler(event, context # <-- Missing closing parenthesis invalid_syntax_here!!! return { 'statusCode': 200, 'body': json.dumps('Hello from AgentCore Runtime') }

When I deployed this broken code, I got the identical error:

Resource handler returned message: "Internal error occurred in the handler." (RequestToken: 000, HandlerErrorCode: HandlerInternalFailure)

After fixing the Python syntax errors, the deployment succeeded without issues.

Recommendation:
 Check your Python code for syntax errors, missing imports, or runtime issues. The BedrockAgentCore service validates your code during deployment, and any Python syntax errors will cause this internal handler failure.

Common issues to check:

  1. Missing closing parentheses/brackets

  2. Invalid Python syntax

  3. Missing required imports

  4. Runtime exceptions in your handler code

Validate your Python code - Run “ python -m py_compile main.py “ locally to check for syntax errors

Test your handler function - Ensure it can be imported and executed without errors

Check your entry point - Verify entryPoint: ['main.py'] matches your actual file structure

If you continue experiencing issues after validating your Python code, please open a support case where we will have more visibility and will be able to assist you better.

AWS
SUPPORT ENGINEER

answered a year ago

  • Thanks, that helped a lot. I had multiple things wrong. The worst of them was not deploying a cpython with a version that matched the runtime version - that causes it to just immediately bomb out.

0

The issue you're experiencing with the HandlerInternalFailure when deploying your AgentCore Runtime is likely related to how you're providing the code artifact to the CfnRuntime resource.

For Amazon Bedrock AgentCore Runtime direct code deployment, there are a few key requirements and limitations to consider:

  1. The code deployment package should be a zip file containing your Python code and dependencies.

  2. When specifying the S3 location in the agentRuntimeArtifact.codeConfiguration.code.s3 property, you need to provide:

  • bucket: The S3 bucket name
  • key: The name of the zip file (not prefix)

In your current implementation, you're using prefix: runtimeCodeAsset.s3ObjectKey which might be causing the issue. The AgentCore Runtime expects a key pointing directly to a zip file, not a prefix.

Also, there's a size limitation to consider. While the exact limit for AgentCore Runtime isn't explicitly stated in the provided information, deployment packages for similar serverless services typically have size constraints (for example, Lambda has a 250 MB unzipped size limit).

Try modifying your code to ensure the asset is properly zipped and referenced correctly:

const runtimeCodeAsset = new s3assets.Asset(this, 'AgentRuntimeAsset', {
path: path.join(__dirname, '../agent'),
bundling: {
image: DockerImage.fromRegistry('python:3.11-slim'),
command: [
'bash',
'-c',
[
'pip install -r requirements.txt -t /tmp/python',
'cp -r . /tmp/python',
'cd /tmp/python',
'zip -r /asset-output/deployment.zip .'
].join(' && '),
],
},
});

// Then in your CfnRuntime configuration:
agentRuntimeArtifact: {
codeConfiguration: {
code: {
s3: {
bucket: runtimeCodeAsset.bucket.bucketName,
key: runtimeCodeAsset.s3ObjectKey,
},
},
runtime: 'PYTHON_3_11',
entryPoint: ['main.py'],
},
},

This approach should create a proper zip file containing your code and dependencies, which is what AgentCore Runtime expects for direct code deployment.

If you continue to experience issues, you might want to try the manual approach first (uploading the zip to S3 and referencing it) to confirm that your code package works correctly with AgentCore Runtime before integrating it into your CDK stack.
Sources
Iterate faster with Amazon Bedrock AgentCore Runtime direct code deployment | Artificial Intelligence
Get started with Amazon Bedrock AgentCore Runtime direct code deployment - Amazon Bedrock AgentCore
Unzipped size must be smaller than 262144000 bytes | AWS re:Post

answered a year ago

  • I think this bot response might misunderstand CDK’s default bundling behavior. The default bundling.outputType is BundlingOutput.AUTO_DISCOVER. That means: if /asset-output contains a single .zip or .jar file, CDK uploads that archive as-is; otherwise, it zips the contents of /asset-output itself and uploads that zip. In other words, you don’t have to create a zip inside /asset-output unless you specifically want to control the archive layout.

    Also, the AgentCore docs for direct code deployment (Step 5, “Custom zip + boto3”) show the s3 shape using a prefix that includes the full path and filename (e.g. "{agent_name}/deployment_package.zip"), not a key field. So the prefix vs key distinction in this answer doesn’t match the public AgentCore documentation.

    I have to give the bot 3/10 stars for this response, and it only deserves that because one of the references was useful. I still have not resolved the issue.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.