gcp-logs-explorer-mcp

savantlabs/gcp-logs-explorer-mcp

3.2

If you are the rightful owner of gcp-logs-explorer-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

An MCP server that enables Claude Code to interact with Google Cloud Logs Explorer using service account authentication.

Tools
9
Resources
0
Prompts
0

GCP Log Explorer MCP

An MCP (Model Context Protocol) server that enables Claude Code to interact with Google Cloud Logs Explorer using service account authentication.

Features

  • Service Account Authentication: Secure, headless authentication using GCP service accounts
  • Automatic Initialization: Connects automatically on startup - no manual authentication needed
  • Log Querying: Query logs using Cloud Logging filter syntax
  • Time-based Search: Search logs within specific time ranges
  • Text Search: Search logs by text content
  • Severity Analysis: Get distribution of log severity levels
  • Resource Discovery: List resource types and available logs
  • Error Monitoring: Quick access to recent errors and critical logs
  • Metrics: View log-based metrics

Prerequisites

  • Python 3.10 or higher
  • Google Cloud project with Cloud Logging API enabled
  • Service account with appropriate IAM roles

Setup

1. Create a Service Account

  1. Go to Google Cloud Console
  2. Select your project
  3. Navigate to IAM & Admin > Service Accounts
  4. Click Create Service Account
  5. Name it (e.g., "log-explorer-mcp")
  6. Grant these roles:
    • Logs Viewer (roles/logging.viewer) - minimum for reading logs
    • OR Logging Admin (roles/logging.admin) - for full access
  7. Click Done
  8. Click on the service account, go to Keys tab
  9. Click Add Key > Create New Key
  10. Choose JSON format
  11. Download the key file

2. Enable Required APIs

Enable the Cloud Logging API:

gcloud services enable logging.googleapis.com

Or enable via Cloud Console

3. Install Dependencies

cd gcp-log-explorer-mcp
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -r requirements.txt

4. Configure Environment

Copy the example environment file:

cp .env.example .env

Edit .env and configure:

# Required: Your GCP project ID
GCP_PROJECT_ID=your-project-id

# Method 1: Path to service account key (RECOMMENDED)
GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json

Alternative authentication methods:

# Method 2: JSON string (for containers/CI)
GOOGLE_SERVICE_ACCOUNT_JSON={"type":"service_account","project_id":"..."}

# Method 3: Application Default Credentials
# Run: gcloud auth application-default login
# (No env variable needed)

5. Test the Server

Run the server directly to test:

python -m src.server

If configured correctly, you'll see:

INFO - Initializing GCP Log Explorer for project: your-project-id
INFO - Authenticated as service account: log-explorer@your-project.iam.gserviceaccount.com
INFO - Successfully initialized GCP Log Explorer MCP

Configure with Claude Code

Add this MCP server to your Claude Code configuration:

macOS/Linux: ~/.config/claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "gcp-log-explorer": {
      "command": "python",
      "args": ["-m", "src.server"],
      "cwd": "/absolute/path/to/gcp-log-explorer-mcp",
      "env": {
        "GOOGLE_APPLICATION_CREDENTIALS": "/absolute/path/to/service-account-key.json"
      }
    }
  }
}

Note: You can set the environment variable in the config instead of using .env file.

Restart Claude Code after updating the configuration.

Usage

The server authenticates automatically on startup - no manual login required!

Check Status

Check the status of the GCP log explorer

Available Tools

Management
  • get_status: Check authentication and connection status
Log Exploration
  • list_logs: List all available logs in the project
  • query_logs: Query logs using Cloud Logging filter syntax
  • query_logs_by_time_range: Query logs within a time range with filters
  • search_logs_by_text: Search logs by text content
  • get_resource_types: List resource types that are logging
  • get_log_severity_distribution: Get severity distribution over time
  • get_log_metrics: List log-based metrics
  • get_recent_errors: Get recent ERROR and CRITICAL logs

Example Queries

Get Recent Errors
Show me errors from the last hour
Search for Specific Text
Search logs for "database connection failed" in the last 24 hours
Query by Severity and Time
Get all ERROR logs from the last 6 hours from k8s_container resources
Custom Filter Query
Query logs with filter: severity="WARNING" AND resource.type="gce_instance"

Cloud Logging Filter Syntax

The query_logs tool supports full Cloud Logging filter syntax:

Basic Filters

severity="ERROR"
resource.type="k8s_container"
logName="projects/my-project/logs/my-log"

Time-based Filters

timestamp>"2024-01-01T00:00:00Z"
timestamp<"2024-01-02T00:00:00Z"

Combining Filters

severity="ERROR" AND resource.type="gce_instance" AND timestamp>"2024-01-01T00:00:00Z"

Text Search

textPayload=~"error.*database"
jsonPayload.message=~"failed"

For more details, see Google Cloud Logging Query Language.

Security Notes

  • Service account keys are sensitive - treat them like passwords
  • Store key files securely and never commit them to version control
  • The .gitignore excludes .json files by default
  • Use least-privilege: grant only roles/logging.viewer unless write access is needed
  • Consider using Workload Identity for GKE deployments instead of key files
  • Rotate service account keys regularly

Troubleshooting

"Could not load credentials"

  1. Verify GOOGLE_APPLICATION_CREDENTIALS points to the correct file
  2. Check that the JSON key file is valid
  3. Ensure the file path is absolute, not relative
  4. Try running: gcloud auth application-default login as fallback

"Permission Denied"

  1. Verify the service account has required IAM roles:

    gcloud projects get-iam-policy YOUR_PROJECT_ID \
      --flatten="bindings[].members" \
      --filter="bindings.members:serviceAccount:YOUR_SA_EMAIL"
    
  2. Grant required role if missing:

    gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
      --member="serviceAccount:YOUR_SA_EMAIL" \
      --role="roles/logging.viewer"
    

"GCP_PROJECT_ID not set"

  1. Create .env file from .env.example
  2. Set GCP_PROJECT_ID=your-project-id
  3. Or set it in Claude Code config's env section

No Logs Found

  1. Verify your project has logs: Visit Cloud Logging Console
  2. Try adjusting the time range - logs might be outside the search window
  3. Check Cloud Logging API is enabled: gcloud services list --enabled | grep logging

Development

Project Structure

gcp-log-explorer-mcp/
├── src/
│   ├── auth/
│   │   └── service_account_manager.py  # Service account authentication
│   ├── logging_client/
│   │   └── client.py                    # GCP Logging API wrapper
│   ├── tools/
│   │   └── log_tools.py                 # MCP tool definitions
│   └── server.py                        # Main MCP server
├── .env                                 # Configuration (gitignored)
├── .env.example                         # Example configuration
├── requirements.txt                     # Python dependencies
├── pyproject.toml                       # Project metadata
└── README.md

Running Tests

pytest tests/

Adding New Tools

  1. Add the tool method to src/logging_client/client.py
  2. Add the tool definition and handler to src/tools/log_tools.py
  3. The tool will automatically be available in Claude Code

Best Practices

For Production

  1. Use Workload Identity (GKE) or IAM roles (GCE) instead of key files
  2. Limit permissions: Use roles/logging.viewer for read-only access
  3. Rotate keys: If using key files, rotate them every 90 days
  4. Monitor usage: Track which logs are being accessed

For Development

  1. Use separate service accounts for dev/staging/prod
  2. Test with gcloud auth application-default login before creating service accounts
  3. Never commit .env files or key files

License

MIT License

Support

For issues and questions: