npm package: @ladybugs/mcp
Description: Model Context Protocol server for LadyBugs MongoDB trace database
Author: LadyBugs
Latest version: 0.0.1

# @ladybugs/mcp

Model Context Protocol (MCP) server for querying the LadyBugs MongoDB trace database. Provides AI assistants with read-only access to execution traces for analysis and debugging.

## Overview

This MCP server enables AI assistants (like Claude) to query and analyze execution traces stored in MongoDB. It provides two powerful tools with built-in safety restrictions to prevent data modification.

## Features

- **Read-only access**: No ability to modify or delete traces
- **Document limit enforcement**: Maximum 1000 documents per query (configurable by AI, capped at 1000)
- **Two query methods**: Simple `find` queries and complex `aggregate` pipelines
- **Rich trace data**: Function calls, variables, loops, errors, and execution flow

## Installation

```bash
# From workspace root
pnpm install

# Build the package
cd packages/mcp
pnpm run build
```

## Usage

### Running the MCP Server

```bash
# Start the server
pnpm run start

# Or with development watch mode
pnpm run dev
```

### Configuring Claude Desktop

Add to your Claude Desktop MCP configuration (`claude_desktop_config.json`):

#### Option 1: Using NPX (Recommended - uses published package)
```json
{
  "mcpServers": {
    "ladybugs": {
      "command": "npx",
      "args": ["-y", "@ladybugs/mcp"],
      "env": {
        "LADYBUGS_SERVER_URL": "http://localhost:3000"
      }
    }
  }
}
```

#### Option 2: Local Development (uses local build)
```json
{
  "mcpServers": {
    "ladybugs": {
      "type": "stdio",
      "command": "node",
      "args": [
        "/path/to/your/Workspace/packages/mcp/build/index.js"
      ],
      "env": {
        "LADYBUGS_SERVER_URL": "http://localhost:3000"
      }
    }
  }
}
```

### Environment Variables

- **`LADYBUGS_SERVER_URL`** - URL of the LadyBugs server (default: `http://localhost:3000`)
  - This is where the MCP server will send queries to access the MongoDB database
  - Change this if your LadyBugs server is running on a different host or port

## Database Schema

### Collection: `traces`

Each trace document has the following structure:

```typescript
{
  rawId: string,           // Unique trace identifier
  parentId: string,        // Parent trace ID (for building execution tree)
  children: string[],      // Array of child trace IDs
  rawTrace: {
    id: string,
    action: string,        // Trace type (see below)
    timestamp: number,     // Milliseconds since epoch
    // Action-specific fields...
  }
}
```

### Trace Action Types

The `rawTrace.action` field determines the trace type:

#### Function Traces
- **`functionCall`**: Function execution
  - `functionName`: Name of the function
  - `params`: Array of parameter values
  - `result`: Return value (if available)
  - `error`: Error object (if function threw)

#### Variable Traces
- **`variableDeclaration`**: Variable declaration/initialization
  - `variableName`: Name of the variable
  - `value`: Initial value
  - `kind`: "const", "let", or "var"

- **`variableAssignment`**: Variable assignment after declaration
  - `variableName`: Name of the variable
  - `value`: New value

#### Loop Traces
- **`forOfLoop`**: For-of loop iteration
  - `variableName`: Iterator variable name
  - `value`: Current iteration value
  - `iterable`: Array/iterable being looped over

- **`forInLoop`**: For-in loop iteration
  - Similar structure to forOfLoop

- **`forLoop`**: Traditional for loop
  - Loop initialization, condition, and iteration details

#### Other Traces
- **`templateLiteral`**: Template string evaluation
  - `expressions`: Array of interpolated expressions
  - `result`: Final string value

- **`dataFlow`**: Data access and manipulation
  - Tracks object property access and mutations

- **`argumentFlow`**: Function argument tracking
  - Parameter passing and argument values

## Available Tools

### 1. traces_mongodb_find

Simple query tool for finding traces by criteria.

**Parameters:**
- `query` (required): MongoDB query filter object
- `limit` (optional): Max documents to return (default: 100, max: 1000)
- `projection` (optional): Fields to include/exclude
- `sort` (optional): Sort specification

**Example Queries:**

```javascript
// Find all function calls
{ "rawTrace.action": "functionCall" }

// Find specific function
{ "rawTrace.functionName": "calculateTotal" }

// Find traces with errors
{ "rawTrace.error": { "$exists": true } }

// Find by parent ID (get all children of a trace)
{ "parentId": "some-trace-id" }

// Find recent traces
{ "rawTrace.timestamp": { "$gte": 1704067200000 } }

// Complex query: Functions with errors in last hour
{
  "rawTrace.action": "functionCall",
  "rawTrace.error": { "$exists": true },
  "rawTrace.timestamp": { "$gte": Date.now() - 3600000 }
}
```

### 2. traces_mongodb_aggregate

Advanced aggregation pipeline for complex analysis.

**Parameters:**
- `pipeline` (required): Array of aggregation stages
- `limit` (optional): Max documents to return (default: 100, max: 1000)

**Allowed Pipeline Stages:**
- `$match`: Filter documents
- `$group`: Group and aggregate data
- `$sort`: Sort documents
- `$project`: Reshape/select fields
- `$limit`: Limit results (automatically enforced)
- `$skip`: Skip documents
- `$unwind`: Deconstruct arrays
- `$lookup`: Join collections (read-only)
- `$count`: Count documents
- `$facet`: Multiple parallel aggregations

**Blocked Stages (Read-only Protection):**
- `$out`: Blocked (would write to collection)
- `$merge`: Blocked (would modify collection)

**Example Pipelines:**

```javascript
// Count traces by action type
[
  {
    "$group": {
      "_id": "$rawTrace.action",
      "count": { "$sum": 1 }
    }
  },
  {
    "$sort": { "count": -1 }
  }
]

// Find most-called functions
[
  {
    "$match": {
      "rawTrace.action": "functionCall"
    }
  },
  {
    "$group": {
      "_id": "$rawTrace.functionName",
      "callCount": { "$sum": 1 },
      "avgDuration": { "$avg": "$rawTrace.duration" }
    }
  },
  {
    "$sort": { "callCount": -1 }
  },
  {
    "$limit": 10
  }
]

// Analyze error patterns
[
  {
    "$match": {
      "rawTrace.error": { "$exists": true }
    }
  },
  {
    "$group": {
      "_id": "$rawTrace.error.message",
      "count": { "$sum": 1 },
      "functions": { "$addToSet": "$rawTrace.functionName" }
    }
  }
]

// Build execution tree (parent-child analysis)
[
  {
    "$match": {
      "parentId": "root-trace-id"
    }
  },
  {
    "$lookup": {
      "from": "traces",
      "localField": "rawId",
      "foreignField": "parentId",
      "as": "childTraces"
    }
  },
  {
    "$project": {
      "functionName": "$rawTrace.functionName",
      "childCount": { "$size": "$childTraces" }
    }
  }
]
```

## Safety Features

### 1. Read-Only Access
- No write operations allowed (`$out`, `$merge` blocked)
- Only query and aggregation operations permitted
- Cannot modify or delete any trace data

### 2. Document Limit Enforcement
- Hard cap of 1000 documents per query
- AI can request lower limits, but cannot exceed 1000
- Automatic `$limit` injection in aggregations if not present
- Prevents overwhelming responses and resource exhaustion

### 3. Query Validation
- Aggregation pipelines scanned for write operations
- Invalid stages rejected with clear error messages
- Connection state validated before queries

## Common Use Cases

### Debugging Function Errors
```javascript
// Find tool
{
  query: {
    "rawTrace.action": "functionCall",
    "rawTrace.functionName": "processPayment",
    "rawTrace.error": { "$exists": true }
  },
  limit: 50
}
```

### Performance Analysis
```javascript
// Aggregate tool
{
  pipeline: [
    { "$match": { "rawTrace.action": "functionCall" } },
    {
      "$group": {
        "_id": "$rawTrace.functionName",
        "totalCalls": { "$sum": 1 },
        "withErrors": {
          "$sum": { "$cond": [{ "$ifNull": ["$rawTrace.error", false] }, 1, 0] }
        }
      }
    },
    { "$sort": { "totalCalls": -1 } }
  ]
}
```

### Execution Flow Tracing
```javascript
// Find all children of a function call
{
  query: { "parentId": "function-trace-id" },
  sort: { "rawTrace.timestamp": 1 },
  limit: 200
}
```

### Variable Value Tracking
```javascript
// Find all assignments to a variable
{
  query: {
    "rawTrace.action": { "$in": ["variableDeclaration", "variableAssignment"] },
    "rawTrace.variableName": "userBalance"
  },
  sort: { "rawTrace.timestamp": 1 }
}
```

## Response Format

All tool responses follow this structure:

```json
{
  "success": true,
  "count": 42,
  "limit": 100,
  "documents": [...]
}
```

Error responses:
```json
{
  "success": false,
  "error": "Error message here"
}
```

## Development

```bash
# Install dependencies
pnpm install

# Build
pnpm run build

# Watch mode for development
pnpm run dev

# Type checking
pnpm run typecheck
```

## Architecture

The MCP server:
1. Connects to the same MongoDB instance as the LadyBugs server
2. Provides read-only query access via MCP protocol
3. Enforces safety limits and validates queries
4. Returns structured JSON responses to AI assistants

## Dependencies

- `@modelcontextprotocol/sdk`: MCP protocol implementation
- `@ladybugs/server`: Shares MongoDB connection and trace database access
- MongoDB: Database for trace storage

## License

MIT