Log-Analyzer-with-MCP
AGENTS.md170 starsChanged 10 months agoApache-2.0View on GitHub
This file provides guidance for AI coding agents working with this codebase. Log-Analyzer-with-MCP is an MCP (Model Context Protocol) server providing AI assistants access to AWS CloudWatch Logs for searching, analysis, and cross-service correlation. Tech Stack: Python 3.12+, uv (package manager), FastMCP, boto3, ruff
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,337 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
13 rules. About 0 are common, 6 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 39
All Python files must start with the Apache-2.0 license header:
- Very specific: line 64
Use type hints consistently.
- Distinctive: line 77
Use Google-style docstrings with Args and Returns:
- Very specific: line 99
Tool methods: Use @handle_exceptions decorator for JSON error responses
- Distinctive: line 107
All tool/resource methods return JSON strings:
- Distinctive: line 113
Always support optional profile and region parameters:
- Distinctive: line 166
Use the MCP Inspector to interactively test and debug tools:
- Very specific: line 179
Tool not appearing: Check decorator order (@mcp.tool() before @with_aws_config())
- Very specific: line 180
AWS errors: Verify credentials with aws sts get-caller-identity --profile PROFILE
- Very specific: line 181
JSON parse errors: Ensure all tool methods return json.dumps() strings
- Distinctive: line 202
Use conventional commit format:
- Very specific: line 283
Don't raise exceptions in tools: Use @handle_exceptions or return JSON errors
- Very specific: line 286
AWS credentials: Always support profile and region parameters
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
This file provides guidance for AI coding agents working with this codebase.
Project Overview
Log-Analyzer-with-MCP is an MCP (Model Context Protocol) server providing AI assistants access to AWS CloudWatch Logs for searching, analysis, and cross-service correlation.
Tech Stack: Python 3.12+, uv (package manager), FastMCP, boto3, ruff
Build & Development Commands
# Installation
uv sync # Install all dependencies
source .venv/bin/activate # Activate virtual environment
# Running the Server (local development)
python -m cw_mcp_server.server [--profile PROFILE] [--region REGION] [--stateless]
uv run python -m cw_mcp_server.server # Alternative
# Via uvx (recommended for users)
uvx --from git+https://github.com/awslabs/Log-Analyzer-with-MCP cw-mcp-server [--profile PROFILE] [--region REGION] [--stateless]
# Linting & Formatting (run before committing)
pre-commit run --all-files # Preferred - runs ruff lint and format
ruff check --fix . # Lint with auto-fix
ruff format . # Format code
# Manual Testing (no pytest configured yet)
python src/client.py list-groups [--prefix PREFIX]
python src/client.py search LOG_GROUP "query" [--hours N]
python src/client.py find-errors LOG_GROUPCode Style Guidelines
File Headers
All Python files must start with the Apache-2.0 license header:
#!/usr/bin/env python3
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0Import Order (ruff-enforced)
- Standard library imports
- Third-party imports (boto3, mcp, etc.)
- Local imports (relative imports with
.)
import asyncio
import json
from typing import List, Optional, Callable
import boto3
from mcp.server.fastmcp import FastMCP
from .tools.search_tools import CloudWatchLogsSearchToolsType Hints
Use type hints consistently. For Python 3.12+, prefer modern syntax but the codebase currently uses typing module imports for compatibility:
async def search_logs(
self,
log_group_name: str,
query: str,
hours: int = 24,
start_time: str = None,
end_time: str = None,
) -> str:Docstrings
Use Google-style docstrings with Args and Returns:
def get_log_groups(self, prefix: str = None, limit: int = 50) -> str:
"""
Get a list of CloudWatch Log Groups with optional filtering.
Args:
prefix: Optional prefix to filter log groups by name
limit: Maximum number of log groups to return (default: 50)
Returns:
JSON string with log groups information
"""Naming Conventions
- Classes: PascalCase (
CloudWatchLogsSearchTools) - Functions/Methods: snake_case (
search_logs,get_log_groups) - Variables: snake_case (
log_group_name,formatted_results) - Private methods: prefix with
_(_detect_log_format)
Error Handling
- Tool methods: Use
@handle_exceptionsdecorator for JSON error responses - Resource methods: Return JSON errors, don't raise exceptions to clients:
except Exception as e:
return json.dumps({"error": str(e)}, indent=2)Return Format
All tool/resource methods return JSON strings:
return json.dumps(formatted_results, indent=2)AWS Client Pattern
Always support optional profile and region parameters:
def __init__(self, profile_name=None, region_name=None):
session = boto3.Session(profile_name=profile_name, region_name=region_name)
self.logs_client = session.client("logs")Architecture
src/
├── client.py # CLI client for testing
└── cw_mcp_server/
├── server.py # Main FastMCP server entry point
├── resources/
│ └── cloudwatch_logs_resource.py # CloudWatch Logs as MCP resources
└── tools/
├── __init__.py # @handle_exceptions decorator
├── utils.py # Time range utilities
├── search_tools.py # Log search/query tools
├── analysis_tools.py # Log analysis tools
└── correlation_tools.py # Cross-service correlationKey Decorators
- @mcp.tool(): Exposes functions as MCP tools
- @mcp.resource(): Exposes data as MCP resources (
logs://groups/{name}) - @mcp.prompt(): Provides prompt templates
- @with_aws_config(): Handles AWS profile/region override per-call
- @handle_exceptions: Returns JSON errors instead of raising
Entry Points
- Main:
cw_mcp_server.server:main() - Console script:
cw-mcp-server(defined in pyproject.toml)
Pre-commit Hooks
Pre-commit is configured (.pre-commit-config.yaml) and runs:
ruff check --fix- Lint with auto-fixruff format- Format code
Install hooks locally:
pre-commit installNote: CI/CD via GitHub Actions is not yet configured. Run pre-commit run --all-files locally before committing.
See .pre-commit-config.yaml for pinned ruff version.
Debugging
MCP Inspector
Use the MCP Inspector to interactively test and debug tools:
npx @modelcontextprotocol/inspector python -m cw_mcp_server.serverVerbose Logging
Enable debug logging by setting the environment variable:
export MCP_LOG_LEVEL=debug
python -m cw_mcp_server.serverCommon Debug Scenarios
- Tool not appearing: Check decorator order (
@mcp.tool()before@with_aws_config()) - AWS errors: Verify credentials with
aws sts get-caller-identity --profile PROFILE - JSON parse errors: Ensure all tool methods return
json.dumps()strings
Dependency Management
uv add <package> # Add a new dependency
uv add --dev <package> # Add a dev dependency
uv remove <package> # Remove a dependency
uv lock # Update lock file
uv sync # Sync environment with lock fileGit Conventions
Branch Naming
feat/<description>- New featuresfix/<description>- Bug fixesdocs/<description>- Documentation changesrefactor/<description>- Code refactoring
Commit Messages
Use conventional commit format:
<type>: <short description>
[optional body]Types: feat, fix, docs, refactor, test, chore
Example:
feat: add log stream filtering by time range
Adds start_time and end_time parameters to filter_log_events toolEnvironment & AWS Configuration
Required AWS Permissions
The server requires CloudWatch Logs permissions:
logs:DescribeLogGroupslogs:DescribeLogStreamslogs:GetLogEventslogs:FilterLogEventslogs:StartQuery/logs:GetQueryResults(for Insights queries)
AWS Credentials
Credentials are resolved via standard boto3 chain:
- Environment variables (
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY) - AWS CLI profile (
--profileflag orAWS_PROFILEenv var) - IAM instance role (EC2/Lambda)
Testing
Manual Testing via CLI
python src/client.py list-groups --prefix /aws/lambda
python src/client.py search "/aws/lambda/my-function" "ERROR"
python src/client.py find-errors "/aws/lambda/my-function"MCP Inspector Testing
npx @modelcontextprotocol/inspector python -m cw_mcp_server.serverAdding New Tools
To add a new MCP tool:
- Create the method in the appropriate tool class (
tools/*.py) - Register in server.py using the pattern:
@mcp.tool()
@with_aws_config(YourToolClass)
async def your_tool_name(
required_param: str,
optional_param: int = 24,
profile: str = None,
region: str = None,
) -> str:
"""
Tool description for MCP clients.
Args:
required_param: Description
optional_param: Description (default: 24)
profile: Optional AWS profile name
region: Optional AWS region name
Returns:
JSON string with results
"""
pass # Decorator handles execution- Add
@handle_exceptionsto the underlying method if it can fail
Common Pitfalls
- Don't raise exceptions in tools: Use
@handle_exceptionsor return JSON errors - Always use JSON returns:
json.dumps(..., indent=2)for all responses - Time ranges: Support both
hoursoffset and ISO8601start_time/end_time - AWS credentials: Always support
profileandregionparameters - Async methods: Tool methods calling AWS APIs should be
async - Decorator order matters:
@mcp.tool()must come before@with_aws_config() - Parameter passthrough: Tool functions have
passbody - logic is in tool classes
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

