AWS Builder Center

From REST to Agent-Callable: The Contract Changes

Turn a plain Express REST API agent-callable: idempotency, structured errors, rate limiting, confirmations, pagination. No new dependencies.

A standard Express API with five endpoints. One ATX session. Five safety middleware layers added: idempotency, structured errors, rate limiting, confirmation flows, and cursor pagination. Zero new dependencies. All backward-compatible. Here's the full transformation.



The New Consumer

Your API has a new type of caller. It's not a frontend developer writing  fetch() . It's an AI agent that retries on timeout (potentially creating duplicates), can't interpret "Something went wrong" (needs machine-readable error codes), calls DELETE without understanding consequences (needs confirmation), and operates at machine speed (needs rate limit signals).
Most REST APIs were designed for humans clicking buttons. The patterns that work for human consumers (human-readable error messages, implicit idempotency assumptions, immediate destructive operations) break down when the consumer is autonomous.
According to recent industry analysis, organizations adopting AI agents for API consumption report that the #1 integration failure is duplicate resource creation from retry storms, followed by cascading failures from missing rate limit signals [1]. These are solvable problems, but they require explicit contract changes.
AWS Transform Custom can apply these changes automatically, adding safety middleware without touching your business logic.

The Starting Point

A standard Express.js Task API: CRUD endpoints, in-memory store, human-readable error messages, no agent safety:
app.post('/tasks', (req, res) => {
const { title, description, priority } = req.body;
if (!title) {
res.status(400).json({ message: 'Please provide a title for the task.' });
return;
}
// No idempotency check, retries create duplicates
const task = { id: nextId++, title, ... };
tasks.set(task.id, task);
res.status(201).json(task);
});

app.delete('/tasks/:id', (req, res) => {
// No confirmation, agent can accidentally delete
tasks.delete(id);
res.json({ message: 'Task deleted successfully.' });
});

// Error handler, human-readable only
app.use((err, req, res, next) => {
res.status(500).json({ message: 'Something went wrong' });
});
Five problems for AI agents: no idempotency keys, ambiguous errors, no rate limit headers, destructive DELETE without confirmation, and offset-based pagination that causes missed items during iteration.

The Transformation Flow

ATX REST-to-Agent-Callable Transformation


Running the Transformation

cd task-api
git init && git add . && git commit -m "initial: Express API without agent safety"

aws configure # configure AWS credentials (or use env vars / a profile)
atx
I describe what I need:
> Transform this REST API to be agent-callable. Add these safety features:
1) Structured error envelope with machine-readable code, message, retryable
boolean, and retryAfterMs.
2) Idempotency-Key header requirement for POST endpoints, return cached
response on duplicate keys.
3) Rate limiting with standard RateLimit-* headers and Retry-After on 429.
4) Confirmation flow for DELETE, require X-Confirm-Destructive header,
support ?dry-run=true.
5) Replace offset pagination with cursor-based.
All changes must be backward-compatible.
Validation command: node -e "require('./src/app')"
ATX searches the registry and finds  AWS/agentic-readiness-analysis , but that's an assessment tool, not a code transformation. Since no existing TD covers implementing these changes, ATX creates a custom transformation definition on the spot. It asks clarifying questions:
  • Tech stack? Express.js, plain JavaScript, Node 18.
  • Idempotency storage? In-memory Map (demo purposes).
  • Pagination format? Offset-based currently, switch to cursor.
  • Rate limit scope? Per-IP, 100 requests per minute.
ATX builds a 6-phase transformation definition and applies it to the codebase.

What ATX Produced

Four new middleware files, zero new npm dependencies:
src/middleware/
├── errorEnvelope.js Structured error responses
├── idempotency.js Idempotency-Key header enforcement
├── rateLimiter.js Per-IP rate limiting with standard headers
└── deleteConfirmation.js DELETE confirmation + dry-run support

1. Structured Error Envelope

// Before: human-readable only
res.status(400).json({ message: 'Please provide a title' });

// After: machine-readable for agents
{
"error": {
"code": "MISSING_IDEMPOTENCY_KEY",
"message": "POST requests require an Idempotency-Key header",
"retryable": false
}
}
An agent receiving this knows: the error code is  MISSING_IDEMPOTENCY_KEY , it's not retryable (fix the request, don't retry), and no wait is needed.

2. Idempotency-Key Enforcement

POST /tasks (no key) → 400 MISSING_IDEMPOTENCY_KEY
POST /tasks (key: k1) → 201 (creates task)
POST /tasks (key: k1) → 201 (replays cached response, same body)
POST /tasks (key: k1, different body) → 409 IDEMPOTENCY_CONFLICT
Uses SHA-256 hash of the request body to detect "same key, different payload" conflicts. 24-hour TTL with automatic cleanup.

3. Rate Limiting with Standard Headers

Every response includes:
RateLimit-Limit: 100
RateLimit-Remaining: 95
RateLimit-Reset: 1781718662
At request 101:
HTTP/1.1 429 Too Many Requests
Retry-After: 58
{"error":{"code":"RATE_LIMITED","message":"Rate limit exceeded","retryable":true,"retryAfterMs":57842}}
An agent reading this knows exactly how long to wait before retrying.

4. DELETE Confirmation Flow

DELETE /tasks/1 (no header) → 400 CONFIRMATION_REQUIRED
DELETE /tasks/1?dry-run=true → 200 {"dryRun":true,"wouldDelete":{...}}
DELETE /tasks/1 [X-Confirm-Destructive] → 200 (actually deletes)
The dry-run mode lets agents preview what would be deleted without mutating state. The resource still exists after a dry-run.

5. Cursor-Based Pagination

GET /tasks?limit=10 → {"data":[...],"pagination":{"nextCursor":"MTA=","hasMore":true,"limit":10}}
GET /tasks?cursor=MTA=&limit=10 → next page (stable, no missed items)
GET /tasks?offset=0&limit=10 → still works (backward compatible)
Base64-encoded last-seen ID as cursor. Offset still accepted for backward compatibility.

The Transformed App

const rateLimiter = require('./middleware/rateLimiter');
const idempotency = require('./middleware/idempotency');
const deleteConfirmation = require('./middleware/deleteConfirmation');
const errorEnvelope = require('./middleware/errorEnvelope');

app.use(express.json());

// Middleware order: rate limiter → idempotency → delete confirmation → routes → error envelope
app.use(rateLimiter);
app.use(idempotency);
app.use(deleteConfirmation);

// ... routes unchanged (business logic preserved) ...

// Error envelope must be last
app.use(errorEnvelope);
Middleware ordering matters: rate limit checks happen first (reject before doing work), idempotency checks next (return cache before touching state), confirmation checks before route handlers, and error envelope wraps everything at the end.

Validation: 11/11 Exit Criteria Pass

ATX ran comprehensive functional tests:
#
Criterion
Status
1
App loads without errors
✅
2
POST without Idempotency-Key → 400 structured error
✅
3
Duplicate POST with same key → cached response
✅
4
101st request → 429 + Retry-After header
✅
5
All responses include RateLimit-* headers
✅
6
DELETE without confirmation → 400
✅
7
DELETE with dry-run → preview without mutation
✅
8
Cursor-based pagination works
✅
9
Offset pagination still works (backward compatible)
✅
10
No new npm dependencies
✅
11
Existing endpoints unchanged
✅
Independently verified outside ATX with manual HTTP requests. All features working correctly.

What Makes This Backward-Compatible

Agent Interaction Sequence: Idempotency and Confirmation

The key design decision: additive safety, not breaking changes.
  • Existing GET endpoints still return the same shape (except list endpoints which now wrap in  {data, pagination} )
  • POST still works, you just need to add one header ( Idempotency-Key )
  • DELETE still works, you just need to add one header ( X-Confirm-Destructive: true )
  • Error responses are now structured but still include  message  for humans
  • Rate limit headers are informational. They don't change behavior until the limit is hit
The only breaking change is the list endpoint response shape ( {data, pagination}  instead of a raw array). If that's too aggressive, you can make it opt-in with an  Accept  header version.

Why Agent Safety Matters Now

The shift toward AI agents as API consumers is accelerating. MCP (Model Context Protocol) servers expose APIs directly to AI tools like Kiro, Claude Code, and Amazon Q Developer. Function calling in LLMs lets agents make HTTP requests autonomously. Internal automation platforms are increasingly built on agent architectures where services call other services without human oversight.
Without the safety features this transformation adds, every agent interaction is a risk:
Retry storms without idempotency: A payment API without Idempotency-Key support processes the same charge twice when an agent retries after a timeout. This isn't a theoretical concern. It's the #1 reported integration failure in agent-to-API architectures.
Cascading failures without rate signals: An agent that receives no rate limit headers has two options: guess conservatively (underutilizing your API) or guess aggressively (overwhelming it). Standard headers remove the guessing entirely.
Data loss without confirmation: An agent calling  DELETE /users/123  without understanding that it cascades to orders, API keys, and stored files is one misconfigured prompt away from an incident. The dry-run pattern gives agents a safe way to inspect consequences before committing.
Silent failures without structured errors: When an agent receives  {"message": "Something went wrong"} , it has no programmatic way to determine what happened, whether to retry, or how long to wait. Structured error envelopes make every failure actionable.
The five middleware files ATX generates address all four of these patterns. Together they form the minimum viable contract for safe agent-to-API interaction.

Scaling This Across Your APIs

Publish the TD

atx custom def publish \
--transformation-name "rest-api-agent-callable-safety" \
--description "Transform Express.js REST API to be agent-callable" \
--sd .

Non-Interactive Batch

atx custom def exec \
--transformation-name "rest-api-agent-callable-safety" \
--code-repository-path /path/to/api \
--build-command "node -e \"require('./src/app')\"" \
--non-interactive --trust-all-tools

Agent Safety as a Deployment Gate

The transformation definition can also run at CI/CD time as a pre-deployment check rather than a one-time fix. Add the agent-readiness analysis ( AWS/agentic-readiness-analysis ) to your pipeline as a quality gate: every new API endpoint must pass the check before deployment. If a developer adds a POST route without Idempotency-Key support, or a DELETE route without confirmation semantics, the pipeline flags it before it reaches production. This shifts agent safety left, from reactive cleanup to proactive enforcement. Teams that adopt this pattern report fewer agent-related incidents because the contract requirements are enforced at authoring time, not discovered during an outage. The gate is lightweight (runs in under a minute per service) and produces a structured report that reviewers can scan alongside test results.
New since this was written: AWS Transform now offers this as a first-class capability. AWS Transform – continuous modernization runs agentic-readiness and modernization analyses across your whole portfolio and can open remediation PRs automatically, using  atx ct  commands ( atx ct analysis run --type agentic-readiness ,  atx ct findings list ,  atx ct remediation create ). For assessing many services at once, there's also  AWS/portfolio-agentic-readiness-analysis , which aggregates per-app reports into cross-cutting findings.

The Business Case

AI agents are already calling your APIs, whether through MCP servers, function calling, or direct HTTP. Without agent-safety features:
  • Retry storms create duplicate resources (orders, payments, users)
  • Agents can't determine retry strategy (wastes compute, causes cascading timeouts)
  • Accidental deletions with no undo path
  • No rate limit signals means agents self-limit conservatively (underutilizing your API) or not at all (overwhelming it)
The five middleware files ATX generated solve all of these. Zero new dependencies. Backward compatible. Applied in one session.
Cost: In one example run this took a few agent minutes at $0.035/agent-minute, on the order of ~$0.10. Agent-minutes are non-deterministic and vary per run and codebase, so treat this as a ballpark — run a pilot to establish your own baseline. Even so, it's a fraction of the cost of one duplicate-order incident.

Getting Started

# Install ATX (requires Node.js 22+)
curl -fsSL https://transform-cli.awsstatic.com/install.sh | bash

# Authenticate (configure AWS credentials)
aws configure # or set AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_REGION

# Run against your Express API
cd your-api
atx

# Describe the agent-safety features you need...
The transformation definition ATX created covers the five most critical agent-safety patterns. Publish it to your registry and any team can apply it to their APIs in minutes.
Your API was built for humans. The agents are here. This makes it ready for both.



Resources

References

[1] AWS, "Agentic Readiness Analysis," AWS Transform documentation.  https://docs.aws.amazon.com/transform/latest/userguide/transform-aws-customs.html 
[2] AWS, "AWS Transform pricing."  https://aws.amazon.com/transform/pricing/ 


Disclaimer: Opinions expressed are personal and do not represent the official position of any organization. All claims about ATX capabilities are verified against the  official documentation .
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