К основному содержанию
скилл CX Codex

launchdarkly-metric-instrument — скилл для Claude Code

Добавляет вызовы track() для метрик LaunchDarkly в клиентский или серверный код и проверяет отправку событий.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add launchdarkly/ai-tooling --skill launchdarkly-metric-instrument -a claude-code
Открыть на GitHub

Что делает launchdarkly-metric-instrument

Скилл определяет, установлен ли LaunchDarkly SDK в проекте, и проверяет его тип. Для серверных SDK (Node.js, Python, Go, Java, Ruby, .NET) контекст передаётся обязательным аргументом в каждый вызов track(). В клиентских библиотеках вроде React контекст задаётся один раз при инициализации клиента.

Если SDK ещё нет, агент находит файл блокировки пакетов вроде package-lock.json или poetry.lock, ставит нужную зависимость и настраивает инициализацию. Вызов track() привязывается к существующему объекту контекста, чтобы не нарушать сегментацию экспериментов. Числовые замеры вроде задержки или суммы покупки передаются через параметр metricValue.

Для работы обязательно нужен удалённый LaunchDarkly MCP-сервер с инструментом list-metric-events. Без него агент не сможет проверить, доходят ли события до платформы после вызова.

Какие задачи решает

  • добавить вызов track() в обработчик действия пользователя
  • определить тип SDK LaunchDarkly и формат передачи контекста
  • установить и инициализировать нужный SDK при его отсутствии
  • проверить поступление метрики через инструмент list-metric-events

Примеры запросов агенту

  • Добавь трекинг LaunchDarkly на успешное оформление заказа в форме оплаты.
  • Настрой вызов track() для замера времени ответа в API-эндпоинте.
  • Проверь через LaunchDarkly MCP, доходят ли события метрики checkout-completed.

Как установить launchdarkly-metric-instrument

1Через Skills CLI (Vercel)

npx skills add launchdarkly/ai-tooling --skill launchdarkly-metric-instrument -a claude-code

2Вручную: положить файлы

~/.claude/skills/launchdarkly-metric-instrument/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/launchdarkly-metric-instrument/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о launchdarkly-metric-instrument

Как установить launchdarkly-metric-instrument в Claude Code?

Выполните команду npx skills add launchdarkly/ai-tooling --skill launchdarkly-metric-instrument -a claude-code.

Что делает launchdarkly-metric-instrument?

Находит подходящее место в кодовой базе, добавляет вызов track() с правильными аргументами под используемый SDK и подтверждает отправку события.

Что нужно настроить перед запуском скилла?

Требуется удалённый LaunchDarkly MCP-сервер с активным инструментом list-metric-events, а для получения ключей сред пригодится инструмент get-project.

Исходный текст

SKILL.md · Apache-2.0
---
name: launchdarkly-metric-instrument
description: "Instrument a LaunchDarkly metric event in a codebase by adding a track() call. Use when the user wants to wire up an event, instrument an action for a metric, add tracking to a feature, or confirm that an event is flowing to LaunchDarkly."
license: Apache-2.0
compatibility: Requires the remotely hosted LaunchDarkly MCP server
metadata:
  author: launchdarkly
  version: "1.0.0-experimental"
---

# LaunchDarkly Metric Instrument

You're using a skill that will guide you through adding a `track()` call to a codebase so a LaunchDarkly metric can measure it. Your job is to detect the SDK in use, find the right place in code to add the call, write it correctly, and verify that events are reaching LaunchDarkly.

## Prerequisites

This skill requires the remotely hosted LaunchDarkly MCP server to be configured in your environment.

**Required MCP tools:**
- `list-metric-events` — verify events are flowing after instrumentation

**Optional MCP tools (enhance workflow):**
- `get-project` — retrieve the SDK key for the right environment when SDK initialization is needed

## Workflow

### Step 1: Detect the SDK

Before writing any code, understand the LaunchDarkly setup already in this codebase.

1. **Search for existing `track()` calls.** This is the fastest signal:
   - Look for `ldClient.track(`, `.track(`, `ld.track(`
   - If any exist, they tell you the SDK type, call signature, and context pattern in one shot — mirror those exactly.

2. **Search for SDK imports and initialization** if no `track()` calls exist:
   - Check `package.json`, `requirements.txt`, `go.mod`, `Gemfile`, `*.csproj` for an LD SDK dependency
   - Look for `LDClient`, `ldclient`, `launchdarkly-server-sdk`, `launchdarkly-node-server-sdk`, `launchdarkly-react-client-sdk`, etc.
   - Find the initialization block to understand how the client is accessed across the codebase

3. **Determine client-side or server-side.** This is the most critical distinction — it determines the `track()` signature:

   | SDK type | `track()` signature | Notes |
   |----------|---------------------|-------|
   | Server-side (Node, Python, Go, Java, Ruby, .NET) | `ldClient.track(eventKey, context, data?, metricValue?)` | Context required per call |
   | Client-side (React, browser JS) | `ldClient.track(eventKey, data?, metricValue?)` | Context set at init, not per call |

   See [SDK Track Patterns](references/sdk-track-patterns.md) for full examples by language.

### Step 2: Install & Initialize (if SDK not present)

Skip this step if the SDK is already in the codebase.

1. **Detect the package manager** from lockfiles: `package-lock.json` / `yarn.lock` / `pnpm-lock.yaml` → npm/yarn/pnpm; `Pipfile.lock` / `poetry.lock` → pip/poetry; `go.sum` → go modules; `Gemfile.lock` → bundler.

2. **Install the appropriate SDK** using the detected package manager. See [SDK Track Patterns](references/sdk-track-patterns.md) for the right package name per language.

3. **Get the SDK key** using `get-project` — fetch the project and choose the key for the environment the user wants to instrument (typically `production` or `staging` for initial testing).

4. **Add SDK initialization** following the patterns already in this codebase. If there's a central config or service layer, add the LD client there. See [SDK Track Patterns](references/sdk-track-patterns.md) for initialization examples.

### Step 3: Find the Right Placement

Locate where in the code the user action or event occurs.

1. **Ask if you're not sure** where the action happens. Don't guess at placement — a `track()` call in the wrong location (e.g. a render method instead of a submit handler) produces misleading data.

2. **Look for signals of the right location:**
   - Form submissions, button click handlers, API route completions, mutation hooks
   - Existing analytics calls (`segment.track()`, `mixpanel.track()`, `gtag()`) — these are often co-located with where LD track calls should go
   - Comments like `// TODO: track this`

3. **Show the candidate location** to the user before writing anything:
   ```
   I'll add the track() call here, in the checkout submit handler (src/checkout/CheckoutForm.tsx, line 47).
   Does that look right?
   ```

4. **Proceed once confirmed** (or if you're confident enough from codebase signals).

### Step 4: Write the `track()` Call

Write the call following the patterns found in Step 1.

**Server-side SDKs** — context is required:
```typescript
ldClient.track('checkout-completed', context);
```

**Client-side SDKs** — context is implicit:
```typescript
ldClient.track('checkout-completed');
```

**For `value` metrics** — include `metricValue` with the numeric measurement:
```typescript
// Server-side: latency metric (ms)
ldClient.track('api-response-time', context, null, responseTimeMs);

// Client-side: revenue metric
ldClient.track('purchase-completed', { orderId }, purchaseAmountUSD);
```

**Key rules:**
- **Match the existing context.** Don't construct a new context inline. Find where the codebase already builds its context/user object (used for `variation()` calls) and use the same one. This is how LD correlates the event to the right experiment participant.
- **`metricValue` only for `value` metrics.** For `count` and `occurrence` metrics, omit `metricValue` entirely.
- **Respect wrapper patterns.** If the codebase wraps LD calls behind a utility (`featureFlags.track()`, `analytics.ldTrack()`), add the new call through that wrapper — not by calling `ldClient` directly.
- **Match the event key exactly.** `track()` event keys are case-sensitive. Use the exact string that the metric was created with.

See [SDK Track Patterns](references/sdk-track-patterns.md) for full per-language examples.

### Step 5: Verify

**Guide the user to trigger the action** in their local or staging environment. Then use `list-metric-events` to confirm the event key appears:

```
list-metric-events(projectKey, environmentKey)
```

**If the event key appears:** confirm success and show a summary.

**If the event key is absent after triggering**, work through this checklist:

| Problem | Check |
|---------|-------|
| Wrong event key casing | Does the `track()` call match the metric's event key exactly? |
| SDK not initialized | Is `ldClient` initialized before the `track()` call runs? |
| Server-side: wrong context | Is the context passed to `track()` the same context used for `variation()` calls? |
| Client-side: no flag evaluation first | Has the SDK initialized and identified the user before `track()` is called? |
| Wrong environment | Is `list-metric-events` querying the same environment where the action was triggered? |
| Data delay | `list-metric-events` shows the last 90 days with up to ~5 min delay — try again in a moment |

Surface a summary once verified:

```
✓ Event flowing: checkout-completed
  Seen in: production
  
Next: this event is now ready to back a metric. Use the metric-create skill to set one up,
or attach an existing metric to your experiment.
```

## Important Context

- **`track()` calls only count in experiments when a flag is evaluated first.** The event is correlated to an experiment participant because LD saw a `variation()` call from that context. If the user triggers the action without evaluating any flag, the event may still be ingested but won't appear in experiment results.
- **Client-side SDKs flush events on an interval** (default ~30 seconds) or on page unload. In tests, you may need to call `ldClient.flush()` explicitly to see events appear immediately.
- **Server-side SDKs also buffer events.** Calling `ldClient.flush()` after `track()` in development ensures the event is sent before the process exits or the test ends.
- **`metricValue` units must match the metric definition.** If the metric was created with unit `ms`, pass milliseconds. Passing seconds into a milliseconds metric will produce silently wrong results.
- **The `data` parameter is for custom metadata, not the metric value.** Pass extra context (order ID, category, etc.) in `data`. Pass the numeric measurement in `metricValue`.

## References

- [SDK Track Patterns](references/sdk-track-patterns.md) — `track()` call syntax, initialization, and package names for every supported SDK

© launchdarkly · Apache-2.0 · launchdarkly/ai-tooling

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
setup-matt-pocock-skills Matt Pocock Скилл настраивает репозиторий для инженерных скиллов Matt Pocock: задаёт трекер задач, метки триажа и расположение доменной документации. Запустите его перед первым использованием остальных скиллов. 1 052 851установок ask-matt Matt Pocock Помогает выбрать подходящий скилл или рабочий поток из набора Matt Pocock. Пригодится, когда непонятно, с чего начать задачу: от идеи до разбора бага. 766 587установок to-tickets Matt Pocock Разбивает план, спецификацию или переписку на небольшие сквозные задачи и отмечает, какие из них блокируют остальные. Пригодится, когда нужно согласовать порядок работы до публикации задач в трекере. 711 230установок writing-plans Jesse Vincent Скилл превращает требования к многошаговой задаче в подробный план реализации до начала работы с кодом. Пригодится, когда исполнителю нужно зафиксировать файлы, интерфейсы и проверки. CX Codex 282 859установок caveman-review JuliusBrussee Пишет замечания к коду одной строкой: место, проблема, исправление. Пригодится, когда ревью диффа или PR надо пройти быстро и без воды. CX Codex +1 411 800установок caveman-compress JuliusBrussee Сжимает CLAUDE.md, списки задач и другие текстовые файлы в краткий формат, сохраняя читаемую резервную копию. CX Codex +1 411 500установок

Из того же набора29

launchdarkly-flag-discovery Проводит аудит фиче-флагов LaunchDarkly, находит устаревшие тумблеры и проверяет безопасность их удаления. Пригодится для устранения долга по флагам в проекте. CX Codex +1 4 200установок launchdarkly-flag-cleanup Безопасно удаляет фиче-флаги LaunchDarkly из кодовой базы после завершения раскатки. Скилл проверяет готовность через MCP и оставляет только активную ветку кода. CX Codex +1 4 100установок launchdarkly-flag-targeting Скилл для управления таргетингом фича-флагов LaunchDarkly: включение, процентные раскатки, правила и отдельные пользователи. CX Codex +1 4 100установок launchdarkly-flag-create Проводит агента по шагам: изучить, как флаги уже используются в проекте, создать новый в LaunchDarkly и вписать проверку в код по существующим паттернам. CX Codex +1 4 100установок launchdarkly-metric-create Проведёт от выбора типа метрики до её создания в LaunchDarkly: сначала наладит события, потом заведёт метрику и проверит результат. CX Codex +1 3 200установок launchdarkly-metric-choose Помогает выбрать метрики для эксперимента, guarded rollout или release policy в LaunchDarkly и показывает, что уже подцепится автоматически. CX Codex +1 3 200установок aiconfig-variations Устаревший скилл-редирект: сам ничего не делает, только отправляет к актуальному скиллу configs-variations. Нужен, если в ваших скриптах или промптах осталось старое имя. CX Codex +1 2 800установок aiconfig-create Устаревший скилл-переадресация для старых ссылок на aiconfig-create. Он направляет к актуальному скиллу configs-create. CX Codex +1 2 800установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой