# FlowState MCP Server

Model Context Protocol (MCP) server for Epic FlowState with dynamic collection support and TODO scanner integration.

## Features

- **Dynamic Collection Operations** - Full CRUD operations for all RxDB collections
- **TODO Scanner** - Bidirectional sync between code comments and FlowState tasks
- **Spec Management** - Create and manage specifications with milestone workflows
- **Workspace & Codebase Management** - Organize projects and code repositories
- **Approval Workflows** - Document and action approval management
- **Observability Integration** (Optional) - Monitor errors, logs, and sessions with AI-enhanced analysis

## Installation

The easiest way to use FlowState MCP is directly from npm using `npx`:

### Quick Setup (Recommended)

Add to your MCP client configuration (e.g., Claude Desktop's `claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "flowstate": {
      "command": "npx",
      "args": ["-y", "@epicdm/flowstate-mcp"],
      "env": {
        "PROJECT_PATH": "/path/to/your/project",
        "RXDB_SERVER_URL": "http://localhost:7080",
        "RXDB_AUTH_TOKEN": "your-auth-token",
        "RXDB_DOMAIN_ID": "your-domain-id",
        "USER_ID": "your-user-id",
        "ORG_ID": "your-org-id"
      }
    }
  }
}
```

The `-y` flag automatically accepts the npx prompt, and the package will always use the latest published version.

### Alternative: Global Installation

If you prefer to install globally:

```bash
npm install -g @epicdm/flowstate-mcp
```

Then configure your MCP client:

```json
{
  "mcpServers": {
    "flowstate": {
      "command": "flowstate-mcp",
      "env": {
        "PROJECT_PATH": "/path/to/your/project",
        "RXDB_SERVER_URL": "http://localhost:7080",
        "RXDB_AUTH_TOKEN": "your-auth-token",
        "RXDB_DOMAIN_ID": "your-domain-id"
      }
    }
  }
}
```

### Using .env File

The MCP server automatically loads environment variables from a `.env` file in your project root.

**1. Create or update your project's `.env` file:**

```bash
# Project root .env file
RXDB_SERVER_URL=http://localhost:7080
RXDB_AUTH_TOKEN=dev-token
RXDB_DOMAIN_ID=epic-flow-dev
USER_ID=your-user-id
ORG_ID=your-org-id
```

**2. Simplified MCP client configuration:**

```json
{
  "mcpServers": {
    "flowstate": {
      "command": "npx",
      "args": ["-y", "@epicdm/flowstate-mcp"],
      "env": {
        "PROJECT_PATH": "/path/to/your/project"
      }
    }
  }
}
```

**Note:** The MCP server will automatically load all configuration from the `.env` file in `PROJECT_PATH`. You only need to specify `PROJECT_PATH` in the MCP client config.

### Environment Variables

| Variable | Description | Required | Default |
|----------|-------------|----------|---------|
| `PROJECT_PATH` | Path to your project root | Yes | `cwd()` |
| `RXDB_SERVER_URL` | RxDB server URL | Yes | - |
| `RXDB_AUTH_TOKEN` or `AUTH_TOKEN` | Authentication token | Yes | - |
| `RXDB_DOMAIN_ID` or `DOMAIN_ID` | Domain identifier | Yes | - |
| `USER_ID` | User identifier | No | - |
| `ORG_ID` | Organization identifier | No | - |
| `OBS_SERVER_URL` | Observability server URL | No | - |
| `OBS_API_KEY` | Observability API key | No | - |

**Variable Loading Priority (highest to lowest):**
1. MCP client configuration
2. Project `.env` file (auto-loaded from `PROJECT_PATH`)
3. System environment variables

## Available Tools

### Collection Operations

See [CRUD Tools Documentation](./docs/CRUD_TOOLS_DOCUMENTATION.md) for complete details on:

- `collection-list-available` - List all available collections
- `collection-get-info` - Get schema information for a collection
- `collection-create` - Create a new document
- `collection-get` - Get a document by ID
- `collection-update` - Update a document
- `collection-delete` - Delete a document
- `collection-query` - Query documents with selectors
- `collection-list` - List documents with minimal fields (id, title, name) for token efficiency

#### Token-Optimized List Operations

The `collection-list` tool is optimized for minimal token usage:

- **Projection**: Returns only `id`, `title`, and `name` fields
- **Default limit**: 20 items per request
- **Max limit**: 20 items (enforced)
- **Pagination**: Use `offset` parameter with `nextOffset` from response `meta`

**Example with pagination:**

```typescript
// First page
{ "tool": "collection-list", "params": { "collection": "tasks" } }
// Response includes: { meta: { limit: 20, offset: 0, hasMore: true, nextOffset: 20, total: 100 } }

// Next page
{ "tool": "collection-list", "params": { "collection": "tasks", "offset": 20 } }
```

**Environment variable overrides:**

- `MCP_LIST_DEFAULT_LIMIT` - Default items per request (default: 20, hard cap: 100)
- `MCP_LIST_MAX_LIMIT` - Maximum allowed limit (default: 20, hard cap: 100)

Note: When `MCP_LIST_DEFAULT_LIMIT` exceeds `MCP_LIST_MAX_LIMIT`, the default is automatically clamped to the max limit.

### TODO Scanner Tool

**Tool:** `scan_todos_in_project`

Scan project for TODO comments and sync with FlowState tasks.

**Parameters:**
- `dryRun` (boolean): Preview changes without modifying files
- `summaryOnly` (boolean): Generate summary without syncing
- `filePath` (string): Scan specific file only

**Example:**

```typescript
{
  "tool": "scan_todos_in_project",
  "params": {
    "dryRun": false
  }
}
```

### Spec Management

- `spec-create` - Create new specification with milestone structure
- `spec-status` - Get specification status and progress
- `spec-list` - List all specifications
- `spec-execute-task` - Execute or queue a task
- `spec-workflow-guide` - Get workflow guide
- `spec-update-phase` - Update phase document content
- `spec-get-phase` - Get phase document content
- `spec-create-tasks` - Create tasks from markdown list
- `spec-get-tasks` - Get all tasks for a spec
- `spec-start-task` - Start a task
- `spec-stop-task` - Stop a task
- `spec-update-task` - Update task fields

### Workspace Management

- `workspace-create` - Create a new workspace
- `workspace-list` - List workspaces with filters
- `workspace-get` - Get workspace details
- `workspace-update` - Update workspace fields
- `workspace-archive` - Archive a workspace

### Codebase Management

- `codebase-create` - Create a new codebase with Git config
- `codebase-list` - List codebases with filters
- `codebase-get` - Get codebase details
- `codebase-update` - Update codebase configuration
- `codebase-archive` - Archive a codebase
- `codebase-validate` - Validate codebase configuration

### Approval Workflows

- `approvals` - Manage approval workflow (request, status, delete)

### Observability Tools (Optional)

**16 additional tools available when `OBS_SERVER_URL` and `OBS_API_KEY` are configured:**

#### Error Management
- `obs__errors-list` - Query errors with filters (level, time range, session)
- `obs__errors-stats` - Get error statistics with aggregation options
- `obs__error-get` - Get detailed error with stack trace and source map

**Example Usage:**
```typescript
// List fatal errors from last 24 hours
{
  "tool": "obs__errors-list",
  "params": {
    "projectId": "proj_123",
    "level": "fatal",
    "timeRange": "24h",
    "limit": 50
  }
}

// Get error statistics by platform
{
  "tool": "obs__errors-stats",
  "params": {
    "projectId": "proj_123",
    "timeRange": "7d",
    "groupBy": "platform"
  }
}
```

#### Log Management
- `obs__logs-list` - Query logs with filters (level, text search, session)
- `obs__logs-search` - Advanced log search with query syntax
- `obs__log-get` - Get detailed log event with context

**Example Usage:**
```typescript
// Search logs for database errors
{
  "tool": "obs__logs-search",
  "params": {
    "projectId": "proj_123",
    "query": "database AND (timeout OR connection)",
    "level": "error",
    "limit": 100
  }
}
```

#### Session Management
- `obs__sessions-list` - List user sessions with filters
- `obs__sessions-get` - Get session details with environment
- `obs__sessions-breadcrumbs` - Get session breadcrumbs timeline

**Example Usage:**
```typescript
// Get session breadcrumbs for debugging
{
  "tool": "obs__sessions-breadcrumbs",
  "params": {
    "sessionId": "sess_abc123"
  }
}
// Returns: Navigation trail, user actions, network events
```

#### Project Management
- `obs__projects-list` - List all observability projects
- `obs__projects-get` - Get project details and statistics
- `obs__projects-create` - Create new observability project

**Example Usage:**
```typescript
// Create new project for application monitoring
{
  "tool": "obs__projects-create",
  "params": {
    "name": "my-web-app",
    "description": "Production monitoring for web application",
    "metadata": {
      "environment": "production",
      "platform": "web"
    }
  }
}
// Returns: Project ID and API key for SDK initialization
```

#### AI-Enhanced Analysis
- `obs__debug-error` - AI-powered error analysis with pattern detection
- `obs__compare-errors` - Compare multiple errors to find common patterns
- `obs__suggest-fixes` - Get AI-generated fix suggestions for errors
- `obs__create-task-from-error` - Create FlowState task from error

**Example Usage:**
```typescript
// Debug error with AI analysis
{
  "tool": "obs__debug-error",
  "params": {
    "errorId": "error_xyz789"
  }
}
// Returns:
// - Error pattern classification (9 types)
// - Severity assessment
// - Root cause analysis
// - 3-5 suggested fixes with code examples
// - Related session context

// Create task from error
{
  "tool": "obs__create-task-from-error",
  "params": {
    "errorId": "error_xyz789",
    "projectId": "proj_123"
  }
}
// Returns: Task ID with embedded error context and fix suggestions
```

**Supported Error Patterns:**
1. `null_reference` - Null/undefined property access
2. `type_error` - Type mismatches and coercion issues
3. `network_error` - Failed API calls and network requests
4. `async_error` - Promise rejections and async/await issues
5. `state_error` - Invalid state transitions
6. `validation_error` - Data validation failures
7. `resource_error` - Missing resources (files, modules, APIs)
8. `timeout_error` - Operation timeouts
9. `unknown` - Unclassified errors

See [OBSERVABILITY_INTEGRATION.md](./OBSERVABILITY_INTEGRATION.md) for detailed configuration and usage.

## Development

```bash
# Install dependencies
yarn install

# Build
yarn build

# Run tests
yarn test

# Watch mode for development
yarn build --watch
```

## Architecture

The MCP server provides a bridge between Claude/AI assistants and the FlowState ecosystem:

```
MCP Client (Claude/Cursor)
    ↓
MCP Server (flowstate-mcp)
    ↓
RxDB Client (@epic-flow/flowstate-rxdb-client)
    ↓
FlowState Database
```

## Documentation

- [CRUD Tools Documentation](./docs/CRUD_TOOLS_DOCUMENTATION.md) - Complete guide to collection operations
- [Observability Integration](./OBSERVABILITY_INTEGRATION.md) - Optional observability tools setup and usage

## License

MIT
