# MONIKA MCP Server

This directory contains the MCP (Model Context Protocol) server implementation for MONIKA, enabling bidirectional communication with AI assistants like Claude.

## Quick Start

### 1. Install MCP SDK

```bash
pip install mcp
```

### 2. Start the Server

```bash
# Start fresh server
python start_mcp_server.py

# Attach to existing conversation state
python start_mcp_server.py --state storage/conversation_state.json

# Load specific checkpoint
python start_mcp_server.py --checkpoint storage/proto_lm/dolly15k.pt
```

### 3. Connect from Claude Desktop

Add to your Claude Desktop config (`%APPDATA%\Claude\claude_desktop_config.json` on Windows):

```json
{
  "mcpServers": {
    "monika": {
      "command": "python",
      "args": [
        "C:\\MONIKA\\start_mcp_server.py",
        "--state", "storage/conversation_state.json"
      ]
    }
  }
}
```

Restart Claude Desktop, and the MONIKA tools will appear in your tool list.

## Available Tools

### Memory Operations

**`memory_apply`** - Execute memory operations
- Add facts: `{op: "add_fact", text: "...", score: 1.0}`
- Schedule todos: `{op: "schedule_todo", text: "...", score: 1.0}`
- Add hypotheses: `{op: "add_hypothesis", text: "...", score: 1.0}`

**`memory_snapshot`** - Get current memory state (facts, hypotheses, todos)

### Introspection

**`yearning_state`** - Get current desire/saturation across all dimensions
- Returns yearning metrics for novelty, retention, coherence, etc.
- Each dimension has `desire`, `saturation`, and `yearning` values

**`controller_dynamics`** - Get controller decision state
- Current action scores and cooldowns
- Bandit statistics and exploration rates
- Recent decision history

**`workspace_listing`** - Browse runtime workspace files

### Runtime Control

**`runtime_step`** - Execute a single runtime step
- Processes input text through the full pipeline
- Returns salience metrics and verification results

**`generate_response`** - Generate conversational response
- Uses the language model to generate text
- Applies salience-driven gating

**`training_step`** - Train on provided text
- Executes one gradient update
- Updates vocabulary if needed

**`adjust_controller_dynamics`** - Modify controller weights
- Fine-tune decision making behavior
- Specify max adjustment step size

### State Management

**`get_training_metrics`** - Get current training status
- Step count, vocab size, learning state

**`save_state`** - Persist conversation and runtime state
- Saves checkpoints, memory, adaptive state

## Bidirectional Architecture

### MONIKA → Claude
MONIKA can use Claude as a tool through MCP client mode:
- Web search for unknown concepts during training
- File operations for corpus management  
- Human validation for generated outputs

### Claude → MONIKA
Claude can supervise MONIKA's training through MCP server mode:
- Monitor yearning state to detect what the system needs
- Inject strategic training examples based on salience
- Adjust controller dynamics when learning plateaus
- Orchestrate multi-phase training runs

## Example Use Cases

### 1. Supervised Training

```python
# Claude's perspective:
yearning = monika.yearning_state()

if yearning["novelty"]["desire"] > 0.8:
    # System craves novel information
    new_corpus = find_novel_training_data()
    monika.training_step(new_corpus)

if yearning["retention"]["saturation"] < 0.3:
    # System hasn't consolidated recent learning
    # Give it more processing time
    for _ in range(100):
        monika.runtime_step(consolidation_prompt)
```

### 2. Interactive Debugging

```python
# Check what the controller is deciding
dynamics = monika.controller_dynamics()
print(f"Current action: {dynamics['last_action']}")
print(f"Action scores: {dynamics['scores']}")

# If it's making poor decisions, adjust weights
if poor_performance:
    monika.adjust_controller_dynamics({
        "novelty_weight": 0.05,  # Increase novelty seeking
        "drag_penalty": -0.03,   # Reduce drag sensitivity
    })
```

### 3. Curriculum Learning

```python
# Stage 1: Basic language
for text in simple_corpus:
    monika.training_step(text)

# Monitor until saturation
yearning = monika.yearning_state()
while yearning["retention"]["saturation"] < 0.7:
    time.sleep(1)
    yearning = monika.yearning_state()

# Stage 2: Complex reasoning
for text in advanced_corpus:
    monika.training_step(text)
```

## Technical Details

### Server Architecture

- **Protocol**: MCP (Model Context Protocol) over stdio
- **Transport**: JSON-RPC 2.0
- **State**: Maintains conversation session with full runtime
- **Threading**: Async event loop for non-blocking I/O

### Resource Mapping

The server exposes three core bridge resources:
- `MemoryResource` → Memory operations and snapshots
- `IntrospectionResource` → Yearning state and controller dynamics
- `SessionOrchestrator` → Training and response generation

### Safety Notes

⚠️ **Concurrent Access**: The server maintains its own session. If you have a training run in a separate process, state divergence may occur. Use `--state` to attach to a shared checkpoint.

⚠️ **Training Interference**: Calling `training_step` or `adjust_controller_dynamics` will modify the model. Be cautious during active training runs.

✅ **Read-Only Safety**: Tools like `yearning_state`, `memory_snapshot`, and `controller_dynamics` are read-only and safe to call anytime.

## Troubleshooting

### "MCP SDK not installed"
```bash
pip install mcp
```

### "Cannot find module salience_os_seed"
Make sure you're running from the MONIKA root directory or have it in PYTHONPATH.

### "State file not found"
Check the path is correct. Relative paths are resolved from the current directory.

### Server not appearing in Claude Desktop
1. Check JSON syntax in config file
2. Verify Python path is correct
3. Try absolute paths instead of relative
4. Restart Claude Desktop after config changes

## Development

### Adding New Tools

Edit `salience_os_seed/runtime/mcp_server.py`:

1. Add tool definition to `list_tools()`
2. Add handler case to `call_tool()`
3. Wire to existing bridge resources or add new ones

### Testing Locally

```bash
# Start server in one terminal
python start_mcp_server.py

# In another terminal, send MCP requests
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | python start_mcp_server.py
```

## Future Enhancements

- [ ] Resource-based memory access (not just tools)
- [ ] Streaming runtime metrics via notifications
- [ ] Multi-session support with session IDs
- [ ] WebSocket transport option
- [ ] Prometheus metrics export
- [ ] Checkpoint management tools
- [ ] Experiment coordination interface

## See Also

- [MCP Specification](https://modelcontextprotocol.io/)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [Claude Desktop MCP Guide](https://docs.anthropic.com/claude/docs/model-context-protocol)
