Guide · AWS Application Signals · Lambda
AWS Application Signals for Lambda-Based MCP Servers — ADOT Layer, Handler Wrapping, and Cold Start
Lambda-based MCP servers can enable Application Signals without code changes by attaching the ADOT Lambda layer and setting two environment variables. The layer provides a wrapper script that intercepts the Lambda handler invocation, initializes OpenTelemetry auto-instrumentation, and exports spans and metrics through the Lambda Telemetry API — without requiring a sidecar container. This guide covers the ADOT layer ARN, the AWS_LAMBDA_EXEC_WRAPPER configuration, MCP protocol compatibility with function URLs, cold start impact, and how Lambda execution maps to Application Signals service operations.
TL;DR
Add the ADOT Lambda layer for Node.js to your function: arn:aws:lambda:REGION:901920570463:layer:aws-otel-nodejs-amd64-ver-1-18-1:4. Set AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-handler and OTEL_AWS_APPLICATION_SIGNALS_ENABLED=true as function environment variables. Set OTEL_RESOURCE_ATTRIBUTES=service.name=mcp-server,deployment.environment=production. The Lambda execution role needs xray:PutTraceSegments and cloudwatch:PutMetricData. See the overview guide for the API surface, SLO guide for reliability tracking, and ECS guide for the sidecar approach.
ADOT Lambda layer architecture
Unlike ECS where the ADOT collector runs as a sidecar container, Lambda auto-instrumentation uses a layer-based approach. The ADOT Lambda layer contains:
- A Node.js require hook (
/opt/nodejs/node_modules/@aws/aws-distro-opentelemetry-node-autoinstrumentation) that patches HTTP, AWS SDK, and database clients - An OpenTelemetry Collector embedded as a Lambda extension (
/opt/extensions/collector) — it runs in the same execution environment alongside your handler - A handler wrapper script (
/opt/otel-handler) that loads the auto-instrumentation before invoking your original handler
When AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-handler is set, Lambda invokes the wrapper script instead of your handler directly. The wrapper script exports NODE_OPTIONS=--require @aws/aws-distro-opentelemetry-node-autoinstrumentation/register and then execs your handler — equivalent to what you configure manually in ECS, but managed by the layer.
The embedded OpenTelemetry Collector uses the Lambda Telemetry API to receive spans from the Node.js SDK and flush them on function invocation lifecycle events. It exports to X-Ray for traces and to CloudWatch for Application Signals metrics. Because it runs as a Lambda extension, it has access to the same execution role as your handler — no separate credential configuration is needed.
ADOT Lambda layer ARN by region
The ADOT Lambda layer is published per region and per architecture. Use the layer ARN matching your function's region and architecture. The account 901920570463 is the AWS-managed ADOT layer account — it is consistent across all regions:
// Layer ARNs for Application Signals-enabled ADOT (Node.js, x86_64):
// Replace REGION with your function's region.
// Check https://github.com/aws-observability/aws-otel-lambda for current version numbers.
// x86_64 (amd64):
// arn:aws:lambda:REGION:901920570463:layer:aws-otel-nodejs-amd64-ver-1-18-1:4
// arm64:
// arn:aws:lambda:REGION:901920570463:layer:aws-otel-nodejs-arm64-ver-1-18-1:4
// To find the latest version for your region:
import { LambdaClient, ListLayerVersionsCommand } from "@aws-sdk/client-lambda";
const lambda = new LambdaClient({ region: process.env.AWS_REGION });
async function getLatestAdotLayerArn(architecture: "x86_64" | "arm64" = "x86_64") {
const arch = architecture === "arm64" ? "arm64" : "amd64";
const layerName = `aws-otel-nodejs-${arch}-ver-1-18-1`;
const response = await lambda.send(new ListLayerVersionsCommand({
LayerName: layerName,
CompatibleRuntime: "nodejs22.x"
}));
const latest = response.LayerVersions?.[0]; // sorted descending
if (!latest) throw new Error(`Layer ${layerName} not found in region ${process.env.AWS_REGION}`);
return latest.LayerVersionArn;
}
AWS updates the ADOT Lambda layer regularly with bug fixes and new OpenTelemetry versions. Pin to a specific version ARN in production to avoid unexpected behavior changes from automatic layer updates. Upgrade the layer ARN in a planned maintenance window after testing in staging.
Configuring a Lambda MCP server with Application Signals
The following example configures a Lambda function that serves MCP requests via function URL. The UpdateFunctionConfigurationCommand adds the ADOT layer and environment variables to an existing function:
import {
LambdaClient,
UpdateFunctionConfigurationCommand,
CreateFunctionUrlConfigCommand,
AddPermissionCommand
} from "@aws-sdk/client-lambda";
const lambda = new LambdaClient({ region: process.env.AWS_REGION });
async function enableApplicationSignalsOnLambda(functionName: string) {
const region = process.env.AWS_REGION!;
const accountId = process.env.AWS_ACCOUNT_ID!;
const adotLayerArn = `arn:aws:lambda:${region}:901920570463:layer:aws-otel-nodejs-amd64-ver-1-18-1:4`;
await lambda.send(new UpdateFunctionConfigurationCommand({
FunctionName: functionName,
Layers: [adotLayerArn],
Environment: {
Variables: {
// ADOT handler wrapper — must point to the layer's otel-handler script
AWS_LAMBDA_EXEC_WRAPPER: "/opt/otel-handler",
// Enable Application Signals CloudWatch metrics pipeline
OTEL_AWS_APPLICATION_SIGNALS_ENABLED: "true",
// Service identity for the Application Signals service map
OTEL_RESOURCE_ATTRIBUTES: `service.name=mcp-server,deployment.environment=production`,
// Propagators: xray for AWS trace context, tracecontext for W3C
OTEL_PROPAGATORS: "xray,tracecontext",
// Use X-Ray central sampling rules
OTEL_TRACES_SAMPLER: "xray"
}
}
}));
console.log(`Updated ${functionName} with ADOT layer and Application Signals config`);
}
// Lambda handler for MCP server (function URL mode):
// handler.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
let server: McpServer | null = null;
function getMcpServer(): McpServer {
if (!server) {
server = new McpServer({ name: "mcp-server", version: "1.0.0" });
server.tool("search", { query: z.string() }, async ({ query }) => {
const results = await performSearch(query);
return { content: [{ type: "text", text: JSON.stringify(results) }] };
});
server.tool("get-document", { id: z.string() }, async ({ id }) => {
const doc = await fetchDocument(id);
return { content: [{ type: "text", text: doc }] };
});
}
return server;
}
export const handler = async (
event: APIGatewayProxyEventV2
): Promise => {
const mcpServer = getMcpServer();
// The ADOT wrapper already loaded auto-instrumentation before this handler runs.
// All AWS SDK calls and HTTP requests inside tool handlers are traced automatically.
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => crypto.randomUUID()
});
await mcpServer.connect(transport);
const body = event.body ? JSON.parse(event.body) : undefined;
const headers: Record = {};
const response = await new Promise((resolve) => {
const mockReq = { headers: event.headers, body };
const mockRes = {
writeHead: (status: number, hdrs: Record) => {
Object.assign(headers, hdrs);
},
write: (chunk: string) => {},
end: (body?: string) => {
resolve({ statusCode: 200, headers, body: body ?? "" });
}
};
transport.handleRequest(mockReq as any, mockRes as any, body);
});
return response;
};
The MCP server instance is initialized outside the handler to take advantage of Lambda's execution environment reuse — subsequent warm invocations skip the server initialization. All tool definitions registered in getMcpServer() are instrumented by the ADOT wrapper because it runs before the first handler invocation.
Lambda execution role permissions
The Lambda execution role needs the same telemetry export permissions as the ECS task role, but without the CloudWatch Logs permissions (Lambda manages its own log delivery):
import { IAMClient, PutRolePolicyCommand } from "@aws-sdk/client-iam";
const iam = new IAMClient({ region: "us-east-1" });
await iam.send(new PutRolePolicyCommand({
RoleName: "mcp-server-lambda-execution-role",
PolicyName: "ApplicationSignalsPolicy",
PolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets"
],
Resource: "*"
},
{
Effect: "Allow",
Action: ["cloudwatch:PutMetricData"],
Resource: "*",
Condition: {
StringEquals: {
"cloudwatch:namespace": "AWS/ApplicationSignals"
}
}
}
]
})
}));
// Verify the function's current layers and environment:
import { GetFunctionConfigurationCommand } from "@aws-sdk/client-lambda";
const lambda = new LambdaClient({ region: process.env.AWS_REGION });
const config = await lambda.send(new GetFunctionConfigurationCommand({
FunctionName: "mcp-server-lambda"
}));
console.log("Layers:", config.Layers?.map(l => l.Arn));
console.log("Environment:", config.Environment?.Variables);
Cold start impact and mitigation
ADOT auto-instrumentation adds measurable cold start latency. The ADOT layer initializes the OpenTelemetry SDK, registers instrumentation hooks for http, AWS SDK, and database clients, and starts the embedded OTEL collector extension. On a typical Node.js Lambda function serving MCP requests, this adds 300-600ms to cold start duration.
Strategies to manage cold start latency with Application Signals enabled:
- Lambda SnapStart — Snapshots the execution environment after initialization, restoring from snapshot on subsequent cold starts. SnapStart effectively eliminates cold start latency for the ADOT SDK initialization because the snapshot includes the already-initialized SDK state. Use SnapStart for MCP server functions that must meet strict latency SLOs. Note: SnapStart is currently only supported for Java runtimes — for Node.js, consider Provisioned Concurrency instead.
- Provisioned Concurrency — Pre-warms a fixed number of execution environments, keeping them initialized. Set via
PutProvisionedConcurrencyConfigCommand. The ADOT initialization runs during provisioning and is not counted in the invocation latency. Use auto-scaling policies to scale provisioned concurrency with traffic patterns. - Reduce instrumentation scope — The ADOT auto-instrumentation package instruments every supported library. If your MCP server only uses AWS SDK and not, e.g., mongoose or redis, you can reduce load by setting
OTEL_NODE_DISABLED_INSTRUMENTATIONS=pg,mysql2,redis,mongodbto skip unused instrumentations.
import {
LambdaClient,
PutProvisionedConcurrencyConfigCommand,
PublishVersionCommand
} from "@aws-sdk/client-lambda";
const lambda = new LambdaClient({ region: process.env.AWS_REGION });
async function enableProvisionedConcurrency(functionName: string, concurrency: number) {
// First, publish a version (provisioned concurrency requires a specific version or alias)
const version = await lambda.send(new PublishVersionCommand({
FunctionName: functionName
}));
const functionVersion = version.Version!;
// Set provisioned concurrency on the version
await lambda.send(new PutProvisionedConcurrencyConfigCommand({
FunctionName: functionName,
Qualifier: functionVersion,
ProvisionedConcurrentExecutions: concurrency
}));
console.log(`Set ${concurrency} provisioned concurrency on ${functionName}:${functionVersion}`);
console.log("Pre-warming eliminates ADOT cold start latency for these execution environments");
}
Application Signals with Lambda function URLs for SSE
MCP servers increasingly use Server-Sent Events (SSE) for streaming tool responses. Lambda function URLs support streaming via RESPONSE_STREAM mode — but Application Signals tracing behavior differs for streaming vs standard invocations.
For streaming function URLs, the ADOT handler wrapper /opt/otel-handler wraps the standard Lambda handler. When the response body is a stream, the span is closed when the stream finishes. For long-running SSE connections that stream data over seconds or minutes, this means the trace span stays open for the full duration — which inflates latency metrics in Application Signals. This is technically correct (the operation did take that long) but can skew P99 latency numbers if most requests are fast but a few stream for many seconds.
import { LambdaClient, CreateFunctionUrlConfigCommand } from "@aws-sdk/client-lambda";
const lambda = new LambdaClient({ region: process.env.AWS_REGION });
// Configure function URL for streaming MCP responses
await lambda.send(new CreateFunctionUrlConfigCommand({
FunctionName: "mcp-server-lambda",
AuthType: "NONE", // Or "AWS_IAM" for authenticated access
InvokeMode: "RESPONSE_STREAM", // Required for SSE/streaming
Cors: {
AllowOrigins: ["*"],
AllowMethods: ["POST", "GET"],
AllowHeaders: ["content-type", "mcp-session-id"],
MaxAge: 86400
}
}));
// Lambda handler for streaming MCP (SSE-compatible):
// When using RESPONSE_STREAM, use awslambda.streamifyResponse wrapper
// This is compatible with ADOT's /opt/otel-handler wrapping.
// In your handler file:
export const handler = awslambda.streamifyResponse(async (event, responseStream, context) => {
// Set SSE headers
const metadataStream = awslambda.HttpResponseStream.from(responseStream, {
statusCode: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no"
}
});
// The MCP SSEServerTransport writes SSE events to the stream
// ADOT wraps this handler call and creates a span for the full stream duration
const transport = new SSEServerTransport("/mcp/message", metadataStream as any);
await mcpServer.connect(transport);
// Keep stream open while client is connected
await transport.waitForClose();
});
For MCP servers with mixed workloads (fast tool calls and long-running SSE streams), create separate Lambda functions: one for the SSE connection endpoint and one for the tool execution endpoint. This lets you define separate Application Signals SLOs for each — the connection SLO tracks connection establishment latency, while the tool execution SLO tracks individual tool completion time.
Lambda-specific Application Signals metrics
Lambda functions emit additional CloudWatch metrics that complement the Application Signals service-level metrics. Use both metric sources together for complete observability:
| Metric source | Namespace | Key metrics | Use for |
|---|---|---|---|
| Application Signals | AWS/ApplicationSignals |
Latency (P50/P90/P99), Fault, Error | Tool operation SLOs, service topology, end-to-end latency |
| Lambda platform | AWS/Lambda |
Duration, Errors, Throttles, ConcurrentExecutions, InitDuration | Concurrency limits, cold start frequency, throttle detection |
| X-Ray traces | (trace storage) | Subsegment durations per downstream call | Identifying slow DynamoDB queries, slow API calls within tools |
InitDuration in the AWS/Lambda namespace measures the cold start time for each invocation that required initialization. When Application Signals shows elevated P99 latency that is not explained by the trace subsegments (all individual operations look fast), check whether the P99 spike aligns with high InitDuration values — ADOT cold start is likely the culprit.
import { CloudWatchClient, GetMetricStatisticsCommand } from "@aws-sdk/client-cloudwatch";
const cw = new CloudWatchClient({ region: process.env.AWS_REGION });
async function getLambdaColdStartStats(functionName: string) {
const now = new Date();
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const response = await cw.send(new GetMetricStatisticsCommand({
Namespace: "AWS/Lambda",
MetricName: "InitDuration",
Dimensions: [{ Name: "FunctionName", Value: functionName }],
StartTime: yesterday,
EndTime: now,
Period: 3600,
Statistics: ["Maximum", "Average", "SampleCount"]
}));
const coldStarts = response.Datapoints?.filter(dp => (dp.SampleCount ?? 0) > 0) ?? [];
return {
totalColdStarts: coldStarts.reduce((sum, dp) => sum + (dp.SampleCount ?? 0), 0),
avgInitDurationMs: coldStarts.reduce((sum, dp) => sum + (dp.Average ?? 0), 0) / (coldStarts.length || 1),
maxInitDurationMs: Math.max(...coldStarts.map(dp => dp.Maximum ?? 0))
};
}
Common Lambda Application Signals issues and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Lambda function fails to start after adding ADOT layer | AWS_LAMBDA_EXEC_WRAPPER set to wrong path, or layer not attached |
Verify the layer ARN is listed in the function configuration (GetFunctionConfigurationCommand); confirm AWS_LAMBDA_EXEC_WRAPPER is exactly /opt/otel-handler (not /opt/otel-sqs-handler which is for SQS-triggered functions) |
| Handler wrapping breaks the Lambda streaming response | /opt/otel-handler does not support awslambda.streamifyResponse |
Use /opt/otel-handler for standard invocations; for streaming, check the ADOT release notes for streaming support. As a workaround, add manual OpenTelemetry spans to the streaming handler instead of using the exec wrapper |
| No Application Signals metrics appear despite X-Ray traces showing up | OTEL_AWS_APPLICATION_SIGNALS_ENABLED is not set or the embedded collector cannot write to CloudWatch |
Verify the environment variable is set; add cloudwatch:PutMetricData to the execution role with the AWS/ApplicationSignals namespace condition; check Lambda function logs for OTEL extension startup errors |
| Application Signals shows very high latency for all operations | ADOT cold start latency included in first-invocation traces | Use Provisioned Concurrency to eliminate cold starts; filter Application Signals SLOs to exclude InitDuration-heavy invocations by using the latency SLO with a threshold that accounts for occasional cold starts (e.g., 95th percentile SLO rather than 99th) |
| Layer version conflict — multiple layers trying to load OpenTelemetry | ADOT layer and another OpenTelemetry layer both attached | Use only the ADOT layer for Application Signals; remove any other OpenTelemetry Lambda layers (aws-otel-*, custom OTEL layers); duplicate SDK initialization causes span export failures and unpredictable sampling behavior |
OTEL_RESOURCE_ATTRIBUTES not propagating to Application Signals service map |
service.name attribute missing or misspelled |
The key-value format is strict: service.name=mcp-server,deployment.environment=production (no spaces around = or ,); if service.name is absent, Application Signals uses the Lambda function name as the service name instead |
Application Signals arc — related guides
This guide covers Lambda-specific Application Signals deployment. The arc also includes:
- AWS Application Signals overview — auto-instrumentation model, service topology, IAM permissions, and the core SDK APIs for querying service health
- Service Level Objectives with Application Signals — SLO creation, error budgets, burn-rate alarms, and per-tool SLO patterns using custom OpenTelemetry spans
- Application Signals for ECS Fargate MCP servers — ADOT sidecar container configuration, task definition environment variables, and ECS-specific IAM setup
Application Signals measures what happens inside a healthy Lambda invocation. For the complementary view — detecting when Lambda-based MCP servers become completely unavailable or return error responses from the client's perspective — AliveMCP provides active probe-based uptime monitoring with Slack and email alerting.