AI agents keep tripping over context limits because they don’t speak the Model Context Protocol (MCP). By the end of this guide you’ll have a real, deployable server that talks MCP‑fluently to Claude, so your assistant can call tools without a single manual hack.
What Is MCP and Why It Matters for AI Agents
MCP stands for Model Context Protocol. Think of it as a common language that lets a large language model (LLM) like Claude ask a downstream service to run a tool and receive a structured answer. Without MCP the model has to “explain” the tool call in plain text, and the surrounding code has to parse that text back into a request – a fragile round‑trip that often exceeds the model’s token budget.
In plain English: MCP is a tiny contract (JSON schema + HTTP semantics) that removes guesswork. The model says “run this tool with these arguments”, the server replies with a clean JSON payload, and the conversation can continue without re‑sending the whole prompt.
Why does this matter?
- Predictable token usage – The model only needs to embed the MCP request once, instead of repeating tool definitions.
- Reliability – The server validates the request against a TypeScript type, guaranteeing that the model cannot ask for something unsupported.
- Scalability – Multiple agents can share the same MCP endpoint; each one gets a deterministic response shape.
The rest of this post shows how to turn that idea into a production‑ready service using AWS CDK (Cloud Development Kit) and a tiny Node.js 22 Express server.
Bootstrapping a CDK Project for a Docker‑Based Service
Before any code runs we need a CDK workspace. CDK lets you describe AWS resources in familiar programming languages (here TypeScript) and then synthesize them into CloudFormation templates.
Why start with CDK?
- Infrastructure as code – Every piece (ECR repo, Fargate task, ALB) lives in source control.
- Repeatable builds – The same stack can be deployed to dev, test, or prod with a single command.
- Built‑in best practices – CDK adds IAM roles, security groups, and logging automatically.
Step‑by‑step bootstrap
-
Install the CDK CLI –
npm i -g aws-cdk. The CLI talks to your AWS account. -
Create a new project –
cdk init app --language=typescript. This scaffolds abin/entry point and alib/folder for stacks. -
Bootstrap the environment – CDK needs a small “bootstrap stack” that holds a bucket for assets and an IAM role for deployments. Run
cdk bootstrap aws://ACCOUNT_ID/REGION. > Tip: If you create a new region you must bootstrap it again; forgetting this is a common source of “AccessDenied” errors later.
Now we have a clean TypeScript project ready to hold our infrastructure code.
Known CDK gotchas (quick reference)
| Gotcha | What happens | How to avoid |
|---|---|---|
| Bootstrap missing | Deploy fails with “Missing bootstrap resources” | Run cdk bootstrap for each account/region you target |
| Large stacks | Deploy takes a long time, sometimes times out | Split resources into logical stacks (e.g., NetworkStack, AppStack) |
| Aspects misuse | Trying to modify a resource after synth silently does nothing |
Use Aspects only for read‑only inspections or add a postSynthesize hook |
| Resource limit (500) | CDK throws “Stack limit exceeded” | Group related resources into nested stacks |
| Token resolution | Some constructs produce “tokens” that can’t be used as plain strings | Use Fn.join, Lazy.string, or explicit cdk.Fn helpers when needed |
With the project ready, let’s write the service code that will live inside a Docker image.
Writing the Node.js 22 Express App that Implements the MCP Endpoint
Why use Express?
Express is a minimal web framework that lets us define a single POST /mcp route with only a few lines. It runs on Node.js 22, the LTS version that ships with built‑in fetch support, making it easy to call Claude’s Bedrock endpoint.
Defining the MCP request shape
MCP expects a JSON payload that looks roughly like:
{
"tool_name": "search",
"arguments": { "query": "latest CDK patterns" }
}
In TypeScript we can describe this shape with an interface and then use the satisfies operator to tell the compiler “this object must match the interface, but don’t narrow the type”.
// src/mcpTypes.ts
/** The exact shape the model will send when it wants a tool executed. */
export interface McpRequest {
/** Name of the tool the model wants to run (e.g. "search", "summarize") */
tool_name: string;
/** Arbitrary key‑value map of arguments the tool needs */
arguments: Record<string, unknown>;
}
The Express server
// src/server.ts
import express from "express";
import { McpRequest } from "./mcpTypes";
import { BedrockClient, InvokeModelCommand } from "@aws-sdk/client-bedrock-runtime";
const app = express();
// Built‑in JSON body parser (Express 4.18+)
app.use(express.json());
// Create a Bedrock client once – reuse the connection for every request
const bedrock = new BedrockClient({ region: process.env.AWS_REGION });
/**
* POST /mcp – receives a model‑generated tool request, forwards it to Claude,
* and returns the structured response.
*/
app.post("/mcp", async (req, res) => {
// Validate the shape at runtime – TypeScript only checks at compile time
const payload = req.body as unknown;
// Quick manual guard (in production you might use a schema library)
if (
typeof payload !== "object" ||
payload === null ||
!("tool_name" in payload) ||
!("arguments" in payload)
) {
return res.status(400).json({ error: "Invalid MCP payload" });
}
// Tell TypeScript that payload satisfies our interface
const mcpReq = payload satisfies McpRequest;
// Build the request we send to Claude via Bedrock
const command = new InvokeModelCommand({
modelId: "anthropic.claude-3-5-sonnet-20240620", // example model
// The model expects a JSON string in the body
body: JSON.stringify({
// The MCP spec for Claude – we wrap the tool request in a known field
messages: [{ role: "user", content: JSON.stringify(mcpReq) }],
}),
contentType: "application/json",
accept: "application/json",
});
try {
const response = await bedrock.send(command);
// Bedrock returns a Uint8Array; turn it into a string then JSON
const responseBody = Buffer.from(response.body).toString("utf-8");
const parsed = JSON.parse(responseBody);
// Forward Claude's structured answer back to the caller
res.json(parsed);
} catch (err) {
console.error("Error invoking Claude:", err);
res.status(500).json({ error: "Failed to call Claude" });
}
});
// Start the server – the port will be injected by the Fargate task definition
const PORT = process.env.PORT ?? 8080;
app.listen(PORT, () => {
console.log(`MCP server listening on port ${PORT}`);
});
Explanation of key lines
| Line | Reason |
|---|---|
app.use(express.json()) |
Tells Express to parse incoming JSON bodies automatically. |
payload satisfies McpRequest |
Guarantees at compile time that the object conforms to our MCP schema without altering its runtime shape. |
new BedrockClient({ region }) |
Creates an AWS SDK client that talks to the Bedrock service where Claude lives. |
InvokeModelCommand |
The low‑level Bedrock API to run a model with a JSON payload. |
Buffer.from(response.body) |
Bedrock returns raw bytes; we need a string to parse as JSON. |
Analogy: Think of the MCP endpoint as a translator booth at a conference. The model hands the booth a request in its own shorthand; the booth checks the request, passes it to the expert (Claude), then hands back a clean transcript.
Now we have a runnable Node app. The next step is to containerize it and let CDK handle the rest.
Defining an ECR Repository and Fargate Service in CDK
Why ECR and Fargate?
- ECR (Elastic Container Registry) stores Docker images securely within AWS, giving us versioned artifacts that CDK can reference.
- Fargate runs containers without us managing servers; it automatically scales and integrates with an Application Load Balancer (ALB) for HTTP traffic.
The CDK stack
Create a new file lib/ClaudeMcpStack.ts:
// lib/ClaudeMcpStack.ts
import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import {
DockerImageAsset,
} from "aws-cdk-lib/aws-ecr-assets";
import {
ApplicationLoadBalancedFargateService,
ApplicationLoadBalancedFargateServiceProps,
} from "aws-cdk-lib/aws-ecs-patterns";
import { Repository } from "aws-cdk-lib/aws-ecr";
export class ClaudeMcpStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// -------------------------------------------------------------------------
// 1️⃣ Create an ECR repository that will hold our Docker image
// -------------------------------------------------------------------------
const repo = new Repository(this, "McpRepository", {
repositoryName: "claude-mcp-server",
// Optionally enable image scan on push for security
imageScanOnPush: true,
});
// -------------------------------------------------------------------------
// 2️⃣ Build the Docker image from the local source directory
// -------------------------------------------------------------------------
const imageAsset = new DockerImageAsset(this, "McpImage", {
directory: "../", // assumes Dockerfile sits at repository root
// IMPORTANT GOTCHA: DockerImageAsset only rebuilds when the Dockerfile
// changes. If you edit only a .ts file the image may stay stale.
// Adding a dummy ARG forces a rebuild when source changes:
buildArgs: {
// Increment this number whenever you change the app code
BUILD_NUMBER: process.env.BUILD_NUMBER ?? "1",
},
});
// -------------------------------------------------------------------------
// 3️⃣ Grant the Fargate task permission to pull from the repository
// -------------------------------------------------------------------------
repo.grantPull(imageAsset.repository.grantPrincipal);
// -------------------------------------------------------------------------
// 4️⃣ Deploy the container as a load‑balanced Fargate service
// -------------------------------------------------------------------------
const fargateProps: ApplicationLoadBalancedFargateServiceProps = {
// The VPC is automatically created if you omit it (default)
taskImageOptions: {
// Use the image we just built
image: cdk.aws_ecs.ContainerImage.fromDockerImageAsset(imageAsset),
// Container port matches what Express listens on
containerPort: 8080,
// Pass environment variables – the Bedrock client reads AWS_REGION
environment: {
AWS_REGION: this.region,
},
// Optionally allocate more memory/CPU for heavy traffic
cpu: 512,
memoryLimitMiB: 1024,
},
// Public load balancer so we can reach it from the internet
publicLoadBalancer: true,
};
const service = new ApplicationLoadBalancedFargateService(
this,
"McpFargateService",
fargateProps,
);
// -------------------------------------------------------------------------
// 5️⃣ Output the service URL – useful for testing
// -------------------------------------------------------------------------
new cdk.CfnOutput(this, "McpEndpoint", {
value: `https://${service.loadBalancer.loadBalancerDnsName}/mcp`,
description: "Public URL for the MCP endpoint",
});
}
}
Dockerfile (placed at repository root)
# Use the official Node.js 22 image (lightweight LTS)
FROM node:22-alpine AS builder
# Set working directory
WORKDIR /app
# Install only production dependencies
COPY package*.json ./
RUN npm ci --omit=dev
# Copy source files
COPY . .
# Build TypeScript (if you have a build step)
RUN npm run build
# Runtime stage – smaller image
FROM node:22-alpine
WORKDIR /app
# Copy only compiled output and node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
# Expose the port the Express app listens on
EXPOSE 8080
# Command to start the server
CMD ["node", "dist/server.js"]
Explaining the cache gotcha
Key takeaway:
DockerImageAssetdecides whether to rebuild the image by hashing the Dockerfile and the build context. If you modify only a.tsfile, the Dockerfile checksum stays the same, so CDK may reuse the previous image. Adding a dummyARG(likeBUILD_NUMBER) that you bump each time forces a cache miss, guaranteeing the newest code runs in production.
Secondary service context – ECR
We use the @aws-sdk/client-ecr package when we need to interact with the repository programmatically (e.g., cleaning up old images).
| Gotcha | Symptom | Fix |
|---|---|---|
Rate‑limit on BatchDeleteImage |
CI pipeline fails after many deployments | Throttle calls or use lifecycle policies in the repo to prune old images automatically |
Missing permissions for ecr:GetAuthorizationToken |
Fargate task cannot pull the image | Add an IAM policy to the task execution role granting ecr:GetAuthorizationToken and ecr:BatchGetImage
|
Now the stack is ready to be synthesized and deployed.
# From the CDK project root
cdk synth # Generates CloudFormation template
cdk deploy # Deploys the stack, building the Docker image first
When the deployment finishes, CDK prints the McpEndpoint output – copy that URL; we’ll use it in the next section.
Calling Claude’s /mcp Endpoint from Your Agent and Verifying Tool Calls
Why test with a real agent?
The whole point of MCP is to let the language model orchestrate tools. By invoking the endpoint from a minimal agent script we can confirm that:
- The request conforms to the MCP schema.
- Claude receives the request and returns a structured tool response.
- Our Express server correctly forwards that response back to the caller.
Minimal agent script (Node.js)
// agent-test.js
import fetch from "node-fetch";
// Replace with the URL printed by CDK
const MCP_URL = "https://xxxxxx.elb.amazonaws.com/mcp";
async function callMcp(toolName, args) {
const payload = {
tool_name: toolName,
arguments: args,
};
const response = await fetch(MCP_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(`MCP call failed: ${response.status}`);
}
const data = await response.json();
console.log("Claude replied:", JSON.stringify(data, null, 2));
}
// Example: ask Claude to perform a web search (the tool is just illustrative)
await callMcp("search", { query: "CDK best practices 2024" });
Run the script:
node agent-test.js
You should see a JSON object that contains Claude’s answer, for example:
{
"tool_result": "Here are three best‑practice areas ...",
"metadata": {
"model": "anthropic.claude-3-5-sonnet-20240620",
"usage": { "input_tokens": 120, "output_tokens": 45 }
}
}
If you get an error like “Invalid MCP payload”, double‑check that the field names match the McpRequest interface exactly (case‑sensitive).
Tip: Use
curlwith-vto inspect raw request/response when troubleshooting network issues.
The Takeaway
- MCP is a tiny, well‑defined contract that lets Claude invoke external tools without bloating the model’s prompt.
- CDK provides a declarative way to spin up an ECR repository, build a Docker image, and run it on Fargate behind an ALB.
- DockerImageAsset caching can hide code changes; adding a dummy build argument (or touching the Dockerfile) forces a rebuild.
-
Bootstrapping each region with
cdk bootstrapis mandatory; otherwise deployments fail with missing resources. -
The Express server validates the payload using TypeScript’s
satisfiesoperator, ensuring the model cannot send malformed requests. - A simple agent script proves end‑to‑end flow, confirming that Claude receives the request, processes it, and returns a structured response that your application can consume.
You now have a fully functional, cloud‑native MCP server that can be extended with additional tools, versioned via Docker, and managed through code. Happy building!
Transparency notice
This article was written with the help of an AI system — Groq (GPT OSS 120B).
Published: 2026-11-19 · Primary focus: CDK
All code blocks are intended to be correct and runnable, but please verify them
against the official docs for the tools mentioned before using in production.Find an error? Drop a comment — corrections are always welcome.
Top comments (0)