AWS Builder Center
Put Your MCP Servers Behind CloudFront and WAF Before Someone Else Finds Them

Put Your MCP Servers Behind CloudFront and WAF Before Someone Else Finds Them

This is a hands-on lab that shows how to build one small MCP server on AgentCore Runtime behind CloudFront distribution and protected by WAF. I also show four attacks of what the edge can and can't stop.

1. The problem

A remote MCP server is an HTTP endpoint that runs code when you ask it to. That's the whole point of it, and it's also the risk.
If you have the URL, you can send  tools/list  and get back every tool the server offers, with names, descriptions and input schemas. Then you can send  tools/call  and run any of them. There's no UI and no "are you sure?" step. It's just JSON-RPC over POST.
This is already happening. In July 2025 Knostic found 1,862 exposed MCP servers. They checked 119 by hand, and all 119 returned their tool list with no credentials ( Knostic ).
"But I use OAuth." Good, you should. But OAuth answers one question: who is this caller? It doesn't answer should this kind of traffic reach my server at all? A valid token says nothing about whether this is the 300th request this minute, whether a tool argument holds a SQL injection string, or whether this caller should touch the tool that moves money. And tokens leak into logs,  .env  files and committed  mcp.json  files.
On AgentCore Runtime there's one more catch: the inbound authorizer (allowed clients, audiences, scopes) applies to the whole runtime, not to individual tools. If a token is good enough to call  lookup_order , it's good enough to call  refund_payment .
So these are the four threats I care about in this post:
  1. Scanning and enumeration. Someone finds the URL and lists your tools to see what's worth attacking.
  1. Volume abuse. A script (or a buggy agent stuck in a loop) hammers the server, and you pay for it. On AgentCore it's worse: every request without a session ID starts a new billed session (see T2).
  1. Injection in tool arguments. Tool arguments are user input. If a tool passes them to a database, a shell or a URL fetcher, the usual web attacks apply.
  1. Direct calls to the dangerous tool. The attacker skips the agent and calls the tool that does damage.
All four are visible in the HTTP request, and that's exactly where AWS WAF looks.

First, ask if it needs to be public

Before adding any protection, ask: does this server need a public URL at all?
  • Only your own agents or staff call it. Keep it private, in a VPC behind an internal load balancer or a VPC endpoint. There's nothing to scan.
  • Users connect from their own clients, from anywhere. Then it has to be public. That's the case this post is about.
Plenty of servers end up public out of convenience, not need. If that's yours, go private first. If it has to be public, the rest of this post is the minimum I'd put in front of it. Let's build something to attack.

2. Build the target

The server is about 30 lines of Python using FastMCP from the official MCP SDK. It has three tools, and each one sits in a different risk tier on purpose:
Tool
Tier
What it does
 lookup_order 
Safe read
Returns the status of an order
 get_account_balance 
Sensitive read
Returns a customer's balance
 refund_payment 
Dangerous write
Refunds money
# server/server.py
from mcp.server.fastmcp import FastMCP

mcp = FastMCP(host="0.0.0.0", stateless_http=True)

ORDERS = {"A1001": {"status": "shipped", "total": 42.50}}
BALANCES = {"cust-7": 1830.22}


@mcp.tool()
def lookup_order(order_id: str) -> dict:
"""Look up the status of an order by its ID."""
return ORDERS.get(order_id, {"error": "order not found"})


@mcp.tool()
def get_account_balance(customer_id: str) -> dict:
"""Return the current account balance for a customer."""
return {"customer_id": customer_id, "balance": BALANCES.get(customer_id, 0.0)}


@mcp.tool()
def refund_payment(order_id: str, amount: float) -> dict:
"""Refund part or all of an order. This moves real money."""
return {"order_id": order_id, "refunded": amount, "status": "queued"}


if __name__ == "__main__":
mcp.run(transport="streamable-http")
# server/requirements.txt
mcp==1.30.0
Pin the SDK below 2.0. Version 2 of the Python MCP SDK removed the  mcp.server.fastmcp  module, so an unpinned  mcp  in  requirements.txt  breaks the import above. I used 1.30.0.
AgentCore Runtime expects an MCP server to listen on  0.0.0.0:8000/mcp , which is FastMCP's default.  stateless_http=True  is the recommended mode on AgentCore; the platform adds the  Mcp-Session-Id  header for you.

AgnetCore Runtime

You can put the code in a container but it's not required. AgentCore Runtime supports direct code deployment: you hand it a folder with your code and its dependencies, and it runs it on Python 3.12, ARM64. The only trick is that the dependencies must be Linux ARM64 wheels, even if you build on a Mac.  uv  can do that cross-install in one line:
uv pip install --python-platform aarch64-manylinux2014 --python-version 3.12 \
--only-binary=:all: --target infra/build/server-pkg -r server/requirements.txt
cp server/server.py infra/build/server-pkg/
In CDK that folder becomes  AgentRuntimeArtifact.fromCodeAsset(...)  (full stack in section 7). The protocol is MCP and a Cognito user pool is the inbound OAuth authorizer. If you prefer a container, the repo also has a Dockerfile.
Once it's deployed, the endpoint looks like this:
https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/<url-encoded-runtime-arn>/invocations?qualifier=DEFAULT

The naked test

Before adding anything, I call all three tools straight against the AgentCore endpoint. This is the control group. Everything later gets compared against it.
export ENC_ARN=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "$RUNTIME_ARN")
export DIRECT_URL="https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/${ENC_ARN}/invocations?qualifier=DEFAULT"

export TOKEN=$(aws cognito-idp initiate-auth \
--client-id "$CLIENT_ID" --auth-flow USER_PASSWORD_AUTH \
--auth-parameters USERNAME=testuser,PASSWORD="$PASSWORD" \
--query 'AuthenticationResult.AccessToken' --output text)

mcp() { # usage: mcp <url> '<json-rpc body>' [extra curl args]
curl -s -X POST "$1" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d "$2" "${@:3}"
}

mcp "$DIRECT_URL" '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
mcp "$DIRECT_URL" '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"lookup_order","arguments":{"order_id":"A1001"}}}'
mcp "$DIRECT_URL" '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_account_balance","arguments":{"customer_id":"cust-7"}}}'
mcp "$DIRECT_URL" '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"refund_payment","arguments":{"order_id":"A1001","amount":42.5}}}'
All four calls came back with HTTP 200, including the refund:
tools/list -> 200 lookup_order, get_account_balance, refund_payment
lookup_order A1001 -> 200 {"status": "shipped", "total": 42.5}
get_account_balance -> 200 {"customer_id": "cust-7", "balance": 1830.22}
refund_payment A1001 -> 200 {"order_id": "A1001", "refunded": 42.5, "status": "queued"}
Those are trimmed. On the wire, responses are Server-Sent Events ( event: message  /  data: {...} ), and the tool result is a JSON string inside  content[0].text .
Without a token, AgentCore says no:
401 {"jsonrpc":"2.0","error":{"code":-32001,"message":"Missing Authentication Token"}}
So OAuth is doing its job. The problem is everything that happens after a request has a valid token.

3. Put CloudFront in front

CloudFront is the front door, and WAF attaches to it. The distribution has one behavior and one origin:
  • Origin:  bedrock-agentcore.us-east-1.amazonaws.com , HTTPS only
  • Origin path:  /runtimes/<url-encoded-runtime-arn>/invocations 
  • Cache policy:  CachingDisabled . Every MCP request is a POST with a unique body, and you never want a tool result served from cache.
  • Origin request policy:  AllViewer , so the  Authorization ,  Accept  and MCP headers reach the runtime. AWS uses the same setup in its  custom domain example for AgentCore . It also forwards the viewer's  Host  header, and I expected AgentCore to reject that. It didn't, with a JWT authorizer.
  • Allowed methods: all. MCP mostly uses POST, but the Python SDK also sends GET (to open an event stream) and DELETE (to end a session).
With the origin path in place, the client URL is just the distribution root:
export EDGE_URL="https://dnsos9eefh1lh.cloudfront.net/"
Point your MCP client at that URL exactly. Many clients add  /mcp  by default, and you don't want that here.
A time-saving tip: skip the custom domain for now. It needs an ACM certificate in us-east-1, DNS validation and an alias record, and you'll be waiting on DNS when you'd rather be testing. The default  *.cloudfront.net  name works fine with WAF.
Use bearer tokens, not SigV4, through CloudFront. SigV4 signs the host and path. CloudFront adds the origin path, so a signature made for the CloudFront URL won't match what AgentCore receives. Bearer tokens pass through unchanged.

CloudFront is not the only way in

Putting CloudFront in front does not make the AgentCore endpoint private. Anyone with a valid token can still call  bedrock-agentcore.us-east-1.amazonaws.com  directly and skip your WAF completely. With a normal HTTP origin you'd fix this by having the origin check a secret header that only CloudFront adds. A managed endpoint can't check a custom header for you.
There are two ways to deal with this, and you should pick one on purpose:
Option A: Public endpoint plus OAuth (what this lab uses). The second lock is the endpoint's own OAuth authorizer. WAF protects traffic that comes through CloudFront, and anyone who goes around it still needs a valid token. Keep token lifetimes short, turn off Cognito self sign-up, and keep the runtime ARN out of public repos. It's fine for a lab, but not airtight, and T3 shows where it leaks.
Option B: Close the side door. AgentCore Runtime supports resource-based policies. You can deny  bedrock-agentcore:InvokeAgentRuntime  unless the request comes through a specific VPC interface endpoint ( aws:SourceVpce ). Then you route CloudFront → ALB →  com.amazonaws.<region>.bedrock-agentcore  interface endpoint → Runtime. Lock the ALB down with an internal ALB and a CloudFront VPC origin, or a public ALB whose security group allows only the  com.amazonaws.global.cloudfront.origin-facing  prefix list. Now WAF is the only path. AWS documents the ALB and resource policy part in  Securing Amazon Bedrock AgentCore Runtime with AWS WAF . It costs more: an ALB plus an interface endpoint per AZ, running all month. If you can pick, this is the safer starting point.
If your tools sit behind AgentCore Gateway instead of Runtime, you can attach a WAF web ACL to the gateway directly.

4. The WAF rule stack

This is the core of the post. A WAF web ACL for CloudFront must be created in us-east-1 with scope  CLOUDFRONT . The default action is Allow, and the rules below block. Rules run in priority order, lowest first, and stop at the first terminating match.
Priority
Rule
Action
Why it's here
10
 AWSManagedRulesAmazonIpReputationList 
Block
Drop known bad IPs before doing any other work
20
 rate-per-ip  (rate-based)
Count → Block
Stop floods and runaway agents
30
 AWSManagedRulesCommonRuleSet 
Block
XSS, LFI/RFI, SSRF to instance metadata, oversized bodies
40
 AWSManagedRulesKnownBadInputsRuleSet 
Block
Log4j, Java deserialization, other known exploit patterns
50
 AWSManagedRulesSQLiRuleSet 
Block
SQL injection in the body and query string
60
 no-jsonrpc-batches 
Block
Closes a bypass for rule 70
70
 refund-needs-admin-key 
Block
The signature rule: guard the dangerous tool at the edge
The web ACL uses 1,140 WCU, under the 1,500 included in the base price.

① Managed rule groups

Three managed groups give you a sensible baseline for almost no effort. I added a fourth, the SQLi group, because the Core Rule Set does not include SQL injection rules. It covers XSS, path traversal, file inclusion, SSRF to  169.254.169.254 , and size limits, but not SQLi. That surprises people.
Two Core Rule Set rules to know with MCP traffic:  SizeRestrictions_BODY  blocks bodies over 8 KB (override it to Count if a tool accepts documents), and  NoUserAgent_HEADER  blocks requests with no  User-Agent  (the MCP SDKs send one, hand-written clients may not).

② Rate limiting: watch first, then block

{
"Name": "rate-per-ip",
"Priority": 20,
"Action": { "Count": {} },
"Statement": {
"RateBasedStatement": {
"Limit": 100,
"EvaluationWindowSec": 60,
"AggregateKeyType": "IP"
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "rate-per-ip"
}
}
Why 100 per minute per IP? Count the requests in a real agent session. In T1 below, the official Python SDK made 7 HTTP requests to open a session, list tools, call one tool and close: four POSTs, two GETs for the event stream, and a DELETE at the end. Each extra tool call is one more POST. An agent doing a 20-step task sends roughly 30 requests over a minute or two. 100 per minute leaves plenty of headroom for a busy agent and is still far below what a scanner or a stuck loop produces.
Don't trust my number. Run the rule in Count for a day with real traffic, then check the busiest IPs per minute in Logs Insights:
fields httpRequest.clientIp
| stats count(*) as reqs by httpRequest.clientIp, bin(1m)
| sort reqs desc
| limit 20
If your top legitimate client peaks at 30, 100 is fine. If many users share one corporate NAT IP, raise the limit, or aggregate on a custom key such as IP plus the  Authorization  header. My laptop reached CloudFront over IPv6, so  clientIp  was an IPv6 address. Keep that in mind if you add IP sets.
When you're happy, switch the action to Block. I return a 429 with  Retry-After  instead of the default 403, so well-behaved clients know to back off:
"Action": {
"Block": {
"CustomResponse": {
"ResponseCode": 429,
"ResponseHeaders": [{ "Name": "retry-after", "Value": "60" }]
}
}
}
That 429 has an empty body. For a readable MCP error, add a  CustomResponseBodyKey  like rule 70 does below.
The minimum limit is 10 requests and the window can be 60, 120, 300 or 600 seconds. Rate rules aren't instant: in T2 the first block came about 42 seconds in, after about twice the limit had gone through. Plan for that.
One more thing: the admin key for rule 70 is a  NoEcho  CloudFormation parameter, and redeploys keep the old value. A redeploy never rotates the key, so rotate it on purpose.

③ The signature rule: guard  refund_payment  at the edge

WAF can parse a JSON body and match on specific fields with JSON Pointer. An MCP tool call always looks like this:
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"refund_payment","arguments":{...}}}
So the rule says: if  /method  is  tools/call  and  /params/name  is  refund_payment  and the  x-admin-key  header is not the right value, block it.
{
"Name": "refund-needs-admin-key",
"Priority": 70,
"Action": {
"Block": {
"CustomResponse": { "ResponseCode": 403, "CustomResponseBodyKey": "admin_required" }
}
},
"Statement": {
"AndStatement": {
"Statements": [
{
"ByteMatchStatement": {
"FieldToMatch": {
"JsonBody": {
"MatchPattern": { "IncludedPaths": ["/method"] },
"MatchScope": "VALUE",
"InvalidFallbackBehavior": "MATCH",
"OversizeHandling": "MATCH"
}
},
"PositionalConstraint": "EXACTLY",
"SearchString": "tools/call",
"TextTransformations": [{ "Priority": 0, "Type": "NONE" }]
}
},
{
"ByteMatchStatement": {
"FieldToMatch": {
"JsonBody": {
"MatchPattern": { "IncludedPaths": ["/params/name"] },
"MatchScope": "VALUE",
"InvalidFallbackBehavior": "MATCH",
"OversizeHandling": "MATCH"
}
},
"PositionalConstraint": "EXACTLY",
"SearchString": "refund_payment",
"TextTransformations": [{ "Priority": 0, "Type": "NONE" }]
}
},
{
"NotStatement": {
"Statement": {
"ByteMatchStatement": {
"FieldToMatch": { "SingleHeader": { "Name": "x-admin-key" } },
"PositionalConstraint": "EXACTLY",
"SearchString": "<admin key, injected at deploy time>",
"TextTransformations": [{ "Priority": 0, "Type": "NONE" }]
}
}
}
}
]
}
},
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "refund-needs-admin-key"
}
}
The custom response body is a JSON-RPC error, so MCP clients show a clean message instead of choking on an HTML error page:
"CustomResponseBodies": {
"admin_required": {
"ContentType": "APPLICATION_JSON",
"Content": "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32001,\"message\":\"Blocked at edge: admin key required for this tool\"}}"
}
}
A few details here took me longer than the rest of the rule:
  •  InvalidFallbackBehavior: MATCH . If the body isn't valid JSON, both JSON conditions count as matched, so a malformed body without the key gets blocked.
  •  OversizeHandling: MATCH . On CloudFront, WAF inspects only the first 16 KB of the body. If an attacker pads the request past that to hide the tool name, it's treated as a match and blocked.
  • Rule 60 blocks JSON-RPC batches. Older MCP versions allowed sending an array of messages in one POST. The JSON Pointer  /params/name  doesn't match anything inside an array, so a batch could carry  refund_payment  right past rule 70. The MCP spec dropped batching in the 2025-06-18 revision, so nothing legitimate needs it. Rule 60 is a regex match on the body for  ^\s*\[  with Block.
Only rule 70 sends JSON back. In the lab, every other block (rule 60, the SQLi group, the Core Rule Set) returned CloudFront's standard HTML "Request blocked" page, because a plain Block action has no custom response. MCP clients don't know what to do with HTML. If you want clean errors everywhere, give rule 60 the same kind of custom response, and for the managed groups either override individual rules with  RuleActionOverrides  (a Block action with a  CustomResponse ) or run the group in Count and add your own rule that blocks on the group's label with a custom response. I didn't do this in the lab. It's the next thing I'd add.
Be clear about what this rule is. It's a gate, not your authorization model. A shared header key is coarse: anyone who can read the web ACL can read it (the lab's test scripts do exactly that), and anyone who has it can refund. In production, the tool should also check the caller's own permissions. Pass the  Authorization  header through to the runtime and check a claim or group inside  refund_payment . The edge rule just keeps most bad requests away from that code.
 get_account_balance  has no edge rule in this lab. You could copy the header-key rule for it, but one shared key can't say whose balance a caller may read. That check belongs inside the tool.

④ Logging from the beginning

Turn on WAF logging before your first test, not after something odd happens. Every test in the next section uses a log line as evidence.
  • Send them to CloudWatch Logs. The log group name must start with  aws-waf-logs- , and for a CloudFront web ACL it lives in us-east-1.
  • Redact  authorization  and  x-admin-key . WAF logs include request headers by default, so without redaction your bearer tokens and admin key end up in CloudWatch.
  • Treat the log group as sensitive anyway. WAF doesn't store the full body, but SQLi and XSS matches log the matched pieces in  terminatingRuleMatchDetails[].matchedData . In T4 that included the first 60-odd characters of my JSON-RPC body.
  • Know what a block looks like.  responseCodeSent  only appears when the rule has a custom response. The rate rule adds no label, so find it by  terminatingRuleId  (Block) or  nonTerminatingMatchingRules  (Count).
The query I used for the evidence below:
fields @timestamp, action, terminatingRuleId, responseCodeSent, httpRequest.httpMethod, labels.0.name
| filter httpSourceName = "CF"
| sort @timestamp asc
| limit 500

5. Red-team it

Four tests. Each has the command, what came back, and the WAF log lines that prove why.

T1: A normal client through CloudFront works

This uses the real MCP Python SDK, not curl, to prove a normal client isn't broken by the edge.
# tests/t1_client.py
import asyncio, os
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

async def main():
headers = {"Authorization": f"Bearer {os.environ['TOKEN']}"}
async with streamablehttp_client(os.environ["EDGE_URL"], headers=headers) as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print([t.name for t in tools.tools])
print(await session.call_tool("lookup_order", {"order_id": "A1001"}))

asyncio.run(main())
Result:
Session termination failed: 404
['lookup_order', 'get_account_balance', 'refund_payment']
meta=None content=[TextContent(type='text', text='{\n "status": "shipped",\n "total": 42.5\n}', ...)] isError=False
Ignore the first line. When the SDK closes the session it sends a DELETE, AgentCore answers 404, and the SDK prints a warning.
WAF log: 7 requests, all  ALLOW  /  Default_Action : POST, GET, POST, POST, GET, POST, DELETE.

T2: 300  tools/list  calls in one minute

for i in $(seq 1 300); do
mcp "$EDGE_URL" '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' \
-o /dev/null -w "%{http_code}\n" &
sleep 0.2
done | sort | uniq -c
That's about 5 requests a second from one IP. I ran it twice: once with the rate rule in Count, and once in Block.
Result (Count):
300 200
Everything gets through. The logs show what would have happened: the first 195 requests matched nothing, and the last 105 carry  rate-per-ip  under  nonTerminatingMatchingRules . The first was request #196, about 41 seconds in.
Result (Block):
201 200
99 429
The first 429 was request #202, about 42 seconds in. So with a limit of 100 per minute, about 200 requests got through before WAF stepped in. That's the detection lag from section 4, measured.
The 429 has  retry-after: 60  and an empty body.
WAF log (the switch from allow to block):
10:35:26.545 ALLOW Default_Action
...
10:36:28.976 BLOCK rate-per-ip responseCodeSent=429
10:36:29.182 BLOCK rate-per-ip responseCodeSent=429
CloudWatch metrics per minute. Green is the Count run flagging requests, purple is the Block run returning 429s:
T2: requests allowed, counted and blocked by rate-per-ip, per minute

It was suprising to see the flood costs money even after WAF catches up. Each  tools/list  here is sent without an  Mcp-Session-Id , so AgentCore starts a new session (a fresh microVM) for every request. Sessions live until the idle timeout, 15 minutes by default, and you pay for their memory the whole time. The runtime's metrics show it: invocations and sessions are the same line.
AgentCore Runtime: invocations vs sessions per minute during the lab

Across the lab, AgentCore counted 776 invocations and 690 sessions, and those idle sessions are almost the whole bill in section 6. Two things help: rate limiting at the edge caps how many sessions an attacker can open, and a shorter  idleRuntimeSessionTimeout  on the runtime limits what each one costs. A normal MCP client reuses one session, so a short timeout doesn't hurt it much.

T3:  refund_payment  with and without the admin key

REFUND='{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"refund_payment","arguments":{"order_id":"A1001","amount":42.5}}}'

# without the key
mcp "$EDGE_URL" "$REFUND" -w "\nHTTP %{http_code}\n"

# with the key
mcp "$EDGE_URL" "$REFUND" -H "x-admin-key: $ADMIN_KEY" -w "\nHTTP %{http_code}\n"
Result:
--- without the key
{"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":"Blocked at edge: admin key required for this tool"}}
HTTP 403
--- with the key
data: {"jsonrpc":"2.0","id":9,"result":{"content":[{"type":"text","text":"{... \"refunded\": 42.5, \"status\": \"queued\" ...}"}],"isError":false}}
HTTP 200
WAF log, the two requests 40 ms apart:
10:29:27.257 BLOCK refund-needs-admin-key responseCodeSent=403
10:29:27.297 ALLOW Default_Action
Redaction works: the allowed record shows  authorization: REDACTED, x-admin-key: REDACTED . The blocked one has no  x-admin-key  entry at all, because the client never sent it.
Now the batch version, to prove rule 60 matters:
mcp "$EDGE_URL" "[$REFUND]" -w "\nHTTP %{http_code}\n"
<!DOCTYPE HTML ...> <H1>403 ERROR</H1> ... Request blocked. ... Generated by cloudfront (CloudFront)
HTTP 403
10:29:31.045 BLOCK no-jsonrpc-batches
Blocked, but with CloudFront's HTML page and no  responseCodeSent .
Last, the same refund against  $DIRECT_URL , without a key:
data: {"jsonrpc":"2.0","id":9,"result":{"content":[{"type":"text","text":"{... \"refunded\": 42.5, \"status\": \"queued\" ...}"}],"isError":false}}
HTTP 200
The refund goes through, and nothing shows up in the WAF log because the request never touched CloudFront. That's the Option A gap from section 3. It's why the tool needs its own check, or why you'd build Option B.

T4: Injection in tool arguments

The first payload is classic SQLi in  order_id :
SQLI=$(cat <<'EOF'
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"lookup_order","arguments":{"order_id":"A1001' OR '1'='1' --"}}}
EOF
)
mcp "$EDGE_URL" "$SQLI" -w "\nHTTP %{http_code}\n"
The second payload is more realistic for agent tools: an SSRF attempt at the instance metadata service, the kind of string you'd pass to any tool that fetches a URL.
mcp "$EDGE_URL" '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"lookup_order","arguments":{"order_id":"http://169.254.169.254/latest/meta-data/iam/security-credentials/"}}}' \
-w "\nHTTP %{http_code}\n"
Result: both came back  HTTP 403  with CloudFront's HTML "Request blocked" page.
WAF log:
10:29:42.696 BLOCK AWS-AWSManagedRulesSQLiRuleSet label awswaf:managed:aws:sql-database:SQLi_Body
10:29:42.733 BLOCK AWS-AWSManagedRulesCommonRuleSet label awswaf:managed:aws:core-rule-set:EC2MetaDataSSRF_Body
Watch the case if you write alarms on these: the rule is  EC2MetaDataSSRF_BODY  but its label ends in  EC2MetaDataSSRF_Body .
Every block from T3 and T4, one request per rule:
T3 and T4: blocked requests by rule

WAF doesn't know whether  lookup_order  is vulnerable. My toy tool doesn't touch a database at all. WAF blocks the shape of the input, which is good defense in depth, but it can false-positive: a support ticket that quotes a SQL error could trip the SQLi rule. Check your logs before you trust managed rules on free-text arguments.

6. The numbers

Latency

I timed 20  tools/call lookup_order  round trips direct and 20 through CloudFront, from my MacBook in Brisbane, Australia, to AgentCore in us-east-1. CloudFront served me from its Brisbane edge ( BNE50-P2 ). One warm-up call per path was dropped.
My first loop gave a useless answer: about 3.6 seconds on both paths. Without an  Mcp-Session-Id , every call starts a new AgentCore session, so I was timing microVM start-up, not the network. A real client keeps its session, so the fair test reuses the ID from the warm-up call:
BODY='{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"lookup_order","arguments":{"order_id":"A1001"}}}'
for url in "$DIRECT_URL" "$EDGE_URL"; do
# warm-up call, keep its session ID
SID=$(mcp "$url" "$BODY" -D - -o /dev/null | awk -F': ' 'tolower($1)=="mcp-session-id"{print $2}' | tr -d '\r')
for i in $(seq 1 20); do
mcp "$url" "$BODY" -H "Mcp-Session-Id: $SID" -o /dev/null -w "%{time_total}\n"
done | sort -n | awk '{a[NR]=$1*1000} END {printf "median %.0f ms, p90 %.0f ms\n", (a[10]+a[11])/2, a[18]}'
done
Averaged over two runs:
Path
Median (20 runs)
p90
Direct to AgentCore
1,015 ms
1,100 ms
CloudFront + WAF
550 ms
970 ms
Difference
CloudFront is ~465 ms faster

Putting a CDN and a WAF in front made my calls faster. From Australia, a direct call does its TLS handshake across the Pacific, which alone is about half a second. Through CloudFront, TLS ends in Brisbane and the long trip runs over connections CloudFront already has open. WAF inspection added nothing I could measure. In the same region as your runtime, expect the two paths to be close. Measure from where your users are.

Cost

WAF pricing is prorated by the hour, so a short lab costs very little. My lab ran for about 1 hour, from  cdk deploy  to the last metric pull. It sent about 900 requests: 747 through CloudFront (643 allowed, 104 blocked) and about 130 direct.
Item
Lab cost
WAF web ACL ($5/month) and 7 rules ($1/rule/month), prorated
~$0.017
WAF requests ($0.60 per million), 747 requests
~$0.0005
WAF logs, CloudFront, Cognito, S3
~$0 (free tier or tiny)
AgentCore Runtime ($0.0895 per vCPU-hour, $0.00945 per GB-hour): 2.53 vCPU-h and 132 GB-h
~$1.47
Total (estimate from list prices)
≈ $1.50
The edge cost about two cents. Almost the whole bill is AgentCore memory from the 690 idle sessions that T2 and the latency test opened. On a per-session platform, request floods turn into memory bills. Check Cost Explorer a day after clean up for the real total.
If you leave the stack running, it costs about $0.017 an hour (WAF plus one secret), about $12 a month. AgentCore costs nothing while no sessions are open.

7. Deploy, verify, clean up

Everything is in one CDK stack in us-east-1. The repo is  https://github.com/starcub/mcp-edge-lab .
You need Node 22+, the CDK CLI,  uv ,  python3 ,  curl , and AWS credentials that can deploy CloudFormation. My default IAM user couldn't, so check that first.

The stack

The rules are the plain JSON from section 4, loaded from  waf/*.json . CloudFormation accepts WAF's PascalCase JSON through  addPropertyOverride , so the rules in this post, the repo and your account are the same text.
const adminKey = new cdk.CfnParameter(this, 'AdminKey', { type: 'String', noEcho: true, minLength: 16 });

const runtime = new agentcore.Runtime(this, 'OrdersMcp', {
runtimeName: 'orders_mcp',
agentRuntimeArtifact: agentcore.AgentRuntimeArtifact.fromCodeAsset({
path: path.join(__dirname, '../build/server-pkg'), // the uv build from section 2
runtime: agentcore.AgentCoreRuntime.PYTHON_3_12,
entrypoint: ['server.py'],
}),
protocolConfiguration: agentcore.ProtocolType.MCP,
authorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration.usingCognito(pool, [client]),
});

// The runtime ARN is a token at synth time, so build the encoded path from its parts.
const originPath = cdk.Fn.join('', [
'/runtimes/arn%3Aaws%3Abedrock-agentcore%3A', this.region, '%3A', this.account,
'%3Aruntime%2F', runtime.agentRuntimeId, '/invocations',
]);

const acl = new wafv2.CfnWebACL(this, 'EdgeAcl', {
name: 'mcp-edge', scope: 'CLOUDFRONT', defaultAction: { allow: {} },
visibilityConfig: { cloudWatchMetricsEnabled: true, sampledRequestsEnabled: true, metricName: 'mcp-edge' },
});
acl.addPropertyOverride('Rules', substitute(readJson('rules.json'), '{{ADMIN_KEY}}', adminKey.valueAsString));
acl.addPropertyOverride('CustomResponseBodies', readJson('custom-response-bodies.json'));

new cloudfront.Distribution(this, 'Edge', {
webAclId: acl.attrArn,
defaultBehavior: {
origin: new origins.HttpOrigin(`bedrock-agentcore.${this.region}.amazonaws.com`, {
originPath, protocolPolicy: cloudfront.OriginProtocolPolicy.HTTPS_ONLY,
}),
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY,
},
});

new wafv2.CfnLoggingConfiguration(this, 'WafLogging', {
resourceArn: acl.attrArn,
logDestinationConfigs: [logGroupArnWithoutStar], // WAF rejects the ":*" that logGroupArn ends in
redactedFields: [{ singleHeader: { Name: 'authorization' } }, { singleHeader: { Name: 'x-admin-key' } }],
});
The log group, the Cognito pool and the  formatArn  call for the log ARN are in the repo. The AgentCore constructs are in the stable  aws-cdk-lib/aws-bedrockagentcore  module (I used 2.276.0).

Deploy

git clone https://github.com/starcub/mcp-edge-lab && cd mcp-edge-lab/infra
npm install && npm run package-server # uv builds the ARM64 package, no Docker
npx cdk bootstrap # once per account and region
ADMIN_KEY=$(openssl rand -hex 24)
npx cdk deploy --parameters AdminKey="$ADMIN_KEY" --outputs-file ../results/cdk-outputs.json
cd .. && ./tests/setup_user.sh # creates the Cognito user "testuser"
The Cognito default password policy wants a symbol, so  openssl rand -hex  passwords fail.  setup_user.sh  generates one that passes. The stack starts with the rate rule in Count.

Verify

source tests/env.sh # sets EDGE_URL, DIRECT_URL, TOKEN, ADMIN_KEY and the mcp() helper
./tests/naked.sh # section 2: all four calls work directly
uv run --python 3.12 --with 'mcp==1.30.0' python tests/t1_client.py # T1
./tests/t2_rate.sh # T2 in Count mode
(cd infra && npx cdk deploy -c rateAction=block) && ./tests/t2_rate.sh # T2 in Block mode
./tests/t3_refund.sh && ./tests/t4_injection.sh # T3, T4

Clean up

cd infra && npx cdk destroy
aws cloudformation describe-stacks --stack-name McpEdgeLab # should say the stack does not exist
aws logs describe-log-groups --log-group-name-prefix aws-waf-logs-mcp-edge
Then check what stays behind: the Cognito pool, the test user's secret (it can sit in pending deletion), and the code asset in the CDK bootstrap bucket, which  cdk destroy  doesn't remove. If you built Option B, the ALB and interface endpoint cost real money if you forget them.

8. Decisions and tradeoffs

  • CloudFront + WAF, not an ALB. Option B needs an ALB and an interface endpoint all month. CloudFront needs neither. The price is the open side door.
  • Option A for the lab, B for real data. Option A is the quickest to test. If the tools touch money or customer data, build B.
  • A shared header key for  refund_payment . It's crude, and anyone who can read the web ACL can read the key. It shows what an edge rule can do. The real check belongs inside the tool, using the caller's JWT claims.
  • Count first, then Block. A day of Count logs gives you the real limit before you block anyone.
  • Direct code deployment, not a container. No Docker. If you need system libraries, use the container path.
  • Managed rule groups plus two custom rules. Managed groups cover known patterns cheaply. Only MCP-specific logic, like the tool name in the JSON body, needed custom rules.

What I'd take from this

The edge is cheap: about two cents of WAF for an hour of attacks. It caught the floods, the obvious injection and direct hits on the tool I care most about, and from Brisbane it made calls faster. But the 42-second rate-limit lag let 200 requests through, and those became billed sessions. What it can't do is judge intent: a valid request from a valid caller looks fine to WAF, even when it does something the user never wanted. Put WAF in front so the dumb attacks never reach your server, then spend your real effort on the layer that understands what the tools do.
Again, the code repo is at  https://github.com/starcub/mcp-edge-lab . Feel free to clone it and try it yourself.
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