npm package: @rhwendt/mycelium-substrate
Description: MCP server for Mycelium substrate - persistent state management for Claude Code
Author: rhwendt
Latest version: 0.2.1

# Mycelium Substrate MCP Server

An MCP server that provides structured access to the Mycelium substrate — task queues, pheromone patterns, metrics, and context caching.

## Why Use This?

| Without MCP Server | With MCP Server |
|--------------------|-----------------|
| Read/write JSON files | Structured queries: `list_tasks(status="blocked")` |
| Manual file parsing | Type-safe operations |
| No query capability | Filter, sort, aggregate |
| No history | PostgreSQL-backed with history |
| File locking issues | Proper concurrency |

## Prerequisites

- Node.js >= 18
- PostgreSQL database (local Docker or remote)

## Quick Start

### 1. Start PostgreSQL

```bash
# Using Docker (recommended)
docker run -d --name mycelium-db \
  -e POSTGRES_USER=mycelium \
  -e POSTGRES_PASSWORD=your-password \
  -e POSTGRES_DB=substrate \
  -p 5432:5432 \
  postgres:16-alpine
```

### 2. Configure Claude Code

Add to your Claude Code MCP settings (`~/.claude/settings.json`):

```json
{
  "mcpServers": {
    "mycelium": {
      "command": "npx",
      "args": ["@rhwendt/mycelium-substrate"],
      "env": {
        "DATABASE_URL": "postgres://mycelium:your-password@localhost:5432/substrate"
      }
    }
  }
}
```

The server will automatically create tables on first run.

### Alternative: Run from Source

```bash
git clone https://github.com/rhwendt/mycelium.git
cd mycelium/mcp-server
cp .env.example .env  # Edit and set POSTGRES_PASSWORD
docker compose up -d  # Start PostgreSQL
npm install && npm run build
```

Then configure with a local path:
```json
{
  "mcpServers": {
    "mycelium": {
      "command": "node",
      "args": ["/path/to/mycelium/mcp-server/dist/index.js"],
      "env": {
        "DATABASE_URL": "postgres://mycelium:your-password@localhost:5432/substrate"
      }
    }
  }
}
```

## Available Tools

### Task Management

| Tool | Description |
|------|-------------|
| `list_tasks` | List tasks with filters (status, project, priority) |
| `add_task` | Add a new task to the queue |
| `update_task` | Update task status, assignment, result |
| `get_task` | Get a specific task by ID |

### Pheromone Patterns

| Tool | Description |
|------|-------------|
| `list_pheromones` | List patterns with filters |
| `get_pheromone` | Get a specific pattern |
| `reinforce_pheromone` | Strengthen (success) or weaken (failure) a pattern |
| `create_pheromone` | Create a new pattern |

### Metrics & Analytics

| Tool | Description |
|------|-------------|
| `record_metric` | Record a metric value |
| `get_metrics` | Query metrics with filters |
| `get_summary` | Get overview of substrate state |

### Context Caching

| Tool | Description |
|------|-------------|
| `cache_context` | Cache context with TTL |
| `get_cached_context` | Retrieve cached context |
| `clear_cache` | Clear expired or all cache |

### Task Router

| Tool | Description |
|------|-------------|
| `route_task` | Analyze task and determine routing (hypha, risk, complexity) |
| `quick_route` | Fast routing - returns just the primary hypha |
| `is_safe` | Check if a task is safe to auto-execute |

### Workflow Engine

| Tool | Description |
|------|-------------|
| `list_workflows` | List available workflow definitions |
| `get_workflow` | Get a specific workflow by ID |
| `find_workflows` | Find workflows matching a task description |
| `create_workflow_instance` | Create a workflow instance |
| `start_workflow` | Start a pending workflow |
| `advance_workflow` | Advance workflow after completing a step |
| `pause_workflow` | Pause a running workflow |
| `resume_workflow` | Resume a paused workflow |
| `cancel_workflow` | Cancel a workflow |
| `get_workflow_instance` | Get instance by ID |
| `list_workflow_instances` | List instances with filters |
| `get_workflow_state` | Get human-readable workflow state |
| `get_current_step_info` | Get current step details |

## Example Usage

Once configured, Claude can use these tools:

```
// List blocked tasks
list_tasks(status="blocked")

// Add a new task
add_task(
  description="Implement rate limiting",
  project="apps",
  priority="high",
  risk="moderate"
)

// Reinforce a successful pattern
reinforce_pheromone(name="scout-before-build", success=true)

// Get substrate summary
get_summary()
```

### Task Routing Example

```
// Analyze a task and get routing recommendation
route_task(description="Review the authentication code for security vulnerabilities")
// Returns: { assessment: { routing: { primary: "guardian", sequence: [...] }, risk: "safe", ... } }

// Quick check which hypha should handle a task
quick_route(description="Write unit tests for the API")
// Returns: { primary_hypha: "tester" }

// Check if safe to auto-execute
is_safe(description="Search for all TypeScript files")
// Returns: { safe: true, auto_execute: true }
```

### Workflow Example

```
// Find workflows matching a feature request
find_workflows(description="Implement user authentication", task_type="feature")

// Create and start a workflow
create_workflow_instance(workflow_id="WF-001", project="my-app")
// Returns: { instance_id: "WFI-ABC12345", status: "created" }

start_workflow(instance_id="WFI-ABC12345")
// Returns: { instance_id: "...", status: "running", current_step: "explore" }

// Complete a step and advance
advance_workflow(
  instance_id="WFI-ABC12345",
  success=true,
  outputs={ exploration_context: { files: [...], patterns: [...] } }
)

// Get current workflow state
get_workflow_state(instance_id="WFI-ABC12345")
// Returns human-readable progress description
```

## Resources

The server also exposes resources you can reference:

- `substrate://tasks` — Current task queue
- `substrate://pheromones` — Active patterns
- `substrate://workflows` — Available workflow definitions
- `substrate://workflow-instances` — Active workflow instances
- `substrate://summary` — State overview

## Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `DATABASE_URL` | Full PostgreSQL connection string | Constructed from individual vars |
| `POSTGRES_USER` | Database user | `mycelium` |
| `POSTGRES_PASSWORD` | Database password | **Required** |
| `POSTGRES_HOST` | Database host | `localhost` |
| `POSTGRES_PORT` | Database port | `5432` |
| `POSTGRES_DB` | Database name | `substrate` |

## Development

```bash
# Start the database
docker compose up -d

# Run in development mode
npm run dev

# Type check
npm run typecheck

# Build
npm run build

# Stop the database
docker compose down

# Stop and remove data
docker compose down -v
```

## Database Management

```bash
# Connect to the database
docker exec -it mycelium-db psql -U mycelium -d substrate

# View tables
\dt

# View tasks
SELECT * FROM tasks;

# View pheromones
SELECT * FROM pheromones;
```

## Architecture

```
┌─────────────────────────────────────────┐
│            Claude Code                  │
│          (MCP Client)                   │
└─────────────────┬───────────────────────┘
                  │ stdio
┌─────────────────▼───────────────────────┐
│       Mycelium MCP Server               │
│  ┌─────────────────────────────────┐    │
│  │  Tools: list_tasks, add_task,   │    │
│  │  reinforce_pheromone, etc.      │    │
│  └─────────────────────────────────┘    │
└─────────────────┬───────────────────────┘
                  │
┌─────────────────▼───────────────────────┐
│        PostgreSQL (Docker)              │
│  ┌─────────┐ ┌──────────┐ ┌─────────┐   │
│  │  tasks  │ │pheromones│ │ metrics │   │
│  └─────────┘ └──────────┘ └─────────┘   │
│  ┌──────────────────────────────────┐   │
│  │         context_cache            │   │
│  └──────────────────────────────────┘   │
└─────────────────────────────────────────┘
```

## Troubleshooting

### Connection Issues

**Error: "Failed to connect to database"**
- Check that PostgreSQL is running: `docker ps | grep mycelium-db`
- Verify the DATABASE_URL is correct
- Ensure the database port (5432) is not blocked

**Error: "password authentication failed"**
- Verify POSTGRES_PASSWORD matches in both docker run command and DATABASE_URL
- If using docker-compose, check the .env file

### Permission Issues

**Error: "permission denied for table"**
- The database user needs ownership of the tables
- Recreate the container: `docker rm -f mycelium-db && docker run ...`

### MCP Server Issues

**Claude Code doesn't see the tools**
1. Verify the MCP configuration in `~/.claude/settings.json`
2. Check the server can run: `npx @rhwendt/mycelium-substrate`
3. Look for errors in Claude Code's developer console

**Server fails to start**
1. Check Node.js version: `node --version` (needs >= 18)
2. Verify DATABASE_URL is accessible
3. Run with debug: `DEBUG=* npx @rhwendt/mycelium-substrate`

### Data Issues

**Tasks/pheromones not persisting**
- Check database connection is stable
- Verify tables exist: `docker exec -it mycelium-db psql -U mycelium -d substrate -c '\dt'`

**Workflow instances not found**
- Ensure workflow definitions are loaded from the workflows directory
- Check MYCELIUM_WORKFLOWS_DIR environment variable if using custom location
- Verify workflow YAML files have valid `id` fields (format: `WF-001`)

### Reset Database

If you need to start fresh:

```bash
# Stop and remove everything
docker rm -f mycelium-db

# Start a fresh database
docker run -d --name mycelium-db \
  -e POSTGRES_USER=mycelium \
  -e POSTGRES_PASSWORD=your-password \
  -e POSTGRES_DB=substrate \
  -p 5432:5432 \
  postgres:16-alpine
```

The server will recreate tables on next connection.

## Type Safety

The server uses comprehensive type safety:

- **TypeScript interfaces** for all data structures (`src/types.ts`)
- **Zod schemas** for runtime validation (`src/schemas.ts`)
- **JSON Schemas** for substrate data (`substrate/schemas/`)

All MCP tool inputs are validated at runtime, returning clear error messages for invalid data.

## Testing

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run specific test file
npm test -- src/workflow.test.ts
```

Test coverage includes:
- Database operations (requires PostgreSQL)
- Task routing logic
- Workflow state machine
- Signal protocol formatting
- Schema validation