MIDI Conversion MCP Server
by bmcgauley
README.md
# MIDI Conversion MCP Server
A comprehensive Model Context Protocol (MCP) server that converts various inputs into functional, multi-track MIDI files. Supports text descriptions, sheet music images, and audio files.
## Features
### 🎵 Text-to-MIDI
Convert natural language descriptions into complete MIDI compositions:
- **Vague prompts**: "happy birthday song" → Simple melody
- **Detailed prompts**: "dubstep drop in D minor at 140 BPM with heavy bass and aggressive drums" → Full production
- **AI-powered generation** with multiple provider options:
- **Ollama** (local, free, private) - Recommended for most users
- **Anthropic Claude** (cloud API, highest quality)
- **Rule-based** (no AI required, always available)
- Support for multiple instruments, scales, keys, and time signatures
### 📄 Sheet Music to MIDI (OCR)
Extract musical notation from images:
- Scanned sheet music
- Photos of handwritten scores
- PDF music files
- Automatic tempo and key detection
### 🎧 Audio-to-MIDI
Convert audio recordings into MIDI:
- Automatic pitch detection
- Optional track separation by pitch range
- Support for MP3, WAV, FLAC, OGG, M4A, AIFF
- Tempo detection and note extraction
## Installation
### Prerequisites
- Python 3.8 or higher
- FFmpeg (required for audio processing)
#### Install FFmpeg
**macOS:**
```bash
brew install ffmpeg
```
**Ubuntu/Debian:**
```bash
sudo apt-get update
sudo apt-get install ffmpeg
```
**Windows:**
Download from [ffmpeg.org](https://ffmpeg.org/download.html) and add to PATH
### Install the MCP Server
1. Clone or download this repository:
```bash
cd midi_conversion_mcp
```
2. Install Python dependencies:
```bash
pip install -r requirements.txt
```
3. (Optional) Set up AI provider for enhanced text-to-MIDI generation:
**Option A: Ollama (Local, Free)**
```bash
# Install Ollama from https://ollama.ai
# Pull a recommended model
ollama pull qwen2.5:14b
# Configure environment
export AI_PROVIDER="ollama"
export OLLAMA_MODEL="qwen2.5:14b"
export OLLAMA_ENDPOINT="http://localhost:11434"
```
**Option B: Anthropic API (Cloud)**
```bash
export AI_PROVIDER="anthropic"
export ANTHROPIC_API_KEY="your-api-key-here"
```
**Option C: Auto (tries Ollama first, then Anthropic, then rule-based)**
```bash
export AI_PROVIDER="auto"
```
## Configuration
### Adding to Claude Desktop
Add to your Claude Desktop configuration (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
**Using Ollama (recommended for local/free):**
```json
{
"mcpServers": {
"midi-conversion": {
"command": "python",
"args": ["/path/to/midi_mcp/midi_conversion_mcp.py"],
"env": {
"AI_PROVIDER": "ollama",
"OLLAMA_MODEL": "qwen2.5:14b",
"OLLAMA_ENDPOINT": "http://localhost:11434"
}
}
}
}
```
**Using Anthropic API:**
```json
{
"mcpServers": {
"midi-conversion": {
"command": "python",
"args": ["/path/to/midi_mcp/midi_conversion_mcp.py"],
"env": {
"AI_PROVIDER": "anthropic",
"ANTHROPIC_API_KEY": "your-api-key-here"
}
}
}
}
```
### Environment Variables
- `AI_PROVIDER` (optional): AI provider to use - `"ollama"`, `"anthropic"`, or `"auto"` (default: auto)
- `OLLAMA_MODEL` (optional): Ollama model name (default: qwen2.5:14b). Recommended: qwen2.5:14b, llama3.1:8b, or mixtral:8x7b
- `OLLAMA_ENDPOINT` (optional): Ollama API endpoint (default: http://localhost:11434)
- `ANTHROPIC_API_KEY` (optional): Anthropic API key for Claude-powered generation
## Usage
The MCP server provides three main tools:
### 1. Text-to-MIDI Conversion
**Tool**: `midi_convert_text_to_midi`
Convert natural language descriptions into MIDI files.
**Parameters:**
- `prompt` (required): Description of the music to generate
- Examples: "jazz piano improvisation", "epic orchestral theme", "dubstep drop"
- `tempo` (optional): BPM (40-240), default 120
- `duration_bars` (optional): Length in bars (1-64), default 8
- `time_signature` (optional): "4/4", "3/4", "6/8", etc., default "4/4"
- `key` (optional): "C", "D#", "Bb", etc., default "C"
- `scale` (optional): "major", "minor", "pentatonic_major", "blues", etc., default "major"
- `complexity` (optional): "simple", "moderate", "complex", default "moderate"
- `instruments` (optional): List of instruments like ["piano", "bass", "drums"]
- `output_filename` (optional): Custom filename (without extension)
**Example Prompts:**
```
"Create a happy birthday song"
"Dubstep drop in D minor, 140 BPM, with heavy bass and drums"
"Jazz piano improvisation over a walking bass line"
"Epic orchestral theme with strings, brass, and timpani"
"Lo-fi hip hop beat with mellow Rhodes and vinyl crackle feel"
"Fast metal riff in E minor with distorted guitar"
```
### 2. Sheet Music to MIDI
**Tool**: `midi_convert_sheet_music_to_midi`
Convert images of sheet music into MIDI files.
**Parameters:**
- `image_data` (required): Base64-encoded image OR file path to image
- `image_format` (optional): "png", "jpg", "jpeg", "pdf", default "png"
- `auto_detect_tempo` (optional): Auto-detect tempo markings, default true
- `tempo` (optional): Manual tempo if auto_detect_tempo is false
- `output_filename` (optional): Custom filename
**Supported Formats:**
- PNG, JPEG, BMP, TIFF images
- PDF files with sheet music
**Example:**
```python
# Using file path
image_data = "/path/to/sheet_music.png"
# Or using base64
with open("sheet_music.png", "rb") as f:
import base64
image_data = base64.b64encode(f.read()).decode()
```
### 3. Audio-to-MIDI
**Tool**: `midi_convert_audio_to_midi`
Convert audio files into MIDI with pitch detection.
**Parameters:**
- `audio_data` (required): Base64-encoded audio OR file path to audio
- `audio_format` (optional): "mp3", "wav", "flac", "ogg", "m4a", "aiff", default "wav"
- `separate_tracks` (optional): Separate by pitch range, default true
- `min_note_duration` (optional): Minimum note length in seconds (0.05-0.5), default 0.1
- `pitch_sensitivity` (optional): Detection sensitivity (0.1-1.0), default 0.5
- `output_filename` (optional): Custom filename
**Best Results:**
- Monophonic audio (single instrument/voice)
- Clear recordings without distortion
- Minimal background noise
- Simple melodies work better than complex polyphonic music
## Output
All tools generate MIDI files saved to `/mnt/user-data/outputs/` with:
- Proper multi-track structure
- Separated instrument lanes
- Correct tempo and time signature
- Standard MIDI format (.mid) compatible with all DAWs
## General MIDI Instruments
The server uses General MIDI (GM) instrument standards. Available instruments include:
**Keyboards**: piano, electric_piano, rhodes, organ, church_organ
**Guitars**: guitar, acoustic_guitar, electric_guitar, distortion_guitar
**Bass**: bass, acoustic_bass, electric_bass, slap_bass
**Strings**: violin, viola, cello, strings, string_ensemble
**Brass**: trumpet, trombone, tuba, brass
**Woodwinds**: saxophone, alto_sax, tenor_sax, flute, clarinet, oboe
**Synths**: synth_lead, synth_pad, synth_bass
**Percussion**: drums (automatically uses MIDI channel 10)
## Scales and Modes
Supported scales for text-to-MIDI generation:
- `major` - Standard major scale
- `minor` - Natural minor scale
- `harmonic_minor` - Minor with raised 7th
- `melodic_minor` - Minor with raised 6th and 7th
- `pentatonic_major` - 5-note major pentatonic
- `pentatonic_minor` - 5-note minor pentatonic
- `blues` - Blues scale with blue notes
- `dorian` - Dorian mode
- `phrygian` - Phrygian mode
- `lydian` - Lydian mode
- `mixolydian` - Mixolydian mode
## Technical Details
### MIDI Specifications
- **Format**: Standard MIDI File (SMF) Format 1
- **Resolution**: 480 ticks per quarter note
- **Channels**: Up to 16 simultaneous channels
- **Velocity**: Dynamic velocity range (0-127)
- **Note Range**: MIDI notes 21-108 (A0-C8)
### Audio Processing
- **Pitch Detection**: Uses librosa's `piptrack` algorithm
- **Tempo Detection**: Beat tracking with librosa
- **Sample Rate**: Adaptive (preserves original or defaults to 22050 Hz)
### Image Processing
- **OCR Engine**: OpenCV-based staff line detection
- **Supported DPI**: 300+ recommended for best results
- **Color Modes**: Grayscale and color images supported
## Troubleshooting
### Installation Issues
**"No module named 'mcp'":**
```bash
pip install --upgrade mcp
```
**"Cannot find FFmpeg":**
- Ensure FFmpeg is installed and in your PATH
- Test with: `ffmpeg -version`
**"librosa import error":**
```bash
pip install --upgrade librosa soundfile numpy scipy
```
### Runtime Issues
**"AI generation service unavailable":**
- Server will automatically fall back to rule-based generation
- To use AI generation, set `ANTHROPIC_API_KEY` environment variable
**"Audio-to-MIDI produces wrong notes":**
- Try adjusting `pitch_sensitivity` (lower for fewer notes, higher for more)
- Increase `min_note_duration` to filter out noise
- Ensure audio is clean and monophonic for best results
**"Sheet music OCR not accurate":**
- Use high-quality scans (300 DPI minimum)
- Ensure good contrast between staff lines and background
- Clean sheet music without stains or marks works best
### Output Issues
**"Cannot find generated MIDI file":**
- Check `/mnt/user-data/outputs/` directory
- Ensure you have write permissions
- Look for error messages in the response
## API Reference
### Response Format
All tools return markdown-formatted responses containing:
- Download link to generated MIDI file
- Musical parameters used
- Track structure and instrument assignments
- Generation notes and statistics
### Error Handling
Errors are returned as descriptive messages:
- Input validation errors specify the parameter issue
- Processing errors include helpful suggestions
- File system errors indicate permission or path problems
## Examples
### Example 1: Simple Song
```
prompt: "simple melody for a children's song in C major"
tempo: 100
duration_bars: 8
complexity: simple
```
### Example 2: Electronic Music
```
prompt: "aggressive dubstep drop with wobble bass and drums"
tempo: 140
duration_bars: 4
key: "D"
scale: "minor"
complexity: complex
instruments: ["synth_bass", "synth_lead", "drums"]
```
### Example 3: Classical Piece
```
prompt: "baroque-style harpsichord piece"
tempo: 96
duration_bars: 16
key: "G"
scale: "major"
complexity: complex
instruments: ["piano"] # piano approximates harpsichord
```
## Contributing
This MCP server was built following the official MCP best practices:
- Agent-centric design for optimal LLM interaction
- Comprehensive input validation with Pydantic
- Clear, actionable error messages
- Efficient context window usage
## License
[Add your license here]
## Version
1.0.0 - Initial release
## Author
Built for comprehensive MIDI conversion capabilities with multi-modal input support.