Guide · Amazon EC2 · Deployment and Operations

Running MCP Servers on Amazon EC2 — Instance Profiles, IMDSv2, and Security Groups

Amazon EC2 is the most common compute platform for self-hosted MCP servers: direct control over instance type, networking, OS, and runtime without the abstraction layers of App Runner or ECS. The tradeoffs are real — you manage patching, bootstrapping, and process supervision — but EC2 gives you the lowest per-hour cost at sustained load, the most flexibility for custom networking, and no cold starts. This guide covers the essential production patterns: instance profile setup so the AWS SDK automatically inherits credentials from the metadata service, IMDSv2 enforcement to block SSRF-based credential theft, security group rules for MCP server ports, instance type selection, EBS volume configuration, and SSM Session Manager as a key-pair-free alternative to SSH.

TL;DR

Attach an IAM instance profile to your EC2 instance — the AWS SDK credential chain picks it up automatically with no hardcoded keys. Enforce IMDSv2 at instance launch (HttpTokens: required) to prevent SSRF attacks from stealing credentials via the metadata endpoint. Open inbound on your MCP port (commonly 3000 or 8080) from your load balancer SG only — not 0.0.0.0/0. Use SSM Session Manager for shell access; avoid opening port 22 entirely. For MCP server workloads: t4g.small for dev (ARM, $0.0168/hr), m7g.medium or m7g.large for production.

Instance profiles — SDK credential chain on EC2

An instance profile is an IAM role that is attached to an EC2 instance. When your Node.js MCP server uses the AWS SDK, the default credential provider chain automatically fetches temporary credentials from the EC2 instance metadata service (IMDS) — no AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment variables required.

# 1. Create the IAM role that the MCP server will assume
aws iam create-role \
  --role-name mcp-server-role \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }]
  }'

# 2. Attach permissions the MCP server needs
aws iam attach-role-policy \
  --role-name mcp-server-role \
  --policy-arn arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess

# 3. Create an instance profile and add the role to it
aws iam create-instance-profile \
  --instance-profile-name mcp-server-profile

aws iam add-role-to-instance-profile \
  --instance-profile-name mcp-server-profile \
  --role-name mcp-server-role

When launching, pass the instance profile by name or ARN:

aws ec2 run-instances \
  --image-id ami-0abcdef1234567890 \
  --instance-type t4g.small \
  --iam-instance-profile Name=mcp-server-profile \
  --metadata-options HttpTokens=required,HttpEndpoint=enabled \
  --security-group-ids sg-mcp-server \
  --key-name "" \          # No key pair needed with SSM Session Manager
  --user-data file://bootstrap.sh

The SDK on the instance finds credentials in this order: environment variables → ~/.aws/credentials → instance metadata. On EC2 with an instance profile, it hits the metadata endpoint and gets short-lived credentials that rotate automatically every hour. Never hardcode AWS credentials in your MCP server source code or environment file.

IMDSv2 — blocking SSRF credential theft

The original instance metadata service (IMDSv1) allows any process on the instance — including server-side request forgery (SSRF) payloads from tool inputs — to query http://169.254.169.254/latest/meta-data/iam/security-credentials/ and steal the instance role's temporary credentials. IMDSv2 requires a session-oriented token exchange before metadata access, blocking unauthenticated GET requests to the metadata endpoint.

Enforce IMDSv2 at launch with HttpTokens: required (shown above). To enforce it on an already-running instance:

aws ec2 modify-instance-metadata-options \
  --instance-id i-0abc123def456 \
  --http-tokens required \
  --http-endpoint enabled \
  --http-put-response-hop-limit 1

The --http-put-response-hop-limit 1 ensures that only processes on the instance itself (hop count 1) can reach the metadata endpoint. Containers with an extra network hop get a hop count of 2, which you need to increase to 2 if running Docker containers that use instance credentials — but for a bare MCP server process, hop limit 1 is correct.

The SDK automatically uses IMDSv2. If you query the metadata endpoint in shell scripts (e.g., user data), use the two-step token exchange:

#!/bin/bash
# IMDSv2 token (TTL 21600 seconds = 6 hours)
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")

# Use token for all metadata queries
REGION=$(curl -s \
  -H "X-aws-ec2-metadata-token: $TOKEN" \
  "http://169.254.169.254/latest/meta-data/placement/region")

INSTANCE_ID=$(curl -s \
  -H "X-aws-ec2-metadata-token: $TOKEN" \
  "http://169.254.169.254/latest/meta-data/instance-id")

echo "Region: $REGION, Instance: $INSTANCE_ID"

Security groups for MCP servers

MCP servers typically accept HTTP/HTTPS connections on port 3000, 8080, or 443. The correct security group configuration depends on whether the instance sits behind a load balancer (ALB) or is accessed directly.

# Create the MCP server security group
aws ec2 create-security-group \
  --group-name mcp-server-sg \
  --description "MCP server inbound rules" \
  --vpc-id vpc-12345678

# If behind an ALB: allow inbound MCP port from ALB SG only
aws ec2 authorize-security-group-ingress \
  --group-id sg-mcp-server \
  --protocol tcp \
  --port 3000 \
  --source-group sg-alb  # ALB security group ID, not 0.0.0.0/0

# Allow all outbound (for AWS API calls to DynamoDB, S3, Secrets Manager, etc.)
# Default security group already allows all egress; verify:
aws ec2 describe-security-groups \
  --group-ids sg-mcp-server \
  --query 'SecurityGroups[0].IpPermissionsEgress'

Do not open port 22 (SSH) unless you have a specific operational need. Use SSM Session Manager instead — it requires no open inbound port at all.

If your MCP server calls private AWS services (RDS, ElastiCache, DocumentDB) in the same VPC, add inbound rules on those services' security groups to accept traffic from sg-mcp-server:

# Allow MCP server SG to reach RDS on port 5432
aws ec2 authorize-security-group-ingress \
  --group-id sg-rds \
  --protocol tcp \
  --port 5432 \
  --source-group sg-mcp-server

Instance type selection

MCP servers are CPU-light and memory-moderate workloads — most tool execution is I/O-bound waiting on AWS API calls or database queries. ARM-based Graviton instances (t4g, m7g, c7g) offer 20–40% better price/performance than equivalent x86 instances for I/O-bound Node.js workloads.

InstancevCPURAMOn-demand priceUse case
t4g.small22 GB$0.0168/hr (~$12/mo)Dev, staging, single-tool MCP servers with <10 req/s
t4g.medium24 GB$0.0336/hr (~$24/mo)Dev/staging with larger Node.js heap or Redis co-location
m7g.medium14 GB$0.0453/hr (~$33/mo)Low-traffic production — dedicated vCPU, no burst credits
m7g.large28 GB$0.0906/hr (~$66/mo)Production with <100 concurrent sessions
m7g.xlarge416 GB$0.1813/hr (~$131/mo)Multi-tool MCP servers with heavy parallel tool execution
c7g.large24 GB$0.0725/hr (~$52/mo)CPU-intensive tools (cryptography, compression, large JSON parsing)

t4g instances use CPU credits — burstable performance from a baseline. Under sustained CPU load (e.g., many concurrent tool calls with heavy JSON transformation), t4g credits deplete and performance drops. If your MCP server regularly spikes above 20% CPU for more than a few minutes, switch to m7g (non-burstable). Monitor CPUCreditBalance in CloudWatch to detect credit depletion before it becomes a production issue.

EBS volume configuration

The default EC2 root volume is an 8 GB gp3 EBS volume. For MCP servers, the main storage considerations are:

gp3 volumes have a free baseline of 3,000 IOPS and 125 MB/s throughput regardless of size. You can provision up to 16,000 IOPS and 1,000 MB/s independently of size (extra cost). For MCP servers there is no need to provision extra IOPS — the gp3 baseline handles most workloads.

aws ec2 run-instances \
  --instance-type m7g.large \
  --block-device-mappings '[{
    "DeviceName": "/dev/xvda",
    "Ebs": {
      "VolumeSize": 30,
      "VolumeType": "gp3",
      "Encrypted": true,
      "DeleteOnTermination": true
    }
  }]'

SSM Session Manager — shell access without port 22

AWS Systems Manager Session Manager provides interactive shell access to EC2 instances over HTTPS without requiring an open SSH port, a key pair, or a bastion host. The SSM agent (pre-installed on Amazon Linux 2023 and Ubuntu 22.04 AMIs) connects outbound to the SSM service endpoint — no inbound port required.

Requirements: attach AmazonSSMManagedInstanceCore managed policy to the instance role:

aws iam attach-role-policy \
  --role-name mcp-server-role \
  --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore

Connect from your terminal:

# Install the Session Manager plugin for AWS CLI first:
# https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html

aws ssm start-session --target i-0abc123def456

# Or port-forward the MCP server port for local testing:
aws ssm start-session \
  --target i-0abc123def456 \
  --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["3000"],"localPortNumber":["3000"]}'

Session Manager logs every session to CloudWatch Logs (configure in SSM console under Session Manager preferences → CloudWatch logging). This gives you a complete audit trail of who ran which commands on the instance — better than SSH logs.

Elastic IP for stable MCP server addressing

EC2 public IP addresses change when an instance is stopped and restarted. If you expose your MCP server directly (without an ALB), allocate an Elastic IP for a stable address:

# Allocate an Elastic IP
ALLOC=$(aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text)

# Associate with the instance
aws ec2 associate-address \
  --instance-id i-0abc123def456 \
  --allocation-id $ALLOC

Elastic IPs are free when associated with a running instance. You are charged $0.005/hr for unassociated Elastic IPs (allocated but not in use) and additional charges for extra IPs beyond one per instance. Release EIPs when you terminate instances.

For production MCP servers, prefer an ALB over a bare Elastic IP — the ALB handles TLS termination, health checks, and traffic shifting for zero-downtime deployments.

IAM permissions summary

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "MCPServerAWSAccess",
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Query",
        "dynamodb:UpdateItem",
        "s3:GetObject",
        "s3:PutObject",
        "secretsmanager:GetSecretValue",
        "ssm:GetParameter",
        "ssm:GetParameters"
      ],
      "Resource": [
        "arn:aws:dynamodb:us-east-1:ACCOUNT_ID:table/mcp-*",
        "arn:aws:s3:::mcp-artifacts-bucket/*",
        "arn:aws:secretsmanager:us-east-1:ACCOUNT_ID:secret:mcp/*",
        "arn:aws:ssm:us-east-1:ACCOUNT_ID:parameter/mcp/*"
      ]
    },
    {
      "Sid": "SSMSessionManager",
      "Effect": "Allow",
      "Action": [
        "ssm:UpdateInstanceInformation",
        "ssmmessages:CreateControlChannel",
        "ssmmessages:CreateDataChannel",
        "ssmmessages:OpenControlChannel",
        "ssmmessages:OpenDataChannel"
      ],
      "Resource": "*"
    }
  ]
}

The AmazonSSMManagedInstanceCore managed policy covers all SSM permissions. If you prefer to inline everything, the SSMSessionManager statement above is the minimum needed for Session Manager shell access.

Common errors and fixes

ErrorCauseFix
Unable to locate credentials in SDKInstance launched without an instance profile, or profile not yet propagatedAttach instance profile; wait 30–60s for IAM propagation; verify aws sts get-caller-identity from the instance shell
Not authorized to perform: sts:AssumeRoleTrust policy on the IAM role does not include ec2.amazonaws.com as principalUpdate trust policy to include "Service": "ec2.amazonaws.com"
Metadata requests return 401 UnauthorizedIMDSv2 required but code uses IMDSv1 (GET without token header)SDK v3 uses IMDSv2 by default; check custom metadata scripts use the two-step token exchange
SSM Session Manager shows instance as offlineInstance role missing AmazonSSMManagedInstanceCore, SSM agent not running, or no outbound HTTPSAttach policy; verify systemctl status amazon-ssm-agent; ensure egress on port 443 to ssm.us-east-1.amazonaws.com
MCP server port unreachable from ALBSecurity group inbound rule missing, or rule allows wrong sourceSource should be ALB security group ID (not CIDR); verify aws ec2 describe-security-groups --group-ids sg-mcp-server
CPU credit balance depleted (t4g)Sustained CPU usage exceeds baseline on burstable instanceSwitch to m7g equivalent; monitor CPUCreditBalance CloudWatch metric with alarm at <10 credits

Related guides