Amazon DevOps Guru · ML Anomaly Detection, Resource Collection, Insights & Notifications · 2026-11-21 · DevOps Guru arc

Amazon DevOps Guru for MCP Servers: ML Anomaly Detection, Ten Setup Gotchas, and a Complete Notification Pipeline

MCP server operators who rely exclusively on hand-written CloudWatch alarms are flying blind on the failure modes they haven't anticipated yet. Amazon DevOps Guru fills that gap with ML-powered anomaly detection: it baselines the normal behavior of your ECS services, Lambda functions, SQS queues, and DynamoDB tables, then generates insights when any resource deviates from that baseline in ways you never thought to threshold-alarm on. But the service has a learning curve — it is not a GuardDuty-style toggle, it has a silent-failure trap in its SNS notification path that affects almost every first-time setup, and its ListInsights API has a date-object requirement that crashes code using epoch integers. This guide synthesises the full DevOps Guru arc for MCP server developers: how to activate resource collection for CloudFormation and Terraform deployments, the distinction between ReactiveInsight (something is wrong now) and ProactiveInsight (something is about to go wrong), how to query and triage insights with the CAUSAL/CONTEXTUAL anomaly model, and how to build a notification pipeline that actually fires when your infrastructure degrades.

Why static CloudWatch alarms cannot protect an MCP server

The standard monitoring approach for a production MCP server starts with the obvious CloudWatch alarms: CPU above 80%, memory above 85%, 5XX error rate above 1%, SQS queue depth above 1,000. You write these alarms when you deploy, test them once, and then largely forget about them until something breaks.

The problem is not the alarms themselves — it is what they cannot see. MCP servers fail in ways that do not fit neatly into static thresholds on a handful of obvious metrics. Consider these real failure patterns:

These failure modes require a different kind of monitoring: one that learns what "normal" looks like for your specific deployment and flags deviations from that learned baseline, not from a threshold you guessed when you deployed six months ago. That is exactly what Amazon DevOps Guru provides.

DevOps Guru ingests CloudWatch metrics for the AWS resources you configure it to monitor, builds a statistical model of normal behavior for each resource, and generates insights when it detects anomalous patterns. It also groups correlated anomalies across related resources — when your ECS CPU spikes, your SQS queue depth builds, and your Lambda handler throttle count rises simultaneously, DevOps Guru surfaces these as a single insight with a CAUSAL anomaly (the root cause it identified) and CONTEXTUAL anomalies (downstream symptoms), plus actionable remediation recommendations. What would otherwise be three independent alarms that an on-call engineer must manually correlate becomes a single, pre-analyzed incident report.

Gotcha #1: DevOps Guru is not auto-enabled — you must call UpdateResourceCollection

The first thing most developers get wrong about DevOps Guru is assuming it activates when you enable it in the console, like GuardDuty does. It does not. Clicking "Enable DevOps Guru" in the console and choosing a coverage scope is equivalent to calling UpdateResourceCollection programmatically — but until that call is made, DevOps Guru does nothing and costs nothing.

There are three collection modes:

For a CloudFormation-managed MCP server deployment:

import {
  DevOpsGuruClient,
  UpdateResourceCollectionCommand,
  DescribeAccountHealthCommand,
} from "@aws-sdk/client-devops-guru";

const devopsGuru = new DevOpsGuruClient({ region: "us-east-1" });

// Activate DevOps Guru monitoring for your MCP server stack.
// This triggers creation of AWSServiceRoleForDevOpsGuru on first call.
async function enrollMcpServerStack(stackName: string): Promise<void> {
  await devopsGuru.send(
    new UpdateResourceCollectionCommand({
      Action: "ADD",
      ResourceCollection: {
        CloudFormation: {
          StackNames: [stackName], // e.g., "mcp-server-prod"
        },
      },
    })
  );

  // Verify resource-hours are accumulating (will be 0 initially).
  const health = await devopsGuru.send(new DescribeAccountHealthCommand({}));
  console.log("Resources under monitoring:", health.ResourceHours);
  console.log("Open reactive insights:", health.OpenReactiveInsights);
}

For Terraform-managed infrastructure, use tag-based collection instead. Apply the tag to every resource you want monitored:

# Terraform: tag all MCP server resources for DevOps Guru coverage
resource "aws_ecs_service" "mcp_server" {
  name = "mcp-server"
  # ... other config ...
  tags = {
    "devops-guru-resource-collection" = "mcp-server-prod"
  }
}

resource "aws_sqs_queue" "tool_queue" {
  name = "mcp-tool-queue"
  tags = {
    "devops-guru-resource-collection" = "mcp-server-prod"
  }
}

Then enroll the tag boundary:

async function enrollTagBasedCollection(): Promise<void> {
  await devopsGuru.send(
    new UpdateResourceCollectionCommand({
      Action: "ADD",
      ResourceCollection: {
        Tags: [{
          AppBoundaryKey: "devops-guru-resource-collection",
          TagValues: ["mcp-server-prod"],
        }],
      },
    })
  );
}

See DevOps Guru Resource Collection for the complete reference on collection modes, limits, and removal procedures.

Gotcha #2: Stack names, not ARNs (ValidationException)

UpdateResourceCollectionCommand takes the stack name in the StackNames array — not the full CloudFormation stack ARN. Passing an ARN string throws a ValidationException:

// ❌ Wrong — throws ValidationException
await devopsGuru.send(new UpdateResourceCollectionCommand({
  Action: "ADD",
  ResourceCollection: {
    CloudFormation: {
      StackNames: ["arn:aws:cloudformation:us-east-1:123456789012:stack/mcp-server-prod/abc123"],
    },
  },
}));

// ✅ Correct — stack name only
await devopsGuru.send(new UpdateResourceCollectionCommand({
  Action: "ADD",
  ResourceCollection: {
    CloudFormation: {
      StackNames: ["mcp-server-prod"],
    },
  },
}));

The stack must exist in the same region as the DevOps Guru client. If your MCP server runs in multiple regions, instantiate a separate DevOpsGuruClient for each region and configure resource collection independently in each one.

Gotcha #3: First call requires iam:CreateServiceLinkedRole

The first call to UpdateResourceCollection creates the AWSServiceRoleForDevOpsGuru service-linked role if it does not already exist. If your calling principal lacks iam:CreateServiceLinkedRole, the call fails with an AccessDeniedException even though the DevOps Guru action itself is permitted.

The required IAM policy for initial setup:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DevOpsGuruManage",
      "Effect": "Allow",
      "Action": [
        "devops-guru:UpdateResourceCollection",
        "devops-guru:GetResourceCollection",
        "devops-guru:ListInsights",
        "devops-guru:GetInsight",
        "devops-guru:ListAnomaliesForInsight",
        "devops-guru:GetRecommendations",
        "devops-guru:PutFeedback",
        "devops-guru:DescribeAccountHealth",
        "devops-guru:DescribeAccountOverview",
        "devops-guru:AddNotificationChannel",
        "devops-guru:ListNotificationChannels",
        "devops-guru:RemoveNotificationChannel",
        "devops-guru:UpdateServiceIntegration",
        "devops-guru:DescribeServiceIntegration"
      ],
      "Resource": "*"
    },
    {
      "Sid": "DevOpsGuruServiceLinkedRole",
      "Effect": "Allow",
      "Action": "iam:CreateServiceLinkedRole",
      "Resource": "arn:aws:iam::*:role/aws-service-role/devops-guru.amazonaws.com/AWSServiceRoleForDevOpsGuru",
      "Condition": {
        "StringLike": {
          "iam:AWSServiceName": "devops-guru.amazonaws.com"
        }
      }
    }
  ]
}

If you cannot grant iam:CreateServiceLinkedRole to your automation principal, pre-create the service-linked role manually before running your Terraform or CDK pipeline:

aws iam create-service-linked-role \
  --aws-service-name devops-guru.amazonaws.com

After the role exists, subsequent UpdateResourceCollection calls do not require iam:CreateServiceLinkedRole.

Gotcha #4: Tag propagation delay and ECS service vs task definition

Two related gotchas affect tag-based coverage for ECS Fargate MCP server deployments.

15-minute tag discovery delay: After you tag resources and enroll the AppBoundaryKey in DevOps Guru's collection, it takes up to 15 minutes for DevOps Guru to discover newly tagged resources and begin ingesting their metrics. Do not expect immediate coverage after a Terraform apply — the resources will not appear in DevOps Guru's coverage until the discovery cycle completes.

ECS tag must be on the service, not the task definition: DevOps Guru discovers ECS coverage from the ECS service resource, not from the task definition. This distinction matters for CDK users who might apply tags at the TaskDefinition construct level:

// CDK — tag the service, not just the task definition
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as cdk from "aws-cdk-lib";

const taskDefinition = new ecs.FargateTaskDefinition(this, "McpTask", {
  // ...
});

const service = new ecs.FargateService(this, "McpService", {
  cluster,
  taskDefinition,
  // ...
});

// Apply the tag to the SERVICE construct, not just the task def.
// Tags.of(this) on the entire stack also works and is simpler.
cdk.Tags.of(service).add(
  "devops-guru-resource-collection",
  "mcp-server-prod"
);

// Alternative: tag the entire stack (applies to all resources recursively)
cdk.Tags.of(this).add(
  "devops-guru-resource-collection",
  "mcp-server-prod"
);

Nested stacks not auto-included: If your CDK app uses nested stacks, DevOps Guru's stack-based collection only monitors resources in the enrolled parent stack — it does not recursively descend into nested stacks. Enroll each nested stack explicitly by name when using stack-based collection mode. With tag-based collection, resources in nested stacks are covered as long as the tag is applied to them.

ReactiveInsight vs ProactiveInsight: how DevOps Guru decides what to generate

Understanding the two insight types prevents confusion when triaging alerts. They serve different purposes and have different prerequisites.

A ReactiveInsight is generated when DevOps Guru detects that an anomaly has already occurred or is currently happening on one of your monitored resources. The metrics have already deviated from their learned baseline. The insight status is ONGOING while the anomaly is active and transitions to CLOSED automatically when metrics return to normal. For MCP servers, reactive insights fire when things are actively failing — elevated Lambda throttle rates during a traffic spike, SQS queue depth building while a tool handler is stuck processing a malformed message, ECS CPU spiking after a hot deployment.

A ProactiveInsight is generated when DevOps Guru's ML model predicts that a resource is trending toward an anomalous state before the threshold is crossed. This is the more valuable alert type for a 24x7 MCP server: it gives you a 15–60 minute warning window to take preventive action before users are impacted. However, proactive insights require at least two weeks of continuous metric history. If you enable DevOps Guru on the day of an incident, you will only see reactive insights. Plan your rollout at least two weeks before a critical traffic event.

Both types share the same CAUSAL/CONTEXTUAL anomaly model and the same recommendation system. The difference is timing: reactive = something is wrong now, proactive = something is about to go wrong.

Gotcha #5: ListInsights requires Date objects, not epoch integers

The ListInsights API has three status filter variants — Ongoing, Closed, and Any — and the Closed and Any variants require time range parameters. The time range fields (FromTime, ToTime) must be JavaScript Date objects, not epoch milliseconds or epoch seconds integers. Passing a raw number causes a serialization error at the SDK level.

import {
  DevOpsGuruClient,
  ListInsightsCommand,
  type ReactiveInsight,
  type ListInsightsCommandInput,
} from "@aws-sdk/client-devops-guru";

const devopsGuru = new DevOpsGuruClient({ region: process.env.AWS_REGION! });

// ✅ Ongoing filter — no time range required
async function listOngoingInsights(): Promise<ReactiveInsight[]> {
  const all: ReactiveInsight[] = [];
  let nextToken: string | undefined;

  do {
    const { ReactiveInsights, NextToken } = await devopsGuru.send(
      new ListInsightsCommand({
        StatusFilter: { Ongoing: { Type: "REACTIVE" } },
        MaxResults: 100,
        NextToken: nextToken,
      })
    );
    all.push(...(ReactiveInsights ?? []));
    nextToken = NextToken;
  } while (nextToken);

  return all;
}

// ✅ Any filter — time range MUST use Date objects
async function listAllInsightsLastWeek(): Promise<ReactiveInsight[]> {
  const toTime = new Date();
  const fromTime = new Date(toTime.getTime() - 7 * 24 * 60 * 60 * 1000);

  const all: ReactiveInsight[] = [];
  let nextToken: string | undefined;

  do {
    const input: ListInsightsCommandInput = {
      StatusFilter: {
        Any: {
          Type: "REACTIVE",
          // Date objects — not epoch integers
          StartTimeRange: { FromTime: fromTime, ToTime: toTime },
        },
      },
      MaxResults: 100,
      NextToken: nextToken,
    };

    const { ReactiveInsights, NextToken } = await devopsGuru.send(
      new ListInsightsCommand(input)
    );
    all.push(...(ReactiveInsights ?? []));
    nextToken = NextToken;
  } while (nextToken);

  return all;
}

// ❌ Wrong — epoch integer causes SDK serialization error
// StartTimeRange: { FromTime: Date.now() - 604800000, ToTime: Date.now() }

Use the Ongoing filter for active alerting (no time range needed). Use Any with a StartTimeRange for incident retrospectives ("all insights from the past week"). Use Closed with an EndTimeRange for auditing resolved incidents.

Note that ListInsights returns only high-level metadata — insight ID, name, severity, and status. It does not return the associated anomalies or recommendations. Call GetInsight to retrieve associated resource ARNs, then ListAnomaliesForInsight and GetRecommendations for the full detail needed to triage.

Gotcha #6: AssociatedResourceArns is populated asynchronously — ListAnomaliesForInsight is faster

When DevOps Guru opens a new insight and immediately delivers an EventBridge event, the GetInsight response may show an empty AssociatedResourceArns array even though the insight is ONGOING. DevOps Guru populates associated resource ARNs as it correlates anomalies across resources — this process takes a few additional minutes after the initial insight creation event.

For Lambda handlers that need to identify affected resources quickly after receiving a new-insight notification, ListAnomaliesForInsight is more reliable than waiting for AssociatedResourceArns to populate:

import {
  ListAnomaliesForInsightCommand,
  GetInsightCommand,
  type ReactiveAnomaly,
} from "@aws-sdk/client-devops-guru";

async function getAffectedResourcesForInsight(insightId: string): Promise<{
  causal: ReactiveAnomaly[];
  contextual: ReactiveAnomaly[];
}> {
  const causal: ReactiveAnomaly[] = [];
  const contextual: ReactiveAnomaly[] = [];
  let nextToken: string | undefined;

  do {
    const { ReactiveAnomalies, NextToken } = await devopsGuru.send(
      new ListAnomaliesForInsightCommand({
        InsightId: insightId,
        MaxResults: 500,
        NextToken: nextToken,
      })
    );

    for (const anomaly of ReactiveAnomalies ?? []) {
      // CAUSAL: the root cause DevOps Guru identified
      // CONTEXTUAL: downstream symptoms on correlated resources
      if (anomaly.Type === "CAUSAL") {
        causal.push(anomaly);
      } else {
        contextual.push(anomaly);
      }
    }
    nextToken = NextToken;
  } while (nextToken);

  return { causal, contextual };
}

// Extract the specific CloudWatch metric that was anomalous
function describeAnomalyMetric(anomaly: ReactiveAnomaly): string {
  return (anomaly.SourceDetails?.CloudWatchMetrics ?? [])
    .map((m) => `${m.Namespace}/${m.MetricName}`)
    .join(", ");
}

// Triage pattern: start with CAUSAL anomalies to identify root cause
async function triageInsight(insightId: string): Promise<void> {
  const { causal, contextual } = await getAffectedResourcesForInsight(insightId);

  console.log("Root cause anomalies:", causal.length);
  causal.forEach((a) => {
    console.log("  Metric:", describeAnomalyMetric(a));
    // Resources associated with this specific anomaly
    a.AssociatedResources?.forEach((r) =>
      console.log("  Resource:", r.Type, r.Name)
    );
  });

  console.log("Downstream symptom anomalies:", contextual.length);
  contextual.forEach((a) => {
    console.log("  Metric:", describeAnomalyMetric(a));
  });
}

For a typical MCP server incident, the CAUSAL anomaly is on the resource that actually caused the problem — a Lambda function's throttle count, an SQS queue's oldest message age, a DynamoDB table's throttled requests. The CONTEXTUAL anomalies confirm downstream impact — your ECS service's response latency rising because the Lambda handler it depends on is throttling.

Gotcha #7: AnomalyTimeRange vs AnomalyReportedTimeRange — a 5–15 minute detection lag

Each anomaly object from ListAnomaliesForInsight contains two distinct time ranges that are frequently confused:

This distinction matters when you are correlating DevOps Guru alerts with other incident signals — specifically, with AliveMCP's external health check data:

// Correlate DevOps Guru anomaly time with external health check failures
function correlateWithExternalMonitoring(
  anomaly: ReactiveAnomaly,
  externalDowntimeStartUtc: Date
): void {
  const anomalyActualStart = anomaly.AnomalyTimeRange?.StartTime;
  const anomalyReportedAt = anomaly.AnomalyReportedTimeRange?.OpenTime;

  if (!anomalyActualStart || !anomalyReportedAt) return;

  const detectionLatencyMs =
    anomalyReportedAt.getTime() - anomalyActualStart.getTime();

  console.log("Anomaly actual start:", anomalyActualStart.toISOString());
  console.log("Anomaly reported at:", anomalyReportedAt.toISOString());
  console.log(
    "DevOps Guru detection lag:",
    Math.round(detectionLatencyMs / 60000),
    "minutes"
  );

  // Compare with external health check failure time
  const internalToExternalGapMs =
    externalDowntimeStartUtc.getTime() - anomalyActualStart.getTime();

  console.log(
    "Infrastructure anomaly → external failure gap:",
    Math.round(internalToExternalGapMs / 60000),
    "minutes"
  );
  // If this is positive, DevOps Guru detected the degradation BEFORE
  // it became visible to users (external health check). This is the
  // "early warning" value of proactive infrastructure monitoring.
}

In practice, internal infrastructure anomalies (detected by DevOps Guru) often precede external connectivity failures (detected by AliveMCP) by several minutes. The gap between AnomalyTimeRange.StartTime and the first failed external health check is the window where infrastructure is degrading but users are not yet impacted — the ideal time to take remedial action.

Getting actionable remediation steps: GetRecommendations

For each insight, DevOps Guru generates one or more recommendations based on the patterns it detected. Recommendations are specific to the anomalies: a Lambda throttle anomaly gets different recommendations than an SQS queue depth anomaly or a DynamoDB partition hot-spot.

import { GetRecommendationsCommand } from "@aws-sdk/client-devops-guru";

async function getRecommendationsForInsight(insightId: string): Promise<void> {
  let nextToken: string | undefined;

  do {
    const { Recommendations, NextToken } = await devopsGuru.send(
      new GetRecommendationsCommand({
        InsightId: insightId,
        Locale: "EN_US",
        NextToken: nextToken,
      })
    );

    for (const rec of Recommendations ?? []) {
      console.log("Recommendation:", rec.Name);
      console.log("  Reason:", rec.Reason);
      console.log("  Description:", rec.Description);
      console.log("  Documentation:", rec.Link);

      // Which specific anomalies triggered this recommendation?
      for (const relatedAnomaly of rec.RelatedAnomalies ?? []) {
        for (const resource of relatedAnomaly.Resources ?? []) {
          console.log("  Triggered by:", resource.Name);
        }
      }
    }
    nextToken = NextToken;
  } while (nextToken);
}

Common DevOps Guru recommendations for MCP server deployments:

Gotcha #8: Training the ML model with PutFeedback — INVALID_FINDING vs INVALID_COLLECTION

DevOps Guru uses per-account feedback to refine its anomaly detection models over time. PutFeedback is the most underused capability in a typical DevOps Guru setup — most teams either skip it entirely or use it inconsistently — but it is the mechanism that reduces false positives over months of operation.

import { PutFeedbackCommand, InsightFeedbackOption } from "@aws-sdk/client-devops-guru";

async function submitFeedback(
  insightId: string,
  outcome: "real_incident" | "false_positive" | "wrong_resources"
): Promise<void> {
  // Map to the correct DevOps Guru feedback option
  const feedbackOption: InsightFeedbackOption =
    outcome === "real_incident"
      ? "VALID_FINDING"
      : outcome === "false_positive"
      ? "INVALID_FINDING"
      : "INVALID_COLLECTION"; // anomaly was real but resource grouping was wrong

  await devopsGuru.send(
    new PutFeedbackCommand({
      InsightFeedback: {
        Id: insightId,
        Feedback: feedbackOption,
      },
    })
  );
}

The critical distinction between INVALID_FINDING and INVALID_COLLECTION:

Feedback only improves future insights — it does not change the current insight's status or recommendations. Build a habit of submitting feedback during your post-incident review: five minutes of feedback entry after each incident review delivers compounding model improvement over a year of MCP server operations.

Gotcha #9: The SNS topic policy silent-drop trap

This is the most common DevOps Guru notification failure mode: you configure an SNS notification channel, everything appears to succeed, the first real incident fires, and no notification arrives. The root cause is almost always a missing or incorrect SNS topic policy.

When DevOps Guru cannot publish to the SNS topic you registered, it silently drops the notification. AddNotificationChannel returns success regardless of whether DevOps Guru can actually publish to the topic. ListNotificationChannels shows the channel as registered. No error surfaces until the first insight fires and the notification is never received.

The required SNS topic policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DevOpsGuruPublish",
      "Effect": "Allow",
      "Principal": {
        "Service": "devops-guru.amazonaws.com"
      },
      "Action": "SNS:Publish",
      "Resource": "arn:aws:sns:us-east-1:123456789012:devops-guru-mcp-alerts",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        }
      }
    }
  ]
}

The aws:SourceAccount condition is not optional — it prevents cross-account confused-deputy attacks where another AWS account could use the DevOps Guru service principal to publish to your topic.

Then register the channel with the filters that reduce alert fatigue:

import {
  AddNotificationChannelCommand,
  type NotificationFilterConfig,
} from "@aws-sdk/client-devops-guru";

async function addNotificationChannel(topicArn: string): Promise<string> {
  const filters: NotificationFilterConfig = {
    // Alert on new insights and severity upgrades (MEDIUM → HIGH)
    // CLOSED_INSIGHT is useful for auto-resolving PagerDuty incidents
    MessageTypes: ["NEW_INSIGHT", "SEVERITY_UPGRADED", "CLOSED_INSIGHT"],
    // Start with HIGH only — add MEDIUM once you've calibrated false positive rate
    Severities: ["HIGH"],
  };

  const { Id } = await devopsGuru.send(
    new AddNotificationChannelCommand({
      Config: { Sns: { TopicArn: topicArn } },
      Filters: filters,
    })
  );
  return Id!;
}

Test the topic policy before you need it. After creating the topic and policy, use aws sns publish to verify that the DevOps Guru service principal can reach the topic, and check a CloudWatch Events log to confirm delivery.

Gotcha #10: EventBridge fires automatically — no configuration needed

Many DevOps Guru users configure SNS notifications and assume that is the only push delivery path. It is not. DevOps Guru automatically publishes events to the account's default EventBridge event bus with source aws.devops-guru for every insight event — no additional API call or configuration is needed. This path works even when the SNS topic policy is misconfigured.

The EventBridge path is preferable for enrichment-based workflows because it delivers a structured event that your Lambda handler can use to call back into DevOps Guru for full context before posting to Slack or PagerDuty:

// EventBridge rule: route HIGH-severity DevOps Guru events to Lambda
// (create this in CloudFormation/CDK — no DevOps Guru API call needed)
{
  "source": ["aws.devops-guru"],
  "detail-type": [
    "DevOps Guru New Insight Open",
    "DevOps Guru Insight Severity Upgraded"
  ],
  "detail": {
    "insightSeverity": ["HIGH"]
  }
}
import {
  DevOpsGuruClient,
  GetInsightCommand,
  GetRecommendationsCommand,
  ListAnomaliesForInsightCommand,
} from "@aws-sdk/client-devops-guru";

const devopsGuru = new DevOpsGuruClient({ region: process.env.AWS_REGION! });

// Lambda handler receives EventBridge event and enriches before Slack post
interface DevOpsGuruInsightEvent {
  "detail-type": string;
  source: "aws.devops-guru";
  detail: {
    insightId: string;
    insightType: "REACTIVE" | "PROACTIVE";
    insightSeverity: "HIGH" | "MEDIUM" | "LOW";
    insightUrl: string;
    insightName: string;
  };
}

export async function handler(event: DevOpsGuruInsightEvent): Promise<void> {
  const { insightId, insightSeverity, insightUrl, insightName } = event.detail;

  // Fetch recommendations for the Slack message
  const { Recommendations } = await devopsGuru.send(
    new GetRecommendationsCommand({ InsightId: insightId })
  );

  // Find the CAUSAL anomaly (root cause metric)
  const { ReactiveAnomalies } = await devopsGuru.send(
    new ListAnomaliesForInsightCommand({ InsightId: insightId, MaxResults: 10 })
  );
  const causal = ReactiveAnomalies?.find((a) => a.Type === "CAUSAL");
  const causalMetric =
    causal?.SourceDetails?.CloudWatchMetrics
      ?.map((m) => `${m.Namespace}/${m.MetricName}`)
      .join(", ") ?? "unknown";

  const severityEmoji = insightSeverity === "HIGH" ? "🔴" : "🟡";
  const topRecs = (Recommendations ?? []).slice(0, 2).map((r) => r.Name).join("; ");

  const slackMessage = {
    text: `${severityEmoji} *DevOps Guru: ${insightSeverity} insight*`,
    blocks: [{
      type: "section",
      text: {
        type: "mrkdwn",
        text: [
          `${severityEmoji} *${insightName}*`,
          `Severity: ${insightSeverity} | Root cause: ${causalMetric}`,
          topRecs ? `Recommendations: ${topRecs}` : "",
          `<${insightUrl}|View in DevOps Guru>`,
        ].filter(Boolean).join("\n"),
      },
    }],
  };

  await fetch(process.env.SLACK_WEBHOOK_URL!, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(slackMessage),
  });
}

The Lambda function's execution role needs devops-guru:GetInsight, devops-guru:GetRecommendations, and devops-guru:ListAnomaliesForInsight — the EventBridge delivery itself does not require DevOps Guru permissions, only the callback calls do. Also add the lambda:InvokeFunction permission for principal events.amazonaws.com to the Lambda's resource-based policy, or the EventBridge rule will silently fail to invoke it.

See DevOps Guru Notifications for the complete reference on SNS channel management, EventBridge event schemas, and SSM OpsCenter ticket lifecycle integration.

Putting it all together: the complete DevOps Guru setup for a production MCP server

Here is the full activation sequence for a production MCP server deployment. Run this once during initial infrastructure provisioning, ideally via your CDK or Terraform pipeline:

import {
  DevOpsGuruClient,
  UpdateResourceCollectionCommand,
  AddNotificationChannelCommand,
  UpdateServiceIntegrationCommand,
  DescribeAccountHealthCommand,
  OptInStatus,
} from "@aws-sdk/client-devops-guru";

const devopsGuru = new DevOpsGuruClient({ region: "us-east-1" });

async function setupDevOpsGuruForMcpServer(params: {
  stackName: string;        // CloudFormation stack name (not ARN)
  snsTopicArn: string;      // Pre-created with correct topic policy
}): Promise<void> {
  const { stackName, snsTopicArn } = params;

  // Step 1: Enroll the CloudFormation stack
  // First call creates the AWSServiceRoleForDevOpsGuru service-linked role.
  // Requires iam:CreateServiceLinkedRole if role doesn't exist yet.
  await devopsGuru.send(
    new UpdateResourceCollectionCommand({
      Action: "ADD",
      ResourceCollection: {
        CloudFormation: { StackNames: [stackName] },
      },
    })
  );
  console.log(`Stack "${stackName}" enrolled. 24–48h until first insights.`);

  // Step 2: Register SNS channel for HIGH severity alerts
  // SNS topic policy must allow devops-guru.amazonaws.com + aws:SourceAccount
  await devopsGuru.send(
    new AddNotificationChannelCommand({
      Config: { Sns: { TopicArn: snsTopicArn } },
      Filters: {
        MessageTypes: ["NEW_INSIGHT", "SEVERITY_UPGRADED", "CLOSED_INSIGHT"],
        Severities: ["HIGH"],
      },
    })
  );
  console.log("SNS notification channel registered.");

  // Step 3: Enable SSM OpsCenter for ticket-based incident lifecycle
  // Requires ssm:CreateOpsItem — check SCPs if OpsItems don't appear.
  await devopsGuru.send(
    new UpdateServiceIntegrationCommand({
      ServiceIntegration: {
        OpsCenter: { OptInStatus: OptInStatus.ENABLED },
      },
    })
  );
  console.log("SSM OpsCenter integration enabled.");

  // Step 4: Verify setup
  const health = await devopsGuru.send(new DescribeAccountHealthCommand({}));
  console.log("Setup complete:");
  console.log("  Resources under monitoring:", health.ResourceHours ?? 0);
  console.log("  Open reactive insights:", health.OpenReactiveInsights ?? 0);
  console.log(
    "  ProactiveInsights will appear after 2+ weeks of baseline data."
  );

  // Step 5: Create EventBridge rule separately via CloudFormation/CDK.
  // No DevOps Guru API call needed — events are auto-emitted to default bus.
  console.log("Remember: Create EventBridge rule for aws.devops-guru source");
  console.log("to route HIGH insights to your enrichment Lambda.");
}

After running this setup, your DevOps Guru deployment will:

See the full reference guides for deeper coverage: DevOps Guru Overview & Concepts, Resource Collection, Insights, Anomalies & Recommendations, and Notifications & EventBridge.

Pricing and cost management

DevOps Guru pricing is based on resource-hours: the number of supported AWS resources under monitoring multiplied by the number of hours they are monitored.

Monitor your spend with DescribeAccountHealth:

async function estimateMonthlyDevOpsGuruCost(): Promise<number> {
  const { ResourceHours } = await devopsGuru.send(
    new DescribeAccountHealthCommand({})
  );
  const PRICE_PER_RESOURCE_HOUR = 0.0028;
  return (ResourceHours ?? 0) * PRICE_PER_RESOURCE_HOUR;
}

To control costs, prefer CloudFormation stack-based collection over ALL_RESOURCES — it limits coverage to only the resources your MCP server actually uses, rather than every resource in the account. If you have multiple environments (dev, staging, prod) in the same AWS account, enroll only the production stack to avoid paying for anomaly detection on non-production resources.

DevOps Guru and AliveMCP: internal and external monitoring in concert

DevOps Guru and AliveMCP provide complementary coverage for MCP server operations — they monitor from different vantage points and catch different failure modes:

The ideal MCP server monitoring stack uses both: AliveMCP confirms that your endpoint is healthy from your users' perspective, while DevOps Guru monitors the infrastructure beneath it and warns you before internal degradation becomes external failure. When both fire simultaneously, the gap between AnomalyTimeRange.StartTime (from DevOps Guru) and the first AliveMCP downtime alert tells you how much lead time your infrastructure monitoring gave you before the user-visible incident.