Copy-Paste AI Safety: 4 Guardrails Every Developer Needs Before Giving an Agent Real Tools
Every AI agent demo shows an LLM calling live tools over MCP or Function Calling. Almost none show what stops the agent from executing a destructive call twice, looping on an untrusted log line, or acting during a partia
Every AI agent demo shows an LLM calling live tools over MCP or Function Calling. Almost none show what stops the agent from executing a destructive call twice, looping on an untrusted log line, or acting during a partial outage.
System prompts and LLM guardrails help, but they are probabilistic. If a model misreads degraded telemetryβor gets tripped by prompt injection inside logsβonly deterministic code between the model and your AWS account will save production.
Here are the 4 copy-paste guardrails we keep in front of every real tool call across BlastGate and our AWS agent stacks.
1. Strip Execution IAM Permissions From the Agent Role
Start with IAM so the answer to "What if the agent completely goes rogue?" becomes boring:
- Give the agent runtime zero
ecs:StopTask,ec2:TerminateInstances, ordynamodb:DeleteItempermissions. - Expose only two gateway paths: read-only diagnostics and structured proposal.
- Pair IAM with a default-deny Cedar policy on your gateway perimeter so the model cannot invent parameters or call unintended actions:
permit (
principal == AgentCore::IamEntity::"arn:aws:iam::123456789012:role/agent-harness-role",
action in [
AgentCore::Action::"broker___propose_worker_replacement",
AgentCore::Action::"propose_worker_replacement"
],
resource == AgentCore::Gateway::"arn:aws:bedrock-agentcore:us-east-1:123456789012:gateway/ops-gateway"
)
when {
context.action_id == "REPLACE_UNHEALTHY_ECS_WORKER"
};
Because Cedar is default-deny, any action outside that explicit context.action_id is blocked at the gateway before model inference even triggers downstream compute. (In our adversarial harness evaluations, 3/8 blocked runs never even reached downstream execution, with zero unauthorized mutations.)
2. Atomic Cooldowns & Idempotency Locks (Fail Closed)
When SQS, EventBridge, or an agent ReAct loop retries after a timeout, a blind script executes the same side effect twice. Put an atomic conditional DynamoDB lock in front of every mutating tool:
import time
from botocore.exceptions import ClientError
def acquire_cooldown_lock(ddb, table_name: str, lock_key: str, cooldown_sec: int = 600) -> bool:
now = int(time.time())
try:
ddb.put_item(
TableName=table_name,
Item={
"lock_id": {"S": lock_key},
"expires_at": {"N": str(now + cooldown_sec)},
},
ConditionExpression="attribute_not_exists(lock_id)",
)
return True
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False # Cooldown active or duplicate retry -> fail closed
raise
Two hard rules make this reliable:
-
Never let the LLM override cooldowns. In BlastGate (
Rule R4), cluster cooldown (600s) lives in DynamoDB, completely outside model reasoning. -
Always attach a TTL (
expires_at) so crashed runs cannot wedge your lock table permanently.
3. Pre-Mutation Audit Gates (Not Just Post-Hoc Logs)
Most builders log actions after the API succeeds. Look at the bug that hides there:
- If
StopTaskorcharge_cardsucceeds, and then your post-execution audit write hits a transient DynamoDB error, raising a hard failure tells callers the action failedβinviting blind retries against the next live resource.
Fix the ordering (Rule R6 in BlastGate):
-
Write the structured audit record before mutation using
ConditionExpression="attribute_not_exists(event_id)"(if the pre-audit write fails, abort cleanlyβzero mutation). - Execute the single bounded mutation.
- If the post-execution audit update hits a warning, keep the warning visible in telemetry without falsely reporting the mutation as denied.
4. Simple Quorum & Blast-Radius Math Before Mutating
Even a valid single action becomes dangerous during a fleet-wide degradation. Before executing any restart, scale-down, or failover, have your deterministic broker verify live inventory independently of whatever the LLM claimed:
def passes_quorum_guard(healthy_after: int, total_desired: int) -> bool:
if total_desired <= 0:
return False
unavailable_pct = ((total_desired - healthy_after) / total_desired) * 100.0
return healthy_after >= 4 and unavailable_pct <= 20.0
If siblings are already missing or degraded, the broker returns DENY immediatelyβturning a potential cascading outage into a safe no-op.
TL;DR Checklist Before Shipping Tool-Calling Agents
- Zero destructive IAM on the agent role β agent proposes, broker executes.
-
Default-deny Gateway rules β bind allowed actions strictly (
context.action_id). - Atomic DynamoDB cooldowns + TTL β kill burst loops and retries deterministically.
- Pre-mutation audit + quorum floor β never trade fleet stability or audit integrity for speed.
Explore the full architecture, Cedar rules, and adversarial trace audit at BlastGate.
Question for fellow builders: Which safety layer do you add first when wiring an LLM to AWS tools β scoped IAM, Gateway policies, or DynamoDB locks? Let's compare setups below!
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.