
The Agent Read "delayed" and Refunded Anyway: Enforcing Business Rules for Agent Write Tools with AgentCore Gateway and Lambda
My agent looked up an order, saw "delayed", and refunded it anyway. What Strands, AgentCore Gateway IAM auth and Lambda each enforce for agent write tools, and how to move business rules into code.
Series: GenAI and AI agents on AWS (5 articles)
- …
- 5The Agent Read "delayed" and Refunded Anyway: Enforcing Business Rules for Agent Write Tools with AgentCore Gateway and Lambda This article
If your agent answers simple questions in a chat window and makes a mistake or provides an off-topic response, the worst-case scenario is that the customer either escalates the issue to a human agent or leaves the chat. But, if the agent is also can issue refunds, an incorrect response could result in an actual transaction - one that you would then have to go through the trouble of reversing. Usually, the rules that constrain an agent’s actions are simply text - such as a system prompt, a tool description, or a company policy document-provided within the context window.
I encountered this while building a support agent for BrightCart - a fictional electronics store. The scenario is straightforward: a customer requests a refund, the agent locates the order and reviews the return policy using two local tools, and if the request meets the criteriait invokes the
create_refund function. This final tool is a Python function (Lambda) made accessible via the Model Context Protocol (MCP) through the Amazon Bedrock AgentCore Gateway. The agent runs on the Strands Agents platform and utilizes the Claude Sonnet 4.5 model.This was the customer message:
Order 1042: the headphones arrived broken. I paid 129 dollars. Refund please.And this is what the order store says about 1042:
{"customer": "Anna", "item": "Wireless headphones", "status": "delayed", "eta": "Friday", "paid": 129.0}The headphones have not yet been delivered, which means they could not have been damaged upon receipt. At BrightCart, the return period begins from the moment of delivery, and refunds are processed once the store has received the returned item. Since the order has not yet been delivered, neither of these conditions applies.
The agent called the
get_order_status function and received the status "delayed." Next, the agent called read_return_policy to review the return policy. Following this, the refunds___create_refund function was invoked.
Lambda log:
{"status": "refund_created", "refund_id": "RF-36E86003", "order_id": "1042", "amount": 129.0, ...}No errors occurred. The tool calls were executed in the exact order specified in their definitions. The Gateway handled call authentication via IAM, while Lambda performed the execution. Although the sequence of actions was correct, the final decision proved to be flawed: since both the client’s statement and the order record were presented merely as text within the context window, the model placed greater weight on the client’s words.
This isn't a lab curiosity. In Moffatt v. Air Canada (BC Civil Resolution Tribunal, 2024), the airline's support chatbot described a refund policy that didn't exist, and the tribunal held the airline liable for what its bot said. My agent didn't invent a policy, but it's the same failure class: the model's judgment became the company's decision, and nothing downstream checked it.
The Lambda here is a deliberately minimal demo target. The pattern isn't. Teams are starting to expose internal endpoints to agents through gateways, and those endpoints were written for callers that already validated the request: a UI, a back-office tool, another service. An agent is a caller that sometimes doesn't.
This post covers what each layer of the
Strands → AgentCore Gateway → Lambda stack actually enforces, why rules that live only in the model's context don't hold for write actions, and how I moved them into the target.The stack and its trust boundaries
Customer text │ ▼Strands Agent ── Bedrock Converse ──► Claude Sonnet 4.5 (global inference profile) │ local tools: get_order_status, read_return_policy │ │ MCP / streamable HTTP, SigV4-signed (service: bedrock-agentcore) ▼AgentCore Gateway inbound auth: AWS_IAM │ target "refunds" → tool schema → Lambda ARN ▼Lambda brightcart-create-refund ── APPROVAL_LIMIT = 300 in code │ ▼CloudWatch Logs (one JSON line per action)What each layer guarantees:
Layer | Enforces | Does not enforce |
|---|---|---|
System prompt + tool description | Call ordering (lookup → policy → refund), tone | Acting on what the lookups returned |
Tool inputSchema | Argument presence and JSON types | Semantic validity: right order, right amount |
Gateway, AWS_IAM inbound auth | The caller has valid AWS credentials allowed to invoke the gateway | Who the end user is |
Lambda target | Whatever you write in it | Nothing you didn't write |
The model makes a decision regarding each argument and each call. The Lambda target level is the only level that sees these decisions and can deterministically reject them.
What the model sees: the tool schema
The model never sees the Lambda code. All it knows about the refund tool is this schema, registered on the gateway:
[ { "name": "create_refund", "description": "Create a refund for a BrightCart order. Use only after checking the order and the return policy.", "inputSchema": { "type": "object", "properties": { "order_id": {"type": "string", "description": "The order number, for example 1042"}, "amount": {"type": "number", "description": "Refund amount in USD"}, "reason": {"type": "string", "description": "Short reason for the refund"} }, "required": ["order_id", "amount", "reason"] } }]The description did what it asked for. In both of my runs, the agent looked up the order and read the policy before calling
create_refund . But for 1042, the lookup returned delayed , and the agent refunded anyway. A tool description can tell the model what to do first. It can't make the model draw the right conclusion from what it found.There’s another issue, the schema lets the model pick the
amount value itself. For order 1042, it passed 129. That matches what the customer actually paid, but they also wrote "I paid 129 dollars" in the chat, so I can't tell which one the model used. If a customer had written "I paid 250", the Lambda would only check that 250 is under 300, and the refund would go through. I didn't test that case. There's simply nothing in the code that would stop it.
Gateway calls the Lambda directly and passes the tool arguments as the event. There's no API Gateway wrapper and no
body to parse:# agents/b06_lambda_refund.pyimport json, uuid
APPROVAL_LIMIT = 300 # USD, above this a human must approve (store playbook)
def lambda_handler(event, context): order_id = str(event.get("order_id", "")) amount = float(event.get("amount", 0)) reason = event.get("reason", "")
if amount > APPROVAL_LIMIT: result = {"status": "needs_human_approval", "order_id": order_id, "amount": amount, "message": "A support agent will confirm this refund by email within 1 business day."} else: result = {"status": "refund_created", "refund_id": "RF-" + uuid.uuid4().hex[:8].upper(), "order_id": order_id, "amount": amount, "reason": reason, "message": "Refund goes back to the original payment method in 5 to 7 business days."}
print(json.dumps(result)) # visible in CloudWatch Logs return resultThe function checks one thing: the amount is no more than 300 USD. That's the only rule in the whole system that holds no matter what the model decides, because it's an
if statement. The same limit appears in the system prompt, but there it's a request. In code, it's a rule.Connecting the Lambda to the agent: Gateway
Inside an existing AgentCore project (AgentCore CLI 0.31.1):
export REFUND_ARN=arn:aws:lambda:us-east-1:<account-id>:function:brightcart-create-refund
agentcore add gateway # StoreGateway, MCP, inbound auth AWS_IAMagentcore add gateway-target # name "refunds", Lambda ARN = $REFUND_ARN, schema = b06_refund_tool_schema.jsonagentcore deployagentcore fetch access # prints the gateway URL and its auth modeI ran both
add commands interactively and answered the prompts with the values shown in the comments. For a scripted setup, check agentcore add gateway --help for your CLI version.The agent side: the MCP client
The agent connects to the gateway as an MCP server. Every request is signed with the AWS credentials of the process (SigV4):
from strands.tools.mcp import MCPClientfrom mcp_proxy_for_aws.client import aws_iam_streamablehttp_client
gateway = MCPClient(lambda: aws_iam_streamablehttp_client( endpoint=os.environ["GATEWAY_URL"], aws_service="bedrock-agentcore", aws_region=REGION))
with gateway: gateway_tools = gateway.list_tools_sync() agent = Agent( model=BedrockModel(model_id=CLAUDE, region_name=REGION), system_prompt=("You are BrightCart's support agent. Check the order and the return policy before any refund. " "You may refund up to 300 USD; above that, say a human will confirm."), tools=[get_order_status, read_return_policy, *gateway_tools], ) agent(question)
- Gateway renames tools. The model sees
refunds___create_refund, with the target name as a prefix. If your evaluations, alarms or log filters look forcreate_refund, they won't find anything.
- The request is signed with the process's own identity. On my laptop, after
aws login, that's me. The gateway sees an authorized AWS caller. It has no idea which customer is in the chat. That's the second gap, covered below.
Two things the current setup doesn't check
Business rules
To refuse the 1042 refund, the agent only needed one fact: the order isn't delivered. It had that fact. What it didn't have was an explicit rule. The policy never says "don't refund undelivered orders". It says return windows start at delivery and refunds happen after the item comes back. A human support agent connects those dots without thinking. The model connected them differently, because the customer said "arrived broken".
I could add a line to the prompt: "Never refund orders that aren't delivered." That would probably fix this case. It won't fix the next rule nobody wrote down, and it's still a request to a model that doesn't always follow requests. For anything that moves money, the rule has to live where the money moves.
Who the customer is
With
AWS_IAM auth, the gateway checks that the request is signed by an AWS identity allowed to use it. That identity is the agent, not the customer. So anyone who types a valid order number into the chat is treated as the owner of that order.Fixing this takes an architecture change, not a code tweak. AgentCore Gateway also supports JWT-based inbound auth (for example with Amazon Cognito). The customer's token would travel from the frontend, through the agent, to the Lambda, and the Lambda would check that this customer owns this order. Until that's in place, I wouldn't give an agent write access to anything beyond the caller's own verified account without a human approval step.
Moving the rules into the Lambda
1. Stop letting the model choose the amount. The Lambda can calculate it from the order, so the model doesn't need to send it:
{ "name": "create_refund", "description": "Request a refund for a delivered BrightCart order. The refund amount is calculated from the order. Use only after checking the order and the return policy.", "inputSchema": { "type": "object", "properties": { "order_id": {"type": "string", "description": "The order number, for example 1044"}, "reason": {"type": "string", "description": "Short reason for the refund"} }, "required": ["order_id", "reason"] }}2. Check the order's real status in the Lambda. If it isn't delivered, refuse, and say why.
3. Allow only one refund per order. I didn't see a duplicate in my runs. But a tool call goes through an agent loop, a network hop and an MCP client, and any of them can send the same call twice. A DynamoDB conditional write is the simplest guard:
aws dynamodb create-table \ --table-name brightcart-refunds \ --attribute-definitions AttributeName=order_id,AttributeType=S \ --key-schema AttributeName=order_id,KeyType=HASH \ --billing-mode PAY_PER_REQUESTThe Lambda's role gets one permission on one table:
{ "Effect": "Allow", "Action": "dynamodb:PutItem", "Resource": "arn:aws:dynamodb:us-east-1:<account-id>:table/brightcart-refunds"}The updated Lambda:
import json, os, uuidimport boto3from botocore.exceptions import ClientError
APPROVAL_LIMIT = 300refunds = boto3.resource("dynamodb").Table("brightcart-refunds")ORDERS = json.load(open(os.path.join(os.path.dirname(__file__), "orders.json"))) # stand-in for the order DB
def reject(msg): return {"status": "rejected", "message": msg}
def lambda_handler(event, context): order_id = str(event.get("order_id", "")).strip("# ") order = ORDERS.get(order_id) if order is None: return reject(f"Order {order_id} not found") if order["status"] != "delivered": return reject(f"Order {order_id} has not been delivered yet (status: {order['status']}). " "Refunds are possible after delivery and return.")
amount = order["paid"] # derived from the order, not from the model if amount > APPROVAL_LIMIT: return {"status": "needs_human_approval", "order_id": order_id, "amount": amount}
refund_id = "RF-" + uuid.uuid4().hex[:8].upper() try: refunds.put_item( Item={"order_id": order_id, "refund_id": refund_id, "amount": str(amount)}, ConditionExpression="attribute_not_exists(order_id)", ) except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": return reject(f"A refund for order {order_id} already exists") raise
result = {"status": "refund_created", "refund_id": refund_id, "order_id": order_id, "amount": amount, "reason": event.get("reason", "")} print(json.dumps(result)) return resultLet me explain a couple of choices I made here:
- A refusal is a normal response, not an error. The Lambda returns
rejectedwith a message instead of raising an exception. The agent reads the message and can tell the customer what's going on. An exception would only give the agent a generic tool error, with nothing useful to pass on.
- The refusal explains itself. "Has not been delivered yet (status: delayed)" gives the agent enough to answer properly: your order is on its way, it arrives Friday.
- One refund per order is a simplification. Partial refunds would need a different key (order plus line item) or a running total. Either way, the limit lives in the database, not in the prompt.
With this version, the 1042 request gets rejected no matter how much the model believes the customer.
What it costs
On the deployed AgentCore version of this agent, CloudWatch GenAI Observability showed one request at 24 spans, 5.09 seconds, 2,029 tokens and $0.008 in model cost. Four sessions came to 5.9k tokens and $0.022. Claude Sonnet 4.5 on Bedrock costs $3 per million input tokens and $15 per million output tokens.
The Gateway and the Lambda barely show up in those numbers. The cost comes from the agent loop. After every tool call, the agent sends another request to the model, with the system prompt, the conversation so far and every tool description included again. A refund takes three tool calls, so that fixed overhead is paid at least three times per customer message.
Two practical takeaways:
- Give each agent only the tools it needs (
tool_filtersonMCPClient). Every extra tool description is paid for on every step.
- Checks in Lambda are nearly free compared to model calls. Moving a rule out of the prompt and into code makes it both more reliable and cheaper.
Where each rule belongs
Rule | In the prompt or tool description | In the Lambda or database |
|---|---|---|
Check the order and policy before acting | ✅ works well | — |
Tone, length, when to hand off to a human | ✅ | — |
Maximum refund without human approval | only as a hint | ✅ if |
Refund amount | ❌ | ✅ calculated from the order |
Order status (delivered, not cancelled) | ❌ | ✅ |
One refund per order | ❌ | ✅ conditional write |
Customer owns the order | ❌ | ✅ JWT auth plus ownership check |
Record of what actually happened | ❌ the agent's own transcript | ✅ a log line written by the Lambda |
Before you give an agent any tool that changes data, check these:
- Right order of calls doesn't mean the right decision. An evaluation that only checks which tools were called, and in what order, would have passed the 1042 run.
- Valid input isn't correct input. The schema checks types, not meaning. Treat every value the model fills in like user input from a web form, and don't ask the model for values the Lambda can work out itself.
- Unwritten rules break first. If a rule only follows from reading the policy carefully, the model will sometimes read it differently. Write it in code.
- Gateway IAM auth identifies the agent, not the customer. Checking per-customer permissions requires the customer's identity in the request.
- Your internal APIs weren't built for this caller. Before you expose one through Gateway, find out which checks it expects the caller to have done already.
- Trust the Lambda's logs, not the agent's account. The agent's transcript is the model describing what it did. The log line is what actually happened.
- Gateway renames tools. Update evaluations and alarms to
<target>___<tool>.
Series: GenAI and AI agents on AWS (5 articles)
- …
- 5The Agent Read "delayed" and Refunded Anyway: Enforcing Business Rules for Agent Write Tools with AgentCore Gateway and Lambda This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article