Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install case-management@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin case-management v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install case-management

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/security-case-management/

Extract the ZIP to .github/skills/ in your repo. The folder name must match security-case-management for Copilot to auto-discover it.

Skill Files (4)

SKILL.md 10.2 KB
---
name: security-case-management
description: >
  Create, search, update, and manage SOC cases via the Kibana Cases API. Use when
  tracking incidents, linking alerts to cases, adding investigation notes, or managing
  triage output.
compatibility: >
  Requires Node.js 22+, network access to Kibana. Environment variables: KIBANA_URL,
  plus KIBANA_API_KEY or KIBANA_USERNAME/KIBANA_PASSWORD.
metadata:
  author: elastic
  version: 0.1.0
---

# Case Management

Manage SOC cases through the Kibana Cases API. All cases are scoped to `securitySolution` — this skill operates
exclusively within Elastic Security. Cases appear in Kibana Security and can be assigned to analysts, linked to alerts,
and pushed to external incident management systems via connectors.

## Prerequisites

Install dependencies before first use from the `skills/security` directory:

```bash
cd skills/security && npm install
```

Set the required environment variables (or add them to a `.env` file in the workspace root):

```bash
export KIBANA_URL="https://your-cluster.kb.cloud.example.com:443"
export KIBANA_API_KEY="your-kibana-api-key"
```

## When to use

- Creating a case after alert triage (classification, IOCs, findings)
- Searching for existing cases to correlate related alerts
- Adding investigation comments or attaching alerts to an existing case
- Updating case status or severity
- Listing recent cases for review

## When NOT to use

- Do not use this skill for Observability or Elasticsearch cases — it hardcodes `owner: securitySolution`
- Do not use for cases outside the Security solution space

## Execution rules

- Start executing tools immediately — do not read SKILL.md, browse the workspace, or list files first.
- Report tool output faithfully. Copy case IDs, titles, tags, severities, and counts exactly as returned by the API. Do
  not abbreviate case IDs, truncate titles, invent details, or round numbers.
- When the API returns zero results, state that explicitly — do not guess at possible results.
- When listing or finding cases, report the **exact total count** from the API response and present each case with its
  verbatim title, severity, and status.

## Quick start

All commands run from the workspace root. All output is JSON. Call the tools directly — do not read the skill file or
explore the workspace first. For attach-alert/attach-alerts, `--rule-id` and `--rule-name` are required by the Kibana
API (use `--rule-id unknown --rule-name unknown` if unknown). Use `attach-alerts` for batch with automatic rate-limit
retry and 2-second spacing between API calls.

## Common multi-step workflows

| Task                        | Tools to call (in order)                                                     |
| --------------------------- | ---------------------------------------------------------------------------- |
| **Create a case**           | `case_manager` create (title, description, tags, severity)                   |
| **Find cases for a host**   | `case_manager` find --tags "agent_id:\<id\>" or find --search "\<hostname\>" |
| **Attach alert to case**    | `case_manager` attach-alert (case-id, alert-id, alert-index, rule-id/name)   |
| **Add investigation notes** | `case_manager` add-comment (case-id, comment text)                           |
| **List recent open cases**  | `case_manager` list --status open --per-page \<n\>                           |
| **Update case**             | `case_manager` update (case-id, status/severity/tags changes)                |

**Finding cases for a host:** Use `find --search "<hostname>"` to search by hostname across title, description, and
comments. Alternatively use `find --tags "agent_id:<agent_id>"` if the agent ID is known. Always add `--status open` to
filter to active cases only. Report the exact `total` count and each case title verbatim from the API response.

```bash
# Create (syncAlerts enabled by default; disable with --sync-alerts false)
node skills/security/case-management/scripts/case-manager.js create --title "Malicious DLL sideloading on host1" --description "Crypto clipper malware detected via DLL sideloading..." --tags "classification:malicious" "confidence:88" "mitre:T1574.002" --severity critical --yes

# Find, list, get
node skills/security/case-management/scripts/case-manager.js find --tags "agent_id:550888e5-357d-4bc1-a154-486eb7b4e076"
node skills/security/case-management/scripts/case-manager.js find --search "DLL sideloading" --status open
node skills/security/case-management/scripts/case-manager.js list --status open --per-page 10
node skills/security/case-management/scripts/case-manager.js get --case-id <case_id>

# Attach single alert
node skills/security/case-management/scripts/case-manager.js attach-alert --case-id <case_id> --alert-id <alert_doc_id> --alert-index .ds-.alerts-security.alerts-default-2025.12.01-000013 --rule-id <rule_uuid> --rule-name "Malware Detection Alert"

# Attach multiple alerts (batch)
node skills/security/case-management/scripts/case-manager.js attach-alerts --case-id <case_id> --alert-ids <id1> <id2> <id3> --alert-index .ds-.alerts-security.alerts-default-2026.02.16-000016 --rule-id <rule_uuid> --rule-name "Malware Detection Alert"

# Add comment, update (--tags merges with existing tags, does not replace)
node skills/security/case-management/scripts/case-manager.js add-comment --case-id <case_id> --comment "Process tree analysis shows..."
node skills/security/case-management/scripts/case-manager.js update --case-id <case_id> --status closed --severity low --yes
```

Write operations (`create`, `update`) prompt for confirmation by default. Pass `--yes` to skip the prompt (required when
called by an agent).

## Reporting list and find results

When reporting results from `list` or `find`:

1. State the exact `total` count from the JSON response (e.g., "There are 12 open cases total").
2. Present each case as a compact one-line entry: `<title> | <severity> | <case_id_short> | <created_at>`. Copy the
   **exact title** verbatim from the `title` field — do not rephrase, abbreviate, or summarize.
3. If the user asked for N cases, present exactly N entries (or fewer if fewer exist). Do not add extra columns (alerts
   count, description, status) unless the user specifically requested them.
4. Do not add information beyond what the API returned. If a field is null or missing, omit it.
5. After presenting the results, stop. Do not add analysis, commentary, or observations about the cases.

## Tag conventions

Use structured tags for machine-searchable metadata:

| Tag pattern              | Example                             | Purpose                                          |
| ------------------------ | ----------------------------------- | ------------------------------------------------ |
| `classification:<value>` | `classification:malicious`          | Triage classification (benign/unknown/malicious) |
| `confidence:<score>`     | `confidence:85`                     | Confidence score 0-100                           |
| `mitre:<technique>`      | `mitre:T1574.002`                   | MITRE ATT&CK technique IDs                       |
| `agent_id:<id>`          | `agent_id:550888e5-...`             | Elastic agent ID for correlation                 |
| `rule:<name>`            | `rule:Malicious Behavior Detection` | Detection rule name                              |

## Case severity mapping

| Classification           | Kibana severity |
| ------------------------ | --------------- |
| benign (score 0-19)      | `low`           |
| unknown (score 20-60)    | `medium`        |
| malicious (score 61-80)  | `high`          |
| malicious (score 81-100) | `critical`      |

## Known limitations

### syncAlerts is security-only

The `syncAlerts` setting (enabled by default) synchronizes case status with attached alert statuses. This feature is
only available for Security Solution cases. Pass `--sync-alerts false` when creating a case if alert sync is not needed.

### Rate limiting

The Kibana API enforces rate limits. When attaching multiple alerts, the `attach-alerts` batch command automatically
handles 429 responses with retry. If using `attach-alert` one at a time, space calls ~10 seconds apart.

### `find --search` on Serverless

The `find --search` parameter may return 500 errors on Kibana Serverless deployments. Use `find --tags` for filtering
instead, or `list` to browse recent cases.

### `find --tags` requires exact match

Tag searches are exact-match only. `find --tags "agent_id:abc123"` works, but partial matches do not.

## Kibana Cases API reference

For detailed API endpoints, request/response formats, and examples, see
[references/kibana-cases-api.md](references/kibana-cases-api.md).

## Examples

- "Create a case for the phishing alert I triaged with severity high"
- "Search for open cases related to brute force attacks"
- "Add the investigation findings as a comment to case ID abc-123"

## Guidelines

- Report only tool output — do not invent IDs, hostnames, IPs, or details not present in the tool response.
- Preserve identifiers from the request — use exact values the user provides in tool calls and responses.
- Confirm actions concisely using the tool's return data.
- Distinguish facts from inference — label conclusions beyond tool output as your assessment.
- When presenting case lists or search results, copy the **exact title** from each case. Do not paraphrase, abbreviate,
  or summarize titles. Include the total count from the API `total` field.
- Start executing tools immediately. Do not read SKILL.md, browse directories, or list files before acting.

## Production use

- Write operations (`create`, `update`) prompt for confirmation. Pass `--yes` or `-y` to skip when called by an agent.
- Verify `KIBANA_URL` and `KIBANA_API_KEY` point to the intended cluster before running any command.
- Cases are scoped to `securitySolution` — this skill does not affect Observability or other Kibana case owners.

## Environment variables

| Variable         | Required | Description                                                      |
| ---------------- | -------- | ---------------------------------------------------------------- |
| `KIBANA_URL`     | Yes      | Kibana base URL (e.g., `https://my-kibana.kb.cloud.example.com`) |
| `KIBANA_API_KEY` | Yes      | Kibana API key for authentication                                |
references/
kibana-cases-api.md 3.9 KB
# Kibana Cases API Reference

Reference for the Kibana Cases REST API endpoints used by the case-management skill. Full documentation:
[Kibana Cases API](https://www.elastic.co/docs/api/doc/kibana/group/endpoint-cases)

## Contents

- Create a case
- Search/find cases
- Get case details
- Update cases
- Add comments
- Attach alerts
- Get alerts for a case
- Find cases for an alert

## Create a case

`POST /api/cases`

```json
{
  "title": "Malicious DLL sideloading on host1",
  "description": "Crypto clipper malware detected...",
  "tags": ["classification:malicious", "confidence:88", "mitre:T1574.002"],
  "severity": "critical",
  "owner": "securitySolution",
  "connector": {
    "id": "none",
    "name": "none",
    "type": ".none",
    "fields": null
  },
  "settings": {
    "syncAlerts": true
  }
}
```

**Response** returns the full case object with `id`, `version`, `created_at`, etc.

**Severity values**: `low`, `medium`, `high`, `critical`

**Owner**: Use `securitySolution` for Elastic Security cases.

## Search/find cases

`GET /api/cases/_find`

Query parameters:

| Param       | Description                                                         |
| ----------- | ------------------------------------------------------------------- |
| `search`    | Free-text search across title, description, comments                |
| `tags`      | Filter by tags (repeat for multiple)                                |
| `status`    | `open`, `in-progress`, `closed`                                     |
| `severity`  | `low`, `medium`, `high`, `critical`                                 |
| `sortField` | `createdAt`, `updatedAt`, `closedAt`, `title`, `severity`, `status` |
| `sortOrder` | `asc`, `desc`                                                       |
| `page`      | Page number (1-based)                                               |
| `perPage`   | Results per page (default 20, max 100)                              |
| `owner`     | Filter by owner (e.g., `securitySolution`)                          |

Example:

```text
GET /api/cases/_find?tags=classification:malicious&status=open&sortField=createdAt&sortOrder=desc
```

## Get case details

`GET /api/cases/{caseId}`

Returns the full case object including comments count, alerts count, and connector info.

## Update cases

`PATCH /api/cases`

Body is an array of case updates:

```json
{
  "cases": [
    {
      "id": "<case_id>",
      "version": "<case_version>",
      "status": "closed",
      "severity": "low",
      "tags": ["classification:benign", "confidence:10"]
    }
  ]
}
```

The `version` field is required for optimistic concurrency control. Get it from a prior GET request.

## Add comments

`POST /api/cases/{caseId}/comments`

User comment:

```json
{
  "type": "user",
  "comment": "Process tree analysis shows legitimate Lenovo utility loading unsigned DLL..."
}
```

## Attach alerts

`POST /api/cases/{caseId}/comments`

Alert attachment (one alert):

```json
{
  "type": "alert",
  "alertId": "<alert_doc_id>",
  "index": ".ds-.alerts-security.alerts-default-2025.12.01-000013",
  "rule": {
    "id": "<rule_id>",
    "name": "Malicious Behavior Detection Alert"
  },
  "owner": "securitySolution"
}
```

Multiple alerts can be attached by repeating the call or using bulk attachment.

## Get alerts for a case

`GET /api/cases/{caseId}/alerts`

Returns all alerts linked to the case.

## Find cases for an alert

`GET /api/cases/alerts/{alertId}`

Returns all cases that contain the given alert ID. Useful for checking if an alert is already part of a case before
creating a new one.

## Required headers

All requests require:

```text
Content-Type: application/json
kbn-xsrf: true
Authorization: ApiKey <base64_api_key>
```

These are handled automatically by `kibana-client.js` in the shared directory.

## Spaces

If using Kibana Spaces, prefix paths with `/s/<space_name>`:

```text
POST /s/security-ops/api/cases
```

The `KibanaClient` accepts a `space` parameter for this.
scripts/
case-manager.js 8.6 KB
#!/usr/bin/env node
/**
 * Case management CLI wrapping the Kibana Cases REST API.
 * Creates, searches, updates cases and attaches alerts/comments.
 */

import { createInterface } from "readline";
import { kibanaGet, kibanaPatch, kibanaPost } from "./kibana-client.js";

const OWNER = "securitySolution";

function promptConfirm(message) {
  const rl = createInterface({ input: process.stdin, output: process.stderr });
  return new Promise((resolve) => {
    rl.question(`${message} [y/N] `, (answer) => {
      rl.close();
      resolve(answer.trim().toLowerCase() === "y");
    });
  });
}

function parseArgs(argv) {
  const result = {};
  for (let i = 0; i < argv.length; i++) {
    const arg = argv[i];
    if (arg === "-y") {
      result.yes = true;
    } else if (arg.startsWith("--")) {
      const key = arg.slice(2).replace(/-/g, "_");
      const next = argv[i + 1];
      if (next !== undefined && !next.startsWith("--")) {
        const values = [];
        let j = i + 1;
        while (j < argv.length && !argv[j].startsWith("--")) {
          values.push(argv[j]);
          j++;
        }
        result[key] = values.length === 1 ? values[0] : values;
        i = j - 1;
      } else {
        result[key] = true;
      }
    }
  }
  return result;
}

async function createCase(args, space) {
  const syncAlerts = args.sync_alerts !== "false";
  const body = {
    title: args.title,
    description: args.description || "",
    tags: Array.isArray(args.tags) ? args.tags : args.tags ? [args.tags] : [],
    severity: args.severity || "medium",
    owner: OWNER,
    connector: { id: "none", name: "none", type: ".none", fields: null },
    settings: { syncAlerts },
  };
  if (args.assignees) {
    const assigneeList = Array.isArray(args.assignees) ? args.assignees : [args.assignees];
    body.assignees = assigneeList.map((uid) => ({ uid }));
  }
  const result = await kibanaPost("/api/cases", body, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function getCase(args, space) {
  const result = await kibanaGet(`/api/cases/${args.case_id}`, undefined, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function findCases(args, space) {
  const params = { owner: OWNER, sortField: "createdAt", sortOrder: "desc" };
  if (args.tags) params.tags = args.tags;
  if (args.status) params.status = args.status;
  if (args.severity) params.severity = args.severity;
  if (args.search) params.search = args.search;
  if (args.per_page) params.perPage = args.per_page;
  if (args.page) params.page = args.page;

  const result = await kibanaGet("/api/cases/_find", params, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function listCases(args, space) {
  const listArgs = { ...args, search: null, tags: null, severity: null };
  if (!listArgs.per_page) listArgs.per_page = 10;
  if (!listArgs.page) listArgs.page = 1;
  return findCases(listArgs, space);
}

async function addComment(args, space) {
  const body = { type: "user", comment: args.comment, owner: OWNER };
  const result = await kibanaPost(`/api/cases/${args.case_id}/comments`, body, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function attachAlert(args, space) {
  const body = {
    type: "alert",
    alertId: args.alert_id,
    index: args.alert_index,
    owner: OWNER,
    rule: {
      id: args.rule_id || "unknown",
      name: args.rule_name || "unknown",
    },
  };
  const result = await kibanaPost(`/api/cases/${args.case_id}/comments`, body, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function attachAlertsBatch(args, space) {
  const alertIds = Array.isArray(args.alert_ids) ? args.alert_ids : [args.alert_ids];
  const index = args.alert_index;
  const ruleId = args.rule_id || "unknown";
  const ruleName = args.rule_name || "unknown";

  const attachments = alertIds.map((aid) => ({
    type: "alert",
    alertId: aid,
    index,
    owner: OWNER,
    rule: { id: ruleId, name: ruleName },
  }));

  const result = await kibanaPost(`/internal/cases/${args.case_id}/attachments/_bulk_create`, attachments, space, {
    "x-elastic-internal-origin": "kibana",
  });
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function updateCase(args, space) {
  const current = await kibanaGet(`/api/cases/${args.case_id}`, undefined, space);
  const version = current.version;

  const update = { id: args.case_id, version };
  if (args.status) update.status = args.status;
  if (args.severity) update.severity = args.severity;
  if (args.tags) {
    const newTags = Array.isArray(args.tags) ? args.tags : [args.tags];
    const merged = [...new Set([...(current.tags || []), ...newTags])];
    update.tags = merged;
  }
  if (args.title) update.title = args.title;
  if (args.description) update.description = args.description;

  const result = await kibanaPatch("/api/cases", { cases: [update] }, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function casesForAlert(args, space) {
  const result = await kibanaGet(`/api/cases/alerts/${args.alert_id}`, undefined, space);
  console.log(JSON.stringify(result, null, 2));
  return result;
}

async function main() {
  const cmd = process.argv[2];
  const rawArgs = parseArgs(process.argv.slice(3));
  const space = rawArgs.space;
  const yes = rawArgs.yes === true;

  const requireArg = (name, msg) => {
    const val = rawArgs[name];
    if (val === undefined || val === null || val === "") {
      console.error(`Error: ${msg}`);
      process.exit(1);
    }
    return val;
  };

  try {
    switch (cmd) {
      case "create": {
        requireArg("title", "--title is required");
        if (!yes) {
          const ok = await promptConfirm(`Create case "${rawArgs.title}"?`);
          if (!ok) {
            console.log("Aborted.");
            process.exit(0);
          }
        }
        await createCase(rawArgs, space);
        break;
      }
      case "get": {
        requireArg("case_id", "--case-id is required");
        await getCase(rawArgs, space);
        break;
      }
      case "find":
        await findCases(rawArgs, space);
        break;
      case "list":
        await listCases(rawArgs, space);
        break;
      case "add-comment": {
        requireArg("case_id", "--case-id is required");
        requireArg("comment", "--comment is required");
        if (!yes) {
          const ok = await promptConfirm(`Add comment to case ${rawArgs.case_id}?`);
          if (!ok) {
            console.log("Aborted.");
            process.exit(0);
          }
        }
        await addComment(rawArgs, space);
        break;
      }
      case "attach-alert": {
        requireArg("case_id", "--case-id is required");
        requireArg("alert_id", "--alert-id is required");
        requireArg("alert_index", "--alert-index is required");
        if (!yes) {
          const ok = await promptConfirm(`Attach alert ${rawArgs.alert_id} to case ${rawArgs.case_id}?`);
          if (!ok) {
            console.log("Aborted.");
            process.exit(0);
          }
        }
        await attachAlert(rawArgs, space);
        break;
      }
      case "attach-alerts": {
        requireArg("case_id", "--case-id is required");
        requireArg("alert_ids", "--alert-ids is required");
        requireArg("alert_index", "--alert-index is required");
        const ids = Array.isArray(rawArgs.alert_ids) ? rawArgs.alert_ids : [rawArgs.alert_ids];
        if (!yes) {
          const ok = await promptConfirm(`Attach ${ids.length} alert(s) to case ${rawArgs.case_id}?`);
          if (!ok) {
            console.log("Aborted.");
            process.exit(0);
          }
        }
        await attachAlertsBatch(rawArgs, space);
        break;
      }
      case "update": {
        requireArg("case_id", "--case-id is required");
        if (!yes) {
          const ok = await promptConfirm(`Update case ${rawArgs.case_id}?`);
          if (!ok) {
            console.log("Aborted.");
            process.exit(0);
          }
        }
        await updateCase(rawArgs, space);
        break;
      }
      case "cases-for-alert": {
        requireArg("alert_id", "--alert-id is required");
        await casesForAlert(rawArgs, space);
        break;
      }
      default:
        console.error(
          "Error: unknown command. Use: create, get, find, list, add-comment, attach-alert, attach-alerts, update, cases-for-alert",
        );
        process.exit(1);
    }
  } catch (err) {
    console.error(`Error: ${err.message}`);
    process.exit(1);
  }
}

main().catch((err) => {
  console.error(`Error: ${err.message}`);
  process.exit(1);
});
kibana-client.js 6.7 KB
/**
 * Lightweight HTTP client for the Kibana REST API.
 * Uses native fetch() with auth, retry on 429, and space support.
 */

try {
  process.loadEnvFile();
} catch {}

const RETRY_DELAYS = [5, 10, 20];

export function getKibanaConfig() {
  const url = process.env.KIBANA_URL;
  const apiKey = process.env.KIBANA_API_KEY;
  const username = process.env.KIBANA_USERNAME || process.env.ELASTICSEARCH_USERNAME;
  const password = process.env.KIBANA_PASSWORD || process.env.ELASTICSEARCH_PASSWORD;
  const spaceId = process.env.KIBANA_SPACE_ID;
  const insecure = process.env.KIBANA_INSECURE === "true";

  if (!url) {
    console.error("Error: No Kibana connection configured.");
    console.error("Set KIBANA_URL environment variable.");
    process.exit(1);
  }

  if (!apiKey && !username && !password && process.env.KIBANA_NO_AUTH !== "true") {
    console.error("Error: No Kibana authentication configured.");
    console.error("Set KIBANA_API_KEY or KIBANA_USERNAME + KIBANA_PASSWORD.");
    console.error("Or set KIBANA_NO_AUTH=true for clusters with security disabled.");
    process.exit(1);
  }

  if (!apiKey && ((username && !password) || (!username && password))) {
    console.error("Error: Both username and password must be set for basic auth.");
    console.error("Set KIBANA_USERNAME + KIBANA_PASSWORD (or ELASTICSEARCH_USERNAME + ELASTICSEARCH_PASSWORD).");
    process.exit(1);
  }

  return { url, apiKey, username, password, spaceId, insecure };
}

function getHeaders(config) {
  const headers = {
    "Content-Type": "application/json",
    "kbn-xsrf": "true",
    "User-Agent": "elastic-agentic",
  };

  if (config.apiKey) {
    headers["Authorization"] = `ApiKey ${config.apiKey}`;
  } else if (config.username && config.password) {
    const auth = Buffer.from(`${config.username}:${config.password}`).toString("base64");
    headers["Authorization"] = `Basic ${auth}`;
  }

  return headers;
}

function getBasePath(config, space) {
  let basePath = config.url.replace(/\/$/, "");
  const effectiveSpace = space || config.spaceId;
  if (effectiveSpace && effectiveSpace !== "default") {
    basePath += `/s/${effectiveSpace}`;
  }
  return basePath;
}

/**
 * Make an HTTP request to the Kibana API with automatic 429 retry.
 *
 * @param {string} path - API path (e.g. "/api/cases")
 * @param {object} [options] - fetch options (method, body, headers, params)
 * @param {string} [options.space] - Override Kibana space for this request
 * @returns {{ success: boolean, data?: any, status?: number, error?: string }}
 */
export async function kibanaFetch(path, options = {}) {
  const config = getKibanaConfig();
  const { space, params, ...fetchOpts } = options;
  const basePath = getBasePath(config, space);

  let url = `${basePath}${path}`;
  if (params) {
    const searchParams = new URLSearchParams();
    for (const [key, value] of Object.entries(params)) {
      if (value !== undefined && value !== null) {
        if (Array.isArray(value)) {
          for (const v of value) searchParams.append(key, v);
        } else {
          searchParams.append(key, String(value));
        }
      }
    }
    const qs = searchParams.toString();
    if (qs) url += `?${qs}`;
  }

  const requestOptions = {
    ...fetchOpts,
    headers: {
      ...getHeaders(config),
      ...fetchOpts.headers,
    },
  };

  if (config.insecure) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  }

  for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt++) {
    try {
      const response = await fetch(url, requestOptions);

      if (response.status === 429 && attempt < RETRY_DELAYS.length) {
        const delay = RETRY_DELAYS[attempt];
        console.error(`Rate limited, retrying in ${delay}s (attempt ${attempt + 1}/${RETRY_DELAYS.length + 1})...`);
        await new Promise((r) => setTimeout(r, delay * 1000));
        continue;
      }

      const contentType = response.headers.get("content-type");
      let data;
      if (contentType && contentType.includes("application/json")) {
        data = await response.json();
      } else {
        data = await response.text();
      }

      if (!response.ok) {
        return {
          success: false,
          status: response.status,
          error: data?.message || data?.error || `HTTP ${response.status}`,
          details: data,
        };
      }

      return { success: true, data };
    } catch (error) {
      if (attempt < RETRY_DELAYS.length && error.message?.includes("429")) {
        const delay = RETRY_DELAYS[attempt];
        console.error(`Rate limited, retrying in ${delay}s...`);
        await new Promise((r) => setTimeout(r, delay * 1000));
        continue;
      }
      return { success: false, error: error.message, details: error };
    }
  }
}

/**
 * Convenience wrappers matching the Python KibanaClient interface.
 * These throw on HTTP errors (matching the old behavior where scripts
 * relied on exceptions for error handling).
 */
export async function kibanaGet(path, params, space) {
  const result = await kibanaFetch(path, { method: "GET", params, space });
  if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
  return result.data;
}

export async function kibanaPost(path, body, space, extraHeaders) {
  const result = await kibanaFetch(path, {
    method: "POST",
    body: body !== undefined ? JSON.stringify(body) : undefined,
    headers: extraHeaders,
    space,
  });
  if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
  return result.data;
}

export async function kibanaPatch(path, body, space) {
  const result = await kibanaFetch(path, {
    method: "PATCH",
    body: body !== undefined ? JSON.stringify(body) : undefined,
    space,
  });
  if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
  return result.data;
}

export async function kibanaPut(path, body, space) {
  const result = await kibanaFetch(path, {
    method: "PUT",
    body: body !== undefined ? JSON.stringify(body) : undefined,
    space,
  });
  if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
  return result.data;
}

export async function kibanaDelete(path, space) {
  const result = await kibanaFetch(path, { method: "DELETE", space });
  if (!result.success) throw new Error(result.error || `HTTP ${result.status}`);
  return result.data;
}

export async function testConnection(space) {
  try {
    const status = await kibanaGet("/api/status", undefined, space);
    const version = status?.version;
    const versionStr = typeof version === "object" ? version?.number : version;
    console.log(`Connected to Kibana: ${status?.name || "unknown"}`);
    console.log(`Version: ${versionStr || "unknown"}`);
    return true;
  } catch (error) {
    console.error(`Connection failed: ${error.message}`);
    return false;
  }
}

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/elastic/agent-skills/blob/main/LICENSE