AWS Builder Center

Design: a secured MCP tool server on AWS

Design: a secured MCP tool server on AWS

Design: a secured MCP tool server on AWS



status
proposed — nothing here is deployed
article
 MCP security on AWS 
depends on
 MCP and A2A on AWS 
§3 (hosting) and §4 (authorisation)
SDK
the official Go SDK,  modelcontextprotocol/go-sdk  v1.7.0
date
2026-09-24



1. Context

A team wants to expose internal capabilities — search a ticket system, read a runbook, restart a deployment — to agents through MCP, so that any compliant client can use them without a bespoke integration. The agents act on behalf of named employees. Some tools read private data; one tool changes production.
The  article  establishes what the SDK defends and what it leaves open. This document chooses one deployment, writes down why, and says how to know it works.

2. Goals and non-goals

Goals
  1. Every tool call is attributable to a named user, not only to an agent.
  1. A token issued for another server, another user's session, or an expired token is refused at the wire.
  1. Every tool call is authorised per user, per tool and per argument, in one place that can be audited without reading handler code.
  1. If a model is steered by injected text, it cannot reach data outside its tool's scope and cannot send anything to an arbitrary host.
  1. Every call leaves one structured record that answers who, what, with which arguments, allowed or not, and how long it took.
  1. A change to a tool's name, description or schema is detected.
Non-goals
  • Preventing prompt injection. No control on this page does; the design bounds its consequences instead (goal 4).
  • Securing the client or the model. The agent is outside this boundary and is treated as a well-meaning but steerable caller.
  • Multi-region. One region, one account per environment.
  • Dynamic client registration. Cognito does not offer it (see the  protocols wishes , wish 1); clients are pre-registered.

3. Threat model

Assets

asset
where it lives
why it matters
ticket and runbook contents
DynamoDB, S3
private data; the thing exfiltration wants
the restart capability
EKS API, via the server's role
the one irreversible action
user tokens
in flight only
a replayable identity
upstream credentials (ticket system API key)
Secrets Manager
a credential the model must never see
tool definitions
the server's code
what the model is told a tool does

Actors

actor
capability
intent
an employee through an agent
a valid token for themselves
legitimate, occasionally over-reaching
another employee
a valid token for themselves
may try another user's session or data
injected text
steers the model inside a legitimate session
exfiltration, destructive action
an internet attacker
can reach the public endpoint
token replay, SSRF, denial of wallet
a compromised dependency
runs inside the server
anything the task role and the network allow

Trust boundaries

  1. Internet → edge. Nothing is trusted.
  1. Edge → server. The token is verified; the user is known.
  1. Server → tool logic. The authorisation decision is made; arguments are still untrusted.
  1. Server → AWS APIs and upstreams. The role decides; the network decides where else.
  1. Tool result → model. Everything returned is untrusted text for the next decision, which this server does not make.

STRIDE

threat
example
control
decision
Spoofing
a token for another MCP server replayed here
issuer + resource check in the verifier
D2
Spoofing
user B drives user A's session
 TokenInfo.UserID = sub ; the SDK returns 403
D3
Tampering
a tool description changed after approval
tool-list hash recorded and compared
D9
Repudiation
"the agent did it, not me"
one log line per call with  sub , tool, argument hash, decision
D8
Information disclosure
injected text makes a tool read another tenant
role session tags + DynamoDB leading-key condition
D6
Information disclosure
the model sends data to an attacker's host
no default route; Network Firewall allowlist
D7
Information disclosure
SSRF to the metadata endpoint
Fargate exposes no EC2 instance metadata; on EC2 or EKS nodes, IMDSv2 with hop limit 1
D7
Denial of service
a flood of calls, or 4 MiB bodies
WAF rate-based rule; the SDK's 413
D1
Denial of service
idle sessions accumulating forever
 SessionTimeout 
D3
Elevation of privilege
 restart_deployment  called by a reader
Verified Permissions; human approval on the destructive tool
D5, D10

4. Architecture


client ──TLS──> CloudFront + WAF ──> ALB ──> Fargate task (private subnet)
│ RequireBearerToken(verifier)
│ StreamableHTTPHandler
│ per call: Verified Permissions
├──> DynamoDB / S3 (VPC endpoints)
├──> Secrets Manager (VPC endpoint)
└──> ticket SaaS (Network Firewall allowlist)
Cognito ── issues tokens, JWKS fetched via NAT → firewall
CloudWatch Logs ← one line per call CloudTrail ← AWS calls

5. Decisions

Each decision records what was chosen, what was rejected, and why.
D1 — Fargate behind an ALB, not Lambda. Chosen one Fargate service, two tasks minimum, ALB idle timeout 300 s. Rejected Lambda with a Function URL — stateless mode only, so no session to bind a user to (D3) and no  listChanged  push; AgentCore Gateway — it would remove hosting work, but its session-to-user binding is not something this design can verify (article §8), and goal 2 depends on it. Because the session is where the hijacking defence lives.
D2 — The verifier checks issuer, token use, resource and expiry. Chosen a  TokenVerifier  that validates the Cognito JWT signature against the pool's JWKS, requires  iss  to equal the pool,  token_use  to equal  access , and at least one scope prefixed with the resource server identifier; the SDK enforces expiry with a 30-second  ClockSkew . Rejected trusting the ALB's OIDC action alone — it authenticates browsers through a redirect, which an MCP client does not follow; checking only the signature — that accepts any token from the pool, for any server. Because token passthrough is the attack the SDK explicitly leaves to the verifier. Cognito access tokens carry  client_id  and  scope , not  aud , so the resource-server scope prefix is the audience this design can check (documentation-sourced; verify).
D3 — Sessions are bound to the user and expire. Chosen  TokenInfo.UserID = sub ;  SessionTimeout = 15m . Rejected the defaults — no binding, and sessions that never close. Because both defaults fail open, and the fix is two fields.
D4 — Cross-origin protection is on. Chosen the handler wrapped in  http.NewCrossOriginProtection() . Rejected the deprecated  CrossOriginProtection  option; leaving it unset, which in v1.7.0 means no protection. Because the server's clients are agents, not browsers, and a browser request arriving here is either a mistake or an attack.
D5 — Verified Permissions decides every tool call. Chosen one  IsAuthorized  call per tool invocation, principal = user, action = tool name, resource = the tenant or object, context = the arguments that matter. Rejected scopes per tool — twelve scopes that every client then requests; authorisation inside each handler — correct on the day it is written, and unauditable a year later. Because goal 3 asks for one place, and a policy store is one place with a change history.
D6 — One task role for this server, tenant-scoped by session tag. Chosen a task role that can read two tables and one bucket, with DynamoDB access conditioned on  dynamodb:LeadingKeys  matching  ${aws:PrincipalTag/tenant} . Rejected a shared "agent tools" role across servers. Because a role is the only boundary the model cannot argue with.
D7 — No default route; an allowlist for the rest. Chosen private subnets; VPC endpoints for DynamoDB, S3, Secrets Manager, CloudWatch Logs, Verified Permissions and ECR; everything else through AWS Network Firewall with a domain allowlist of exactly the ticket SaaS and the Cognito domain; Route 53 Resolver DNS Firewall allowing the same domains and blocking the rest. Rejected security groups alone — they filter by IP, and SaaS IPs move; an egress proxy in the task — it runs inside the thing it is meant to contain. Because exfiltration has to leave by some route, and this makes the route a list of two names.
D8 — One log line per call, arguments hashed. Chosen a JSON line to CloudWatch Logs: request id,  sub ,  client_id , session id hash, tool, SHA-256 of the canonical arguments, decision, the policy ids that decided it, latency, outcome. Raw arguments go to a separate log group with shorter retention and tighter access. Rejected logging raw arguments in the main stream — they contain the private data the design is protecting. Because goal 5, without making the log the new leak.
D9 — Tool definitions are pinned. Chosen at startup the server computes a SHA-256 over its sorted tool names, descriptions and input schemas, logs it, and publishes it as a CloudWatch metric dimension; an alarm fires when a deployment changes it without a matching approved value in Parameter Store. Rejected trusting code review — descriptions change in the same pull request as behaviour and are read less carefully. Because the rug pull is invisible to every other control here.
D10 — The destructive tool needs a human. Chosen  restart_deployment  returns a task id immediately and starts a Step Functions execution that waits on a task token; an approver in chat completes it. Rejected relying on  destructiveHint  — it is a hint, and the SDK says not to make decisions on it. Because the one irreversible action deserves the one control that does not depend on the model.

6. Configuration

6.1 The server's wire (D2, D3, D4)

// Verifier for Cognito access tokens. jwks is a keyfunc.Keyfunc built from
// the user pool's JWKS document: <issuer>/.well-known/jwks.json
func cognitoVerifier(issuer, resource string, jwks keyfunc.Keyfunc) auth.TokenVerifier {
return func(ctx context.Context, raw string, _ *http.Request) (*auth.TokenInfo, error) {
claims := jwt.MapClaims{}
parsed, err := jwt.ParseWithClaims(raw, claims, jwks.Keyfunc,
jwt.WithIssuer(issuer),
jwt.WithValidMethods([]string{"RS256"}),
jwt.WithExpirationRequired())
if err != nil || !parsed.Valid {
return nil, fmt.Errorf("%w: %v", auth.ErrInvalidToken, err)
}
if claims["token_use"] != "access" {
return nil, fmt.Errorf("%w: not an access token", auth.ErrInvalidToken)
}
scopeClaim, _ := claims["scope"].(string)
var scopes []string
for _, s := range strings.Fields(scopeClaim) {
// The resource-server prefix is the audience: a token minted for
// another server has no scope under this prefix.
if rest, ok := strings.CutPrefix(s, resource+"/"); ok {
scopes = append(scopes, rest)
}
}
if len(scopes) == 0 {
return nil, fmt.Errorf("%w: no scope for %s", auth.ErrInvalidToken, resource)
}
exp, _ := claims.GetExpirationTime()
sub, _ := claims.GetSubject()
return &auth.TokenInfo{
Scopes: scopes,
Expiration: exp.Time,
UserID: sub, // binds the MCP session to this user (D3)
Extra: map[string]any{"client_id": claims["client_id"]},
}, nil
}
}

func handler(server *mcp.Server, issuer, resource string, jwks keyfunc.Keyfunc) http.Handler {
mux := http.NewServeMux()
mux.Handle("/.well-known/oauth-protected-resource",
auth.ProtectedResourceMetadataHandler(&oauthex.ProtectedResourceMetadata{
Resource: resource,
AuthorizationServers: []string{issuer},
ScopesSupported: []string{"read", "write"},
}))

mcpHandler := mcp.NewStreamableHTTPHandler(
func(*http.Request) *mcp.Server { return server },
&mcp.StreamableHTTPOptions{SessionTimeout: 15 * time.Minute})

protected := auth.RequireBearerToken(cognitoVerifier(issuer, resource, jwks),
&auth.RequireBearerTokenOptions{
ResourceMetadataURL: resource + "/.well-known/oauth-protected-resource",
Scopes: []string{"read"},
ClockSkew: 30 * time.Second,
})(mcpHandler)

mux.Handle("/mcp", http.NewCrossOriginProtection().Handler(protected))
return mux
}
 DisableLocalhostProtection  stays false and  MaxRequestBodyBytes  stays at its 4 MiB default; neither is set, so neither can be set wrongly.

6.2 Per-call authorisation (D5)

A Verified Permissions schema with the tool as the action:
namespace Mcp {
entity Tenant;
entity User { tenant: Tenant, groups: Set<String> };
action "search_tickets", "read_runbook" appliesTo {
principal: User, resource: Tenant,
context: { query_length: Long }
};
action "restart_deployment" appliesTo {
principal: User, resource: Tenant,
context: { namespace: String, environment: String }
};
}
and the policies, which are the whole of the authorisation logic:
// Anyone may read inside their own tenant.
permit (principal, action in [Mcp::Action::"search_tickets", Mcp::Action::"read_runbook"], resource)
when { resource == principal.tenant };

// Only on-call may restart, and never in production through this path.
permit (principal, action == Mcp::Action::"restart_deployment", resource)
when { principal.groups.contains("oncall") && context.environment != "prod" };

// Unbounded searches are a scraping pattern, not a question.
forbid (principal, action == Mcp::Action::"search_tickets", resource)
when { context.query_length > 512 };
Every handler starts with the same call; a tool that forgets it is caught by the abuse test in §7 that calls every tool as a user with no permissions.

6.3 The task role (D6)

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "TicketsForThisTenantOnly",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:Query"],
"Resource": "arn:aws:dynamodb:*:*:table/tickets",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": ["${aws:PrincipalTag/tenant}"]
}
}
},
{
"Sid": "Runbooks",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::runbooks/*"
},
{
"Sid": "UpstreamCredential",
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:*:*:secret:mcp/ticket-saas-*"
},
{
"Sid": "Authorise",
"Effect": "Allow",
"Action": "verifiedpermissions:IsAuthorized",
"Resource": "arn:aws:verifiedpermissions::*:policy-store/*"
}
]
}
The  tenant  principal tag is set per request by assuming a tenant-scoped session ( sts:AssumeRole  with  Tags , and  sts:TagSession  in the trust policy) using the tenant from the verified token — never from a tool argument.

6.4 Egress (D7)

Network Firewall stateful rule group, domain list:
{
"RulesSource": {
"RulesSourceList": {
"Targets": ["<ticket-saas-domain>", "<cognito-domain>"],
"TargetTypes": ["TLS_SNI", "HTTP_HOST"],
"GeneratedRulesType": "ALLOWLIST"
}
}
}
with the firewall policy's stateful default action set to drop. DNS Firewall on the server's VPC: an ALLOW rule for the same two domains at a lower priority number, then a BLOCK rule for  *  returning NXDOMAIN. VPC endpoints carry every AWS API, so neither list names an AWS service.

6.5 The record (D8, D9)

One line per call:
{"ts":"2026-09-24T10:14:03Z","req":"7f3c…","sub":"a1b2…","client_id":"4k9…",
"session":"sha256:9e0…","tool":"search_tickets","args":"sha256:52d…",
"decision":"ALLOW","policies":["p-read-own-tenant"],"ms":212,"outcome":"ok"}
CloudWatch Logs metric filters on  decision = "DENY"  and  outcome = "error"  per tool, and an alarm on DENY rate per  sub  — one user being refused forty times a minute is either a broken agent or an injected one. The tool-list hash (D9) is logged at startup as  {"event":"tools","hash":"sha256:…"}  and compared to  /mcp/tools-hash/approved  in Parameter Store.

7. How we know it works — abuse tests

Each is an automated test against a deployed stage, and each maps to a decision. The suite runs on every deployment and blocks promotion on failure.
#
test
expected
proves
1
no  Authorization  header
401,  WWW-Authenticate  contains  resource_metadata= 
D2, discovery works
2
valid token from another resource server in the same pool
401
D2, passthrough refused
3
expired token, 31 s past  exp 
401
D2, skew bounded
4
an ID token instead of an access token
401
D2
5
user B's token on user A's session id
403
D3
6
a session idle for 16 minutes
session not found
D3
7
a browser-style cross-origin POST
refused
D4
8
5 MiB body
413
SDK default
9
every tool, called by a user with no permissions
every call DENY
D5, no handler skipped the check
10
 search_tickets  for another tenant's id, by argument
DENY at the policy, and AccessDenied at DynamoDB if the policy were bypassed
D5 and D6, two layers
11
from inside the task: a request to any public host not on the allowlist
connection fails
D7
12
from inside the task: resolve an unlisted name
NXDOMAIN
D7
13
change one tool description and deploy to the test stage
alarm fires
D9
14
 restart_deployment  by on-call
returns a task id; nothing restarts until approval
D10

8. Rollout

Each phase is worth shipping alone, in this order, because the earlier phases bound the damage of everything after them.
phase
ships
done when
1 — contain
private subnets, VPC endpoints, Network Firewall and DNS Firewall allowlists, the scoped task role
abuse tests 10–12 pass
2 — identify
Cognito resource server and app clients, the verifier,  UserID ,  SessionTimeout , cross-origin wrapper, protected resource metadata
tests 1–8 pass
3 — authorise
Verified Permissions schema and policies, the per-call check, the per-call log line
test 9 passes and every call has a log line
4 — detect
tool-list hash and alarm, DENY-rate alarm, human approval on the destructive tool, GuardDuty Runtime Monitoring on the cluster, Security Hub
tests 13–14 pass
Containment ships first, before identity, because it is the only phase that still helps when every other control has a bug.

9. Operations

  • Key rotation. The verifier caches the JWKS and refreshes on an unknown  kid ; Cognito's signing keys can rotate without a deployment.
  • Revocation. Cognito access tokens cannot be revoked individually once issued; keep their lifetime short (15–60 minutes) so that disabling a user takes effect within one lifetime, and revoke the refresh token.
  • Policy change. Verified Permissions policies change without a deploy; every change is a CloudTrail event, reviewed like code.
  • Incident. Pivot on  sub  or  session  in the call log; follow  req  into CloudTrail for the AWS calls the tool made.

10. Open questions

  1. Does Cognito now offer RFC 8693 token exchange? If it does, the server's calls to other MCP servers can carry the user rather than this server's identity, and D6 can be tightened. ( wish 2 )
  1. Is AgentCore Gateway's session binding documented well enough to replace D1? If so, the hosting burden goes away. ( wish 3 )
  1. Should raw arguments be retained at all? The current answer is seven days, for incident response; privacy review may say zero.
  1. What approves a tool-list hash change — the same pull request, or a separate security review? D9 detects; it does not decide.
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