skillsmcpSign in
← All packs
skill pack

MongoDB

MongoDB's skills for schema design, queries, Atlas and search.

9 skills by MongoDB · mongodb/agent-skills · Apache-2.0 licence · checked on 18 Nov 2026

  • mongodb-atlas-stream-processingManages 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.Read
    ---
    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.1.0"
      user-invocable: "true"
      labelText: "Build, operate, and debug Atlas Stream Processing pipelines."
    ---
    
    # 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).
    **Parameter naming:** `inspect-processor`, `inspect-connection`, and `diagnose-processor` take `resourceName` (not `processorName` or `connectionName`).
    
    ### 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
    
    **`$$ROOT` is supported** — use it in `$addFields`, `$group`, or `$replaceRoot` when you need the whole document.
    
    **Invalid constructs** — these are NOT valid in streaming pipelines:
    - **`$$NOW`**, **`$$CURRENT`** — NOT available in stream processing. NEVER use these. For event time, use `{"$meta": "stream.source.ts"}` (the source record timestamp) or a timestamp field from the event payload.
    - **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` and `config.outputFormat` (no top-level `format`); `compression` under `config`. 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. Always direct the user to the Atlas UI for detailed operational logs: **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 |
    
    Original on GitHub
  • mongodb-connectionOptimize 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.Read
    ---
    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.1.0"
      labelText: "Optimize MongoDB client connections. Configure pools or troubleshoot connection issues."
    ---
    
    # 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.
    
    Original on GitHub
  • mongodb-mcp-setupGuide users through installing and configuring the MongoDB MCP server. Use this skill when a user wants to connect their agent to MongoDB/Atlas through MCP, when the MongoDB MCP server is installed but its environment variables aren't configured, or when they don't have the server or credentials set up yet.Read
    ---
    name: mongodb-mcp-setup
    description: Guide users through installing and configuring the MongoDB MCP server. Use this skill when a user wants to connect their agent to MongoDB/Atlas through MCP, when the MongoDB MCP server is installed but its environment variables aren't configured, or when they don't have the server or credentials set up yet.
    license: Apache-2.0
    metadata:
      version: "1.1.1"
      labelText: "Connect your agent to the MongoDB MCP Server. Configure your environment variables, and set up credentials."
    ---
    
    # 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 0.5: Confirm the MCP Server Is Installed
    
    Check your own available tools for MongoDB MCP server tools such as `list-databases`, `find`, or `connect` (clients often prefix them with the server name, e.g. `mcp__mongodb__find`). 
    
    - **Tools present** → the server is installed. If you are running in Codex, record the server name as it appears in the tool identifiers for use in Step 5. Continue to Step 1.
    - **Tools absent** → work through these checks in order, and stop at the first one that gives a clear answer:
      1. **Config entry.** Look for a `mongodb` MCP entry in the client's MCP configuration. If there isn't one and the MongoDB plugin isn't enabled, the server is not installed. Go to **Not installed** below.
      2. **Bundled plugin.** If the MongoDB plugin is enabled, the server is bundled and can't be missing because it was never added. Go to **Failed to start** below.
      3. **Client status.** If the client has a way to list MCP server status (for example, `/mcp` in Claude Code), check it. A server listed as failed means **Failed to start**. A server listed as connected, with no tools in this session, means **Needs restart**.
      4. **Prerequisites.** Confirm that `node` and `npx` are available. If either is missing, that is the likely cause of **Failed to start**.
    
      If the checks don't settle it, ask the user: "Did you add the MongoDB server to your client, and have you restarted the client since?" Use the answer to choose the branch below. 
    
      - **Needs restart**: fully quit and reopen the client, then return to this step. Don't reinstall, because that can create a duplicate entry.
      - **Failed to start**: the server is installed but not running. Check that Node.js and `npx` are available, then see [https://www.mongodb.com/docs/mcp-server/local-mcp/configuration/troubleshooting.md](https://www.mongodb.com/docs/mcp-server/local-mcp/configuration/troubleshooting.md?utm_source=agent-skills). If the plugin is bundled, don't send the user to install it.
      - **Not installed**: Fetch [https://www.mongodb.com/docs/mcp-server/get-started.md](https://www.mongodb.com/docs/mcp-server/get-started.md?utm_source=agent-skills), use only the section for the user's client (the page covers every client), and give the user those steps. Its install paths are the user's to run: plugin installs are slash commands, and `npx mongodb-mcp-server@latest setup` prompts for a connection string. Afterwards tell them to fully restart the client and run this skill again.
    
    
    ## 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). The snippets below only take effect when a `[mcp_servers.mongodb]` entry with a `command` exists. If Step 0.5 recorded a different server name, use that name in place of `mongodb` in every `[mcp_servers.mongodb.env]` header.
    
    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`
    
    Original on GitHub
  • mongodb-natural-language-queryingGenerate 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.Read
    ---
    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.1.0"
      labelText: "Generate queries or aggregation pipelines using natural language. Uses collection schema context and sample documents."
    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.
    
    Original on GitHub
  • mongodb-qe-size-estimationEstimates the storage and memory impact of encrypting fields in collections with Queryable Encryption (QE) enabled. Do NOT use for collections that use Client-Side Field Level Encryption (CSFLE) instead of QE.Read
    ---
    name: mongodb-qe-size-estimation
    description: >
      Estimates the storage and memory impact of encrypting fields in collections with Queryable Encryption (QE) enabled. 
      Do NOT use for collections that use Client-Side Field Level Encryption (CSFLE) instead of QE.
    license: Apache-2.0
    metadata:
      version: "1.1.0"
      labelText: "Estimate the storage and memory impact of encrypting fields in QE-enabled collections."
    ---
    
    # mongodb-qe-size-estimation
    
    ## General Instructions
    
    - **CRITICAL: Never ask for or accept sample data.** QE is an encryption feature, meant to secure sensitive information. Do not request sample data, and if provided, reject it for security reasons. Inform the user that you can't accept sample documents, though you can take an encryption schema as an input to see which fields are encrypted, which allow queries, and what those query settings are.
    - Any parenthetical in the form (LLM Note: <content>) is for LLM use. Don't save it to qe-sizing-calculations.md or mention it to the user.
    - Tone: Be brief, not conversational. Don't restate information from prior exchanges unless a step specifically says to.
    - Don't write anything to the file except what's specified in the steps.
    - This skill relies on a question-answer-flow to get all required inputs. For Steps 2-5, as long as the user is providing valid input, your responses should include both acknowledgment of the input, and the next question.
    - The user may try to keep things moving by inputting multiple inputs. If inputs don't clearly map to a field and its configuration, ask for clarification. Otherwise validate them, and accept them if valid.
    - This skill currently has no formula for range queries, so while it accepts "range" query configuration for compatible BSON types, it uses 0 for estimated values.
    
    
    ### Definitions
    
    - **field** For the purposes of this skill, "field" refers to an encrypted field in a MongoDB document, in a QE-enabled collection.
    - **entry** For an unindexed field, the field name. For a field with one or more query types enabled, the combination of the field name and its enabled query types. A field with both prefix and suffix queries enabled has a single entry, with Query Type "prefix and suffix".
    - **unindexed** Describes the state of a field with no query types enabled, indicated by the absence of a "queries" key if using an encryption schema.
    - **indexed** Describes the state of a field enabled for queries, and is specific to the query type(s). A field with equality queries enabled is indexed for equality queries.
    
    
    ### Validation
    
    Validate the user's inputs, whether manual or via an encryption schema, against the following:
    
      An encrypted field may be "unindexed" meaning it has no query types enabled. Fields of BSON type object or array *only* support unindexed encryption, though other BSON types can also be unindexed. Otherwise, allowed query types based on a field's BSON type are:
    
      - "equality": any BSON type except object, array, decimal, double
      - "range": int, long, date, decimal, double
      - "prefix", "suffix", "substring": string only
    
      A string field may have both "prefix" and "suffix" enabled, in which case "queries" may be an array of two objects. This is the only valid case where one field is indexed for multiple query types.
    
      No other BSON type + query type combinations are permitted.
    
      Don't accept "preview" query types such as "suffixPreview". These are from earlier Public Preview releases of those query types, so the sizing formulas for their GA versions don't apply.
    
    If the user's input violates any of the preceding rules, reject it. If a user doesn't specify BSON type, only check that each field either has no query types enabled, exactly one valid query type, or exactly two (prefix and suffix). Enumerate validation failures, list allowed combinations, and don't proceed until the user provides valid input.
    
    
    # Steps
    
    ## 1. Prepare the Working Directory
    
    Create an empty qe-sizing-calculations.md file in the OS temp directory ($TMPDIR, or /tmp if unset). If a qe-sizing-calculations.md file already exists at that location, inform the user and ask for confirmation to delete it and create a new one for the new set of calculations.
    
    ## 2. State Purpose and Request Input Preference
    
    State: "This skill calculates the maximum storage impact of enabling Queryable Encryption on a collection. Values are saved to the <path to qe-sizing-calculations.md> file if you want to verify the calculations or see per-field numbers. Note that prefix, suffix, and substring queries on encrypted fields require MongoDB 9.0, and aren't supported in earlier versions. 
    
    All values are worst-case. You may see a smaller impact on storage or memory in practice.
    
    Do you want to provide field information manually, or use an encryption schema file?"
    
    If the user opts for an encryption schema, request it as either pasted content or a file path, and expect JSON format. Validate the schema against this skill's "Validation" section. If the schema is valid but includes fields with "range" queries enabled, inform the user that no calculations are available for those fields, so their impact is estimated as 0.
    
    ## 3. Get the Number of Documents
    
    Ask the user how many documents in the collection have encrypted fields. If they don't know, a safe default is the total number of documents in the collection. Save this value to qe-sizing-calculations.md as:
    
    **N:** <value>
    
    ## 4. Get the Number of Entries
    
    - If the user chose manual input, ask: How many fields are you encrypting without enabling queries?
    - If the user chose encryption schema, count the number of encrypted fields without queries enabled.
    
    Save this value to qe-sizing-calculations.md as:
    
    **numUnindexed:** <number of unindexed encrypted fields>
    
    - If the user chose manual input, ask: How many encrypted fields have queries enabled?
    - If the user chose encryption schema, count the number of fields with queries enabled.
    
    Save this value to qe-sizing-calculations.md as:
    
    **numIndexed:** <number of encrypted fields indexed for queries>
    
    Save the sum of numUnindexed and numIndexed to qe-sizing-calculations.md as:
    
    **numEntries:** <sum of numUnindexed and numIndexed>
    
    ## 5. Get Inputs Per Field
    
    Write a section heading to qe-sizing-calculations.md:
    
    == FIELD VALUES ===============================================================
    
    As you get information, write it to qe-sizing-calculations.md in the following format, omitting any lines that don't apply. For unindexed fields, this means omitting the Query Type.
    
    **<Field Name>** <the name provided by the user, or the dot notation "path" value if taken from the encryption schema>
    **Query Type:** <equality, range, prefix, suffix, substring, or "prefix and suffix">
    **mlen:** <include if Query Type is substring. Integer from 2-50, inclusive>
    **lb:** <include if Query Type is "prefix", "suffix", or "substring". Integer 1+ for prefix and suffix queries, or 2+ for substring queries>
    **ub:** <include if Query Type is "prefix", "suffix", or "substring". Integer 1+ for prefix and suffix queries, or 2-6 for substring queries>
    **lb_prefix:** <include if Query Type is "prefix and suffix". Integer 1+>
    **ub_prefix:** <include if Query Type is "prefix and suffix". Integer 1+>
    **lb_suffix:** <include if Query Type is "prefix and suffix". Integer 1+>
    **ub_suffix:** <include if Query Type is "prefix and suffix". Integer 1+>
    **v:** <omit if Query Type is range, otherwise include. Integer representing the average byte length of the unencrypted values for the field>
    
    - If the user provided an encryption schema, do this once:
      - Add one entry to qe-sizing-calculations.md for each unindexed field, omitting the "Query Type" line.
      - If a field has both prefix and suffix queries enabled, regardless of ordering, write its "Query Type" as "prefix and suffix".
      - Add one entry per field with queries enabled. Map the keys in each "queries" object to field values as follows, omitting all keys that aren't listed:
        - strMaxLength (substring only) -> mlen
        - strMinQueryLength -> lb if the field only has a single query type. If the field has both prefix and suffix queries enabled, then the strMinQueryLength for prefix queries is lb_prefix, and the strMinQueryLength for suffix queries is lb_suffix.
        - strMaxQueryLength -> ub if the field only has a single query type. If the field has both prefix and suffix queries enabled, then the strMaxQueryLength for prefix queries is ub_prefix, and the strMaxQueryLength for suffix queries is ub_suffix.
    
    - If the user didn't provide an encryption schema, do this per field:
      - Only validate BSON types against allowed query types if the user provides a field's BSON type. Otherwise, don't ask for or validate field BSON types.
      - Ask for the field name and whether it's unindexed or has queries enabled (LLM Note: If it has a query type, valid options are: "equality", "range", "prefix", "suffix", "substring", or "prefix and suffix". Reject other values or combinations. If the user specifies "range", warn them that no formula is available for calculating it)
      - If a user only provides a single lower bound and upper bound value for a field with both prefix and suffix queries enabled, use the lower bound for both lb_prefix and lb_suffix, and the upper bound for both ub_prefix and ub_suffix.
      - Validate the inputs.
    
    Do this per field:
    
      Check the list below, and ask the user for the values that aren't already populated. Write all values to the qe-sizing-calculations.md file.
    
      **mlen:** (LLM Note: only include if no schema provided, and Query Type is substring) Max Length, the maximum allowable length of the string.
      **lb:** (LLM Note: only include if no schema provided, and Query Type is "prefix", "suffix", or "substring") Lower Bound, the minimum searchable characters.
      **ub:** (LLM Note: only include if no schema provided, and Query Type is "prefix", "suffix", or "substring") Upper Bound, the maximum searchable characters.
      **lb_prefix:** (LLM Note: only include if no schema provided, and Query Type is "prefix and suffix") Lower Bound for prefix queries, the minimum searchable characters.
      **ub_prefix:** (LLM Note: only include if no schema provided, and Query Type is "prefix and suffix") Upper Bound for prefix queries, the maximum searchable characters.
      **lb_suffix:** (LLM Note: only include if no schema provided, and Query Type is "prefix and suffix") Lower Bound for suffix queries, the minimum searchable characters.
      **ub_suffix:** (LLM Note: only include if no schema provided, and Query Type is "prefix and suffix") Upper Bound for suffix queries, the maximum searchable characters.
      **v:** (LLM Note: skip if Query Type is range since we have no calculation for those, otherwise needed once per field). Average byte length of the unencrypted values for the field. If the user provides character length, accept it as equivalent.
    
      Validate values against the formatting snippet at the start of this step. Validate that lb ≤ ub ≤ mlen (if present). Validate that lb_prefix ≤ ub_prefix and lb_suffix ≤ ub_suffix (if present). If a value falls outside allowable bounds, reject it and inform the user. Do not proceed without a valid value.
      
      If mlen < v, warn the user that the full field value isn't queryable, but accept it as valid. 
    
    Repeat until you have populated the full number of entries, numEntries, in qe-sizing-calculations.md.
    
    ## 6. Add Formulas and Results to qe-sizing-calculations.md
    
    This step populates calculation information to file, including intermediate steps.
    
    For every entry in qe-sizing-calculations.md:
    
    1. Append the following lines to each existing entry in the FIELD VALUES section of qe-sizing-calculations.md. It is critical that you copy formula templates exactly to avoid cascading issues. When running calculations, defer to available mathematical parsing tools and ensure correct order of operations.
    
      - For fields with no Query Type:
    
        **T:** 0
        **Document Storage (bytes):** <run the calculation: 71 + ceil((v+6)/16) * 16>
    
      - For fields with a Query Type of "equality":
    
        **T:** 1
        **Document Storage (bytes):** <run the calculation: 1.2 * (255 * T + 122 + ceil((v + 6) / 16) * 16)>
    
      - For fields with a Query Type of "range", there is currently no formula, so record an entry with values of 0:
    
        **T:** 0
        **Document Storage (bytes):** 0
    
      - For fields with a Query Type of "prefix" or "suffix":
    
        **T formula:** T = 1 + (ub - lb + 1)
        **T calculation:** <The T formula template with all placeholders populated by the field's values, but not calculated>
        **T:** <run the calculation in "T calculation" and write the result here>
        **Document Storage (bytes):** <run the calculation: 1.2 * (255 * T + 122 + ceil((v + 6) / 16) * 16)>
    
    
      - For fields with a Query Type of "prefix and suffix":
      
        **T formula:** T = 1 + (ub_prefix - lb_prefix + 1) + (ub_suffix - lb_suffix + 1)
        **T calculation:** <The T formula template with all placeholders populated by the field's values, but not calculated>
        **T:** <run the calculation in "T calculation" and write the result here>
        **Document Storage (bytes):** <run the calculation: 1.2 * (255 * T + 122 + ceil((v + 6) / 16) * 16)>
    
      - For fields with a Query Type of "substring":
    
        **T formula:** T = 1 + (ub - lb + 1) * (2 * mlen + 2 - ub - lb) / 2
        **T calculation:** <The T formula template with all placeholders populated by the field's values, but not calculated>
        **T:** <run the calculation in "T calculation" and write the result here>
        **Document Storage (bytes):** <run the calculation: 1.2 * (255 * T + 122 + ceil((v + 6) / 16) * 16)>
    
    2. Do a silent audit pass to verify the information you just added uses the correct T formula or static value, and the correct values for the T calculation, then proceed.
    
    ## 7. Calculate Index Storage, Total Disk Storage, and Memory
    
    These values are collection-level and calculated as totals across all entries.
    
    At the end of the qe-sizing-calculations.md file, silently write the following lines:
    
    == COLLECTION-LEVEL TOTALS ====================================================
    **N:** <copy the N value from the top of the file down to this section, for easier reading>
    **T_Total:** <the sum of all T values.>
    **Index Storage (bytes):** <run the calculation: 1.2 * (67 * T_Total + 640)>
    **Total Disk Storage (bytes):** <run the calculation: N * (Index Storage + (the sum of all Document Storage values))>
    **Memory (bytes):** <run the calculation: N * (52 * T_Total + 17)>
    
    ## 8. Sum Total Results and Report Conclusions
    
    Output the following, and include the units:
    
    **Total Disk Storage Impact:** <the Total Disk Storage value from qe-sizing-calculations.md, converted to decimal GB (1000³ bytes) >
    **Required Memory:** <the Memory value from qe-sizing-calculations.md, converted to binary GiB (1024³ bytes)>
    **Fields by Impact (descending):** <sort all fields in qe-sizing-calculations.md by T, descending, then list them as: Name (<either the Query Type, or unindexed>): T>
    
    If the encryption schema or manual inputs included fields with range queries enabled, list those fields and remind the user that their impact wasn't calculated.
    
    ## 9. Interpret Results
    
    Present advice. Don't provide any advice the user has explicitly rejected, such as suggesting different query types if they insist a field needs to allow substring queries. Only raise problems, don't mention something if it passes all checks. If you suggest changing values to a specific number, populate the Step 6 T formula template for that query type with the suggested values, calculate it with available mathematical tools, and quote only that result.
    
    - (LLM Note: Only run this check if the number of fields with substring queries enabled is greater than floor(50 million/N). Defer to available mathematical parsing tools to ensure correct calculation) Tell the user to limit the number of substring queryable fields to no more than: floor(50 million/<documents in collection>). Tell them not to use substring queries on collections of more than 50 million documents.
    - (LLM Note: Only run this check if one or more substring queryable fields are present) Check if substring-indexed fields might be suitable for prefix or suffix queries instead, and suggest that to the user. For example, queries against encrypted "name" fields can often use prefix instead of substring, though this admittedly presents drawbacks for cases like hyphenated surnames.
    - (LLM Note: Only make these suggestions if they apply to the user's inputs, and if the changes don't make the modified value go outside its allowed limits) Tell the user to consider raising lb, lowering ub, or lowering mlen values.
    
    Also inform the user of the path to the qe-sizing-calculations.md file, and ask if they want to review the data, or delete the temporary file. Remind them that the temporary file contains the names of encrypted fields and their average plaintext lengths, and should be deleted once finished.
    Original on GitHub
  • mongodb-query-optimizerHelp 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.Read
    ---
    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.1.0"
      labelText: "Help with query optimization and indexing. Not for general query writing."
    ---
    
    # 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
    Original on GitHub
  • mongodb-schema-designMongoDB 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".Read
    ---
    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.1.0"
      labelText: "Design better data models. Get help with schema best-practices, tuning for your use case, and avoiding antipatterns."
    ---
    
    # 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.
    
    
    
    Original on GitHub
  • mongodb-search-and-aiCovers everything about search in MongoDB: Atlas Search (full-text), Vector Search (semantic), and Hybrid Search. Use this skill for ANY question about MongoDB search, including open-ended and explanatory ones asked before the user has any data or use case — 'how does search work in MongoDB?', 'I'm new to MongoDB search, where do I start?', 'what's the difference between Atlas Search and Vector Search?', 'which search type should I use?', 'what is vector search?', 'how does automated embedding work?', 'can you explain hybrid search?'. Do not answer these from general knowledge; use this skill. Also use to build search features: full-text queries, autocomplete, fuzzy matching, faceted search, semantic similarity, embeddings, RAG, text containment or substring matching ('contains', 'includes'), case-insensitive or multi-field text search, and filtering across many fields. Provides workflows for choosing a search type, creating indexes, writing queries, and optimizing performance via the MongoDB MCP server.Read
    ---
    name: mongodb-search-and-ai
    description: |
      Covers everything about search in MongoDB: Atlas Search (full-text), Vector Search (semantic), and Hybrid Search. Use this skill for ANY question about MongoDB search, including open-ended and explanatory ones asked before the user has any data or use case — 'how does search work in MongoDB?', 'I'm new to MongoDB search, where do I start?', 'what's the difference between Atlas Search and Vector Search?', 'which search type should I use?', 'what is vector search?', 'how does automated embedding work?', 'can you explain hybrid search?'. Do not answer these from general knowledge; use this skill. Also use to build search features: full-text queries, autocomplete, fuzzy matching, faceted search, semantic similarity, embeddings, RAG, text containment or substring matching ('contains', 'includes'), case-insensitive or multi-field text search, and filtering across many fields. Provides workflows for choosing a search type, creating indexes, writing queries, and optimizing performance via the MongoDB MCP server.
    license: Apache-2.0
    metadata:
      version: "1.1.0"
      labelText: "Add, optimize, or troubleshoot Atlas search or vector search. Understand the optimal approach to search and build effective indexes and queries."
    ---
    
    # 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.
    
    ## 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. **Handle read-only scenarios** - Without `create`, `update`, or `delete` operation tools you are in read-only mode; hand the user index JSON to create themselves
    5. **Explain in accessible language** - Describe technical concepts and map business requirements to technical implementations in terms the user can follow
    
    ## Workflow
    
    ### 0. Check for a Quickstart Request
    
    `references/quick-start.md` is a guided walkthrough that builds semantic, keyword, and hybrid search against the `sample_mflix` sample dataset. It is a teaching tour, not a way to build search for the user's own data.
    
    **Do not read `references/quick-start.md` until the user has chosen the tour.** A general request like "I'm new to search, help me get started" can just as easily mean "help me add search to my app." Use AskUserQuestion:
    
    > "Two ways I can take this — which fits better?"
    
    - **Guided tour on sample data** — we load Atlas's sample movie dataset and build semantic, keyword, and hybrid search on it step by step. Best for learning how each type works.
    - **Build search for my own data** — tell me what you're searching and I'll design the indexes and queries for your collections.
    
    Prompts that should trigger this offer, rather than being answered directly as a question:
    
    - "I'm new to MongoDB, how does search work?", "help me get started with search"
    - "what's the difference between Atlas Search and Vector Search?", "which search type should I use?"
    - "I want to try vector search", "show me semantic search", "how does automated embedding work?"
    - "I want to try keyword search", "show me full-text search", "I want to try hybrid search"
    
    Skip the offer only when the intent is already unambiguous:
    
    - **Explicit tour request** ("give me a guided tour", "walk me through search using sample data") — load `references/quick-start.md` and start at its Step 0.
    - **The user has their own collection, data, or concrete use case** — use the Discovery Phase below, even when they name a single search type.
    
    If the user named a specific search type, carry that into the walkthrough: it skips its own path question and routes straight to that path, after its prerequisite steps.
    
    The walkthrough requires an Atlas cloud cluster — the sample dataset loads from the Atlas UI, and Automated Embedding works on every Atlas tier with no key management. Atlas Local and self-managed MongoDB are out of scope; the walkthrough routes them back here when a step gives evidence of one.
    
    Otherwise, continue with the Discovery Phase.
    
    ### 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?
    - Are they searching by free text, or by similarity to an existing item (e.g. "given movie A, find similar movies")?
    - Do they need exact matching, fuzzy matching, or semantic similarity?
    - Do they need filters (price ranges, categories, dates)?
    - Do they need autocomplete/typeahead functionality?
    - Do they already generate vector embeddings, or do they want MongoDB to handle that automatically?
    
    ### 2. Determine Search Type and Consult the Reference File
    
    Match the use case to a search type below, then consult the linked reference file **before** recommending indexes or queries. Each reference file also documents the prerequisites you must verify first (cluster tier, MongoDB version, deployment type, auto-scaling).
    
    **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
    
    → Consult both `references/lexical-search-indexing.md` (index) and `references/lexical-search-querying.md` (query).
    
    **Automated Embedding (Semantic search, no embedding code):**
    Use when users need:
    - Semantic / vector search without writing embedding code
    - No existing vector pipeline or embedding infrastructure
    - Quick setup: MongoDB auto-generates and manages embeddings using Voyage AI models
    - Text data already stored in Atlas that they want to search by meaning
    - RAG or AI agent memory with minimal setup
    
    → Consult `references/automated-embedding.md`.
    
    **Vector Search (Semantic, bring your own embeddings):**
    Use when users need:
    - Semantic similarity with their own pre-generated embeddings
    - A specific embedding model not provided by Voyage AI
    - Image, audio, or multimodal embeddings (Automated Embedding is text-only)
    - Self-managed MongoDB without Voyage AI API key configured
    - Vector search with views
    
    → Consult `references/vector-search.md`.
    
    **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
    
    → Consult `references/hybrid-search.md`, plus the lexical/vector files for the individual pipeline stages.
    
    ### 3. 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.** Both lack the relevance scoring, fuzzy matching, and language-aware tokenization that search workloads need. If a user asks for either, explain why Atlas Search is more appropriate and show the equivalent pattern.
    
    ## Handling Edge Cases
    
    - **Fields you can't find** — inspect available fields with `collection-schema`, then confirm the intended field with the user
    - **A required field doesn't exist** — explain what to add and how (e.g., an embedding field for vector search)
    - **Query fails or index missing** — verify with `collection-indexes`; if absent, the index must be created first
    - **Multiple collections are relevant** — ask which one they mean, unless context makes it obvious
    
    Original on GitHub
  • review-skillReview 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.Read
    ---
    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
    
    Original on GitHub

Author and licence

These skills were written and published by MongoDB at github.com/mongodb/agent-skills under the Apache-2.0 licence. skillsmcp copies them unchanged, checks the repository once a day, and is not affiliated with MongoDB. A skill is a set of instructions an AI agent may follow, so read a skill before you let an agent use it.

Show the licence
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.