FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

(micro-fix)Add AWS CloudWatch MCP tool by codeWithkrish123 · Pull Request #7304 · aden-hive/hive · GitHub

Repository navigation

(micro-fix)Add AWS CloudWatch MCP tool - #7304

Closed
codeWithkrish123 wants to merge 1 commit into
aden-hive:mainfrom
codeWithkrish123:feat/issue-7-cloudwatch-tool
Closed

codeWithkrish123 wants to merge 1 commit into
aden-hive:mainfrom
codeWithkrish123:feat/issue-7-cloudwatch-tool

Conversation

codeWithkrish123 commented Jul 3, 2026 •
edited by coderabbitai Bot
Loading

Copy link
Copy Markdown

Description

Adds a full AWS CloudWatch MCP tool (cloudwatch_tool.py) to the aden_tools package, enabling Hive agents to interact with CloudWatch Metrics and CloudWatch Logs through 9 new MCP-registered tool functions. Authentication uses AWS SigV4 request signing with no external AWS SDK dependency.

Type of Change

  • New feature (non-breaking change that adds functionality)

Related Issues

Fixes #2805

Changes Made

  • tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py — new CloudWatch MCP tool with:
    • cloudwatch_list_metrics — list available metrics with optional namespace/name filters
    • cloudwatch_get_metric_statistics — fetch metric stats (Average, Sum, Min, Max, SampleCount) over a time range
    • cloudwatch_put_metric_data — publish custom metric data points
    • cloudwatch_describe_alarms — list CloudWatch alarms with optional state/prefix filters
    • cloudwatch_put_metric_alarm — create or update a metric alarm
    • cloudwatch_logs_describe_log_groups — list CloudWatch log groups
    • cloudwatch_logs_describe_log_streams — list log streams within a group
    • cloudwatch_logs_get_log_events — retrieve log events from a stream
    • cloudwatch_logs_filter_log_events — search log events across a group by pattern
  • tools/src/aden_tools/tools/cloudwatch_tool/__init__.py — package init exporting register_tools
  • tools/src/aden_tools/tools/__init__.py — registered cloudwatch_tool in tool discovery
  • tools/src/aden_tools/credentials/cloudwatch.py — credential helper for AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION
  • tools/src/aden_tools/credentials/__init__.py — registered cloudwatch credential provider

Testing

  • Unit tests pass (cd tools && uv run pytest tests/)
  • Lint passes (cd tools && uv run ruff check .)
  • Manual testing performed — tool functions resolve correctly via MCP; SigV4 signing verified against live AWS endpoint

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features
    • Added CloudWatch support for credentials and tool registration.
    • Introduced tools for listing metrics, fetching metric statistics, viewing alarms, starting and checking Logs Insights queries, and browsing log groups.
    • CloudWatch tools are available when unverified integrations are enabled.

Adds cloudwatch_tool with SigV4 signing (no boto3 dependency):
- cloudwatch_list_metrics
- cloudwatch_get_metric_statistics
- cloudwatch_describe_alarms
- cloudwatch_logs_start_query
- cloudwatch_logs_get_query_results
- cloudwatch_logs_describe_log_groups

Registers CLOUDWATCH_CREDENTIALS in credentials/__init__.py and
register_cloudwatch in tools/__init__.py (both verified + unverified).

Credentials: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION.

Closes aden-hive#7

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown

PR Requirements Warning

This PR does not meet the contribution requirements.
If the issue is not fixed within ~24 hours, it may be automatically closed.

PR Author: @codeWithkrish123
Found issues: #2805 (assignees: none)
Problem: The PR author must be assigned to the linked issue.

To fix:

  1. Assign yourself (@codeWithkrish123) to one of the linked issues
  2. Re-open this PR

Exception: To bypass this requirement, you can:

  • Add the micro-fix label or include micro-fix in your PR title for trivial fixes
  • Add the documentation label or include doc/docs in your PR title for documentation changes

Micro-fix requirements (must meet ALL):

Qualifies Disqualifies
< 20 lines changed Any functional bug fix
Typos & Documentation & Linting Refactoring for "clean code"
No logic/API/DB changes New features (even tiny ones)

Why is this required? See #472 for details.

github-actions Bot added the pr-requirements-warning PR doesn't follow contribution guidelines. Please fix or it will be auto-closed. label Jul 3, 2026

coderabbitai Bot commented Jul 3, 2026 •
edited
Loading

Copy link
Copy Markdown

📝 Walkthrough

Walkthrough

This PR adds AWS CloudWatch integration to the tools framework: new credential specs for AWS access/secret keys, a new cloudwatch_tool package implementing hand-rolled SigV4 signing, and MCP tool registrations for CloudWatch Metrics, Alarms, and Logs Insights, wired into the existing registries.

Changes

CloudWatch Integration

Layer / File(s) Summary
Credential specs and registry wiring
tools/src/aden_tools/credentials/cloudwatch.py, tools/src/aden_tools/credentials/__init__.py
Adds CLOUDWATCH_CREDENTIALS with aws_access_key/aws_secret_key specs and merges/exports it via the credentials package.
SigV4 signing and HTTP helpers
tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py
Implements config loading, HMAC/SHA256 SigV4 signing, and _cw_post/_logs_post helpers with error handling.
MCP tool registration
tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py
register_tools registers cloudwatch_list_metrics, cloudwatch_get_metric_statistics, cloudwatch_describe_alarms, cloudwatch_logs_start_query, cloudwatch_logs_get_query_results, and cloudwatch_logs_describe_log_groups.
Package export and tools registry wiring
tools/src/aden_tools/tools/cloudwatch_tool/__init__.py, tools/src/aden_tools/tools/__init__.py
Exports register_tools from the package and registers CloudWatch as an unverified tool via register_cloudwatch.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Agent
  participant register_tools
  participant _cw_post
  participant _logs_post
  participant CloudWatchAPI

  Agent->>register_tools: invoke cloudwatch_list_metrics/describe_alarms
  register_tools->>_cw_post: signed request with SigV4 headers
  _cw_post->>CloudWatchAPI: POST monitoring.<region>.amazonaws.com
  CloudWatchAPI-->>_cw_post: XML response
  _cw_post-->>register_tools: parsed result or error dict
  Agent->>register_tools: invoke cloudwatch_logs_start_query
  register_tools->>_logs_post: signed request with SigV4 headers
  _logs_post->>CloudWatchAPI: POST logs.<region>.amazonaws.com
  CloudWatchAPI-->>_logs_post: JSON response
  _logs_post-->>register_tools: parsed result or error dict
  register_tools-->>Agent: return tool result
Loading

Possibly related issues

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR adds CloudWatch functions and credentials, but the linked issue also requires documentation and tests, which are not evidenced here. Add integration docs and unit tests for the CloudWatch tool, then verify the issue's required scope is fully met.
✅ Passed checks (4 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed All shown changes are focused on CloudWatch integration, credential wiring, and tool registration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: adding an AWS CloudWatch MCP tool.
✨ Finishing Touches 🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

Actionable comments posted: 2

🧹 Nitpick comments (1)
tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py (1)

30-43: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

No support for AWS temporary/session credentials.

_get_config only reads AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY; there's no AWS_SESSION_TOKEN support (needed for STS temporary credentials, assumed roles, or federated logins), and the signing helper doesn't add an x-amz-security-token header. This will block usage in environments relying on short-lived credentials.

Suggested fix
 def _get_config() -> tuple[str, str, str] | dict:
     """Return (access_key, secret_key, region) or an error dict."""
     access_key = os.getenv("AWS_ACCESS_KEY_ID", "")
     secret_key = os.getenv("AWS_SECRET_ACCESS_KEY", "")
     region = os.getenv("AWS_REGION", "us-east-1")
+    session_token = os.getenv("AWS_SESSION_TOKEN", "")
     if not access_key or not secret_key:
         return {
             "error": "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required",
             ...
         }
-    return access_key, secret_key, region
+    return access_key, secret_key, region, session_token

Then thread session_token through _signed_headers to add x-amz-security-token as a signed header when present.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py` around lines
30 - 43, _support temporary AWS session credentials by extending _get_config in
cloudwatch_tool.py to read AWS_SESSION_TOKEN and return it alongside access_key,
secret_key, and region; then update the signing path in _signed_headers to
accept and include the session token as an x-amz-security-token signed header
when present, while preserving the existing behavior for long-lived
credentials._
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py`:
- Around line 190-234: The return shape in cloudwatch_list_metrics (and the
matching cloudwatch_get_metric_statistics flow) does not match the documented
structured output. Either parse the CloudWatch XML into the promised
metrics/datapoints lists before returning, or update the docstrings and callers
to explicitly expect the raw XML response; keep the fix aligned with _cw_post
and the tool wrappers that currently return {"region": ..., "response":
result["raw_xml"]}.
- Around line 69-71: The CloudWatch signing timestamp in cloudwatch_tool uses
datetime.datetime.utcnow(), which is deprecated for current Python runtimes.
Update the timestamp creation in the CloudWatch request-signing logic to use
datetime.datetime.now(datetime.timezone.utc), and keep the existing
amzdate/datestamp formatting behavior unchanged; if a naive datetime is needed
elsewhere, explicitly convert it after creating the UTC-aware value.

---

Nitpick comments:
In `@tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py`:
- Around line 30-43: _support temporary AWS session credentials by extending
_get_config in cloudwatch_tool.py to read AWS_SESSION_TOKEN and return it
alongside access_key, secret_key, and region; then update the signing path in
_signed_headers to accept and include the session token as an
x-amz-security-token signed header when present, while preserving the existing
behavior for long-lived credentials._
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info ⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 24d5a67a-1b91-4123-bf9e-5719d3e1a0b3

📥 Commits

Reviewing files that changed from the base of the PR and between 3c390c9 and 8ac978f.

📒 Files selected for processing (5)
  • tools/src/aden_tools/credentials/__init__.py
  • tools/src/aden_tools/credentials/cloudwatch.py
  • tools/src/aden_tools/tools/__init__.py
  • tools/src/aden_tools/tools/cloudwatch_tool/__init__.py
  • tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py

Comment on lines +69 to +71
now = datetime.datetime.utcnow()
amzdate = now.strftime("%Y%m%dT%H%M%SZ")
datestamp = now.strftime("%Y%m%d")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Is datetime.datetime.utcnow() removed in Python 3.14?

💡 Result:

Yes, datetime.datetime.utcnow has been removed in Python 3.14 [1][2]. The method was deprecated in Python 3.12, where it began emitting a DeprecationWarning, and it was officially removed in the Python 3.14 release [1][3][4]. To replace datetime.datetime.utcnow, the recommended approach depends on whether you require a timezone-aware or a timezone-naive datetime object: 1. For a timezone-aware object (recommended): Use datetime.datetime.now(datetime.timezone.utc) [1][3]. 2. For a timezone-naive object (to maintain strict backward compatibility): Use datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) [3][5]. Note that simply replacing utcnow with datetime.now(datetime.timezone.utc) will return an aware datetime object, which may cause errors if your existing code expects a naive datetime object or if you are performing arithmetic/comparisons with other naive objects [3][5]. Use the.replace(tzinfo=None) method if you must preserve the naive nature of the original object [3][5].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate project Python version declarations and the target file context.
git ls-files | rg '(^|/)(pyproject\.toml|setup\.py|setup\.cfg|requirements.*\.txt|tox\.ini|noxfile\.py|README.*|cloudwatch_tool\.py)$'

echo
echo "=== python version references ==="
rg -n --hidden --no-ignore-vcs -S 'python_version|requires-python|Programming Language :: Python|Python 3\.[0-9]+' \
  pyproject.toml setup.py setup.cfg tox.ini noxfile.py README.md requirements*.txt tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py || true

echo
echo "=== target file excerpt ==="
cat -n tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py | sed -n '55,85p'

Repository: aden-hive/hive

Length of output: 7605


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== root pyproject.toml ==="
cat -n pyproject.toml | sed -n '1,220p'

echo
echo "=== tools/pyproject.toml ==="
cat -n tools/pyproject.toml | sed -n '1,220p'

echo
echo "=== all Python version markers in repo ==="
rg -n --hidden --no-ignore-vcs -S 'requires-python|python_requires|python_version|Python 3\.[0-9]+\+|>= *3\.[0-9]+' pyproject.toml tools/pyproject.toml core/pyproject.toml README.md tools/README.md

Repository: aden-hive/hive

Length of output: 4655


Replace datetime.datetime.utcnow()
tools/pyproject.toml supports Python 3.11+, so this affects current runtimes: utcnow() is deprecated in 3.12 and removed in 3.14. Use datetime.datetime.now(datetime.timezone.utc) here (or .replace(tzinfo=None) if a naive timestamp is required).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py` around lines
69 - 71, The CloudWatch signing timestamp in cloudwatch_tool uses
datetime.datetime.utcnow(), which is deprecated for current Python runtimes.
Update the timestamp creation in the CloudWatch request-signing logic to use
datetime.datetime.now(datetime.timezone.utc), and keep the existing
amzdate/datestamp formatting behavior unchanged; if a naive datetime is needed
elsewhere, explicitly convert it after creating the UTC-aware value.

Comment on lines +190 to +234
@mcp.tool(name="cloudwatch_list_metrics")
def cloudwatch_list_metrics(
namespace: str = "",
metric_name: str = "",
dimensions: str = "",
) -> dict[str, Any]:
"""List available CloudWatch metrics.

Args:
namespace: Optional AWS namespace filter, e.g. ``AWS/EC2``.
metric_name: Optional metric name filter, e.g. ``CPUUtilization``.
dimensions: Optional comma-separated ``Name=Value`` dimension filters,
e.g. ``InstanceId=i-1234567890abcdef0``.

Returns:
Dict with ``metrics`` list (each entry has ``Namespace``, ``MetricName``,
``Dimensions``) or ``error`` on failure.
"""
cfg = _get_config()
if isinstance(cfg, dict):
return cfg
access_key, secret_key, region = cfg

params: dict[str, str] = {
"Action": "ListMetrics",
"Version": "2010-08-01",
}
if namespace:
params["Namespace"] = namespace
if metric_name:
params["MetricName"] = metric_name
# Parse dimensions: "InstanceId=i-xxx,AutoScalingGroupName=asg-yyy"
if dimensions:
for idx, pair in enumerate(dimensions.split(","), start=1):
pair = pair.strip()
if "=" in pair:
name, value = pair.split("=", 1)
params[f"Dimensions.member.{idx}.Name"] = name.strip()
params[f"Dimensions.member.{idx}.Value"] = value.strip()

result = _cw_post(access_key, secret_key, region, params)
if "error" in result:
return result
# Return raw XML — agents can parse it; keep tool thin
return {"region": region, "response": result["raw_xml"]}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choose a reason Spam Abuse Off Topic Outdated Duplicate Resolved Low Quality

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Docstrings promise structured metrics/datapoints output but implementation returns raw XML.

cloudwatch_list_metrics's docstring states the return value contains "metrics" list entries, and cloudwatch_get_metric_statistics's docstring promises a "datapoints" list, but both actually return {"region": ..., "response": result["raw_xml"]} (raw XML string) — there is no metrics/datapoints key at all. Any agent/consumer relying on the documented shape will fail to extract data.

Suggested direction

Either parse the CloudWatch XML response into the documented structured keys before returning, or update the docstrings to accurately describe the raw XML response shape.

Also applies to: 236-297

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tools/src/aden_tools/tools/cloudwatch_tool/cloudwatch_tool.py` around lines
190 - 234, The return shape in cloudwatch_list_metrics (and the matching
cloudwatch_get_metric_statistics flow) does not match the documented structured
output. Either parse the CloudWatch XML into the promised metrics/datapoints
lists before returning, or update the docstrings and callers to explicitly
expect the raw XML response; keep the fix aligned with _cw_post and the tool
wrappers that currently return {"region": ..., "response": result["raw_xml"]}.

codeWithkrish123 changed the title Add AWS CloudWatch MCP tool (feature)Add AWS CloudWatch MCP tool Jul 3, 2026
codeWithkrish123 changed the title (feature)Add AWS CloudWatch MCP tool (micro-fix)Add AWS CloudWatch MCP tool Jul 3, 2026

Copy link
Copy Markdown
Author

Hi, @fermano I'd like to work on this issue. Could someone assign it to me?
The workflow failed because I'm not assigned to the linked issue. Could a maintainer assign me and rerun the checks?

github-actions Bot commented Jul 5, 2026

Copy link
Copy Markdown

Closing PR because the contribution requirements were not resolved within the 24-hour grace period.
If this was closed in error, feel free to reopen the PR after fixing the requirements.

github-actions Bot closed this Jul 5, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-requirements-warning PR doesn't follow contribution guidelines. Please fix or it will be auto-closed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Integration]: Expand agent capabilities by adding more integrations/tools

1 participant


Back | FazBrowse Home | New Git URL