generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 984
feat(cloudwatch-mcp-server): Add Anomaly Detection Alarm recommendation to AWS CloudWatch MCP server #1454
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
abarkley123
wants to merge
11
commits into
awslabs:main
Choose a base branch
from
abarkley123:cloudwatch-metric-analysis-enhanced
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,603
−86
Open
feat(cloudwatch-mcp-server): Add Anomaly Detection Alarm recommendation to AWS CloudWatch MCP server #1454
Changes from 3 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ea2ca6a
feat: add comprehensive CloudWatch metric analysis with anomaly detec…
f6f39bc
feat: add comprehensive CloudWatch metric analysis with anomaly detec…
00155e1
refactor: replace Jinja2 with Python dict approach for CloudFormation…
f4450da
Add heuristics for statistic selection in new tooling, code-style imp…
9a3a8c2
Merge branch 'main' into cloudwatch-metric-analysis-enhanced
3184811
chore: bump version to 0.0.12
f472588
Merge branch 'main' into cloudwatch-metric-analysis-enhanced
abarkley123 b6b512b
Add remaining test coverage and address linter changes.
6891805
Merge branch 'main' of https://github.com/awslabs/mcp into cloudwatch…
f2be918
Fix linter issue blocking precommit in aws-dataprocessing-mcp-server.
2bfb609
Revert "Fix linter issue blocking precommit in aws-dataprocessing-mcp…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
162 changes: 162 additions & 0 deletions
162
...ver/awslabs/cloudwatch_mcp_server/cloudwatch_metrics/cloudformation_template_generator.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import logging | ||
from awslabs.cloudwatch_mcp_server.cloudwatch_metrics.constants import COMPARISON_OPERATOR_ANOMALY | ||
from awslabs.cloudwatch_mcp_server.cloudwatch_metrics.models import AnomalyDetectionAlarmThreshold | ||
from typing import Any, Dict | ||
|
||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class CloudFormationTemplateGenerator: | ||
"""Generate CloudFormation JSON for CloudWatch Anomaly Detection Alarms.""" | ||
|
||
def _generate_metric_alarm_template(self, alarm_data: Dict[str, Any]) -> Dict[str, Any]: | ||
abarkley123 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
"""Generate CFN template for a single CloudWatch Alarm.""" | ||
if not self._is_anomaly_detection_alarm(alarm_data): | ||
return {} | ||
abarkley123 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# Validate required fields | ||
if not alarm_data.get('metricName'): | ||
raise ValueError( | ||
'Metric Name is required to generate CloudFormation templates for Cloudwatch Alarms' | ||
) | ||
if not alarm_data.get('namespace'): | ||
raise ValueError( | ||
'Metric Namespace is required to generate CloudFormation templates for Cloudwatch Alarms' | ||
) | ||
|
||
# Process alarm data and add computed fields | ||
formatted_data = self._format_anomaly_detection_alarm_data(alarm_data) | ||
|
||
# Build resources dict | ||
anomaly_detector_key = f'{formatted_data["resourceKey"]}AnomalyDetector' | ||
alarm_key = f'{formatted_data["resourceKey"]}Alarm' | ||
|
||
resources = { | ||
anomaly_detector_key: { | ||
'Type': 'AWS::CloudWatch::AnomalyDetector', | ||
'Properties': { | ||
'MetricName': formatted_data['metricName'], | ||
'Namespace': formatted_data['namespace'], | ||
'Stat': formatted_data['statistic'], | ||
'Dimensions': formatted_data['dimensions'], | ||
}, | ||
}, | ||
alarm_key: { | ||
'Type': 'AWS::CloudWatch::Alarm', | ||
'DependsOn': anomaly_detector_key, | ||
'Properties': { | ||
'AlarmDescription': formatted_data['alarmDescription'], | ||
'Metrics': [ | ||
{ | ||
'Expression': f'ANOMALY_DETECTION_BAND(m1, {formatted_data["sensitivity"]})', | ||
'Id': 'ad1', | ||
}, | ||
{ | ||
'Id': 'm1', | ||
'MetricStat': { | ||
'Metric': { | ||
'MetricName': formatted_data['metricName'], | ||
'Namespace': formatted_data['namespace'], | ||
'Dimensions': formatted_data['dimensions'], | ||
}, | ||
'Stat': formatted_data['statistic'], | ||
'Period': formatted_data['period'], | ||
}, | ||
}, | ||
], | ||
'EvaluationPeriods': formatted_data['evaluationPeriods'], | ||
'DatapointsToAlarm': formatted_data['datapointsToAlarm'], | ||
'ThresholdMetricId': 'ad1', | ||
'ComparisonOperator': formatted_data['comparisonOperator'], | ||
'TreatMissingData': formatted_data['treatMissingData'], | ||
}, | ||
}, | ||
} | ||
|
||
final_template = { | ||
'AWSTemplateFormatVersion': '2010-09-09', | ||
'Description': 'CloudWatch Alarms and Anomaly Detectors', | ||
'Resources': resources, | ||
} | ||
|
||
return final_template | ||
|
||
def _is_anomaly_detection_alarm(self, alarm_data: Dict[str, Any]) -> bool: | ||
return alarm_data.get('comparisonOperator') == COMPARISON_OPERATOR_ANOMALY | ||
|
||
def _format_anomaly_detection_alarm_data(self, alarm_data: Dict[str, Any]) -> Dict[str, Any]: | ||
"""Sanitize alarm data and add computed fields.""" | ||
formatted_data = alarm_data.copy() | ||
|
||
# Generate resource key from metric name and namespace | ||
formatted_data['resourceKey'] = self._generate_resource_key( | ||
metric_name=alarm_data.get('metricName', ''), | ||
namespace=alarm_data.get('namespace', ''), | ||
dimensions=alarm_data.get('dimensions', []), | ||
) | ||
|
||
# Process threshold value | ||
threshold = alarm_data.get('threshold', {}) | ||
formatted_data['sensitivity'] = threshold.get( | ||
'sensitivity', AnomalyDetectionAlarmThreshold.DEFAULT_SENSITIVITY | ||
) | ||
|
||
# Set defaults | ||
formatted_data.setdefault( | ||
'alarmDescription', 'CloudWatch Alarm generated by CloudWatch MCP server.' | ||
) | ||
formatted_data.setdefault('statistic', 'Average') | ||
formatted_data.setdefault('period', 300) | ||
formatted_data.setdefault('evaluationPeriods', 2) | ||
formatted_data.setdefault('datapointsToAlarm', 2) | ||
formatted_data.setdefault('comparisonOperator', COMPARISON_OPERATOR_ANOMALY) | ||
formatted_data.setdefault('treatMissingData', 'missing') | ||
formatted_data.setdefault('dimensions', []) | ||
|
||
return formatted_data | ||
|
||
def _generate_resource_key(self, metric_name: str, namespace: str, dimensions: list) -> str: | ||
"""Generate CloudFormation resource key from metric components to act as logical id.""" | ||
# Strip AWS/ prefix from namespace (AWS CDK style) | ||
clean_namespace = namespace.replace('AWS/', '') | ||
|
||
# Add first dimension key and value for uniqueness if present | ||
dimension_suffix = '' | ||
if dimensions: | ||
first_dim = dimensions[0] | ||
dim_name = first_dim.get('Name', '') | ||
dim_value = first_dim.get('Value', '') | ||
dimension_suffix = f'{dim_name}{dim_value}' | ||
|
||
resource_base = f'{clean_namespace}{metric_name}{dimension_suffix}' | ||
return self._sanitize_resource_name(resource_base) | ||
|
||
def _sanitize_resource_name(self, name: str) -> str: | ||
abarkley123 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Sanitize name for CloudFormation resource key.""" | ||
# Remove non-alphanumeric characters | ||
sanitized = ''.join(c for c in name if c.isalnum()) | ||
|
||
# Ensure it starts with letter | ||
if not sanitized or not sanitized[0].isalpha(): | ||
sanitized = 'Resource' + sanitized | ||
|
||
# Truncate if too long | ||
if len(sanitized) > 255: | ||
sanitized = sanitized[:255] | ||
|
||
return sanitized |
30 changes: 30 additions & 0 deletions
30
src/cloudwatch-mcp-server/awslabs/cloudwatch_mcp_server/cloudwatch_metrics/constants.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# CloudWatch MCP Server Constants | ||
|
||
# Time constants | ||
SECONDS_PER_MINUTE = 60 | ||
MINUTES_PER_HOUR = 60 | ||
HOURS_PER_DAY = 24 | ||
DAYS_PER_WEEK = 7 | ||
|
||
# Analysis constants | ||
DEFAULT_ANALYSIS_PERIOD_MINUTES = 20160 # 2 weeks | ||
|
||
# Threshold constants | ||
COMPARISON_OPERATOR_ANOMALY = 'LessThanLowerOrGreaterThanUpperThreshold' | ||
|
||
# Numerical stability | ||
NUMERICAL_STABILITY_THRESHOLD = 1e-10 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.