Controlling tool use for Runtime-hosted agents with AgentCore Policy

The AgentCore Policy component allows developers to control what agents can do with tools exposed by AgentCore Gateway. Depending on the Gateway auth type, policies can take different shapes.

Instructor, cloud consultant, software developer

1. The scenario

Suppose we have an agent hosted on Bedrock  AgentCore Runtime . The agent has access to a tool exposed by  AgentCore Gateway .
The agentic application has end users. When the agent acts on users' behalf, I want to control what agents can do for each user.
The sample application is a shopping assistant that helps users place orders.  testuser1  can add any items and submit orders with any total value.  testuser2  can place an order only if its total value is less than $100.
This post compares two authorization patterns and discusses their advantages and disadvantages.

2. Architecture overview

Every component of the shopping assistant application runs on Bedrock AgentCore.
Shopping assistant application

The app has two users,  testuser1  and  testuser2 . A  Cognito user pool  serves as the identity provider, and users authenticate against it.
When users submit a prompt, the UI calls AgentCore Runtime's  /invocations  endpoint with the access token. The agent is configured with the JWT inbound auth type, and  AgentCore Identity  verifies that the request is authorized.
The agent implements an MCP client using the  Strands Agents  SDK and calls AgentCore Gateway, a managed MCP server.
Here, I discuss two versions of gateway authorization.
In Version A, AgentCore Gateway is configured with the JWT inbound auth type, where the same Cognito user pool is the identity provider. The same access token that was used with Runtime is verified here (token forwarding).
But why pass tokens between Runtime and Gateway when AgentCore Gateway is an AWS service?  IAM  authorizes requests to AWS APIs, so Version B discusses the same flow but this time AgentCore Gateway is configured with the IAM auth type.
The next AgentCore component is Policy, which dynamically intercepts each request and evaluates them. We can write policies in  Cedar policy language  to control what an agent can and can't do. As you'll see below, the two versions require somewhat different policies.
For simplicity, the app has only one tool hosted on a  Lambda Event Function  (the new name for the traditional/original Lambda functions). When the LLM decides that the agent should call the order placement tool, AgentCore Gateway will invoke the Lambda target.

3. Version A - JWT auth

First, let's look at version A, where AgentCore Gateway is configured with the JWT inbound auth type. In this case, Runtime and Gateway verify the same JWT.

3.1. Agent and gateway configuration

The agent's code is pretty simple. We need to send the access token in the Authorization header with each request to the Gateway.
In Strands, we can do something like this:
mcp_client = MCPClient(
url=gateway_url, headers={"Authorization": f"Bearer {token}"}
)

agent = Agent(
model=model,
system_prompt=f"{SYSTEM_PROMPT}",
tools=[mcp_client],
)
The Gateway's configuration should set  "authorizerType"  to  "CUSTOM_JWT"  and specify the app client ID(s) for token verification.

3.2. Cedar policy

Next, we write the Cedar policy. Again, no restrictions apply to  testuser1 , but  testuser2  can only place orders if their total value is less than $100.
Here, the agent makes tool calls for both users, but we want to control the agent's behaviour when it acts on each user's behalf.
For this simple, two-user scenario, the Cedar policy can look like this:
permit(
principal is AgentCore::OAuthUser,
action == AgentCore::Action::"shopping___place_order",
resource == AgentCore::Gateway::"<SHOPPING_GATEWAY_ARN>"
)
when {
principal.hasTag("username") &&
(
principal.getTag("username") == "testuser1" ||
(
principal.getTag("username") == "testuser2" &&
context.input.total_amount.lessThan(decimal("100.00"))
)
)
};

3.3. Why does this policy work?

The  principal  element shows that the user authenticated against an OAuth-compatible authorization server.
The access token includes the  username  claim:
{
"sub": "12345678-90ab-cdef-1234-567890abcdef",
"iss": "https://cognito-idp.REGION.amazonaws.com/USER_POOL_ID",
"token_use": "access",
"scope": "SCOPES HERE",
"username": "testuser1", // <-- HERE
// other claims
}
The Cedar policy needs the username, so we must transfer it from the access token to the Cedar authorization request.
AgentCore Gateway extracts the claims from the token and stores them as tags in an object called the entity store. It looks like this:
{
"uid": {
"type": "AgentCore::OAuthUser",
// the "sub" claim (user ID) from the access token
"id": "12345678-90ab-cdef-1234-567890abcdef"
},
"tags": {
"username": "testuser1",
"iss": "https://cognito-idp.REGION.amazonaws.com/USER_POOL_ID",
// other tags
},
"attrs": {
// identity information
}
}
AgentCore Policy can now refer to  username  as a tag. So, access to the  shopping___place_order  tool is allowed to  testuser2 , but only if the  total_amount  is less than $100.
This way, the prompt  I want to order 2 books for 83 USD each  succeeds for  testuser1 , but AgentCore Policy rejects it for  testuser2 .

4. Version B - IAM auth

Let's look at the second option when AgentCore Gateway is configured with the IAM auth type. This version requires minor changes to how the agent calls AgentCore Gateway and how the policy is written.

4.1. Sign the request

Every AWS API call must be signed with the  Signature V4  signing protocol. Tools like the AWS Console, the  AWS CLI , and the  SDKs  automatically sign the requests, but agents, similar to any other custom code, don't.
We can use packages to sign requests. The  MCP Proxy for AWS  package in Python is a popular one:
from mcp_proxy_for_aws.client import aws_iam_streamablehttp_client

mcp_client = MCPClient(
lambda: aws_iam_streamablehttp_client(
endpoint=gateway_url,
aws_service="bedrock-agentcore",
aws_region=REGION,
)
)
No access tokens should be sent to AgentCore Gateway here because it's configured with IAM auth:
"authorizerType": "AWS_IAM"

4.2. Injecting the username

The agent doesn’t forward the token to the Gateway. But then how can AgentCore Policy access the username?
Tool parameters, like  product_name  or  quantity , will become part of the Cedar authorization request. Policies read these parameters from the  context.input  object.
So, if we could inject  username  into the MCP tool's arguments, we could write a Cedar policy that targets specific users.
Good news: Strands  hooks  make this possible. The  BeforeToolCallEvent  hook can modify the arguments:
class InjectUsername(HookProvider):
def register_hooks(self, registry: HookRegistry, **kwargs) -> None:
registry.add_callback(BeforeToolCallEvent, self._inject)

def _inject(self, event: BeforeToolCallEvent) -> None:
event.tool_use["input"]["username"] =
event.invocation_state["username"]
Then, add it to the agent:
agent = Agent(
model=model,
system_prompt=f"{SYSTEM_PROMPT}",
tools=[mcp_client],
hooks=[InjectUsername()],
)
Finally, add the user's username, which was extracted from the token, when you call the agent:
agent(prompt="PROMPT", username=username)
It requires a bit more work on the agent's side than the JWT auth solution.

4.3. Cedar policy

We can now refer to specific users in the AgentCore policy:
permit(
principal,
action == AgentCore::Action::"shopping___place_order",
resource == AgentCore::Gateway::"<GATEWAY_ARN>"
)
when {
context.input has username &&
(
context.input.username == "testuser1" ||
(
context.input.username == "testuser2" &&
context.input.total_amount.lessThan(decimal("100.00"))
)
)
};
The principal type is  AgentCore::IamEntity , which is the caller's (Runtime's) IAM role ARN. It doesn't carry any end user information.
But  context.input  does, since the agent injects it there, and AgentCore Policy can access it. Every other policy element is the same as with the JWT scenario.

5. Considerations

Let’s discuss a few considerations along with some advantages and disadvantages of both versions.

5.1. Scaling

The policies shown above don't scale. If you have 500 users, you probably don't want to name them all in the policy.
To solve this problem, you can add users to Cognito groups and refer to the group in the policy as  principal.getTag("cognito:groups") .

5.2. JWT forwarding concerns

The JWT solution is plain token forwarding, which is usually not recommended, especially in multi-tenant applications. Multi-tenant applications require audience token claims specific to the tenant. Token forwarding doesn't change the audience between Runtime and Gateway, so it introduces the confused deputy problem. Since this example describes a single-tenant application (one authorization server, one gateway), token forwarding can be sufficient here.
Also, AgentCore Policy, as an exteral entity, verifies user identity and decides whether the tool call is allowed, and if so, how.
Second, AgentCore Policy reads this information from the token, and not what the agent provided.
Third, if a policy exists, the default implicit deny logic applies. AgentCore Policy denies every request with a made-up user who's not explicitly in the policy.
Nevertheless, this solution requires more hardening. The gateway authorizer can check for scopes in the token, or you can  exchange the token  between Runtime and Gateway.

5.3. IAM is great but...

In general, IAM authorization is robust and secure, and it eliminates token-forwarding problem.
But it introduces a new one.
With the IAM auth type, AgentCore Gateway sees only the Runtime's role as the principal, and the  username  becomes a tool argument (the hook writes it there). Gateway trusts the agent on user identity, so a compromised agent could send requests on  testuser1 's behalf (confused deputy) to place large orders. Common sense developer practices (input validation, least privilege, reliable dependencies) can mitigate this risk.
AgentCore Policy can also help by limiting what agents can do. So instead of letting  testuser1  place no-limit orders, we can set a maximum amount for every user and require human approval for high-value orders.

6. Conclusion

We can use AgentCore Policy to fine-grain control agents' access to tools exposed by AgentCore Gateway. Policies also act as independent, external components that control what an agent can or can’t do.
Both solutions has advantages and disadvantages.
Using the JWT auth type with the same token can be sufficient for single-tenant applications, but it may not be secure enough in general. It’s relatively simple to implement in suitable applications.
The IAM auth type at AgentCore Gateway assumes that the gateway trusts the agent. Malicious code can compromise the agent and send unwanted requests to the tool impersonating elevated users.

7. Further reading

 The confused deputy problem  - Description of the issue
 Supported authentication patterns  - AgentCore Identity authentication
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article