---
title: "mongodb/agent-skills"
description: "Use the official MongoDB Skills with your favorite coding agent to build faster."
source: https://github.com/mongodb/agent-skills
ref: main
license: Apache-2.0
licenseName: "Apache License 2.0"
canonical: https://skillsdocs.com/mongodb/agent-skills
base: https://github.com/mongodb/agent-skills/blob/main/
chapters: 8
inlined: 8
withheld: 0
words: 10153
updated: 2026-08-07T21:16:26Z
generator: "Skills Docs"
---

> **mongodb/agent-skills** — every Agent Skill in this repository, inlined verbatim.
>
> Canonical HTML: https://skillsdocs.com/mongodb/agent-skills
> Per-chapter Markdown: https://skillsdocs.com/mongodb/agent-skills/<skill>.md
> Machine manifest: https://skillsdocs.com/mongodb/agent-skills/.well-known/agent-skills/index.json
> JSON: https://skillsdocs.com/api/v1/books/mongodb/agent-skills
> Install: `npx skills add mongodb/agent-skills`
> Upstream: https://github.com/mongodb/agent-skills @ `main`
> Licence: Apache-2.0
>
> Content is mirrored from GitHub and © its authors, served unmodified. Takedown: https://github.com/kyleledbetter/skillsdocs/issues/new?labels=takedown&title=Takedown+request

# mongodb/agent-skills

Use the official MongoDB Skills with your favorite coding agent to build faster.

- **Chapters:** 8
- **Inlined:** 8 (licence detected)
- **Words:** 10,153
- **Reading time:** 46 min
- **Stars:** 166

## Table of contents

1. [mongodb-atlas-stream-processing](https://skillsdocs.com/mongodb/agent-skills/mongodb-atlas-stream-processing.md) — Manages MongoDB Atlas Stream Processing (ASP) workflows. Handles workspace provisioning, data source/sink connections, processor lifecycle operations, debuggin…
2. [mongodb-connection](https://skillsdocs.com/mongodb/agent-skills/mongodb-connection.md) — Optimize MongoDB client connection configuration (pools, timeouts, patterns) for any supported driver language. Use this skill when working/updating/reviewing…
3. [mongodb-mcp-setup](https://skillsdocs.com/mongodb/agent-skills/mongodb-mcp-setup.md) — Guide users through configuring key MongoDB MCP server options. Use this skill when a user has the MongoDB MCP server installed but hasn't configured the requi…
4. [mongodb-natural-language-querying](https://skillsdocs.com/mongodb/agent-skills/mongodb-natural-language-querying.md) — Generate read-only MongoDB queries (find) or aggregation pipelines using natural language, with collection schema context and sample documents. Use this skill…
5. [mongodb-query-optimizer](https://skillsdocs.com/mongodb/agent-skills/mongodb-query-optimizer.md) — Help with MongoDB query optimization and indexing. Use only when the user asks for optimization or performance: "How do I optimize this query?", "How do I inde…
6. [mongodb-schema-design](https://skillsdocs.com/mongodb/agent-skills/mongodb-schema-design.md) — MongoDB schema design patterns and anti-patterns. Use when designing data models, reviewing schemas, migrating from SQL, or troubleshooting performance issues…
7. [mongodb-search-and-ai](https://skillsdocs.com/mongodb/agent-skills/mongodb-search-and-ai.md) — Guides MongoDB users through implementing and optimizing Atlas Search (full-text), Vector Search (semantic), and Hybrid Search solutions. Use this skill when u…
8. [review-skill](https://skillsdocs.com/mongodb/agent-skills/review-skill.md) — Review a proposed Agent Skill for structural validity and content quality before publishing. Runs the skill-validator CLI to check for structural issues, score…


## Front matter

_The repository README, verbatim except that relative links are resolved against https://github.com/mongodb/agent-skills/blob/main/._

# MongoDB Agent Skills

Collection of official MongoDB agent skills for use in agentic workflows. For more information, refer to the [MongoDB Agent Skills documentation](https://www.mongodb.com/docs/agent-skills/).

This README covers the **`mongodb-atlas`** plugin, which connects your agent to the **MongoDB-hosted Atlas MCP server** over HTTP using OAuth. It bundles the official MongoDB agent skills for writing queries, designing schemas, optimizing queries, using Atlas Search and Vector Search, and more.

> **Connecting to MongoDB Community or Enterprise Advanced?**
> For self-managed deployments, use the **`mongodb`** plugin instead — it runs the MongoDB MCP server locally and connects to your own deployment. See **[Community & Enterprise Advanced setup](https://github.com/mongodb/agent-skills/blob/main/README.community.md)** for installation and configuration instructions.

The `mongodb-atlas` plugin is available on Claude, Cursor, Codex, GitHub Copilot (CLI and VS Code), and Grok.

## Installation

### Claude

Install `mongodb-atlas` from the [Claude marketplace](https://claude.com/plugins/mongodb-atlas), or run the following command from a Claude session:

1. Install the plugin:

   ```bash
   /plugin install mongodb-atlas
   ```

2. Follow the prompts to complete the installation, then run `/reload-plugins` to activate it.

### Cursor

Install `mongodb-atlas` from the [Cursor marketplace](https://cursor.com/marketplace/mongodb-atlas), or run the following command from a Cursor session:

1. Install the plugin:

   ```bash
   /add-plugin mongodb-atlas
   ```

2. Follow the prompts to complete the installation.

### Codex

1. Open the plugins browser:

   ```bash
   /plugins
   ```

2. Find the `mongodb-atlas` plugin and install it.

### GitHub Copilot CLI

1. Install the plugin:

   ```bash
   copilot plugin install mongodb-atlas
   ```

   To browse first, run `copilot plugin marketplace browse`.

### VS Code

Open the Extensions view (`⇧⌘X` / `Ctrl+Shift+X`), search for `@agentPlugins`,
find `mongodb-atlas`, and select **Install**.

### Grok

1. Open the marketplace browser in Grok Build:

   ```bash
   /marketplace
   ```

2. Find `mongodb-atlas` and press `i` to install it.

## Authentication

The `mongodb-atlas` plugin connects to the MongoDB-hosted Atlas MCP server using OAuth. The first time your agent uses the server, you'll be prompted to sign in to MongoDB Atlas in your browser.

## Installing the skills directly

The methods below install just the agent skills — the same skills both plugins bundle — for agents or workflows that don't use a plugin marketplace. They don't configure an MCP server; to add one, run `npx "mongodb-mcp-server@latest" setup`, which can configure either the hosted Atlas MCP server or a self-managed deployment. Installing the `mongodb-atlas` or `mongodb` plugin just does this for you as a convenience (bundling the MCP configuration); for self-managed specifics, see [Community & Enterprise Advanced setup](https://github.com/mongodb/agent-skills/blob/main/README.community.md).

### Vercel's Agent Skills Directory

[https://skills.sh/](https://skills.sh/) is a popular directory and CLI that automates installing skills:

```bash
npx skills add mongodb/agent-skills
```

### Local install from repository

1. Clone the repository:

   ```bash
   git clone https://github.com/mongodb/agent-skills.git
   ```

2. Copy the `skills/` directory to the location where your coding agent reads its skills or context files. Refer to your agent's documentation for the correct path.

---

<!-- chapter:begin slug=mongodb-atlas-stream-processing position=1 -->

## 1. mongodb-atlas-stream-processing

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-atlas-stream-processing/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-atlas-stream-processing.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

Bundled files (6), referenced from this skill's directory:
  - `references/connection-configs.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/references/connection-configs.md
  - `references/development-workflow.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/references/development-workflow.md
  - `references/mcp-troubleshooting.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/references/mcp-troubleshooting.md
  - `references/output-diagnostics.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/references/output-diagnostics.md
  - `references/pipeline-patterns.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/references/pipeline-patterns.md
  - `references/sizing-and-parallelism.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-atlas-stream-processing/references/sizing-and-parallelism.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-atlas-stream-processing
description: "Manages MongoDB Atlas Stream Processing (ASP) workflows. Handles workspace provisioning, data source/sink connections, processor lifecycle operations, debugging diagnostics, and tier sizing. Supports Kafka, Atlas clusters, S3, HTTPS, and Lambda integrations for streaming data workloads and event processing. NOT for general MongoDB queries or Atlas cluster management. Requires MongoDB MCP Server with Atlas API credentials."
license: Apache-2.0
metadata:
  version: "1.0.0"
  user-invocable: "true"
---

# MongoDB Atlas Streams

Build, operate, and debug Atlas Stream Processing (ASP) pipelines using four MCP tools from the MongoDB MCP Server.

## Prerequisites

This skill requires the **MongoDB MCP Server** connected with:
- Atlas API credentials (`apiClientId` and `apiClientSecret`)

The 4 tools: `atlas-streams-discover`, `atlas-streams-build`, `atlas-streams-manage`, `atlas-streams-teardown`.

**All operations require an Atlas project ID.** If unknown, call `atlas-list-projects` first to find your project ID.

## If MCP tools are unavailable

If the MongoDB MCP Server is not connected or the streams tools are missing, see [references/mcp-troubleshooting.md](references/mcp-troubleshooting.md) for diagnostic steps and fallback options.

## Tool Selection Matrix

### atlas-streams-discover — ALL read operations
| Action | Use when |
|--------|----------|
| `list-workspaces` | See all workspaces in a project |
| `inspect-workspace` | Review workspace config, state, region |
| `list-connections` | See all connections in a workspace |
| `inspect-connection` | Check connection state, config, health |
| `list-processors` | See all processors in a workspace |
| `inspect-processor` | Check processor state, pipeline, config |
| `diagnose-processor` | Full health report: state, stats, errors |
| `get-networking` | PrivateLink and VPC peering details. Optional: `cloudProvider` + `region` to get Atlas account details for PrivateLink setup |

**Pagination** (all list actions): `limit` (1-100, default 20), `pageNum` (default 1).
**Response format**: `responseFormat` — `"concise"` (default for list actions) or `"detailed"` (default for inspect/diagnose).

### atlas-streams-build — ALL create operations
| Resource | Key parameters |
|----------|---------------|
| `workspace` | `cloudProvider`, `region`, `tier` (default SP10), `includeSampleData` |
| `connection` | `connectionName`, `connectionType` (Kafka/Cluster/S3/Https/Kinesis/Lambda/SchemaRegistry/Sample), `connectionConfig` |
| `processor` | `processorName`, `pipeline` (must start with `$source`, end with `$merge`/`$emit`), `dlq`, `autoStart` |
| `privatelink` | `privateLinkConfig` (project-level, not tied to a specific workspace) |

**Field mapping — only fill fields for the selected resource type:**

- **resource = "workspace":** Fill: `projectId`, `workspaceName`, `cloudProvider`, `region`, `tier`, `includeSampleData`. Leave empty: all connection and processor fields.
- **resource = "connection":** Fill: `projectId`, `workspaceName`, `connectionName`, `connectionType`, `connectionConfig`. Leave empty: all workspace and processor fields. (See [references/connection-configs.md](references/connection-configs.md) for type-specific schemas.)
- **resource = "processor":** Fill: `projectId`, `workspaceName`, `processorName`, `pipeline`, `dlq` (recommended), `autoStart` (optional). Leave empty: all workspace and connection fields. (See [references/pipeline-patterns.md](references/pipeline-patterns.md) for pipeline examples.)
- **resource = "privatelink":** Fill: `projectId`, `privateLinkConfig`. Note: PrivateLink is **project-level**, not workspace-level. `workspaceName` is not required — omit it. Leave empty: all connection and processor fields.

### atlas-streams-manage — ALL update/state operations
| Action | Notes |
|--------|-------|
| `start-processor` | Begins billing. Optional `tier` override, `resumeFromCheckpoint` |
| `stop-processor` | Stops billing. Retains state 45 days |
| `modify-processor` | Processor must be stopped first. Change pipeline, DLQ, or name |
| `update-workspace` | Change tier or region |
| `update-connection` | Update config (networking is immutable — must delete and recreate) |
| `accept-peering` / `reject-peering` | VPC peering management |

**Field mapping** — always fill `projectId`, `workspaceName`, then by action:

- `"start-processor"` → `resourceName`. Optional: `tier`, `resumeFromCheckpoint`, `startAtOperationTime` (ISO 8601 timestamp to resume from a specific point)
- `"stop-processor"` → `resourceName`
- `"modify-processor"` → `resourceName`. At least one of: `pipeline`, `dlq`, `newName`
- `"update-workspace"` → `newRegion` or `newTier`
- `"update-connection"` → `resourceName`, `connectionConfig`. **Exception: networking config (e.g., PrivateLink) cannot be modified after creation** — delete and recreate.
- `"accept-peering"` → `peeringId`, `requesterAccountId`, `requesterVpcId`
- `"reject-peering"` → `peeringId`

**State pre-checks:**
- `start-processor` → errors if processor is already STARTED
- `stop-processor` → no-ops if already STOPPED or CREATED (not an error)
- `modify-processor` → errors if processor is STARTED (must stop first)

**Processor states:** `CREATED` → `STARTED` (via start) → `STOPPED` (via stop). Can also enter `FAILED` on runtime errors. Modify requires STOPPED or CREATED state.

**Teardown safety checks:**
- **Processor deletion** → auto-stops before deleting (no need to stop manually first)
- **Connection deletion** → blocks if any running processor references it. Stop/delete referencing processors first.
- **Workspace deletion** → See detailed workflow below (lines 108-111).

### atlas-streams-teardown — ALL delete operations
| Resource | Safety behavior |
|----------|----------------|
| `processor` | Auto-stops before deleting |
| `connection` | Blocks if referenced by running processor |
| `workspace` | Cascading delete of all connections and processors |
| `privatelink` / `peering` | Remove networking resources |

**Field mapping** — always fill `projectId`, `resource`, then:

- `resource: "workspace"` → `workspaceName`
- `resource: "connection"` or `"processor"` → `workspaceName`, `resourceName`
- `resource: "privatelink"` or `"peering"` → `resourceName` (the ID). These are project-level resources, not tied to a specific workspace.

**Before deleting a workspace**, inspect it first:
1. `atlas-streams-discover` → `inspect-workspace` — get connection/processor counts
2. Present to user: "Workspace X contains N connections and M processors. Deleting permanently removes all. Proceed?"
3. Wait for confirmation before calling `atlas-streams-teardown`

## CRITICAL: Validate Before Creating Processors

**You MUST call `search-knowledge` before composing any processor pipeline.** This is not optional.
- **Field validation:** Query with the sink/source type, e.g. "Atlas Stream Processing $emit S3 fields" or "Atlas Stream Processing Kafka $source configuration". This catches errors like `prefix` vs `path` for S3 `$emit`.
- **Pattern examples:** Query with `dataSources: [{"name": "devcenter"}]` for working pipelines, e.g. "Atlas Stream Processing tumbling window example".

Also fetch examples from the official ASP examples repo when building non-trivial processors: **https://github.com/mongodb/ASP_example** (quickstarts, example processors, Terraform examples). Start with `example_processors/README.md` for the full pattern catalog.

Key quickstarts:
| Quickstart | Pattern |
|-----------|---------|
| `00_hello_world.json` | Inline `$source.documents` with `$match` (zero infra, ephemeral) |
| `01_changestream_basic.json` | Change stream → tumbling window → `$merge` to Atlas |
| `03_kafka_to_mongo.json` | Kafka source → tumbling window rollup → `$merge` to Atlas |
| `04_mongo_to_mongo.json` | Chained processors: rollup → archive to separate collection |
| `05_kafka_tail.json` | Real-time Kafka topic monitoring (sinkless, like `tail -f`) |

## Pipeline Rules & Warnings

**Invalid constructs** — these are NOT valid in streaming pipelines:
- **`$$NOW`**, **`$$ROOT`**, **`$$CURRENT`** — NOT available in stream processing. NEVER use these. Use the document's own timestamp field or `_stream_meta` metadata for event time instead of `$$NOW`.
- **HTTPS connections as `$source`** — HTTPS is for `$https` enrichment or sink only, NOT as a data source
- **Kafka `$source` without `topic`** — topic field is required
- **Pipelines without a sink** — terminal stage (`$merge`, `$emit`, `$https`, or `$externalFunction` async) required for deployed processors (sinkless only works via `sp.process()`)
- **Lambda as `$emit` target** — Lambda uses `$externalFunction` (mid-pipeline enrichment), not `$emit`
- **`$validate` with `validationAction: "error"`** — crashes processor; use `"dlq"` instead

**Required fields by stage:**
- **`$source` (change stream)**: include `fullDocument: "updateLookup"` to get the full document content
- **`$source` (Kinesis)**: use `stream` (NOT `streamName` or `topic`)
- **`$emit` (Kinesis)**: MUST include `partitionKey`
- **`$emit` (S3)**: use `path` (NOT `prefix`)
- **`$https`**: must include `connectionName`, `path`, `method`, `as`, `onError: "dlq"`
- **`$externalFunction`**: must include `connectionName`, `functionName`, `execution`, `as`, `onError: "dlq"`
- **`$validate`**: must include `validator` with `$jsonSchema` and `validationAction: "dlq"`
- **`$lookup`**: include `parallelism` setting (e.g., `parallelism: 2`) for concurrent I/O
- **AWS connections** (S3, Kinesis, Lambda): IAM role ARN must be registered via Atlas Cloud Provider Access first. Always confirm this with user. See [references/connection-configs.md](references/connection-configs.md) for details.

See [references/pipeline-patterns.md](references/pipeline-patterns.md) for stage field examples with JSON syntax.

**SchemaRegistry connection:** `connectionType` must be `"SchemaRegistry"` (not `"Kafka"`). Schema type values are case-sensitive (use lowercase `avro`, not `AVRO`). See [references/connection-configs.md](references/connection-configs.md#schemaregistry) for required fields and auth types.

## MCP Tool Behaviors

**Elicitation:** When creating connections, the build tool auto-collects missing sensitive fields (passwords, bootstrap servers) via MCP elicitation. Do NOT ask the user for these — let the tool collect them.

**Auto-normalization:**
- `bootstrapServers` array → auto-converted to comma-separated string
- `schemaRegistryUrls` string → auto-wrapped in array
- `dbRoleToExecute` → defaults to `{role: "readWriteAnyDatabase", type: "BUILT_IN"}` for Cluster connections

**Workspace creation:** `includeSampleData` defaults to `true`, which auto-creates the `sample_stream_solar` connection.

**Region naming:** The `region` field uses Atlas-specific names that differ by cloud provider. Using the wrong format returns a cryptic `dataProcessRegion` error.

| Provider | Cloud Region | Streams `region` Value |
|----------|-------------|----------------------|
| **AWS** | us-east-1 | `VIRGINIA_USA` |
| **AWS** | us-east-2 | `OHIO_USA` |
| **AWS** | eu-west-1 | `DUBLIN_IRL` |
| **GCP** | us-central1 | `US_CENTRAL1` |
| **GCP** | europe-west1 | `EUROPE_WEST1` |
| **Azure** | eastus | `eastus` |
| **Azure** | westeurope | `westeurope` |

See [references/connection-configs.md](references/connection-configs.md) for the full region mapping table. If unsure, inspect an existing workspace with `atlas-streams-discover` → `inspect-workspace` and check `dataProcessRegion.region`.

## Connection Capabilities — Source/Sink Reference

Know what each connection type can do before creating pipelines:

| Connection Type | As Source ($source) | As Sink ($merge / $emit) | Mid-Pipeline | Notes |
|-----------------|---------------------|--------------------------|--------------|-------|
| **Cluster** | ✅ Change streams | ✅ $merge to collections | ✅ $lookup | Change streams monitor insert/update/delete/replace operations |
| **Kafka** | ✅ Topic consumer | ✅ $emit to topics | ❌ | Source MUST include `topic` field |
| **Sample Stream** | ✅ Sample data | ❌ Not valid | ❌ | Testing/demo only |
| **S3** | ❌ Not valid | ✅ $emit to buckets | ❌ | Sink only - use `path`, `format`, `compression`. Supports AWS PrivateLink. |
| **Https** | ❌ Not valid | ✅ $https as sink | ✅ $https enrichment | Can be used mid-pipeline for enrichment OR as final sink stage |
| **AWSLambda** | ❌ Not valid | ✅ $externalFunction (async only) | ✅ $externalFunction (sync or async) | **Sink:** `execution: "async"` required. **Mid-pipeline:** `execution: "sync"` or `"async"` |
| **AWS Kinesis** | ✅ Stream consumer | ✅ $emit to streams | ❌ | Similar to Kafka pattern |
| **SchemaRegistry** | ❌ Not valid | ❌ Not valid | ✅ Schema resolution | **Metadata only** - used by Kafka connections for Avro schemas |

**Common connection usage mistakes to avoid:**
- ❌ Using `$externalFunction` as sink with `execution: "sync"` → Must use `execution: "async"` for sink stage
- ❌ Forgetting change streams exist → Atlas Cluster is a powerful source, not just a sink
- ❌ Using `$merge` with Kafka → Use `$emit` for Kafka sinks

See [references/connection-configs.md](references/connection-configs.md) for detailed connection configuration schemas by type.

## Core Workflows

### Setup from scratch
1. `atlas-streams-discover` → `list-workspaces` (check existing)
2. `atlas-streams-build` → `resource: "workspace"` (region near data, SP10 for dev)
3. `atlas-streams-build` → `resource: "connection"` (for each source/sink/enrichment)
4. **Validate connections:** `atlas-streams-discover` → `list-connections` + `inspect-connection` for each — verify names match targets, present summary to user
5. Call `search-knowledge` to validate field names. Fetch relevant examples from https://github.com/mongodb/ASP_example
6. `atlas-streams-build` → `resource: "processor"` (with DLQ configured)
7. `atlas-streams-manage` → `start-processor` (warn about billing)

### Workflow Patterns

**Incremental pipeline development (recommended):**
See [references/development-workflow.md](references/development-workflow.md) for the full 5-phase lifecycle.
1. Start with basic `$source` → `$merge` pipeline (validate connectivity)
2. Add `$match` stages (validate filtering)
3. Add `$addFields` / `$project` transforms (validate reshaping)
4. Add windowing or enrichment (validate aggregation logic)
5. Add error handling / DLQ configuration

**Modify a processor pipeline:**
1. `atlas-streams-manage` → `action: "stop-processor"` — **processor MUST be stopped first**
2. `atlas-streams-manage` → `action: "modify-processor"` — provide new pipeline
3. `atlas-streams-manage` → `action: "start-processor"` — restart

**Debug a failing processor:**
1. `atlas-streams-discover` → `diagnose-processor` — one-shot health report. Always call this first.
2. **Commit to a specific root cause.** Match symptoms to diagnostic patterns:
   - **Error 419 + "no partitions found"** → Kafka topic doesn't exist or is misspelled
   - **State: FAILED + multiple restarts** → connection-level error (bypasses DLQ), check connection config
   - **State: STARTED + zero output + windowed pipeline** → likely idle Kafka partitions blocking window closure; add `partitionIdleTimeout` to Kafka `$source` (e.g., `{"size": 30, "unit": "second"}`)
   - **State: STARTED + zero output + non-windowed** → check if source has data; inspect Kafka offset lag
   - **High memoryUsageBytes approaching tier limit** → OOM risk; recommend higher tier
   - **DLQ count increasing** → per-document errors; use MongoDB `find` on DLQ collection
   See [references/output-diagnostics.md](references/output-diagnostics.md) for the full pattern table.
3. Classify processor type before interpreting output volume (alert vs transformation vs filter).
4. Provide concrete, ordered fix steps specific to the diagnosed root cause. Do NOT present a list of hypothetical scenarios.
5. If detailed logs are needed, direct the user to the Atlas UI: **Atlas → Stream Processing → Workspace → Processor → Logs tab**.

### Chained processors (multi-sink pattern)
**CRITICAL: A single pipeline can only have ONE terminal sink** (`$merge` or `$emit`). When users request multiple output destinations (e.g., "write to Atlas AND emit to Kafka"), you MUST acknowledge the single-sink constraint and propose chained processors using an intermediate destination. See [references/pipeline-patterns.md](references/pipeline-patterns.md) for the full pattern with examples.

## Pre-Deploy & Post-Deploy Checklists

See [references/development-workflow.md](references/development-workflow.md) for the complete pre-deploy quality checklist (connection validation, pipeline validation) and post-deploy verification workflow.

## Tier Sizing & Performance

See [references/sizing-and-parallelism.md](references/sizing-and-parallelism.md) for tier specifications, parallelism formulas, complexity scoring, and performance optimization strategies.

## Troubleshooting

See [references/development-workflow.md](references/development-workflow.md) for the complete troubleshooting table covering processor failures, API errors, configuration issues, and performance problems.

## Billing & Cost

**Atlas Stream Processing has no free tier.** All deployed processors incur continuous charges while running.

- Charges are per-hour, calculated per-second, only while the processor is running
- `stop-processor` stops billing; stopped processors retain state for 45 days at no charge
- **For prototyping without billing:** Use `sp.process()` in mongosh — runs pipelines ephemerally without deploying a processor
- See `references/sizing-and-parallelism.md` for tier pricing and cost optimization strategies

## Safety Rules

- `atlas-streams-teardown` and `atlas-streams-manage` require user confirmation — do not bypass
- **BEFORE calling `atlas-streams-teardown` for a workspace**, you MUST first inspect the workspace with `atlas-streams-discover` to count connections and processors, then present this information to the user before requesting confirmation
- **BEFORE creating any processor**, you MUST validate all connections per the "Pre-Deployment Validation" section in [references/development-workflow.md](references/development-workflow.md)
- Deleting a workspace removes ALL connections and processors permanently
- After stopping a processor, state is preserved 45 days — then checkpoints are discarded
- `resumeFromCheckpoint: false` drops all window state — warn user first
- Moving processors between workspaces is not supported (must recreate)
- Dry-run / simulation is not supported — explain what you would do and ask for confirmation
- Always warn users about billing before starting processors
- Store API authentication credentials in connection settings, never hardcode in processor pipelines

## Reference Files

| File | Read when... |
|------|-------------|
| [`references/pipeline-patterns.md`](references/pipeline-patterns.md) | Building or modifying processor pipelines |
| [`references/connection-configs.md`](references/connection-configs.md) | Creating connections (type-specific schemas) |
| [`references/development-workflow.md`](references/development-workflow.md) | Following lifecycle management or debugging decision trees |
| [`references/output-diagnostics.md`](references/output-diagnostics.md) | Processor output is unexpected (zero, low, or wrong) |
| [`references/sizing-and-parallelism.md`](references/sizing-and-parallelism.md) | Choosing tiers, tuning parallelism, or optimizing cost |

<!-- chapter:end slug=mongodb-atlas-stream-processing -->

---

<!-- chapter:begin slug=mongodb-connection position=2 -->

## 2. mongodb-connection

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-connection/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-connection/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-connection.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

Bundled files (1), referenced from this skill's directory:
  - `references/monitoring-guide.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-connection/references/monitoring-guide.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-connection
description: Optimize MongoDB client connection configuration (pools, timeouts, patterns) for any supported driver language. Use this skill when working/updating/reviewing on functions that instantiate or configure a MongoDB client (eg, when calling `connect()`), configuring connection pools, troubleshooting connection errors (ECONNREFUSED, timeouts, pool exhaustion), optimizing performance issues related to connections. This includes scenarios like building serverless functions with MongoDB, creating API endpoints that use MongoDB, optimizing high-traffic MongoDB applications, creating long-running tasks and concurrency, or debugging connection-related failures.
license: Apache-2.0
metadata:
  version: "1.0.0"
---

# MongoDB Connection Optimizer

You are an expert in MongoDB connection management across all officially supported driver languages (Node.js, Python, Java, Go, C#, Ruby, PHP, etc.). Your role is to ensure connection configurations are optimized for the user's specific environment and requirements, avoiding the common pitfall of blindly applying arbitrary parameters.

## Core Principle: Context Before Configuration

**NEVER add connection pool parameters or timeout settings without first understanding the application's context.** Arbitrary values without justification lead to performance issues and harder-to-debug problems.

## Understanding How Connection Pools Work

- Connection pooling exists because establishing a MongoDB connection is expensive (TCP + TLS + auth = 50-500ms). Without pooling, every operation pays this cost.
- Open connections consume system memory on the MongoDB server instances, ~1 MB per connection on average, even when they are not active. It is advised to avoid having idle connections.

**Connection Lifecycle**: Borrow from pool → Execute operation → Return to pool → Prune idle connections exceeding `maxIdleTimeMS`.

**Synchronous vs. Asynchronous Drivers**:
- **Synchronous** (PyMongo, Java sync): Thread blocks; pool size often matches thread pool size
- **Asynchronous** (Node.js, Motor): Non-blocking I/O; smaller pools suffice

**Monitoring Connections**: Each MongoClient establishes 2 monitoring connections per replica set member (automatic, separate from your pool). Formula: `Total = (minPoolSize + 2) × replica members × app instances`. Example: 10 instances, minPoolSize 5, 3-member set = 210 server connections. Always account for this when planning capacity.

## Configuration Design

**Before suggesting any configuration changes**, ensure you have the sufficient context about the user's application environment to inform pool configuration (see **Environmental Context** below). If you don't have enough information, ask targeted questions to gather it. Ask **only one question at a time**, starting with broad context (deployment type, workload, concurrency) before drilling down into specifics.

When you suggest configuration, briefly explain WHY each parameter has its specific value based on the context you gathered. Use the user's environment details (deployment type, workload, concurrency) to justify your recommendations.

Example: `maxPoolSize: 50` — "Based on your observed peak of 40 concurrent operations with 25% headroom for traffic bursts"

If you provide code snippets, add inline comments explaining the rationale for each parameter choice.

### Calculating Initial Pool Size

If performance data available: `Pool Size ≈ (Ops/sec) × (Avg duration) + 10-20% buffer`

Example: `(10,000 ops/sec) × (10ms) + 20% buffer = 120 connections`

Use when: Clear requirements, known latency, predictable traffic.
Don't use when: variable durations—start conservative (10-20), monitor, adjust.

Query optimization can dramatically reduce required pool size.

The total number of supported connections in a cluster could inform the upper limit of poolSize based on the number of MongoClient's instances employed. For example, if you have 10 instances of MongoClient using a size of 5 connecting to a 3 node replica set: `10 instances × 5 connections × 3 servers = 150 connections`. 

Each connection requires ~1 MB of physical RAM, so you may find that the optimal value for this parameter is also informed by the resource footprint of your application's workload.

#### The role of Topology:
- Pools are created per server per MongoClient. 
- By default, clients connect to one mongos router per sharded cluster (which manages connections to the shards internally), not to individual shards; so the shard amount do not affect the pool size directly.
- Shards share the workload and reduce stress on each individual server, increasing cluster capacity.
- Replica members do not affect the max pool directly. If the driver communicates with multiple replica set members (for example for reads with secondary read preference), it may create a pool per member.
- Replica set members do not increase write capacity (only the primary handles writes). However, they can increase read capacity if your application uses read preferences that allow secondary reads.

#### Server-Side Connection Limits: 
Total potential connections = instances × (maxPoolSize + 2) × replica set members. The + 2 accounts for the two monitoring connections per replica set member, per MongoClient instance. Monitor `connections.current` to avoid hitting limits. See `references/monitoring-guide.md` for how to set up monitoring.

**Self-managed Servers**: Set `net.maxIncomingConnections` to a value slightly higher than the maximum number of connections that the client creates, or the maximum size of the connection pool. This setting prevents the mongos from causing connection spikes on the individual shards that disrupt the operation and memory allocation of the sharded cluster.

### Configuration Scenarios

**General best practices:**

- Create client once only and reuse across application (in serverless, initialize outside handler)
- Don't manually close connections unless shutting down
- Max pool size must exceed expected concurrency
- Make use of timeouts to keep only the required connections ready as per your workload's needs
- Use default max pool size (100) unless you have specific needs (see scenarios below)

#### Scenario: Serverless Environments (Lambda, Cloud Functions)

**Critical pattern**: Initialize client OUTSIDE handler/function scope to enable connection reuse across warm invocations.

**Recommended configuration**:

| Parameter | Value | Reasoning |
|-----------|-------|-----------|
| `maxPoolSize` | 3-5 | Each serverless function instance has its own pool |
| `minPoolSize` | 0 | Prevent maintaining unused connections. Increase to mitigate cold starts if needed |
| `maxIdleTimeMS` | 10-30s | Release unused connections more quickly |
| `connectTimeoutMS` | >0 | Set to a value greater than the longest network latency you have to a member of the set |
| `socketTimeoutMS` | >0 | Use socketTimeoutMS to ensure that sockets are always closed |

##### Scenario: Traditional Long-Running Servers (OLTP Workload)

**Recommended configuration**:

| Parameter | Value | Reasoning |
|-----------|-------|-----------|
| `maxPoolSize` | 50+ | Based on peak concurrent requests (monitor and adjust) |
| `minPoolSize` | 10-20 | Pre-warmed connections ready for traffic spikes |
| `maxIdleTimeMS` | 5-10min | Stable servers benefit from persistent connections |
| `connectTimeoutMS` | 5-10s | Fail fast on connection issues |
| `socketTimeoutMS` | 30s | Prevent hanging queries; appropriate for short OLTP operations |
| `serverSelectionTimeoutMS` | 5s | Quick failover for replica set topology changes |

MongoDB 8.0+ introduces defaultMaxTimeMS on Atlas clusters, which provides server-side protection against long-running operations.

##### Scenario: OLAP / Analytical Workloads

**Recommended configuration**:

| Parameter | Value | Reasoning |
|-----------|-------|-----------|
| `maxPoolSize` | 10-20 | Fewer concurrent operations. Match your expected concurrent analytical operations |
| `minPoolSize` | 0-5 | Queries are infrequent; minimal pre-warming needed |
| `socketTimeoutMS` | >0 | Set socketTimeoutMS to two or three times the length of the slowest operation that the driver runs. |
| `maxIdleTimeMS` | 10min | Minimize connection churn while not keeping truly idle connections too long. Consider the timeouts of intermediate network devices |

##### Scenario: High-Traffic / Bursty Workloads

**Recommended configuration**:

| Parameter | Value | Reasoning |
|-----------|-------|-----------|
| `maxPoolSize` | 100+ | Higher ceiling to accommodate sudden traffic spikes |
| `minPoolSize` | 20-30 | More pre-warmed connections ready for immediate bursts |
| `maxConnecting` | 2 (default) | Prevent thundering herd during sudden demand |
| `waitQueueTimeoutMS` | 2-5s | Fail fast when pool exhausted rather than queueing indefinitely |
| `maxIdleTimeMS` | 5min | Balance between reuse during bursts and cleanup between spikes |

## Troubleshooting Connection Issues
If the user requires help to troubleshoot connection issues, determine whether this is a client config issue or infrastructure problem.

Types of issues:

- **Infrastructure or Network Issues (Out of Scope)**: redirect to publicly available infractructure documentation.
  - eg: DNS/SRV resolution failures, network/VPC blocking, IP not whitelisted, TLS cert issues, auth mechanism mismatches
- **Client Configuration Issues (Your Territory)**:
  - eg: Pool exhaustion, inappropriate timeouts, poor reuse patterns, suboptimal sizing, missing serverless caching, connection churn

### Guidelines
- Ask **only one question at a time**, starting with broad context (deployment type, workload, concurrency) before drilling down into specifics (current config, error messages). This approach allows you to quickly narrow down the root cause and avoid unnecessary configuration changes or excessive questions.
- Review `references/monitoring-guide.md` for how to instrument and monitor the relevant parameters that can inform your troubleshooting and recommendations.

### Pool Exhaustion
When operations queue, pool is exhausted.

**Symptoms**: `MongoWaitQueueTimeoutError`, `WaitQueueTimeoutError` or `MongoTimeoutException`, increased latency, operations waiting.

**Solutions**:
- **Increase `maxPoolSize`** when: Wait queue has operations waiting (size > 0) + server shows low utilization
- **Don't increase** when: Server is at capacity. Suggest query optimization.

### Connection Timeouts (ECONNREFUSED, SocketTimeout)

**Client Solutions**: Increase `connectTimeoutMS`/`socketTimeoutMS` if legitimately needed

**Infrastructure Issues** (redirect): 
- Cannot connect via shell: Network/firewall; 
- Environment-specific: VPC/security; 
- DNS errors: DNS/SRV resolution

### Connection Churn
**Symptoms**: Rapidly increasing `connections.totalCreated` server metric, high connection handling CPU

**Causes**: Not using pooling, not caching in serverless, `maxIdleTimeMS` too low, restart loops

### High Latency
- Ensure `minPoolSize` > 0 for traffic spikes
- Network compression for high-latency (>50ms): `compressors: ['snappy', 'zlib']`
- Nearest read preference for geo-distributed setups

---
## Environmental Context (MANDATORY)

**ALWAYS** verify you have the sufficient context about the user's application environment to inform pool configuration BEFORE suggesting any configuration changes.

### Parameters that inform a pool configuration
- **Server's memory limits**: each connection takes 1MB against the server.
- **Number of clients and servers in a cluster**: pools are per client and per server, taking memory from the cluster.
- **OLAP vs OLTP**: timeout values must support the expected duration of operations.
  - Expected duration of operations: Short OLTP queries may require lower socketTimeoutMS to fail fast on hanging operations, while long-running OLAP queries may need higher values to avoid premature timeouts.
- **Server version**: MongoDB 8.0+ also introduces defaultMaxTimeMS on Atlas clusters, which provides server-side protection against long-running operations.
- **Serverless vs Traditional**: Serverless functions should initialize clients outside the handler to enable connection reuse across warm invocations, while traditional servers can maintain larger pools with pre-warmed connections.
- **Concurrency and traffic patterns**: High concurrency and bursty traffic may require larger pools and more pre-warmed connections, while steady, low-concurrency workloads can often operate efficiently with smaller pools.
-  **Operating System**: Some OSes have limits on the number of open file descriptors, which can impact the maximum number of connections. It's important to consider these limits when configuring connection pools, especially for high-traffic applications.
- **Driver version**: Different driver versions may have different default settings and performance characteristics. Always check the documentation for the specific driver version being used to ensure optimal configuration.

**Guidelines:**
- Ask only questions relevant to the scenarios in **Configuration Design Phase**. Omit questions that won't lead to a clear use of the content in **Configuration Design Phase**.
- If an answer not provided, make a reasonable assumption and disclose it.

---

## Advising on Monitoring & Iteration

**You must guide users to monitor** the relevant parameters to their pool configuration. 
For detailed monitoring setup, see `references/monitoring-guide.md`.

---

## When creating code
For every connection parameter you provide (in recommendations or code snippets), ensure you have enough context about the user's application environment to inform values. If not, ask targeted questions before suggesting specific values. If you get no answer, make a reasonable assumption, disclose it and comment the relevant parameters accordingly in the code.

<!-- chapter:end slug=mongodb-connection -->

---

<!-- chapter:begin slug=mongodb-mcp-setup position=3 -->

## 3. mongodb-mcp-setup

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-mcp-setup/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-mcp-setup/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-mcp-setup.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-mcp-setup
description: Guide users through configuring key MongoDB MCP server options. Use this skill when a user has the MongoDB MCP server installed but hasn't configured the required environment variables, or when they ask about connecting to MongoDB/Atlas and don't have the credentials set up.
license: Apache-2.0
metadata:
  version: "1.0.0"
---

# MongoDB MCP Server Setup

This skill guides users through configuring the MongoDB MCP server for use with an agentic client.

## Overview

The MongoDB MCP server requires authentication. Users have three options:

1. **Connection String** (Option A): Direct connection to a specific cluster
   - Quick setup for single cluster
   - Requires `MDB_MCP_CONNECTION_STRING` environment variable

2. **Service Account Credentials** (Option B): MongoDB Atlas Admin API access
   - **Recommended for Atlas users** - simplifies authentication and data access
   - Access to Atlas Admin API and dynamic cluster connection via `atlas-connect-cluster`
   - No manual DB user credential management
   - Requires `MDB_MCP_API_CLIENT_ID` and `MDB_MCP_API_CLIENT_SECRET` environment variables

3. **Atlas Local** (Option C): Local development with Docker
   - **Best for local testing** - zero configuration required
   - Runs Atlas locally in Docker, requires Docker installed
   - No credentials or cloud cluster access

This is an interactive step-by-step guide. The agent detects the user's environment and provides tailored instructions, but **never asks for or handles credentials** — users add those directly to their shell profile or agentic client config in Step 5. Make this clear to the user whenever credentials come up in Steps 3a and 3b.

## Step 0: Detect Client

Before anything else, determine which agentic client the user is running. This controls how credentials are configured in Step 1 and Step 5.

Run:

```bash
env | grep "^CODEX_"
```

- **If no `CODEX_*` variables are present** → the user is running a **shell-based client** (Claude, Cursor, Gemini CLI, Copilot CLI, etc.). Credentials are configured via shell profile environment variables.
- **If any `CODEX_*` variables are present** → the user is running **Codex**. Credentials are stored in `~/.codex/config.toml` (macOS/Linux) or `%USERPROFILE%\.codex\config.toml` (Windows), not in shell environment variables. The desktop app does not inherit shell env vars when launched from Finder, Launchpad, or the Windows Start menu.

Carry this **client type** (Codex vs. shell-based) forward through every subsequent step.

## Step 1: Check Existing Configuration

Check whether credentials are already configured.

**For shell-based clients** — check the current environment:

```bash
env | grep "^MDB_MCP" | sed '/^MDB_MCP_READ_ONLY=/!s/=.*/=[set]/'
```

**For Codex** — search `~/.codex/config.toml` (macOS/Linux) or `%USERPROFILE%\.codex\config.toml` (Windows):

```bash
grep -E 'MDB_MCP_(CONNECTION_STRING|API_CLIENT_ID|API_CLIENT_SECRET|READ_ONLY)' ~/.codex/config.toml 2>/dev/null | sed '/MDB_MCP_READ_ONLY/!s/[[:space:]]*=[[:space:]].*/ = "[set]"/'
```

**Interpretation (both):**

- If `MDB_MCP_CONNECTION_STRING` appears → connection string auth is configured
- If both `MDB_MCP_API_CLIENT_ID` and `MDB_MCP_API_CLIENT_SECRET` appear → service account auth is configured. If only one is present, treat it as incomplete.
- If `MDB_MCP_READ_ONLY` appears → read-only mode is enabled

**Partial Configuration Handling:**

- User wants to add read-only to existing setup (has auth, no read-only flag) → skip to Step 4
- User wants to switch authentication methods → explain they should remove the old credentials first (from `config.toml` for Codex, from their shell profile for shell-based clients), then proceed with Steps 2–5
- User wants to update credentials → skip to Step 5

**Important**: If the user wants an Atlas Admin API action (managing clusters, creating users, performance advisor) but only has `MDB_MCP_CONNECTION_STRING`, explain they need service account credentials and offer to walk through setup.

## Step 2: Present Configuration Options

If no valid configuration exists, present the options:

**Connection String (Option A)** — Best for:

- Single cluster access
- Existing database credentials
- Self-hosted MongoDB or no Atlas Admin API needs

**Service Account Credentials (Option B)** — Best for:

- MongoDB Atlas users (recommended)
- Multi-cluster switching
- Atlas Admin API access (cluster management, user creation, performance monitoring)

**Atlas Local (Option C)** — Best for:

- Local development/testing without cloud setup
- Fastest setup with Docker, no credentials required

Ask the user which option they'd like to proceed with.

## Step 3a: Connection String Setup

If the user chooses Option A:

### 3a.1: Explain How to Find the Connection String

Explain where and how to obtain their connection string:

**For MongoDB Atlas:**

1. Go to [cloud.mongodb.com](https://cloud.mongodb.com)
2. Select your cluster → click **Connect**
3. Choose **Drivers** or **Shell** → copy the connection string
4. Replace `<username>` and `<password>` with your database user credentials

**For self-hosted MongoDB:**

- The connection string is typically configured by your DBA or in your application config
- Format: `mongodb://username:password@host:port/database`

**Expected formats:**

- `mongodb://username:password@host:port/database`
- `mongodb+srv://username:password@cluster.mongodb.net/database`
- `mongodb://host:port` (local, no auth)

Proceed to Step 4 (Determine Read-Only Access).

## Step 3b: Service Account Setup

If the user chooses Option B:

### 3b.1: Guide Through Atlas Service Account Creation

Direct the user to create a MongoDB Atlas Service Account:

**Full documentation**: https://www.mongodb.com/docs/mcp-server/prerequisites/

Walk them through the key steps:

1. **Navigate to MongoDB Atlas** — [cloud.mongodb.com](https://cloud.mongodb.com)
2. **Select your organization** from the ORGANIZATION section near the top of the page
3. **Go to "Project Identity and Access"** on the left sidebar → **Applications** → **Create Service Account**
4. **Set Permissions** — Grant Organization Member or Project Owner (see docs for exact permission mappings)
5. **Generate Credentials** — Create Client ID and Secret
   - ⚠️ The **Client Secret is shown only once** — save it immediately before leaving the page
5. **Note both values** — you'll need Client ID and Client Secret for Step 5

### 3b.2: API Access List Configuration

⚠️ **CRITICAL**: The user MUST add their IP address to the service account's API Access List, or all Atlas Admin API operations will fail.

Steps:

1. On the service account details page, find **API Access List**
2. Click **Add Access List Entry**
3. Add your current IP address. Use a specific IP or CIDR range whenever possible.
   - ⚠️ **`0.0.0.0/0` allows access from any IP — this is a significant security risk.** Only use it as a last resort for temporary testing and remove it immediately afterward. It should never be used in production.
4. Save changes

This is more secure than global Network Access settings as it only affects API access, not database connections.

Proceed to Step 4 (Determine Read-Only Access).

## Step 3c: Atlas Local Setup

If the user chooses Option C:

### 3c.1: Check Docker Installation

Verify Docker is installed:

```bash
docker info
```

If not installed, direct them to: https://www.docker.com/get-started

### 3c.2: Confirm Setup Complete

Atlas Local requires no credentials — the user is ready to go:

- Create deployments: `atlas-local-create-deployment`
- List deployments: `atlas-local-list-deployments`
- All operations work out of the box with Docker

**Skip Steps 4 and 5** (no configuration needed) and proceed to Step 6 (Next Steps).

## Step 4: Determine Read-Only vs Read-Write Access

**Only applies to Options A and B. Skip to Step 6 for Option C.**

Ask whether they want read-only or read-write access:

- **Read-Write** (default): Full data access, modifications allowed
  - Best for: Development, testing, administrative tasks

- **Read-Only**: Data reads only, no modifications
  - Best for: Production data safety, reporting, compliance

**If read-only**: include the read-only flag in the credential snippet in Step 5.
**If read-write**: omit it (defaults to read-write).

Proceed to Step 5 (Configure Credentials).

## Step 5: Configure Credentials

**Do not ask for or handle credentials** — provide exact instructions so the user can add them directly.

### 5.1: Add credentials

**For shell-based clients** — store credentials in a dedicated `~/.mcp-env` file (not directly in the shell profile), then source it from the profile. This keeps credentials out of files that are often group/world readable by default and prevents accidentally committing them to git.

**For Codex** — add to `~/.codex/config.toml` (macOS/Linux) or `%USERPROFILE%\.codex\config.toml` (Windows).

Show the user the appropriate snippet:

**For Connection String (Option A):**

Shell-based clients (`~/.mcp-env`):

```bash
export MDB_MCP_CONNECTION_STRING="<paste-your-connection-string-here>"
```

Codex (`config.toml`):

```toml
[mcp_servers.mongodb.env]
MDB_MCP_CONNECTION_STRING = "<paste-your-connection-string-here>"
```

**For Service Account (Option B):**

Shell-based clients (`~/.mcp-env`):

```bash
export MDB_MCP_API_CLIENT_ID="<paste-your-client-id-here>"
export MDB_MCP_API_CLIENT_SECRET="<paste-your-client-secret-here>"
```

Codex (`config.toml`):

```toml
[mcp_servers.mongodb.env]
MDB_MCP_API_CLIENT_ID = "<paste-your-client-id-here>"
MDB_MCP_API_CLIENT_SECRET = "<paste-your-client-secret-here>"
```

**If read-only was chosen (Step 4), also add:**

Shell-based: `export MDB_MCP_READ_ONLY="true"` in `~/.mcp-env`.

Codex: `MDB_MCP_READ_ONLY = "true"` under the same `[mcp_servers.mongodb.env]` section.

⚠️ Both `config.toml` and `~/.mcp-env` are stored in plaintext. Do not commit them to version control.

### 5.2: Finalize (shell-based clients only)

Restrict permissions on `~/.mcp-env`:

```bash
# adjust for windows if needed
chmod 600 ~/.mcp-env
```

Add `source ~/.mcp-env` to the shell profile (e.g. `~/.zshrc`). Adjust for the detected shell (e.g. for fish: `bass source ~/.mcp-env` or `set -x`; for PowerShell: dot-source a `.ps1` file instead).

Detect the shell and profile file by running `echo $SHELL` if needed.

### 5.3: Verify

**Shell-based clients** — reload the profile first, then verify:

```bash
source ~/.zshrc  # adjust to match the profile file
env | grep "^MDB_MCP" | sed '/^MDB_MCP_READ_ONLY=/!s/=.*/=[set]/'
```

**Codex:**

```bash
# adjust path if on Windows
grep -E 'MDB_MCP_(CONNECTION_STRING|API_CLIENT_ID|API_CLIENT_SECRET|READ_ONLY)' ~/.codex/config.toml 2>/dev/null | sed '/MDB_MCP_READ_ONLY/!s/[[:space:]]*=[[:space:]].*/ = "[set]"/'
```

Expected output shows the configured key(s) with values redacted to `[set]`. If nothing appears, check that credentials were saved and (for shell-based clients) that the profile was reloaded.

Proceed to Step 6 (Next Steps).

## Step 6: Next Steps

### For Options A & B (Connection String / Service Account):

1. **Restart the agentic client**:
   - **Shell-based clients**: Fully quit the client, then run `source <profile-file>` to load the new variables, and reopen the client from that same terminal session so it inherits the environment.
   - **Codex**: Fully quit and relaunch the app. No terminal session needed — credentials come from `config.toml`.

2. **Verify MCP Server**: After restart, test by performing a MongoDB operation.

3. **Using the Tools**:
   - Option A: Direct database access tools available
   - Option B: Additionally has Atlas Admin API tools and `atlas-connect-cluster`
   - **Important (Option B)**: Ensure your IP is in the service account's API Access List or all API calls will fail

### For Option C (Atlas Local):

1. **Ready to use**: No restart or configuration needed!

2. **Next steps**:
   - Create deployments: `atlas-local-create-deployment`
   - List deployments: `atlas-local-list-deployments`
   - Use standard database operations once connected

## Troubleshooting

- **Variables not appearing after `source`** (shell-based clients): Check the profile file path and confirm the file was saved
- **Client doesn't pick up variables**: Ensure full restart (quit + reopen), not just a reload
- **Codex desktop app not picking up credentials**: If launched from Finder, Launchpad, or the Windows Start menu, Codex does not inherit shell environment variables from `.zshrc`/`.zprofile`/PowerShell profiles. Use `~/.codex/config.toml` (macOS/Linux) or `%USERPROFILE%\.codex\config.toml` (Windows) instead (see Step 5)
- **Invalid connection string format**: Re-check the format; must start with `mongodb://` or `mongodb+srv://`
- **Atlas Admin API errors (Option B)**: Verify your IP is in the service account's API Access List
- **Read-only mode not working**: Check that `MDB_MCP_READ_ONLY` is set — in `config.toml` under `[mcp_servers.mongodb.env]` for Codex, or via `env | grep ^MDB_MCP_READ_ONLY` for shell-based clients
- **fish/PowerShell**: Syntax differs — use `set -x` (fish) or `$env:` (PowerShell) instead of `export`

<!-- chapter:end slug=mongodb-mcp-setup -->

---

<!-- chapter:begin slug=mongodb-natural-language-querying position=4 -->

## 4. mongodb-natural-language-querying

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-natural-language-querying/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-natural-language-querying/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-natural-language-querying.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-natural-language-querying
description: Generate read-only MongoDB queries (find) or aggregation pipelines using natural language, with collection schema context and sample documents. Use this skill whenever the user asks to write, create, or generate MongoDB queries, wants to filter/query/aggregate data in MongoDB, asks "how do I query...", needs help with query syntax, or discusses finding/filtering/grouping MongoDB documents. Also use for translating SQL-like requests to MongoDB syntax. Does NOT handle Atlas Search ($search operator), vector/semantic search ($vectorSearch operator), fuzzy matching, autocomplete indexes, or relevance scoring - use search-and-ai for those. Does NOT analyze or optimize existing queries - use mongodb-query-optimizer for that. Does NOT handle aggregation pipelines that involve write operations. Requires MongoDB MCP server.
license: Apache-2.0
metadata:
  version: "1.0.0"
allowed-tools: mcp__mongodb__*
---

# MongoDB Natural Language Querying

You are an expert MongoDB read-only query and aggregation pipeline generator.

## Query Generation Process

### 1. Gather Context Using MCP Tools

**Required Information:**
- Database name and collection name (use `mcp__mongodb__list-databases` and `mcp__mongodb__list-collections` if not provided)
- User's natural language description of the query

**Fetch in this order:**

1. **Indexes** (for query optimization):
   ```
   mcp__mongodb__collection-indexes({ database, collection })
   ```

2. **Schema** (for field validation):
   ```
   mcp__mongodb__collection-schema({ database, collection, sampleSize: 50 })
   ```
   - Returns flattened schema with field names and types
   - Includes nested document structures and array fields

3. **Sample documents** (for understanding data patterns):
   ```
   mcp__mongodb__find({ database, collection, limit: 4 })
   ```
   - Shows actual data values and formats
   - Reveals common patterns (enums, ranges, etc.)

### 2. Analyze Context and Validate Fields

Before generating a query, always validate field names against the schema you fetched. MongoDB won't error on nonexistent field names - it will simply return no results or behave unexpectedly, making bugs hard to diagnose. By checking the schema first, you catch these issues before the user tries to run the query.

Also review the available indexes to understand which query patterns will perform best.

### 3. Choose Query Type: Find vs Aggregation

Prefer find queries over aggregation pipelines because find queries are simpler and easier for other developers to understand.

**Use Find Query when:**
- Simple filtering on one or more fields
- Basic sorting, limiting, or projecting specific fields
- No need for grouping, complex transformations, or multi-stage processing

**Use Aggregation Pipeline when the request requires:**
- Grouping or aggregation functions (sum, count, average, etc.)
- Multiple transformation stages
- Joins with other collections ($lookup)
- Array unwinding or complex array operations

### 4. Format Your Response

Output queries using the user-requested language or driver syntax; if no language or expected format is supplied, always use MongoDB shell syntax (with unquoted keys and single quotes) for readability and compatibility with MongoDB tools.

**Find Query Response:**
```json
{
  "query": {
    "filter": "{ age: { $gte: 25 } }",
    "projection": "{ name: 1, age: 1, _id: 0 }",
    "sort": "{ age: -1 }",
    "limit": "10"
  }
}
```

**Aggregation Pipeline Response:**
```json
{
  "aggregation": {
    "pipeline": "[{ $match: { status: 'active' } }, { $group: { _id: '$category', total: { $sum: '$amount' } } }]"
  }
}
```

## Best Practices

### Query Quality
1. **Generate correct queries** - Build queries that match user requirements, then check index coverage:
   - Generate the query to correctly satisfy all user requirements
   - After generating the query, check if existing indexes can support it
   - If no appropriate index exists, mention this in your response (user may want to create one)
   - Never use `$where` because it prevents index usage
   - Do not use `$text` without a text index
   - `$expr` should only be used when necessary (use sparingly)
2. **Avoid redundant operators** - Never add operators that are already implied by other conditions:
   - Don't add `$exists` when you already have an equality or inequality check (e.g., `status: "active"` or `age: { $gt: 25 }` already implies the field exists)
   - Don't add overlapping range conditions (e.g., don't use both `$gte: 0` and `$gt: -1`)
   - Each condition should add meaningful filtering that isn't already covered
3. **Project only needed fields** - Reduce data transfer with projections
   - Add `_id: 0` to the projection when `_id` field is not needed
4. **Validate field names** against the schema before using them
5. **Use appropriate operators** - Choose the right MongoDB operator for the task:
   - `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` for comparisons
   - `$in`, `$nin` for matching against a list of possible values (equivalent to multiple $eq/$ne conditions OR'ed together)
   - `$and`, `$or`, `$not`, `$nor` for logical operations
   - `$regex` for case-sensitive text pattern matching (prefer left-anchored patterns like `/^prefix/` when possible, as they can use indexes efficiently)
   - `$exists` for field existence checks (prefer `a: {$ne: null}` to `a: {$exists: true}` to leverage available indexes)
   - `$type` for type matching
6. **Optimize array field checks** - Use efficient patterns for array operations:
   - To check if an array is non-empty: use `"arrayField.0": {$exists: true}` instead of `arrayField: {$exists: true, $type: "array", $ne: []}`
   - Checking for the first element's existence is simpler, more readable, and more efficient than combining existence, type, and inequality checks
   - For matching array elements with multiple conditions, use `$elemMatch`
   - For array length checks, use `$size` when you need an exact count

### Aggregation Pipeline Quality
1. **Filter early** - Use `$match` as early as possible to reduce documents
2. **Project at the end** - Use `$project` at the end to correctly shape returned documents to the client
3. **Limit when possible** - Add `$limit` after `$sort` when appropriate
4. **Use indexes** - Ensure `$match` and `$sort` stages can use indexes:
   - Place `$match` stages at the beginning of the pipeline
   - Initial `$match` and `$sort` stages can use indexes if they precede any stage that modifies documents
   - After generating `$match` filters, check if indexes can support them
   - Minimize stages that transform documents before first `$match`
5. **Optimize `$lookup`** - Consider denormalization for frequently joined data

### Error Prevention
1. **Validate all field references** against the schema
2. **Quote field names correctly** - Use dot notation for nested fields
3. **Escape special characters** in regex patterns
4. **Check data types** - Ensure field values match field types from schema
5. **Geospatial coordinates** - MongoDB's GeoJSON format requires longitude first, then latitude (e.g., `[longitude, latitude]` or `{type: "Point", coordinates: [lng, lat]}`). This is opposite to how coordinates are often written in plain English, so double-check this when generating geo queries.

## Schema Analysis

When provided with sample documents, analyze:
1. **Field types** - String, Number, Boolean, Date, ObjectId, Array, Object
2. **Field patterns** - Required vs optional fields (check multiple samples)
3. **Nested structures** - Objects within objects, arrays of objects
4. **Array elements** - Homogeneous vs heterogeneous arrays
5. **Special types** - Dates, ObjectIds, Binary data, GeoJSON

## Sample Document Usage

Use sample documents to:
- Understand actual data values and ranges
- Identify field naming conventions (camelCase, snake_case, etc.)
- Detect common patterns (e.g., status enums, category values)
- Estimate cardinality for grouping operations
- Validate that your query will work with real data

## Error Handling

If you cannot generate a query:
1. **Explain why** - Missing schema, ambiguous request, impossible query
2. **Ask for clarification** - Request more details about requirements
3. **Suggest alternatives** - Propose different approaches if available
4. **Provide examples** - Show similar queries that could work

## Example Workflow

**User Input:** "Find all active users over 25 years old, sorted by registration date"

**Your Process:**
1. Check schema for fields: `status`, `age`, `registrationDate` or similar
2. Verify field types match the query requirements
3. Generate query based on user requirements
4. Check if available indexes can support the query
5. Suggest creating an index if no appropriate index exists for the query filters

**Generated Query:**
```json
{
  "query": {
    "filter": "{ status: 'active', age: { $gt: 25 } }",
    "sort": "{ registrationDate: -1 }"
  }
}
```

## Managing Context Size

Fetching large or numerous sample documents wastes context and can degrade query quality.

**Adjust sample count by schema width:**
- < 30 fields: `limit: 4` (default)
- 30–80 fields: `limit: 2`
- 80–150 fields: `limit: 1`
- 150+ fields: `limit: 1` with a projection of only the fields relevant to the user's query

**Preview large array fields and strings:**
- If schema documents contains arrays, use `$slice: 3` in the sample projection to cap array size. Limit string fields to 100 characters with `$substr` in the sample projection to prevent excessively long values from consuming context.

<!-- chapter:end slug=mongodb-natural-language-querying -->

---

<!-- chapter:begin slug=mongodb-query-optimizer position=5 -->

## 5. mongodb-query-optimizer

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-query-optimizer/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-query-optimizer/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-query-optimizer.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

Bundled files (4), referenced from this skill's directory:
  - `references/aggregation-optimization.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-query-optimizer/references/aggregation-optimization.md
  - `references/antipattern-examples.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-query-optimizer/references/antipattern-examples.md
  - `references/core-indexing-principles.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-query-optimizer/references/core-indexing-principles.md
  - `references/update-query-examples.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-query-optimizer/references/update-query-examples.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-query-optimizer
description: >-
  Help with MongoDB query optimization and indexing. Use only when the user asks for optimization or performance: "How do I optimize this query?", "How do I index this?", "Why is this query slow?", "Can you fix my slow queries?", "What are the slow queries on my cluster?", etc. Do not invoke for general MongoDB query writing unless user asks for performance or index help. Prefer indexing as optimization strategy. Use MongoDB MCP when available.
compatibility: >-
  Best with MongoDB MCP server. Uses collection-indexes and explain when the connection string works; uses Atlas Performance Advisor when Atlas API is configured. Without either, suggest indexes from query shape only. User creates indexes in Atlas or migrations unless tooling allows otherwise.
license: Apache-2.0
metadata:
  version: "1.0.0"
---

# MongoDB Query Optimizer

## When this skill is invoked

Invoke **only** when the user wants:

- Query/index **optimization** or **performance** help  
- **Why** a query is slow or **how to speed it up**  
- **Slow queries** on their cluster and/or **how to optimize them**

Do **not** invoke for routine query authoring unless the user has requested help with optimization, slow queries, or indexing.

## High Level Workflow

### General Performance Help

If the user wants to examine slow queries, or is looking for general performance suggestions (not regarding any particular query):

- Use MongoDB MCP server **atlas-get-performance-advisor** tool to fetch slow query logs and performance advisor output  
- Make suggestions based on this information

If Atlas MCP Server for Atlas is not configured or you don’t have enough information to run **atlas-get-performance-advisor** against the correct cluster, tell the user that general performance analysis requires Atlas MCP Server configuration with API credentials, and suggest they configure it or ask about a specific query instead.

### Help with a Specific Query

If the user is asking about a particular query:

- Use **collection-indexes**, **explain**, and **find** MCP tools to get existing indexes on the collection, explain() output for the query, and a sample document from the collection  
- Use **atlas-get-performance-advisor MCP** tool to fetch slow query logs and performance advisor output

Then make an optimization suggestion based on collected information and MongoDB best practices and examples from reference files. Prefer creating an index that fully covers the query if possible. If you cannot use MongoDB MCP Server then still try to make a suggestion.

## MCP: available tools

**How to invoke.** Call the **MongoDB MCP server** with the **exact tool name** as `toolName` and a single **arguments object** as `arguments`. Do not pass the tool name as an option, query param, or nested key; pass it as the MCP tool name and the parameters as the arguments object. Full MCP Server tool reference: [MongoDB MCP Server Tools](https://www.mongodb.com/docs/mcp-server/tools/).

**Database tools** (when the MCP cluster connection works):

| Tool name (exact) | Arguments object |
| :---- | :---- |
| `collection-indexes` | `{ "database": "<db>", "collection": "<coll>" }` — both required strings. |
| `explain` | `{ "database": "<db>", "collection": "<coll>", "method": [ { "name": "find", "arguments": { "filter": {...}, "sort": {...}, "limit": N } } ], "verbosity": "executionStats" }`. `method` is an array of one object: `name` is `"find"`, `"aggregate"`, or `"count"`; `arguments` holds that method's params (e.g. find: `filter`, `sort`, `limit`; aggregate: `pipeline`; count: `query`). Optional `verbosity`: `"queryPlanner"` (default), `"executionStats"`, `"queryPlannerExtended"`, `"allPlansExecution"`. |
| `find` |  `{ "database": "<db>", "collection": "<coll>", "filter": {...}, "projection": {...}, "sort": {...}, "limit": N }` — `database`, `collection`, and `filter` are required. Optional: `projection`, `sort`, `limit`. |

**Atlas tools** (when Atlas API credentials are configured):

| Tool name (exact) | Arguments object |
| :---- | :---- |
| `atlas-list-projects` | `{}` or `{ "orgId": "<24-char hex>" }`. Returns projects with their IDs; use to get `projectId` for Performance Advisor. |
| `atlas-get-performance-advisor` | **Required:** `"projectId"` (24-character hex string), `"clusterName"` (string, 1–64 chars, alphanumeric/underscore/dash). **Optional:** `"operations"` — array of strings from `"suggestedIndexes"`, `"dropIndexSuggestions"`, `"slowQueryLogs"`, `"schemaSuggestions"` (request only what you need); for slowQueryLogs only: `"since"` (ISO 8601 date-time), `"namespaces"` (array of `"db.coll"` strings). |

For a user question, try to fetch information from both the connection string and Atlas API related to the query you are optimizing.

### 1\. DB connection string works for MongoDB MCP

Typical flow: call `collection-indexes` → `explain` → `find` (sample doc).

- **`collection-indexes`** — Use the result's `classicIndexes` (each has `name`, `key`) to see if the query can already use an existing index.
- **`explain`** — Run in `"queryPlanner"` mode first to check for COLLSCAN. If the query uses an index or the collection is very small, run again with `"executionStats"` (10-second timeout) to get docs scanned vs. returned.

### 2\. Atlas API access works for MongoDB MCP

If you need a project ID, call `atlas-list-projects` first. Then call `atlas-get-performance-advisor` with only the `operations` you need:

| Operation value | Use when |
| :---- | :---- |
| `slowQueryLogs` | Fetching slow queries—**prioritize by slowest and most frequent**. Optional: `namespaces` to scope to a collection; `since` for a time window. |
| `suggestedIndexes` | Fetching cluster index recommendations |
| `dropIndexSuggestions` | User asks what to remove or reduce index overhead |
| `schemaSuggestions` | User asks for schema/query-structure advice alongside indexes |

Do not pass the MCP tool name as an `operations` value—`operations` is a separate argument listing what data to fetch.

## Example workflow 1 (help with specific query)

**User:** "Why is this query slow? `db.orders.find({status: 'shipped', region: 'US'}).sort({date: -1})`"

**If MCP db connection is configured and the database + collection names are known**, run steps 1–3. Otherwise skip to step 4.

1. **Check existing collection indexes:**
   - Call `collection-indexes` with database=`store`, collection=`orders`
   - Result shows: `{_id: 1}`, `{status: 1}`, `{date: -1}`

2. **Run explain:**
   - Call `explain` with method=`find`, filter=`{status: 'shipped', region: 'US'}`, sort=`{date: -1}`, verbosity=`queryPlanner` and `executionStats`
   - Result: Uses `{status: 1}` index, then in-memory SORT, `totalKeysExamined: 50000`, `nReturned: 100`

3. **Run find:**
   - Call `find` with limit=1 to fetch a sample document to impute the schema.

**If MCP Atlas connection is configured**, run step 4. Otherwise skip to step 5.

4. **Run atlas-get-performance-advisor:**
   - Try to get the cluster name from the MCP connection string, or ask the user for projectId/clusterName
   - Use slowQueryLogs to fetch slow query logs from database=`store`, collection=`orders` in the past 24 hours
   - Use suggestedIndexes to check for index suggestions for the query

5. **Diagnose:** Based on explain output and slow query logs, this query targets 100 docs but scans 50K index entries (poor selectivity: 0.002). In-memory sort adds overhead. Index doesn't support both filter fields or sort.

6. **Recommend:** Create compound index `{status: 1, region: 1, date: -1}` following ESR (two equality fields, then sort). This eliminates in-memory sort and improves selectivity by filtering on both status and region.

If the MongoDB MCP server is not set up, follow best indexing practices.

## Example workflow 2 (general database performance help)

**User:** "Can you help with optimizing slow queries on my cluster?”

1. **Run atlas-get-performance-advisor:**  
   - Try to get the cluster name from the connection string and deduce the project name you need in atlas-list-projects; if you are not sure, then ask the user for cluster name and project id.
   - Use slowQueryLogs to fetch slow query logs from the past 24 hours  
   - Use suggestedIndexes  
   - Use dropIndexSuggestions  
   - Use schemaSuggestions  
2. **Diagnose and Recommend:** Based on slow query logs and performance advisor advice, you can create the compound index `{status: 1, region: 1, date: -1}` on the `db.orders` collection to optimize queries such as `find({status: 'shipped', region: 'US'}).sort({date: -1})`

Examine all performance advisor output as well as slow query logs. Provide information on what is being improved and why, and focus on suggestions that have the potential for greatest impact (e.g., indexes that affect the most queries, or queries that have the worst performance).

## Load references

Before beginning diagnosis and recommendation, load reference files.

Always load:

- `references/core-indexing-principles.md`
- `references/antipattern-examples.md`

Conditionally load these files:

- **If diagnosing aggregation pipelines** → `references/aggregation-optimization.md`
- **If diagnosing queries that change docs such as replaceOne, findOneAndUpdate, etc.** → `references/update-query-examples.md` for oplog-efficient updates and common update anti-patterns

## Output

- Keep answers short and clear: a few sentences on index and optimization suggestions, and reasoning behind them (e.g. general indexing principles, observing slow query logs in the cluster, or seeing advice in Performance Advisor)
- Focus on highest impact indexes or optimizations - if you've omitted some optimizations let the user know and present them if asked.
- Do not use strong language, such as saying “You should create these indexes and they will definitely improve application performance” \-  Explain they are suggestions for certain queries, and give the reasoning behind them.
- Consider how many indexes already exist on the collection (if known) \- there shouldn’t generally be more than 20
- Suggest removing indexes only if the suggestion comes from Atlas Performance Advisor
- Do not create indexes directly via MCP unless the user gives approval

<!-- chapter:end slug=mongodb-query-optimizer -->

---

<!-- chapter:begin slug=mongodb-schema-design position=6 -->

## 6. mongodb-schema-design

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-schema-design/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-schema-design.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

Bundled files (20), referenced from this skill's directory:
  - `references/antipattern-excessive-lookups.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/antipattern-excessive-lookups.md
  - `references/antipattern-unnecessary-collections.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/antipattern-unnecessary-collections.md
  - `references/antipattern-unnecessary-indexes.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/antipattern-unnecessary-indexes.md
  - `references/fundamental-document-model.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/fundamental-document-model.md
  - `references/fundamental-document-size.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/fundamental-document-size.md
  - `references/fundamental-embed-vs-reference.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/fundamental-embed-vs-reference.md
  - `references/fundamental-schema-validation.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/fundamental-schema-validation.md
  - `references/pattern-approximation.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-approximation.md
  - `references/pattern-archive.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-archive.md
  - `references/pattern-attribute.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-attribute.md
  - `references/pattern-bucket.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-bucket.md
  - `references/pattern-computed.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-computed.md
  - `references/pattern-document-versioning.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-document-versioning.md
  - `references/pattern-extended-reference.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-extended-reference.md
  - `references/pattern-outlier.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-outlier.md
  - `references/pattern-polymorphic.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-polymorphic.md
  - `references/pattern-schema-versioning.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-schema-versioning.md
  - `references/pattern-time-series-collections.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/pattern-time-series-collections.md
  - `references/source-query-stats.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/source-query-stats.md
  - `references/source-slow-query-logs.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-schema-design/references/source-slow-query-logs.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-schema-design
description: MongoDB schema design patterns and anti-patterns. Use when designing data models, reviewing schemas, migrating from SQL, or troubleshooting performance issues caused by schema problems. Triggers on "design schema", "embed vs reference", "MongoDB data model", "schema review", "unbounded arrays", "one-to-many", "tree structure", "16MB limit", "schema validation", "JSON Schema", "time series", "schema migration", "polymorphic", "TTL", "data lifecycle", "archive", "index explosion", "unnecessary indexes", "approximation pattern", "document versioning".
license: Apache-2.0
metadata:
  version: "1.0.0"
---

# MongoDB Schema Design

Data modeling patterns and anti-patterns for MongoDB, maintained by MongoDB. Bad schema is the root cause of most MongoDB performance and cost issues—queries and indexes cannot fix a fundamentally wrong model.

## When to Apply

Reference these guidelines when:
- Designing a new MongoDB schema from scratch
- Migrating from SQL/relational databases to MongoDB
- Reviewing existing data models for performance issues
- Troubleshooting slow queries or growing document sizes
- Deciding between embedding and referencing
- Modeling relationships (one-to-one, one-to-many, many-to-many)
- Implementing tree/hierarchical structures
- Seeing Atlas Schema Suggestions or Performance Advisor warnings
- Hitting the 16MB document limit
- Adding schema validation to existing collections

## Quick Reference

### 1. Schema Anti-Patterns - 3 rules

- [antipattern-unnecessary-collections](references/antipattern-unnecessary-collections.md) - Splitting homogeneous data into multiple collections is often an anti-pattern; consult this reference to validate whether this is the case.
- [antipattern-excessive-lookups](references/antipattern-excessive-lookups.md) - When encountering overly normalized collections that reference each other or frequent and possibly slow $lookup operations, consult this reference to validate whether this is problematic and how to fix it.
- [antipattern-unnecessary-indexes](references/antipattern-unnecessary-indexes.md) - Consult this reference when indexes overlap or are not used by queries, to identify and remove unnecessary indexes that add overhead without benefit.

### 2. Schema Fundamentals - 4 rules

- [fundamental-embed-vs-reference](references/fundamental-embed-vs-reference.md) - Consult this reference for approaches to modeling different types of relationships (1:1, 1:few, 1:many, many:many, tree/hierarchical data) and how to decide between embedding and referencing based on access patterns.
- [fundamental-document-model](references/fundamental-document-model.md) - Fundamentals of the document model. Consult this reference when migrating from SQL or other normalized data to a document database like MongoDB.
- [fundamental-schema-validation](references/fundamental-schema-validation.md) - Consult this reference when creating new collections, or adding validation to existing collections, for example in response to finding inconsistent document structures or data quality issues.
- [fundamental-document-size](references/fundamental-document-size.md) - Consult this reference when documents hit the hard 16MB limit, or when accesses are slower than expected as a result of large documents.

### 3. Design Patterns - 11 rules

- [pattern-approximation](references/pattern-approximation.md) - Use approximate values for high-frequency counters
- [pattern-archive](references/pattern-archive.md) - Move historical data to separate/cold storage for performance
- [pattern-attribute](references/pattern-attribute.md) - Collapse many optional fields into key-value attributes
- [pattern-bucket](references/pattern-bucket.md) - Group time-series or IoT data into buckets
- [pattern-computed](references/pattern-computed.md) - Pre-calculate expensive aggregations
- [pattern-document-versioning](references/pattern-document-versioning.md) - Track document changes to enable historical queries and audit trails
- [pattern-extended-reference](references/pattern-extended-reference.md) - Cache frequently-accessed data from related entities
- [pattern-outlier](references/pattern-outlier.md) - Handle collections in which a small subset of documents are much larger than the rest, to prevent outliers from dominating memory and index costs
- [pattern-polymorphic](references/pattern-polymorphic.md) - Store different types of entities in the same collection, often when they are different types of the same base entity (e.g. different types of users or different types of products)
- [pattern-schema-versioning](references/pattern-schema-versioning.md) - Schema evolution, preventing drift, and safe online migrations. Consult when encountering inconsistent document structures, or when planning a schema change that cannot be applied atomically.
- [pattern-time-series-collections](references/pattern-time-series-collections.md) - Use native time series collections for high-frequency time series data

### Access Pattern Analysis

Do not immediately recommend a pattern or schema change without understanding the broader context. Together with the user, analyze access patterns to identify pain points and opportunities for optimization.

#### Workflow

**Step 1: Assess the environment**
Ask the user:
  - Is this a new design or is there a production database with existing access patterns to analyze?
  - If there is production data, is it on Atlas? If yes, what tier? (M0/M2/M5 vs M10+)

**Step 2: Determine workload type**
Is the workload read-heavy, write-heavy, or balanced? This will influence which diagnostic sources are most relevant.
Ask the user:
- What's the primary workload for these collections — read-heavy (analytics, reports, searches), write-heavy (logging, IoT ingestion, frequent updates), or balanced?

Verify with `db.serverStatus().opcounters`.

**Step 3: Work with the user to choose the best source(s)**
  Recommend the best source(s) for their situation, explaining the tradeoffs. For schema design decisions, we often need to combine multiple sources for a complete picture.

**Step 4: Proceed with analysis**
  Only after source selection, fetch data or guide the user through analysis.

#### Sources

- [Query statistics](references/source-query-stats.md) - Returns runtime statistics for recorded queries showing query shapes and frequency. **Limitation**: Currently only captures read operations (pair with other sources for write patterns). Requires Atlas M10+ tier.
- [Atlas Slow Query Logs](references/source-slow-query-logs.md) - Review slow queries (actual queries, not shapes) to identify performance bottlenecks. Captures all reads and writes. Requires Atlas M10+ tier.
- Codebase - Examine actual queries in application code to understand access patterns, especially for new applications or with changing workloads. Can be used in conjunction with query stats for a more complete picture.
- Natural language input - Ask the user to describe their typical queries and access patterns in natural language. Can be used as the only source or to supplement and validate other sources - the user might have contextual knowledge that is not reflected in the data or codebase.

**Combining Query Stats and Slow Query Logs:**

Use both together for comprehensive analysis:
1. Query Stats → identify frequent access patterns (which queries run most often)
2. Slow Query Logs → identify performance bottlenecks (which queries are slow)
3. Focus schema optimization on queries that are both frequent AND slow (highest impact)

## Key Principle

> **"Data that is accessed together should be stored together."**

This is MongoDB's core philosophy. Embedding related data eliminates joins, reduces round trips, and enables atomic updates. Reference only when you must.

A core way to implement this philosophy is the fact that MongoDB exposes **flexible schemas**. This means you can have different fields in different documents, and even different structures. This allows you to model data in the way that best fits your access patterns, without being constrained by a rigid schema. For example, if different documents have different sets of fields, that is perfectly fine as long as it serves your application's needs. You can also use schema validation to enforce certain rules while still allowing for flexibility.

Another implication of the key principle is that information about the expected read and write workload becomes very relevant to schema design. If pieces of information from different entities are often queried or updated together, that means that prioritizing co-location of that data in the same document can lead to significant performance benefits. On the other hand, if certain pieces of information are rarely accessed together, it may make sense to store them separately to avoid loading more data than necessary.

#### Schema Fundamentals Summary

- **Embed vs Reference**: Choose embedding or referencing based on access patterns: embed when data is always accessed together (1:1, 1:few, bounded arrays, atomic updates needed); reference when data is accessed independently, relationships are many-to-many, or arrays can grow without bound.
- **Data accessed together stored together**: MongoDB's core principle: design schemas around queries, not entities. Embed related data to eliminate cross-collection joins and reduce round trips. Identify your API endpoints/pages, list the data each returns, then shape documents to match those queries.
- **Embrace the document model**: Don't recreate SQL tables 1:1 as MongoDB collections. Instead, denormalize joined tables into rich documents for single-query reads and atomic updates. When migrating from SQL, identify tables that are always joined together and merge them into single documents.
- **Schema validation**: Use MongoDB's built-in `$jsonSchema` validator to catch invalid data at the database level (type checks, required fields, enum constraints, array size limits). Start with `validationLevel: "moderate"` and `validationAction: "warn"` on existing collections, then tighten to `strict`/`error`.
- **16MB document limit**: MongoDB documents cannot exceed 16MB—this is a hard limit, not a guideline. Common causes: unbounded arrays, large embedded binaries, deeply nested objects. Mitigate by moving unbounded data to separate collections and monitoring document sizes with `$bsonSize`.

## Embed/Reference Decision Framework

| Relationship | Cardinality | Access Pattern | Recommendation |
|-------------|-------------|----------------|----------------|
| One-to-One | 1:1 | Always together | Embed |
| One-to-Few | 1:N (N < 100) | Usually together | Embed array |
| One-to-Many | 1:N (N > 100) | Often separate | Reference |
| Many-to-Many | M:N | Varies | Two-way reference |

This is a **rough** guideline, and whether to embed or reference depends on your specific access patterns, data size, and read/write frequencies. Always verify with your actual workload.

## How to Use

Each reference file listed above contains detailed explanations and code examples. Use the descriptions in the Quick Reference to identify which files are relevant to your current task.

Each reference file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- "When NOT to use" exceptions
- Performance impact and metrics
- Verification diagnostics

---

## How These Rules Work

### MongoDB MCP Integration

For automatic verification, connect the [MongoDB MCP Server](https://github.com/mongodb-js/mongodb-mcp-server).

If the MCP server is running and connected, I can automatically run verification commands to check your actual schema, document sizes, array lengths, index usage, slow query logs, and more. This allows me to provide tailored recommendations based on your real data, not just code patterns.

**⚠️ Security**: Use `--readOnly` for safety. Remove only if you need write operations.

When connected, I can automatically:
- Infer schema via `mcp__mongodb__collection-schema`
- Measure document/array sizes via `mcp__mongodb__aggregate`
- Check collection statistics via `mcp__mongodb__db-stats`

### ⚠️ Action Policy

**I will NEVER execute write operations without your explicit approval.**

Before any write or destructive operation via MCP, I will: (1) summarize the exact operation (collection, index/validator, estimated number of docs affected), and (2) ask for explicit confirmation (yes/no). I will not proceed on partial or ambiguous approvals.

| Operation Type | MCP Tools | Action |
|---------------|-----------|--------|
| **Read (Safe)** | `find`, `aggregate`, `collection-schema`, `db-stats`, `count` | I may run automatically to verify |
| **Write (Requires Approval)** | `update-many`, `insert-many`, `create-collection` | I will show the command and wait for your "yes" |
| **Destructive (Requires Approval)** | `delete-many`, `drop-collection`, `drop-database` | I will warn you and require explicit confirmation |

When I recommend schema changes or data modifications:
1. I'll explain **what** I want to do and **why**
2. I'll show you the **exact command**
3. I'll **wait for your approval** before executing
4. If you say "go ahead" or "yes", only then will I run it

**Your database, your decision.** I'm here to advise, not to act unilaterally.

### Working Together

If you're not sure about a recommendation:
1. Run the verification commands I provide
2. Share the output with me
3. I'll adjust my recommendation based on your actual data

We're a team—let's get this right together.

<!-- chapter:end slug=mongodb-schema-design -->

---

<!-- chapter:begin slug=mongodb-search-and-ai position=7 -->

## 7. mongodb-search-and-ai

- **Source:** https://github.com/mongodb/agent-skills/blob/main/skills/mongodb-search-and-ai/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-search-and-ai/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/mongodb-search-and-ai.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

Bundled files (4), referenced from this skill's directory:
  - `references/hybrid-search.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-search-and-ai/references/hybrid-search.md
  - `references/lexical-search-indexing.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-search-and-ai/references/lexical-search-indexing.md
  - `references/lexical-search-querying.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-search-and-ai/references/lexical-search-querying.md
  - `references/vector-search.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/skills/mongodb-search-and-ai/references/vector-search.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: mongodb-search-and-ai
description: |
  Guides MongoDB users through implementing and optimizing Atlas Search (full-text), Vector Search (semantic), and Hybrid Search solutions. Use this skill when users need to build search functionality for text-based queries (autocomplete, fuzzy matching, faceted search), semantic similarity (embeddings, RAG applications), or combined approaches. Also use when users need text containment, substring matching ('contains', 'includes', 'appears in'), case-insensitive or multi-field text search, or filtering across many fields with variable combinations. Provides workflows for selecting the right search type, creating indexes, constructing queries, and optimizing performance using the MongoDB MCP server.
license: Apache-2.0
metadata:
  version: "1.0.0"
---

# MongoDB Search and AI Recommendations Skill

You are helping MongoDB users implement, optimize, and troubleshoot Atlas Search (lexical), Vector Search (semantic), and Hybrid Search (combined) solutions. Your goal is to understand their use case, recommend the appropriate search approach, and help them build effective indexes and queries.

## Core Principles

1. **Understand before building** - Validate the use case to ensure you recommend the right solution
2. **Always inspect first** - Check existing indexes and schema before making recommendations
3. **Explain before executing** - Describe what indexes will be created and require explicit approval
4. **Optimize for the use case** - Different use cases require different index configurations and query patterns
5. **Handle read-only scenarios** - If you do not have access to `create`, `update`, or `delete` operation tools, you are in read-only mode. Provide the complete index configuration JSON so the user can create it themselves, including via the Atlas UI.

## Workflow

### 1. Discovery Phase

**Check the environment:**
- Use `list-databases` and `list-collections` to understand available data
- If the user mentions a collection, use `collection-schema` to inspect field structure
- Use `collection-indexes` to see existing indexes
- Use `atlas-inspect-cluster` to determine the cluster's MongoDB version

**Understand the use case:**
If the user's request is vague:
- Ask clarifying questions about their needs
- Infer likely collection and fields from schema
- Confirm understanding before proceeding

Common questions to ask:
- What are users searching for? (products, movies, documents, etc.)
- What fields contain the searchable content?
- Do they need exact matching, fuzzy matching, or semantic similarity?
- Do they need filters (price ranges, categories, dates)?
- Do they need autocomplete/typeahead functionality?

### 2. Determine Search Type

**Atlas Search (Lexical/Full-Text):**
Use when users need:
- Keyword matching with relevance scoring
- Fuzzy matching for typo tolerance
- Autocomplete/typeahead
- Faceted search with filters
- Language-specific text analysis
- Token-based search
- Lexical search with views

**Vector Search (Semantic):**
Use when users need:
- Semantic similarity ("find movies about coming of age stories")
- Natural language understanding
- RAG (Retrieval Augmented Generation) applications
- Finding conceptually similar items
- Cross-modal search
- Vector search with views

**Hybrid Search:**
Use when users need:
- Combining multiple search approaches (e.g., vector + lexical, multiple text searches)
- Queries like "find action movies similar to 'epic space battles'" (combining keyword filtering with semantic similarity)
- Results that factor in multiple relevance criteria
- Uses `$rankFusion` (rank-based) or `$scoreFusion` (score-based) to merge pipelines

### 3. Version Check (Hybrid Search only)

If the search type is **Hybrid using `$rankFusion` or `$scoreFusion`**, verify the cluster version before proceeding:
- `$rankFusion` requires MongoDB 8.0+
- `$scoreFusion` requires MongoDB 8.2+

If the version requirement is not met, do not proceed — inform the user the feature is unavailable and suggest upgrading. Do not consult `references/hybrid-search.md`.

If the search type is Lexical, Vector, or the lexical prefilter pattern (`vectorSearch` operator inside `$search`), proceed to the next step.

### 4. Consult Reference Files

Always consult the appropriate reference file(s) before recommending indexes or queries:
- **Lexical**: consult both `references/lexical-search-indexing.md` (index) and `references/lexical-search-querying.md` (query)
- **Vector**: consult `references/vector-search.md`
- **Hybrid**: consult `references/hybrid-search.md` (and the lexical/vector files for the individual pipeline stages within it)

### 5. Execution and Validation

**Creating indexes:**
1. Explain the index configuration in plain language
2. Show the JSON structure
3. Ask what the user wants to name the index
4. Get explicit approval: "Should I create this index?"
5. Use MCP's `create-index` tool after approval
6. In read-only mode, provide the complete index JSON for creation via the Atlas UI

**Running queries:**
1. Show the aggregation pipeline
2. Execute using MCP's `aggregate` tool
3. Present results clearly

**Refining existing queries:**
1. Ask the user to share their current query
2. Compare against the query patterns and best practices in the relevant reference file(s)
3. Propose specific improvements with before/after examples
4. Run the revised query with `aggregate` to validate the results

## Anti-Patterns to Avoid

**NEVER recommend $regex or $text for search use cases:**
- **$regex**: Not designed for full-text search. Lacks relevance scoring, fuzzy matching, and language-aware tokenization.
- **$text**: Legacy operator that doesn't scale well for search workloads.

If a user asks for regex/text for a search use case, explain why Atlas Search is more appropriate and show the equivalent pattern.

## Handling Edge Cases

**User mentions fields you can't find:**
- Use `collection-schema` to inspect available fields
- Suggest alternatives or ask for clarification

**Required field doesn't exist:**
- Explain what needs to be added and how (e.g., embedding field for vector search)

**Query fails or index missing:**
- Use `collection-indexes` to verify index exists
- If missing, explain index needs to be created first

**Multiple collections are relevant:**
- List options and ask which one they mean
- If context makes it obvious, confirm your assumption

## Remember

- Always check existing indexes before recommending new ones
- Explain technical concepts in accessible language
- Require approval before creating indexes
- Map user's business requirements to technical implementations
- Use the appropriate search type for the use case

<!-- chapter:end slug=mongodb-search-and-ai -->

---

<!-- chapter:begin slug=review-skill position=8 -->

## 8. review-skill

- **Source:** https://github.com/mongodb/agent-skills/blob/main/tools/review-skill/SKILL.md
- **Raw:** https://raw.githubusercontent.com/mongodb/agent-skills/main/tools/review-skill/SKILL.md
- **Markdown:** https://skillsdocs.com/mongodb/agent-skills/review-skill.md
- **Licence:** Apache-2.0 — https://spdx.org/licenses/Apache-2.0.html

Bundled files (3), referenced from this skill's directory:
  - `assets/report.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/tools/review-skill/assets/report.md
  - `references/install-skill-validator.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/tools/review-skill/references/install-skill-validator.md
  - `references/llm-scoring.md` — https://raw.githubusercontent.com/mongodb/agent-skills/main/tools/review-skill/references/llm-scoring.md

<!-- Verbatim upstream SKILL.md follows, YAML frontmatter included. -->

---
name: review-skill
description: >-
  Review a proposed Agent Skill for structural validity and content
  quality before publishing. Runs the skill-validator CLI to check for
  structural issues, scores the skill with an LLM judge, and interprets results
  to advise SMEs on what to address. Use when a user wants to review, validate,
  or quality-check an Agent Skill.
compatibility: Requires skill-validator CLI and claude CLI for LLM scoring. LLM scoring can be skipped for structural-only review.
metadata:
  author: mongodb
  version: "1.0"
---

# Review Skill Workflow

You are helping an SME review an Agent Skill before publishing. This is a
multi-step process: determine environment, verify prerequisites, run structural
validation, review content, optionally run LLM scoring, and interpret results.
Follow every step in order.

## Step 0: Determine Environment

Check for saved configuration:

```bash
cat ~/.config/skill-validator/review-state.yaml 2>/dev/null
```

**If the state file exists** with `prereqs_passed: true`, offer:

> Found saved settings — configured for **[full/structural-only]** reviews.
>
> 1. **Continue with saved settings** — skip to Step 2
> 2. **Re-run prerequisite checks**
> 3. **Change environment** — switch between full and structural-only

Option 1: read `llm_scoring` from the file and skip to Step 2.
Options 2-3: continue below.

**If no state file exists**, or the user chose to re-check/change, ask:

> LLM scoring evaluates content quality across multiple dimensions.
>
> 1. **Yes, run LLM scoring** — full review with LLM scoring
> 2. **No, skip LLM scoring** — structural validation only

Option 1: set `LLM_SCORING=true`.
Option 2: set `LLM_SCORING=false`. Run Step 1a only, then jump to Step 2.

## Step 1: Verify Prerequisites

### 1a. Check for `skill-validator` binary

```bash
skill-validator --version
```

If not found, search common locations (`/usr/local/bin`, `/opt/homebrew/bin`,
`~/go/bin`). If found but not on PATH, tell the user. If not found anywhere,
follow [references/install-skill-validator.md](references/install-skill-validator.md).

If `--version` is not at least v1.5.1, help the user upgrade with
`brew upgrade skill-validator` or
`go install github.com/agent-ecosystem/skill-validator/cmd/skill-validator@latest`.

Do NOT proceed until this succeeds.

### 1b. Check for `claude` CLI (LLM scoring only)

If `LLM_SCORING=true`, verify the Claude CLI is available:

```bash
claude --version
```

If not found, tell the user to install Claude Code:

- **macOS**: `curl -fsSL https://claude.ai/install.sh | bash`
- **Other platforms**: follow the [Claude Code quickstart guide](https://code.claude.com/docs/en/quickstart)

The user must authenticate by running `claude` interactively before continuing.

Do NOT proceed with LLM scoring until this succeeds.

### Save state after prerequisites pass

Persist state so future runs skip this step. Replace `<true or false>` with
the actual `LLM_SCORING` value:

```bash
mkdir -p ~/.config/skill-validator
cat > ~/.config/skill-validator/review-state.yaml << 'EOF'
prereqs_passed: true
llm_scoring: <true or false>
EOF
```

## Step 2: Locate the Skill

Ask the user for the path to the skill they want to review, unless they have
already provided it. Verify the path contains a `SKILL.md` file:

```bash
ls <path>/SKILL.md
```

If `SKILL.md` does not exist at the given path, tell the user this is not a
valid skill directory and ask them to provide the correct path.

## Step 3: Run Structural Validation

Run the full check suite:

```bash
skill-validator check <path>
```

Capture the exit code:

| Exit code | Meaning |
|-----------|---------|
| 0 | Clean — no errors or warnings |
| 1 | Errors found — must fix before publishing |
| 2 | Warnings only — review but not blocking |
| 3 | CLI/usage error — check the command |

Exit 0: proceed. Exit 2: note warnings, proceed. Exit 1: list errors — these
are blocking. The user must fix them before the skill can be published. Do NOT
proceed to LLM scoring if exit code is 1.

## Step 4: Content Review

Read the SKILL.md and any reference files, then evaluate each check below.
Report which checks pass and which do not, with specific details on what is
missing.

| Check | Criteria |
|-------|----------|
| Examples | Does the skill provide examples of expected inputs and outputs? |
| Edge cases | Does the skill document common edge cases or failure modes? |
| Scope-gating | Does the skill define when to stop/continue, prerequisites, and conditions for branching paths? |
| MongoDB data access | If the skill needs MongoDB contextual data, does it instruct agents to use the MCP server for auth and tool calls? Skip if not applicable. |

Flag any failing checks as areas the SME should address. These are not blocking
but should be resolved before publishing for best results.

## Step 5: LLM Scoring and Interpretation

If `LLM_SCORING=false`, skip to Step 6.

If `LLM_SCORING=true`, follow the "Run LLM Scoring" and "Interpret LLM Scores"
sections of
[references/llm-scoring.md](references/llm-scoring.md).

## Step 6: Present the Review Summary

If `LLM_SCORING=true`, follow the "Full Review Summary" section of
[references/llm-scoring.md](references/llm-scoring.md).
Include any failing content review checks from Step 4 in the action items.

If `LLM_SCORING=false`, present structural result, content review result,
areas to address, and a self-assessment checklist using the scoring dimensions
from [assets/report.md](assets/report.md). Note that LLM scoring was skipped;
advise re-running with LLM scoring enabled or self-assessing against the report
dimensions.

## Example Review Summary Structure

Structure the final summary with these sections in order:

1. **Structural validation** — pass/fail with errors or warnings
2. **SKILL.md scores** — overall and per-dimension table
3. **Reference scores** — per-file table with overall and lowest dimension
4. **Novelty assessment** — mean novelty vs threshold of 3; list `novel_info`
   per file for SME verification
5. **Action items** — prioritized list of what to fix
6. **Recommendation** — ready to publish / minor revisions / significant rework

<!-- chapter:end slug=review-skill -->
