# Coralogix MCP Server

MCP server exposing a Coralogix query tool for AI agents.

## Overview

This Model Context Protocol (MCP) server provides tools for AI agents to query Coralogix logs and manage alert definitions using either Lucene or DataPrime syntax.

## Installation

Install the MCP server using npm:

```bash
npx -y @nickholden/coralogix-mcp-server@latest
```

## MCP Configuration

Add this configuration to your MCP settings file (e.g., `cline_mcp_settings.json`):

```json
"coralogix-mcp-server": {
  "autoApprove": [
    "coralogix_query",
    "create_alert",
    "update_alert",
    "delete_alert",
    "get_alert",
    "list_alerts"
  ],
  "disabled": false,
  "timeout": 60,
  "type": "stdio",
  "command": "npx",
  "args": [
    "-y",
    "@nickholden/coralogix-mcp-server@latest"
  ],
  "env": {
    "CORALOGIX_API_KEY": "PUT_YOUR_API_KEY_HERE",
    "CORALOGIX_REGION": "auto",
    "CORALOGIX_ENV": "production"
  }
}
```

### Getting a Coralogix API Key

1. Log in to your Coralogix account
2. Navigate to Settings → API Keys
3. Create a new API key with appropriate permissions (see Required Permissions below)
4. Copy the key and replace `PUT_YOUR_API_KEY_HERE` in the configuration above

#### Required Permissions

The MCP server requires specific permissions based on the operations you want to perform:

**Essential Permissions (Required for all operations):**
- **Logs Query** - Required for `coralogix_query` tool
- **External API Access** - Required for all alert management operations

**Alert Management Permissions:**
- **Alerts Management** - Required for `create_alert`, `list_alerts`, `get_alert` operations
- **Integrations Read** - Required for notification groups functionality (converts integration names to IDs)

**API Key Type:**
- **Personal API Key** recommended - Works with all v2 External API endpoints
- Team-scoped API keys may have limitations with certain endpoints

**Operations by Permission Level:**

| Operation | Required Permissions | API Endpoint Used |
|-----------|---------------------|-------------------|
| `coralogix_query` | Logs Query | `/api/v1/dataprime/query` |
| `create_alert` | Alerts Management + Integrations Read | `/api/v2/external/alerts` + `/api/v1/external/integrations` |
| `list_alerts` | Alerts Management | `/api/v2/external/alerts` |
| `get_alert` | Alerts Management | `/api/v2/external/alerts` (via list) |
| `update_alert` | Alerts Management + Integrations Read | `/com.coralogixapis.alerts.v3.AlertDefsService/ReplaceAlertDef` (gRPC-Web) |
| `delete_alert` | Alerts Management | `/com.coralogixapis.alerts.v3.AlertDefsService/DeleteAlertDef` (gRPC-Web) |

**Note about Notification Groups:**
The server automatically converts friendly integration names to the required numeric IDs:

1. **With Integrations Permission**: Uses `/api/v1/external/integrations` endpoint for real-time lookup
2. **Without Integrations Permission**: Falls back to known integration mappings:
   - `"attorneys-stats-errors"` → ID: 7047 (Slack)
   - `"vinny-dispatch-alerts"` → ID: 8447 (Slack)
   - `"required-documents-alerts"` → ID: 10426 (Slack)

**Recommendation**: Add "Integrations Read" permission to your API key for full integration discovery. The fallback ensures core functionality works even without this permission.

### Regional Configuration

The server automatically detects your Coralogix region, but you can configure it explicitly:

**Environment Variables:**
- `CORALOGIX_REGION`: Set to `eu`, `us1`, `us2`, `ap1`, `ap2`, or `auto` (default: auto-detect)
- `CORALOGIX_ENV`: Optional - Set to `production`, `staging`, or `development` for debugging context
- `NODE_ENV`: Alternative to `CORALOGIX_ENV` for environment identification

**Supported Regions:**
- `eu`: Europe (coralogix.com)
- `us1`: US East (us1.coralogix.com)
- `us2`: US West (us2.coralogix.com)
- `ap1`: Asia Pacific India (app.coralogix.in)
- `ap2`: Asia Pacific Singapore (coralogixsg.com)

If region auto-detection fails, check your API key and network connectivity.

### Environment Configuration Examples

**Production Environment:**
```json
{
  "env": {
    "CORALOGIX_API_KEY": "your_production_api_key",
    "CORALOGIX_REGION": "eu",
    "CORALOGIX_ENV": "production"
  }
}
```

**Staging Environment:**
```json
{
  "env": {
    "CORALOGIX_API_KEY": "your_staging_api_key", 
    "CORALOGIX_REGION": "eu",
    "CORALOGIX_ENV": "staging"
  }
}
```

**Development Environment:**
```json
{
  "env": {
    "CORALOGIX_API_KEY": "your_dev_api_key",
    "CORALOGIX_REGION": "eu", 
    "CORALOGIX_ENV": "development"
  }
}
```

## Development Setup

For local development:

```bash
git clone https://github.com/nickohold/coralogix-mcp-server.git
cd coralogix-mcp-server
npm install
npm run build
```

## Usage

### Available Tools

The server exposes the following tools:

#### `coralogix_query`
Query Coralogix logs and aggregations.

**Parameters:**
- `query` (string, required): Lucene/DataPrime query string
- `syntax` (string, optional): `"QUERY_SYNTAX_LUCENE"` or `"QUERY_SYNTAX_DATAPRIME"` (default)
- `startDate` (string, optional): ISO-8601 start date (default: now - 15 min)
- `endDate` (string, optional): ISO-8601 end date (default: now)
- `limit` (integer, optional): Maximum results (1-1000)

#### Alert Management Tools

**`create_alert`**: Create a new alert definition
- `alert` (object, required): Alert definition with name, description, priority, etc.
- `alert.notificationGroups` (array, optional): List of integration names for notifications (e.g., `["slack-alerts"]`)

**`update_alert`**: Update an existing alert
- `id` (string, required): Alert ID
- `alert` (object, required): Updated alert properties
- Supports notification groups with automatic integration ID lookup

**`delete_alert`**: Delete an alert
- `id` (string, required): Alert ID
- `safety` (object, optional): Safety configuration (deprecated but kept for compatibility)

**`get_alert`**: Get a specific alert by ID
- `id` (string, required): Alert ID

**`list_alerts`**: List all alerts with optional filtering
- `limit` (number, optional): Maximum alerts to return
- `offset` (number, optional): Pagination offset
- `filter` (object, optional): Filter by enabled, priority, or alertType

### Example Usage with AI Agent

Query recent error logs:
```json
{
  "tool": "coralogix_query",
  "arguments": {
    "query": "source logs | filter severity == `Error`",
    "syntax": "QUERY_SYNTAX_DATAPRIME",
    "limit": 50
  }
}
```

Search for specific text in logs:
```json
{
  "tool": "coralogix_query",
  "arguments": {
    "query": "error OR failed",
    "syntax": "QUERY_SYNTAX_LUCENE",
    "startDate": "2025-06-11T12:00:00.000Z",
    "endDate": "2025-06-11T13:00:00.000Z"
  }
}
```

Count logs by application:
```json
{
  "tool": "coralogix_query",
  "arguments": {
    "query": "source logs | count by applicationName"
  }
}
```

Create an alert with Slack notifications:
```json
{
  "tool": "create_alert",
  "arguments": {
    "alert": {
      "name": "High Error Rate Alert",
      "description": "Alert when error rate exceeds threshold",
      "priority": "warning",
      "enabled": true,
      "alertType": "LOGS_THRESHOLD",
      "notificationGroups": ["slack-alerts", "team-notifications"],
      "filters": {
        "query": "level:ERROR",
        "severities": ["error"]
      },
      "conditions": {
        "threshold": 10,
        "timeWindow": "5MIN"
      }
    }
  }
}
```

### Alert Management Features

Full alert lifecycle management using v2 External API:

#### Supported Operations
- **`create_alert`**: Create new alerts with notification groups
- **`update_alert`**: Update existing alerts (PUT operation)
- **`delete_alert`**: Delete alerts (DELETE operation)  
- **`list_alerts`**: List and filter alerts
- **`get_alert`**: Get specific alert details

#### Key Features
- **Notification Groups**: Automatic conversion of integration names to IDs (requires integrations permission)
- **Hybrid API Strategy**: v2 for create/read, v3 for update/delete operations
- **Full CRUD Support**: Complete alert lifecycle management
- **Error Handling**: Comprehensive error messages and context
- **Regional Support**: Automatic region detection

## Development

### Setup

```bash
git clone <repository>
cd coralogix-mcp-server
npm install
```

### Build

```bash
npm run build
```

### Watch Mode

```bash
npm run watch
```

### Testing

```bash
npm test
```

### Inspector

Use the MCP inspector to test the server:

```bash
npm run inspector
```

## API Reference

### Alert Management Endpoints

The server uses Coralogix External API v2 for optimal compatibility:
- **CREATE**: External API v2 (`/api/v2/external/alerts`) with notification group support
- **READ (GET/LIST)**: External API v2 (`/api/v2/external/alerts`)
- **UPDATE**: gRPC-Web v3 (`/com.coralogixapis.alerts.v3.AlertDefsService/ReplaceAlertDef`)
- **DELETE**: gRPC-Web v3 (`/com.coralogixapis.alerts.v3.AlertDefsService/DeleteAlertDef`)

**API Version Strategy:**
- **v2 External API**: Primary API for create and read operations (simple, reliable)
- **v3 gRPC-Web API**: Used for update and delete operations (full functionality)
- **v1 External API**: Used only for integration lookup (`/api/v1/external/integrations`) and DataPrime queries (`/api/v1/dataprime/query`)

This hybrid approach provides full CRUD functionality while using the most appropriate API version for each operation.

#### Notification Groups

The server automatically converts notification group names (e.g., `"slack-alerts"`) to the required numeric integration IDs using the `/api/v1/external/integrations` endpoint. This enables seamless Slack and webhook notifications without manual ID lookup.

## API Documentation

For detailed API schemas and protobuf definitions, refer to the official Coralogix documentation:

- **v3 gRPC API Schema**: [GitHub - coralogix/cx-api-alerts](https://github.com/coralogix/cx-api-alerts/blob/master/docs/alert-api-v3.md)
- **Official API Documentation**: [Coralogix Alerts API v3](https://coralogix.com/docs/developer-portal/apis/data-management/alerts-api/alerts-grpc-api/)

**Note**: The GitHub repository contains the authoritative protobuf definitions and examples for the v3 gRPC API.

### Coralogix Query Syntax

The server supports both Lucene and DataPrime query syntaxes:

**Lucene Examples:**
- `error OR failed` - Search for logs containing "error" or "failed"
- `severity:Error` - Filter by severity level
- `applicationName:"my-app" AND level:ERROR` - Complex filtering

**DataPrime Examples:**
- `source logs | filter severity == 'Error'` - Filter error logs
- `source logs | count by applicationName` - Count by application
- `source logs | filter timestamp > now() - 1h` - Recent logs

### Default Behavior

- **Time Range**: If no `startDate`/`endDate` provided, queries the last 15 minutes
- **Syntax**: Defaults to `QUERY_SYNTAX_DATAPRIME` if not specified
- **Timeout**: Requests timeout after 30 seconds

## Error Handling

The server provides detailed error messages for:
- Missing or invalid API key
- Invalid query parameters
- Coralogix API errors
- Network timeouts

## License

MIT
