Skip to main content
Glama
README.md
# PsiAnimator-MCP

**Quantum Physics Simulation and Animation Server**

A Model Context Protocol (MCP) server that integrates [QuTip](https://qutip.org/) (Quantum Toolbox in Python) for quantum physics computations with [Manim](https://www.manim.community/) (Mathematical Animation Engine) for visualization.

## Features

- ๐Ÿ”ฌ **Quantum Physics Engine**: Complete state management, time evolution, and measurement tools
- ๐ŸŽฌ **Manim Animations**: Publication-quality visualizations with quantum-specific scenes
- ๐Ÿ”Œ **MCP Integration**: Seamless integration with MCP-compatible clients
- ๐Ÿงฎ **Scientific Computing**: Built on NumPy, SciPy, and QuTip for accuracy
- ๐Ÿ“Š **Visualization Types**: Bloch spheres, Wigner functions, state tomography, circuits
- ๐ŸŽ“ **Educational Focus**: Perfect for quantum mechanics education and research

## Installation

### Quick Install

#### Option 1: One-line install (Unix/macOS)
```bash
curl -fsSL https://raw.githubusercontent.com/username/PsiAnimator-MCP/main/scripts/install.sh | bash
```

#### Option 2: PowerShell (Windows)
```powershell
iwr https://raw.githubusercontent.com/username/PsiAnimator-MCP/main/scripts/install.ps1 | iex
```

#### Option 3: pip (when available on PyPI)
```bash
# Core installation (quantum computation only)
pip install psianimator-mcp

# Full installation with animation support
pip install "psianimator-mcp[animation]"

# Development installation
pip install "psianimator-mcp[dev,animation]"
```

#### Option 4: From source
```bash
git clone https://github.com/username/PsiAnimator-MCP.git
cd PsiAnimator-MCP
./scripts/install.sh --from-source
```

### Prerequisites

- Python โ‰ฅ 3.10
- Git (for development installation)

**For animation features:**
- LaTeX (for advanced mathematical rendering)
- FFmpeg (for video generation)
- Cairo graphics library (for high-quality rendering)

### Installation Options Explained

**๐Ÿš€ Core Installation** (Recommended for most users)
```bash
pip install psianimator-mcp
```
- Includes all quantum computation features
- MCP server functionality
- QuTip, NumPy, SciPy for quantum physics
- Works immediately without system dependencies

**๐ŸŽฌ Animation Installation** (For visualization)
```bash
pip install "psianimator-mcp[animation]"
```
- Everything from core installation
- Manim for generating animations
- Requires system dependencies (LaTeX, FFmpeg)
- Larger download and installation time

**๐Ÿ”ง Development Installation**
```bash
git clone https://github.com/username/PsiAnimator-MCP.git
cd PsiAnimator-MCP
pip install -e ".[dev,animation]"
```

### Why Animation is Optional

Animation features (Manim) are kept optional because:

- **Heavy Dependencies**: Manim requires LaTeX, FFmpeg, and Cairo which can be several GB
- **Installation Complexity**: System dependencies can fail on different platforms
- **Use Case Separation**: Many users only need quantum computation, not visualization
- **CI/Testing Reliability**: Core features can be tested without system dependencies
- **Disk Space**: Core installation is ~100MB vs ~2GB+ with full animation stack

### Dependencies

**Core dependencies** (automatically installed):
- QuTip โ‰ฅ 4.7.0 (quantum physics computations)
- MCP โ‰ฅ 1.0.0 (Model Context Protocol)
- NumPy, SciPy, matplotlib (scientific computing)
- Pydantic, aiohttp (async web framework)

**Animation dependencies** (optional extras):
- Manim โ‰ฅ 0.18.0 (mathematical animations)
- h5py โ‰ฅ 3.9.0 (data storage)
- pandas โ‰ฅ 2.0.0 (data analysis)

### Post-Installation Setup

After installation, run the setup command:
```bash
psianimator-mcp setup
```

This will:
- Create configuration directory (`~/.config/psianimator-mcp/`)
- Copy example configuration file
- Test installation and show feature availability
- Provide Claude Desktop integration instructions

### Verifying Installation

Check your installation status:
```bash
python -c "import psianimator_mcp; print(f'โœ… Core: OK, Animation: {psianimator_mcp.is_animation_available()}')"
```

Expected outputs:
- `โœ… Core: OK, Animation: True` - Full installation with animations
- `โœ… Core: OK, Animation: False` - Core installation only

### Troubleshooting

**Import Errors**
```bash
# If you get "No module named 'psianimator_mcp'"
pip install psianimator-mcp

# If you get animation-related errors
pip install "psianimator-mcp[animation]"
```

**Animation Dependencies**
```bash
# Ubuntu/Debian
sudo apt-get install texlive-latex-base ffmpeg libcairo2-dev

# macOS
brew install mactex ffmpeg cairo

# Windows
# Install MiKTeX, FFmpeg from official websites
```

## Claude Desktop Integration

### Automatic Configuration

Generate Claude Desktop configuration:
```bash
psianimator-mcp claude-config
```

### Manual Configuration

Add to your Claude Desktop configuration file:

**Windows:** `%USERPROFILE%\AppData\Roaming\Claude\claude_desktop_config.json`
**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Linux:** `~/.config/claude-desktop/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "psianimator-mcp": {
      "command": "python3",
      "args": ["-m", "psianimator_mcp.cli", "serve"],
      "env": {
        "PSIANIMATOR_CONFIG": "~/.config/psianimator-mcp/config.json"
      }
    }
  }
}
```

**Note:** Restart Claude Desktop after configuration changes.

## Quick Start

### 1. Start the Server

**Default (serves via MCP protocol):**
```bash
psianimator-mcp
```

**Stdio transport explicitly:**
```bash
psianimator-mcp serve --transport stdio
```

**WebSocket transport:**
```bash
psianimator-mcp serve --transport websocket --port 3000
```

### 2. Test Installation

```bash
psianimator-mcp test
```

### 3. Basic Usage Example

```python
import asyncio
from psianimator_mcp.tools.quantum_state_tools import create_quantum_state
from psianimator_mcp.tools.measurement_tools import measure_observable
from psianimator_mcp.server.config import MCPConfig

async def basic_example():
    config = MCPConfig()
    
    # Create a qubit in |0โŸฉ state
    result = await create_quantum_state({
        'state_type': 'pure',
        'system_dims': [2],
        'parameters': {'state_indices': [0]},
        'basis': 'computational'
    }, config)
    
    state_id = result['state_id']
    
    # Measure โŸจฯƒzโŸฉ
    measurement = await measure_observable({
        'state_id': state_id,
        'observable': 'sigmaz',
        'measurement_type': 'expectation'
    }, config)
    
    print(f"โŸจฯƒzโŸฉ = {measurement['measurement_results']['expectation_value']}")

asyncio.run(basic_example())
```

## MCP Tools

### 1. `create_quantum_state`
Create quantum states of various types:
- **Pure states**: |ฯˆโŸฉ (ket vectors)
- **Mixed states**: ฯ (density matrices)
- **Coherent states**: |ฮฑโŸฉ (harmonic oscillator)
- **Squeezed states**: reduced uncertainty
- **Thermal states**: finite temperature
- **Fock states**: definite photon number

### 2. `evolve_quantum_system`
Time evolution with multiple methods:
- **Unitary**: Schrรถdinger equation (closed systems)
- **Master equation**: Lindblad form (open systems)
- **Monte Carlo**: Quantum trajectories
- **Stochastic**: Continuous measurement

### 3. `measure_observable`
Quantum measurements and analysis:
- **Expectation values**: โŸจOโŸฉ
- **Variances**: ฮ”ยฒO
- **Probability distributions**: P(outcome)
- **Correlation functions**: โŸจAโŸฉโŸจBโŸฉ

### 4. `animate_quantum_process`
Generate Manim animations:
- **Bloch sphere evolution**: Qubit dynamics
- **Wigner functions**: Phase space representation
- **State tomography**: Density matrix visualization
- **Circuit execution**: Gate sequence animation
- **Energy levels**: Population dynamics

### 5. `quantum_gate_sequence`
Apply quantum gates with visualization:
- **Single-qubit gates**: Pauli, Hadamard, rotations
- **Two-qubit gates**: CNOT, CZ, SWAP
- **Parameterized gates**: RX, RY, RZ with custom angles
- **Circuit visualization**: Step-by-step animation

### 6. `calculate_entanglement`
Compute entanglement measures:
- **Von Neumann entropy**: S(ฯ) = -Tr(ฯ log ฯ)
- **Concurrence**: Two-qubit entanglement measure
- **Negativity**: Partial transpose criterion
- **Mutual information**: I(A:B)

## Configuration

Configure via environment variables or `MCPConfig`:

```python
from psianimator_mcp.server.config import MCPConfig

config = MCPConfig(
    quantum_precision=1e-12,
    max_hilbert_dimension=1024,
    animation_cache_size=100,
    output_directory="./output",
    render_backend="cairo"
)
```

### Environment Variables

Configure PsiAnimator-MCP via environment variables:

**Server Configuration:**
- `PSIANIMATOR_CONFIG` - Path to configuration file
- `PSIANIMATOR_TRANSPORT` - Transport protocol (stdio/websocket)
- `PSIANIMATOR_HOST` - Host for WebSocket transport
- `PSIANIMATOR_PORT` - Port for WebSocket transport

**Quantum Settings:**
- `PSIANIMATOR_QUANTUM_PRECISION` - Quantum computation precision
- `PSIANIMATOR_MAX_HILBERT_DIM` - Maximum Hilbert space dimension
- `PSIANIMATOR_OUTPUT_DIR` - Output directory for animations

Example:
```bash
export PSIANIMATOR_TRANSPORT=websocket
export PSIANIMATOR_PORT=3001
psianimator-mcp
```

## CLI Commands

PsiAnimator-MCP provides several CLI commands:

```bash
psianimator-mcp                    # Start server (default: stdio)
psianimator-mcp serve              # Start server with options
psianimator-mcp config             # Show current configuration
psianimator-mcp setup              # Run post-installation setup
psianimator-mcp test               # Test installation
psianimator-mcp claude-config      # Generate Claude Desktop config
psianimator-mcp examples           # Show usage examples
psianimator-mcp version            # Show version
psianimator-mcp --help             # Show help
```

### Command Examples

**Start with custom config:**
```bash
psianimator-mcp serve --config /path/to/config.json
```

**WebSocket mode:**
```bash
psianimator-mcp serve --transport websocket --host 0.0.0.0 --port 8080
```

**Verbose logging:**
```bash
psianimator-mcp serve -vvv
```

## Examples

Comprehensive examples are provided in the `examples/` directory:

- `basic_usage.py` - Core functionality walkthrough
- Bell state creation and entanglement analysis
- Harmonic oscillator coherent state evolution
- Multi-qubit quantum circuits

Run examples:
```bash
python examples/basic_usage.py
```

## Development

### Setup Development Environment

```bash
git clone https://github.com/username/PsiAnimator-MCP.git
cd PsiAnimator-MCP
pip install -e ".[dev]"
pre-commit install
```

### Run Tests

```bash
pytest tests/
```

### Code Quality

```bash
black src/ tests/
isort src/ tests/
mypy src/
```

## Architecture

```
PsiAnimator-MCP/
โ”œโ”€โ”€ src/psianimator_mcp/
โ”‚   โ”œโ”€โ”€ server/          # MCP server implementation
โ”‚   โ”œโ”€โ”€ quantum/         # Quantum physics engine
โ”‚   โ”œโ”€โ”€ animation/       # Manim visualization components
โ”‚   โ””โ”€โ”€ tools/           # MCP tool implementations
โ”œโ”€โ”€ tests/               # Comprehensive test suite
โ”œโ”€โ”€ examples/            # Usage examples
โ””โ”€โ”€ docs/               # Documentation
```

## Limitations

- Animation rendering requires sufficient system resources
- Large Hilbert spaces (>1024 dimensions) may impact performance
- Some advanced quantum error correction features are not yet implemented

## License

MIT License - see [LICENSE](LICENSE) for details.

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for:
- Development guidelines
- Code standards
- Testing requirements
- Pull request process

## Support

- **Documentation**: See `docs/API_REFERENCE.md`
- **Examples**: Check `examples/` directory
- **Issues**: Report bugs via GitHub issues