An experimental Model Context Protocol (MCP) server that enables Claude to control Strudel.cc for AI-assisted music generation, live coding, and algorithmic composition. Current State: Functional but under active development. Core features work reliably, but expect rough edges. Test coverage is at 78% with 1470 tests passing (1521 total, 51 skipped). See open issues for known limitations. - Instal
Add this skill
npx mdskills install williamzujkowski/strudel-mcp-serverComprehensive music generation MCP with 65 well-documented tools, clear examples, and thoughtful architecture
1# Strudel MCP Server23> π΅ Open source MCP server for AI-powered music generation with Strudel.cc4>5> **Status:** Actively developed | Experimental | Contributions welcome67<a href="https://glama.ai/mcp/servers/@williamzujkowski/strudel-mcp-server">8 <img width="380" height="200" src="https://glama.ai/mcp/servers/@williamzujkowski/strudel-mcp-server/badge" alt="Strudel Server MCP server" />9</a>1011[](https://github.com/williamzujkowski/strudel-mcp-server/actions)12[](https://www.npmjs.com/package/@williamzujkowski/strudel-mcp-server)13[]()14[](LICENSE)1516An experimental Model Context Protocol (MCP) server that enables Claude to control [Strudel.cc](https://strudel.cc/) for AI-assisted music generation, live coding, and algorithmic composition.1718**Current State:** Functional but under active development. Core features work reliably, but expect rough edges. Test coverage is at 78% with 1470 tests passing (1521 total, 51 skipped). See [open issues](https://github.com/williamzujkowski/strudel-mcp-server/issues) for known limitations.1920## Table of Contents2122- [Features](#-features)23- [Installation](#-installation)24- [Quick Reference](#-quick-reference)25- [Quick Start](#-quick-start)26- [Available Tools](#-available-tools-65)27- [Usage Examples](#-usage-examples)28- [Architecture](#-architecture)29- [Advanced Usage](#-advanced-usage)30- [Configuration](#-configuration)31- [Security](#-security)32- [Troubleshooting](#-troubleshooting)33- [Development](#-development)34- [Contributing](#-contributing)3536## β¨ Features3738### πΉ Complete Music Control39- **65 MCP Tools**: Comprehensive suite for music creation and manipulation40- **Real Browser Automation**: Direct control of Strudel.cc through Playwright41- **Live Audio Analysis**: Real-time frequency analysis via Web Audio API42- **Pattern Generation**: AI-powered creation across 8+ music genres43- **Music Theory Engine**: Scales, chords, progressions, euclidean rhythms44- **Session Management**: Save, load, undo/redo with pattern storage4546### π§ Testing & Development Status47- β **Test Suite**: 1470 tests passing (1521 total, 51 skipped)48- β **Code Coverage**: 78% statement coverage (goal: 80%)49- β **Browser Integration**: Works with live Strudel.cc website50- β **Audio Analysis**: Real-time FFT analysis functional51- β **Pattern Generation**: Core music generation features working52- β **OIDC Publishing**: Secure npm publishing with provenance attestation5354**Not Production-Ready:** This is experimental software under active development. Use for exploration and experimentation. Expect breaking changes, bugs, and incomplete features. See [CONTRIBUTING.md](CONTRIBUTING.md) to help improve it.5556### πΌ Example Patterns5758Explore 17 curated example patterns across 10 genres in [`patterns/examples/`](patterns/examples/):5960- **Techno**: Hard techno, minimal techno61- **House**: Deep house, tech house62- **Drum & Bass**: Liquid, neurofunk63- **Ambient**: Dark ambient, drone64- **Trap**: Modern trap, cloud trap65- **Jungle**: Classic jungle, ragga jungle66- **Jazz**: Bebop, modal jazz67- **Intelligent DnB**: Atmospheric, liquid, LTJ Bukem style68- **Trip Hop**: Portishead, Massive Attack, Flying Lotus style69- **Boom Bap**: DJ Premier, Alchemist, golden era hip hop7071Each example includes pattern code, BPM, key, and description. See [`patterns/examples/README.md`](patterns/examples/README.md) for details.7273## π¦ Installation7475### Prerequisites7677| Requirement | Version | Notes |78|-------------|---------|-------|79| Node.js | 18.x or 20.x | LTS versions recommended |80| npm | 9+ | Comes with Node.js |81| Chromium | Latest | Auto-installed by Playwright |82| Audio output | Any | Required for playback (speakers/headphones) |8384**Optional:** Docker for containerized deployment.8586### From npm87```bash88npm install -g @williamzujkowski/strudel-mcp-server8990# Install browser (required once)91npx playwright install chromium92```9394### From Source95```bash96# Clone repository97git clone https://github.com/williamzujkowski/strudel-mcp-server.git98cd strudel-mcp-server99100# Install dependencies101npm install102103# Install Chromium for browser automation104npx playwright install chromium105106# Build the project107npm run build108```109110## π Quick Reference111112Common commands for immediate use:113114| Action | Command |115|--------|---------|116| Initialize browser | `init` |117| Create techno beat | `generate_pattern` with `style: "techno"` |118| Play pattern | `play` |119| Stop playback | `stop` |120| Get current pattern | `get_pattern` |121| Analyze audio | `analyze` |122| Save pattern | `save` with `name: "my-pattern"` |123| Undo last change | `undo` |124125**One-shot workflow:**126```127compose with style: "dnb", key: "Am", bpm: 174, auto_play: true128```129130## π― Quick Start131132### 1. Add to Claude133```bash134# If installed globally135claude mcp add strudel strudel-mcp136137# If built from source138claude mcp add strudel node /path/to/strudel-mcp-server/dist/index.js139```140141### 2. Start Using142```bash143claude chat144```145146Then ask Claude:147- "Initialize Strudel and create a techno beat"148- "Generate a jazz chord progression in F major"149- "Create a drum & bass pattern at 174 BPM"150151## π οΈ Available Tools (65)152153### Core Control (10 tools)154| Tool | Description | Example |155|------|-------------|---------|156| `init` | Initialize Strudel in browser | "Initialize Strudel" |157| `write` | Write pattern to editor | "Write pattern: s('bd*4')" |158| `play` | Start playback | "Play the pattern" |159| `stop` | Stop playback | "Stop playing" |160| `clear` | Clear editor | "Clear the editor" |161| `get_pattern` | Get current pattern | "Show current pattern" |162| `append` | Add to pattern | "Add hi-hats" |163| `insert` | Insert at line | "Insert at line 2" |164| `replace` | Replace text | "Replace bd with sn" |165| `pause` | Pause playback | "Pause" |166167### Pattern Generation & Manipulation (10 tools)168| Tool | Description | Options |169|------|-------------|---------|170| `generate_pattern` | Complete patterns | techno, house, dnb, ambient, trap, jungle, jazz, intelligent_dnb, trip_hop, boom_bap |171| `generate_drums` | Drum patterns | All styles + complexity (0-1) |172| `generate_bassline` | Bass patterns | techno, house, dnb, acid, dub, funk, jazz, intelligent_dnb, trip_hop, boom_bap |173| `generate_melody` | Melodic lines | Any scale, custom length |174| `generate_variation` | Pattern variations | subtle, moderate, extreme, glitch |175| `transpose` | Transpose notes | Β±12 semitones |176| `reverse` | Reverse pattern | - |177| `stretch` | Time stretch | Factor 0.1-10 |178| `quantize` | Quantize to grid | 1/4, 1/8, 1/16, etc. |179| `humanize` | Add timing variation | Amount 0-1 |180181### Music Theory (6 tools)182| Tool | Description | Options |183|------|-------------|---------|184| `generate_scale` | Generate scales | major, minor, modes, pentatonic, blues |185| `generate_chord_progression` | Chord progressions | pop, jazz, blues, rock, folk |186| `generate_euclidean` | Euclidean rhythms | hits/steps/sound |187| `generate_polyrhythm` | Polyrhythms | Multiple patterns |188| `generate_fill` | Generate drum fills | All styles, 1-4 bars |189| `apply_scale` | Apply scale to notes | Any scale |190191### Effects (4 tools)192| Tool | Description |193|------|-------------|194| `add_effect` | Add audio effect (reverb, delay, etc.) |195| `remove_effect` | Remove an effect from the chain |196| `set_tempo` | Set BPM (60-200) |197| `add_swing` | Add swing feel (0-1 amount) |198199### Session Management (5 tools)200| Tool | Description |201|------|-------------|202| `save` | Save pattern with tags |203| `load` | Load saved pattern |204| `list` | List all patterns |205| `undo` | Undo last action |206| `redo` | Redo action |207208### Pattern History (3 tools)209| Tool | Description |210|------|-------------|211| `list_history` | Browse pattern history with timestamps and previews |212| `restore_history` | Restore a previous pattern by ID |213| `compare_patterns` | Compare two patterns showing line-by-line differences |214215### Audio Analysis (6 tools)216| Tool | Description |217|------|-------------|218| `analyze` | Basic audio analysis (frequency, playing state) |219| `analyze_spectrum` | FFT spectral analysis |220| `analyze_rhythm` | Rhythm complexity analysis |221| `detect_tempo` | BPM detection |222| `detect_key` | Musical key detection |223| `validate_pattern_runtime` | Validate pattern with browser error checking |224225### UX & Browser Control (6 tools)226| Tool | Description |227|------|-------------|228| `compose` | One-shot pattern generation with auto-play |229| `status` | Get current browser/playback state |230| `diagnostics` | Detailed system diagnostics |231| `show_browser` | Bring browser window to foreground |232| `screenshot` | Capture browser screenshot |233| `show_errors` | Display captured console errors |234235### Performance (2 tools)236| Tool | Description |237|------|-------------|238| `performance_report` | Timing metrics and bottleneck analysis |239| `memory_usage` | Memory consumption statistics |240241### AI Feedback (1 tool)242| Tool | Description | Options |243|------|-------------|---------|244| `get_pattern_feedback` | AI-powered creative feedback via Gemini | `includeAudio`: analyze audio (default: false), `style`: hint for context |245246> **Note:** Requires `GEMINI_API_KEY` environment variable. Returns pattern complexity, estimated style, strengths, and suggestions.247248## π΅ Usage Examples249250### Basic Pattern Creation251252**Create a Simple Beat**253```254You: Initialize Strudel and create a simple techno beat255256Claude: [Initializes browser]257 [Generates and writes pattern]258 [Starts playback]259260Pattern created:261setcpm(130)262stack(263 s("bd*4"),264 s("~ cp ~ cp"),265 s("hh*8").gain(0.4)266).gain(0.8)267```268269**Generate a Bassline**270```271You: Add a techno bassline in C272273Claude: [Generates bassline]274 [Appends to current pattern]275276Added: note("c2 c2 c2 c2").s("sawtooth").cutoff(800)277```278279### Advanced Music Generation280281**Jazz Composition**282```283You: Create a jazz progression in F major with a walking bass284285Claude: Generated progression: "Gm7" "C7" "Fmaj7"286287Pattern:288stack(289 note("Gm7" "C7" "Fmaj7").struct("1 ~ ~ ~").s("piano"),290 note("g2 c2 f2").s("sine").gain(0.7)291)292```293294**Drum & Bass Track**295```296You: Generate a complete drum & bass track at 174 BPM297298Claude: [Creates multi-layer pattern with drums, bass, and pads]299300// dnb pattern in C at 174 BPM301setcpm(174)302stack(303 // Drums304 s("bd ~ ~ [bd bd] ~ ~ bd ~, ~ ~ cp ~ ~ cp ~ ~").fast(2),305306 // Bass307 note("c1 ~ ~ c2 ~ c1 ~ ~").s("square").cutoff(400),308309 // Pads (atmospheric)310 note("c3 eb3 g3 bb3").s("sawtooth")311 .attack(2).release(4).room(0.8).gain(0.6)312)313```314315### Real-Time Manipulation316317**Live Audio Analysis**318```319You: Analyze what's playing and show me the frequency breakdown320321Claude: Audio Analysis Results:322{323 "connected": true,324 "features": {325 "average": 78.5,326 "peak": 180,327 "peakFrequency": 120,328 "bass": 145,329 "mid": 82,330 "treble": 45,331 "isPlaying": true,332 "brightness": "balanced"333 }334}335336Strong bass presence detected - typical for techno/house patterns.337```338339**Pattern Variations**340```341You: Create a glitchy variation of the current pattern342343Claude: [Applies glitch transformation]344345Added: .sometimes(x => x.chop(8).rev).rarely(x => x.speed(-1))346```347348### Multi-Track Composition349350**Layered Ambient Track**351```352You: Create an ambient soundscape with multiple layers353354Claude: [Generates complex multi-layer pattern]355356setcpm(90)357stack(358 // Deep bass drone359 note("c1").s("sine").attack(4).release(8).gain(0.5),360361 // Texture pad362 note("c3 eb3 g3").s("sawtooth")363 .attack(2).release(6).room(0.9).gain(0.4),364365 // Sparse percussion366 s("bd ~ ~ ~, ~ ~ ~ hh:8").room(0.9).gain(0.3),367368 // Melodic sparkles369 note("c5 g5 eb5 bb5").struct("~ 1 ~ 1 ~ ~ 1 ~")370 .s("triangle").delay(0.5).room(0.8).gain(0.3)371)372```373374### Session Management375376**Save and Load Patterns**377```378You: Save this pattern as "techno-groove-1" with tags "techno" and "experimental"379380Claude: Pattern saved as "techno-groove-1"381382---383384You: List all my techno patterns385386Claude: Saved patterns with tag "techno":387β’ techno-groove-1 [techno, experimental] - 2025-10-23T19:30:00.000Z388β’ acid-bassline [techno, acid] - 2025-10-23T18:15:00.000Z389390---391392You: Load "acid-bassline"393394Claude: Loaded pattern "acid-bassline"395[Pattern written to editor]396```397398### Music Theory Applications399400**Generate Euclidean Rhythms**401```402You: Create a 5/8 euclidean rhythm with kick drum403404Claude: Generated Euclidean rhythm (5/8)405406Pattern: s("bd").struct("1 ~ 1 ~ 1 1 ~ 1")407```408409**Complex Polyrhythms**410```411You: Generate a polyrhythm with kick (4/16), snare (7/16), and hi-hat (3/16)412413Claude: Generated polyrhythm414415stack(416 s("bd").euclid(4, 16),417 s("cp").euclid(7, 16),418 s("hh").euclid(3, 16)419)420```421422### Integration with LLM Agents423424**AI-Assisted Composition**425```426You: Analyze the mood of my current pattern and suggest complementary elements427428Claude: [Analyzes pattern structure and audio features]429430Your pattern has:431- Energetic rhythm (130 BPM)432- Strong bass presence433- Minimal melodic content434435Suggestions:4361. Add arpeggiated synth for movement4372. Include occasional breaks/fills4383. Layer atmospheric pad for depth439440Would you like me to add any of these?441442You: Add an arpeggiated synth in C minor443444Claude: [Generates and adds]445446note("c4 eb4 g4 bb4 c5").struct("1 1 1 1 1 1 1 1")447 .s("triangle").delay(0.25).room(0.3).gain(0.5)448```449450## π§ͺ Testing451452All tools have been tested with real Strudel.cc interaction:453454```bash455# Run integration tests456npm run test:integration457458# Run browser tests459node tests/strudel-integration.js460461# Test results: 1470/1521 tests passing (96.6%), 51 skipped (browser tests in CI)462```463464## βοΈ Configuration465466### config.json467```json468{469 "headless": false, // Set true for background operation470 "strudel_url": "https://strudel.cc/",471 "patterns_dir": "./patterns",472 "audio_analysis": {473 "fft_size": 2048,474 "smoothing": 0.8475 }476}477```478479## ποΈ Architecture480481### System Overview482483The Strudel MCP Server is built with a modular architecture that separates concerns and enables robust music generation:484485```486βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ487β Claude AI β488β (MCP Client) β489βββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββ490 β MCP Protocol (stdio)491 β492βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββ493β EnhancedMCPServerFixed β494β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β495β β Tool Request Handler β β496β β - Validates inputs β β497β β - Routes to appropriate service β β498β β - Handles errors gracefully β β499β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β500βββββββββ¬βββββββββββββ¬βββββββββββββ¬ββββββββββββ¬βββββββββββββββ501 β β β β502 ββββββΌβββββ βββββΌβββββ βββββΌβββββ ββββΌβββββββ503 β Strudel β β Music β βPattern β β Pattern β504 βControllerβ β Theory β βGeneratorβ β Store β505 ββββββ¬βββββ ββββββββββ ββββββββββ βββββββββββ506 β507 ββββββΌβββββββββββββββββββββββββββββ508 β Playwright Browser β509 β ββββββββββββββββββββββββββββ β510 β β Strudel.cc Website β β511 β β ββββββββββββββββββββββ β β512 β β β CodeMirror Editor β β β513 β β ββββββββββββββββββββββ β β514 β β ββββββββββββββββββββββ β β515 β β β Audio Context β β β516 β β β + Web Audio API β β β517 β β ββββββββββ¬ββββββββββββ β β518 β βββββββββββββΌβββββββββββββββ β519 ββββββββββββββββΌβββββββββββββββββββ520 β521 βββββββββΌβββββββββ522 β Audio Analyzer β523 β - FFT Analysisβ524 β - Frequency β525 β - Spectral β526 ββββββββββββββββββ527```528529### Core Components530531#### 1. **EnhancedMCPServerFixed** (`src/server/EnhancedMCPServerFixed.ts`)532533Main MCP server implementation handling:534- **65 Tool Definitions**: Complete API surface for music control535- **Request Routing**: Directs tool calls to appropriate handlers536- **State Management**: Tracks initialization, undo/redo stacks, pattern cache537- **Error Handling**: Graceful degradation and informative error messages538- **Lazy Initialization**: Browser starts only when needed539540Key Features:541```typescript542- Pattern caching before browser init543- Undo/redo stack management544- Session history tracking545- Generated pattern storage546- Safe fallback mechanisms547```548549#### 2. **StrudelController** (`src/StrudelController.ts`)550551Browser automation layer using Playwright:552- **Browser Management**: Chromium instance lifecycle553- **Editor Control**: CodeMirror manipulation via DOM554- **Playback Control**: Keyboard shortcuts for play/stop555- **Performance Optimizations**:556 - Editor content caching (100ms TTL)557 - Direct CodeMirror API access558 - Resource blocking (images, fonts)559 - Fast DOM content loading560561```typescript562// Example: Optimized pattern writing563async writePattern(pattern: string) {564 await this.page.evaluate((newPattern) => {565 const editor = document.querySelector('.cm-content');566 const view = editor.__view;567 view.dispatch({568 changes: { from: 0, to: view.state.doc.length, insert: newPattern }569 });570 }, pattern);571}572```573574#### 3. **AudioAnalyzer** (`src/AudioAnalyzer.ts`)575576Real-time audio analysis via Web Audio API injection:577- **FFT Analysis**: 1024-point FFT for spectral data578- **Frequency Bands**: Bass, low-mid, mid, high-mid, treble579- **Analysis Caching**: 50ms TTL for performance580- **Features Extracted**:581 - Average amplitude582 - Peak frequency583 - Spectral centroid584 - Playing state detection585 - Frequency distribution586587```typescript588Features provided:589- average: Overall amplitude (0-255)590- peak: Maximum amplitude591- peakFrequency: Dominant frequency in Hz592- bass/mid/treble: Band-specific amplitudes593- brightness: Timbral classification594- isPlaying: Boolean playback state595```596597#### 4. **MusicTheory** (`src/services/MusicTheory.ts`)598599Music theory engine providing:600- **15+ Scales**: Major, minor, modes, pentatonic, blues, whole-tone601- **Chord Progressions**: Pop, jazz, blues, rock, folk, EDM602- **Euclidean Rhythms**: Mathematical rhythm generation603- **Arpeggio Generation**: Multiple patterns (up, down, random)604- **Note Transposition**: Semitone-based pitch shifting605606Supported scales:607```typescript608major, minor, dorian, phrygian, lydian, mixolydian,609aeolian, locrian, pentatonic, blues, chromatic,610wholetone, harmonic_minor, melodic_minor611```612613#### 5. **PatternGenerator** (`src/services/PatternGenerator.ts`)614615AI-powered pattern creation:616- **Genre Templates**: Techno, house, DnB, trap, ambient, jazz, intelligent_dnb, trip_hop, boom_bap617- **Drum Patterns**: 4 complexity levels per genre618- **Basslines**: 8 different styles619- **Melody Generation**: Scale-based with musical intervals620- **Variations**: Subtle, moderate, extreme, glitch, evolving621- **Fills**: 1-4 bar drum fills622623Example generation:624```typescript625generateCompletePattern('techno', 'C', 130)626β Multi-layer pattern with drums, bass, chords, melody627```628629#### 6. **PatternStore** (`src/PatternStore.ts`)630631Persistent pattern storage:632- **JSON-based**: Simple file storage633- **Metadata**: Name, tags, timestamp, audio features634- **Tag Filtering**: Organize by genre, mood, project635- **Sorted Retrieval**: Most recent first636637### Directory Structure638639```640strudel-mcp-server/641βββ src/642β βββ server/643β β βββ EnhancedMCPServer.ts # Original implementation644β β βββ EnhancedMCPServerFixed.ts # Production version645β βββ services/646β β βββ MusicTheory.ts # Theory engine647β β βββ PatternGenerator.ts # Pattern creation648β βββ utils/649β β βββ Logger.ts # Logging utility650β βββ types/651β β βββ index.ts # TypeScript types652β βββ StrudelController.ts # Browser automation653β βββ AudioAnalyzer.ts # Audio analysis654β βββ PatternStore.ts # Pattern persistence655β βββ index.ts # Entry point656βββ tests/657β βββ browser-test.js # Browser integration658β βββ integration.test.js # Integration tests659β βββ manual-test.js # Manual testing660β βββ mcp-tools.test.ts # MCP tool tests661β βββ strudel-integration.js # Full integration662βββ patterns/ # Saved patterns663βββ config.json # Server configuration664βββ package.json # Dependencies665βββ tsconfig.json # TypeScript config666```667668### Data Flow6696701. **Tool Invocation**671 ```672 Claude β MCP Protocol β EnhancedMCPServerFixed673 ```6746752. **Pattern Generation** (without browser)676 ```677 Server β PatternGenerator β MusicTheory β Pattern String678 ```6796803. **Pattern Execution** (with browser)681 ```682 Server β StrudelController β Playwright β Strudel.cc683 ```6846854. **Audio Analysis**686 ```687 Strudel.cc β Web Audio API β AudioAnalyzer β Feature Data688 ```689690### Performance Characteristics691692| Operation | Latency | Notes |693|-----------|---------|-------|694| Pattern Generation | <100ms | Pure computation |695| Browser Init | ~3s | One-time cost |696| Pattern Write | ~50ms | With caching |697| Play/Stop | ~100ms | Keyboard shortcuts |698| Audio Analysis | ~20ms | With 50ms cache |699| Pattern Save | ~10ms | File I/O |700701### Optimization Strategies7027031. **Caching**704 - Editor content: 100ms TTL705 - Audio analysis: 50ms TTL706 - Generated patterns: Until browser init7077082. **Resource Blocking**709 - Images, fonts, media blocked710 - Only load essential JavaScript/CSS7117123. **Direct API Access**713 - CodeMirror view manipulation714 - Keyboard shortcuts over button clicks7157164. **Lazy Loading**717 - Browser starts only when needed718 - Services initialized on-demand719720## πΉ Pattern Examples721722### Minimal Techno (Verified Working)723```javascript724setcpm(130)725stack(726 s("bd*4").gain(0.9),727 s("~ cp ~ cp").room(0.2),728 s("hh*16").gain(0.4).pan(sine.range(-0.5, 0.5)),729 note("c2 c2 eb2 c2").s("sawtooth").cutoff(800)730).swing(0.05)731```732733### Drum & Bass (Verified Working)734```javascript735setcpm(174)736stack(737 s("bd ~ ~ [bd bd] ~ ~ bd ~, ~ ~ sn:3 ~ ~ sn:3 ~ ~").fast(2),738 s("hh*16").gain(0.5),739 note("e1 ~ ~ e2 ~ e1 ~ ~").s("sine:2").lpf(200)740)741```742743### Generated Jazz Progression744```javascript745// Jazz ii-V-I in F746stack(747 note("Gm7" "C7" "Fmaj7").struct("1 ~ ~ ~").s("piano"),748 note("g2 c2 f2").s("sine").gain(0.7)749)750```751752## π³ Docker Support753754```bash755# Build image756docker build -t strudel-mcp .757758# Run container759docker run -it --rm strudel-mcp760761# Or use docker-compose762docker-compose up763```764765## π§ Development766767### Setup Development Environment768769```bash770# Clone the repository771git clone https://github.com/williamzujkowski/strudel-mcp-server.git772cd strudel-mcp-server773774# Install dependencies775npm install776777# Install Playwright browsers778npx playwright install chromium779780# Build the project781npm run build782```783784### Available Scripts785786```bash787# Development mode with hot reload788npm run dev789790# Build TypeScript to dist/791npm run build792793# Start production server794npm start795796# Run all tests797npm test798799# Run integration tests with real browser800npm run test:integration801802# Run browser-specific tests803npm run test:browser804805# Validate MCP protocol compliance806npm run validate807808# Lint code809npm run lint810811# Format code812npm run format813814# Clean build artifacts815npm clean816```817818### Publishing to npm819820See [NPM_PUBLISHING.md](NPM_PUBLISHING.md) for complete publishing instructions.821822**Quick publish via GitHub Release:**823```bash824npm version patch # or minor, major825git push && git push --tags826gh release create v$(node -p "require('./package.json').version") --generate-notes827```828829The package uses OIDC trusted publishing with provenance attestation for supply chain security.830831### Project Structure832833```834src/835βββ server/836β βββ EnhancedMCPServer.ts # Original implementation837β βββ EnhancedMCPServerFixed.ts # Production version with caching838β839βββ services/840β βββ MusicTheory.ts # Music theory engine841β β - 15+ scales (major, minor, modes, etc.)842β β - Chord progressions (jazz, pop, blues, etc.)843β β - Euclidean rhythm generation844β β - Arpeggio generation845β β846β βββ PatternGenerator.ts # Pattern creation service847β - Genre-specific drum patterns848β - Bassline generation849β - Melody composition850β - Pattern variations851β - Complete track generation852β853βββ utils/854β βββ Logger.ts # Logging utility855β βββ PerformanceMonitor.ts # Performance tracking856β βββ PatternValidator.ts # Pattern syntax validation857β βββ ErrorRecovery.ts # Error handling & recovery858β859βββ types/860β βββ index.ts # TypeScript type definitions861β862βββ StrudelController.ts # Browser automation863β - Chromium management via Playwright864β - CodeMirror editor manipulation865β - Playback control866β - Pattern validation867β - Error recovery868β869βββ AudioAnalyzer.ts # Real-time audio analysis870β - Web Audio API injection871β - FFT spectral analysis872β - Frequency band detection873β - Playing state monitoring874β875βββ PatternStore.ts # Pattern persistence876β - JSON-based storage877β - Tag-based organization878β - Metadata tracking879β - List caching880β881βββ index.ts # Application entry point882```883884### Adding New Tools885886To add a new MCP tool:8878881. **Define the tool** in `getTools()` method:889```typescript890{891 name: 'my_new_tool',892 description: 'Description of what it does',893 inputSchema: {894 type: 'object',895 properties: {896 param1: { type: 'string', description: 'Parameter description' },897 param2: { type: 'number', description: 'Numeric parameter' }898 },899 required: ['param1']900 }901}902```9039042. **Implement the handler** in `executeTool()` switch statement:905```typescript906case 'my_new_tool':907 // Your implementation here908 return await this.someService.doSomething(args.param1, args.param2);909```9109113. **Add necessary service methods** if needed:912```typescript913// In appropriate service file914async doSomething(param1: string, param2?: number): Promise<string> {915 // Implementation916 return `Result: ${param1}`;917}918```9199204. **Test the tool**:921```bash922# Build923npm run build924925# Test via MCP926echo '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"my_new_tool","arguments":{"param1":"test"}},"id":2}' | node dist/index.js927```928929### Testing Strategy930931#### 1. Unit Tests932```bash933# Run with Jest934npm test935936# Watch mode937npm run test:watch938```939940#### 2. Integration Tests941```bash942# Full integration with real browser943npm run test:integration944945# This tests:946# - Browser initialization947# - Pattern generation948# - Audio analysis949# - Pattern storage950# - All 65 tools951```952953#### 3. Manual Testing954```bash955# Development mode956npm run dev957958# In another terminal959claude mcp add strudel-dev node $(pwd)/dist/index.js960claude chat961962# Then interact with Claude963```964965### Code Quality966967**TypeScript Configuration**968```json969// tsconfig.json970{971 "compilerOptions": {972 "strict": true, // Strict type checking973 "esModuleInterop": true, // Better module compatibility974 "target": "ES2020", // Modern JavaScript975 "module": "ES2020", // ES modules976 "moduleResolution": "node"977 }978}979```980981**Linting & Formatting**982```bash983# ESLint984npm run lint985986# Prettier987npm run format988989# Pre-commit hooks recommended990```991992### Debugging993994**Enable Debug Logging**995```bash996# Set DEBUG environment variable997DEBUG=strudel:* npm start998999# Or specific modules1000DEBUG=strudel:controller npm start1001DEBUG=strudel:audio npm start1002```10031004**VS Code Launch Configuration**1005```json1006{1007 "type": "node",1008 "request": "launch",1009 "name": "Debug MCP Server",1010 "program": "${workspaceFolder}/dist/index.js",1011 "preLaunchTask": "npm: build",1012 "console": "integratedTerminal",1013 "env": {1014 "DEBUG": "strudel:*"1015 }1016}1017```10181019**Playwright Debugging**1020```typescript1021// In StrudelController.ts1022this.browser = await chromium.launch({1023 headless: false, // See the browser1024 devtools: true, // Open DevTools1025 slowMo: 100 // Slow down actions1026});1027```10281029### Performance Monitoring10301031The server includes built-in performance monitoring:10321033```typescript1034// Access performance metrics1035You: Show me performance metrics10361037Claude: Performance Report:1038{1039 "averageLatency": {1040 "init": "3.2s",1041 "write": "52ms",1042 "play": "105ms",1043 "analyze": "18ms"1044 },1045 "cacheHitRate": "85%",1046 "totalOperations": 1247,1047 "bottlenecks": [1048 {"tool": "init", "avgTime": 3200, "calls": 1},1049 {"tool": "write", "avgTime": 52, "calls": 156}1050 ]1051}1052```10531054### Contributing Guidelines105510561. **Fork the repository**1057 ```bash1058 git clone https://github.com/YOUR_USERNAME/strudel-mcp-server.git1059 ```106010612. **Create a feature branch**1062 ```bash1063 git checkout -b feature/my-new-feature1064 ```106510663. **Make your changes**1067 - Follow existing code style1068 - Add tests for new features1069 - Update documentation1070 - Ensure all tests pass107110724. **Commit with meaningful messages**1073 ```bash1074 git commit -m "feat: Add support for custom scale generation"1075 ```10761077 Follow [Conventional Commits](https://www.conventionalcommits.org/):1078 - `feat:` New feature1079 - `fix:` Bug fix1080 - `docs:` Documentation changes1081 - `refactor:` Code refactoring1082 - `test:` Adding tests1083 - `chore:` Maintenance tasks108410855. **Push and create PR**1086 ```bash1087 git push origin feature/my-new-feature1088 ```10891090 Then create a Pull Request on GitHub with:1091 - Clear description of changes1092 - Link to related issues1093 - Screenshots/examples if relevant10941095### Release Process10961097```bash1098# 1. Update version in package.json1099npm version patch # or minor/major11001101# 2. Update CHANGELOG.md1102# Add entry for new version11031104# 3. Build and test1105npm run build1106npm test1107npm run test:integration11081109# 4. Commit version bump1110git add .1111git commit -m "chore: Bump version to X.Y.Z"11121113# 5. Create git tag1114git tag vX.Y.Z11151116# 6. Push to GitHub1117git push origin main --tags11181119# 7. Publish to npm (if you have access)1120npm publish --access public11211122# 8. Create GitHub release1123gh release create vX.Y.Z --generate-notes1124```11251126### Docker Development11271128```bash1129# Build development image1130docker build -t strudel-mcp:dev .11311132# Run with volume mount for hot reload1133docker run -it --rm \1134 -v $(pwd)/src:/app/src \1135 -v $(pwd)/patterns:/app/patterns \1136 strudel-mcp:dev11371138# Run tests in container1139docker run -it --rm strudel-mcp:dev npm test1140```11411142### Environment Variables11431144```bash1145# Logging level1146LOG_LEVEL=debug # debug, info, warn, error11471148# Performance monitoring1149ENABLE_PERF_MONITORING=true11501151# Pattern storage1152PATTERNS_DIR=./patterns11531154# Browser configuration1155HEADLESS=false1156BROWSER_TIMEOUT=1500011571158# Audio analysis1159FFT_SIZE=10241160SMOOTHING=0.81161```11621163## π Performance11641165- **Pattern Generation**: <100ms1166- **Browser Initialization**: ~3 seconds1167- **Pattern Writing**: Instant1168- **Playback Start**: ~500ms1169- **Audio Analysis**: Real-time1170- **Memory Usage**: <150MB11711172## π Advanced Usage11731174### Custom Music Theory11751176**Create Custom Scales**1177```typescript1178// The MusicTheory service supports 15+ built-in scales1179// You can request any combination:11801181You: Generate a lydian scale starting on D11821183Claude: D lydian scale: D, E, F#, G#, A, B, C#1184```11851186**Complex Chord Progressions**1187```typescript1188You: Create a jazz ii-V-I progression in Bb with extended voicings11891190Claude: Generated jazz progression in Bb: "Cm7" "F7" "Bbmaj7"11911192Pattern:1193note("Cm7" "F7" "Bbmaj7")1194 .struct("1 ~ ~ ~")1195 .s("sawtooth")1196 .add(note("7")) // Add 7th extensions1197 .room(0.4)1198```11991200### Advanced Rhythm Techniques12011202**Euclidean Patterns**1203```1204You: Create a complex polyrhythm using euclidean patterns:1205 - Bass drum: 7 hits in 16 steps1206 - Snare: 5 hits in 16 steps1207 - Hi-hat: 11 hits in 16 steps12081209Claude: [Generates mathematically perfect polyrhythm]12101211stack(1212 s("bd").euclid(7, 16),1213 s("cp").euclid(5, 16),1214 s("hh").euclid(11, 16)1215)1216```12171218**Generative Variations**1219```1220You: Create 3 variations of my current pattern: subtle, moderate, and glitchy12211222Claude: [Generates three variants]12231224Version 1 (subtle):1225original.sometimes(x => x.fast(2))12261227Version 2 (moderate):1228original.every(4, x => x.rev).sometimes(x => x.fast(2))12291230Version 3 (glitchy):1231original.sometimes(x => x.chop(8).rev).rarely(x => x.speed(-1))1232```12331234### Performance Optimization Tips12351236**Pattern Caching**1237```1238// The server caches patterns intelligently:1239// - Generated patterns stored before browser init1240// - Editor content cached for 100ms1241// - Audio analysis cached for 50ms12421243// For fastest performance:12441. Generate patterns before initializing browser12452. Initialize once and reuse the session12463. Batch multiple changes together1247```12481249**Headless Mode**1250```json1251// In config.json:1252{1253 "headless": true, // Faster, no GUI1254 "strudel_url": "https://strudel.cc/",1255 "patterns_dir": "./patterns"1256}1257```12581259### Integration Patterns12601261**Workflow Automation**1262```1263You: Create a complete track:1264 1. Start with techno drums at 130 BPM1265 2. Add acid bassline in E1266 3. Layer ambient pads1267 4. Save as "track-001" with tags "techno", "acid", "experimental"12681269Claude: [Executes full workflow]1270 [Initializes browser]1271 [Generates drum pattern]1272 [Adds bassline]1273 [Layers pads]1274 [Saves with metadata]12751276Complete! Pattern saved as "track-001"1277```12781279**Audio-Reactive Composition**1280```1281You: Monitor the audio and suggest adjustments based on frequency balance12821283Claude: [Analyzes current playback]12841285Analysis shows:1286- Bass: 180 (strong)1287- Mid: 45 (weak)1288- Treble: 30 (weak)12891290Recommendations:12911. Reduce bass gain by 20%12922. Add mid-range melodic content12933. Include hi-hat pattern for treble12941295Apply changes? [Yes/No]1296```12971298### Advanced Pattern Manipulation12991300**Dynamic Transformations**1301```1302You: Apply these transformations in sequence:1303 1. Transpose up 3 semitones1304 2. Add 10% humanization1305 3. Apply reverb with 0.6 room size1306 4. Every 4th cycle, reverse the pattern13071308Claude: [Applies transformations]13091310Final pattern:1311[original]1312 .transpose(3)1313 .nudge(rand.range(-0.1, 0.1))1314 .room(0.6)1315 .every(4, x => x.rev)1316```13171318**Conditional Logic**1319```1320You: Create a pattern that evolves:1321 - Bars 1-4: Simple kick pattern1322 - Bars 5-8: Add snare1323 - Bars 9-16: Add full drum kit1324 - Then loop with variations13251326Claude: [Generates evolving pattern]13271328s("bd*4")1329 .struct("1 ~ ~ ~")1330 .mask("<1 1 1 1 0 0 0 0>/4") // First 4 bars1331 .stack(1332 s("~ cp ~ cp")1333 .mask("<0 0 0 0 1 1 1 1>/8") // Bars 5-81334 )1335 // Full complexity from bar 91336 .every(8, x => x.sometimes(y => y.fast(2)))1337```13381339## π Security13401341### Pattern Validation13421343All patterns are validated before execution:1344- **Dangerous gain levels** (>2.0) are flagged1345- **Eval blocks** are rejected1346- **Path traversal** attacks are blocked in PatternStore13471348### Browser Sandboxing13491350- Playwright runs Chromium in sandbox mode1351- No access to local filesystem from browser context1352- Resource blocking prevents loading external content13531354### Known Limitations13551356- **No authentication**: The MCP server trusts all incoming requests1357- **Local only**: Designed for local development, not network deployment1358- **Pattern execution**: Patterns execute in browser context with audio access13591360### Reporting Security Issues13611362Found a vulnerability? Please [open a security issue](https://github.com/williamzujkowski/strudel-mcp-server/security/advisories/new) or email the maintainer directly. Do not disclose publicly until patched.13631364## π Troubleshooting13651366### Common Issues13671368#### Browser doesn't open1369**Symptom**: `Error: Browser not initialized` or Chromium launch fails13701371**Solutions**:1372```bash1373# Install Chromium for Playwright1374npx playwright install chromium13751376# If that fails, try installing all browsers1377npx playwright install13781379# Check Playwright installation1380npx playwright --version13811382# For Linux, install dependencies1383sudo npx playwright install-deps chromium1384```13851386#### Audio analysis returns "not connected"1387**Symptom**: Audio analysis shows `connected: false`13881389**Solutions**:13901. Ensure pattern is playing first:1391 ```1392 You: Play the pattern, wait 2 seconds, then analyze1393 ```139413952. Reinitialize the browser:1396 ```1397 You: Stop, close the browser, reinitialize, and try again1398 ```139914003. Check audio context activation:1401 - Audio contexts require user interaction on some systems1402 - The browser window must be visible (not headless) for first run14031404#### Pattern syntax errors1405**Symptom**: Pattern doesn't play or shows errors in console14061407**Solutions**:1408```1409Common issues:14101. Missing quotes: s(bd*4) β s("bd*4")14112. Unmatched parentheses: stack(s("bd")) β stack(s("bd")))14123. Invalid note names: note("h2") β note("c2")14131414Test with minimal pattern first:1415s("bd*4")14161417Then build complexity gradually.1418```14191420#### MCP connection issues1421**Symptom**: Claude can't find the server or tools14221423**Solutions**:1424```bash1425# Verify server is built1426npm run build14271428# Check if server responds1429echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | node dist/index.js14301431# Should return JSON with 65 tools14321433# Reinstall MCP server in Claude1434claude mcp remove strudel1435claude mcp add strudel node $(pwd)/dist/index.js14361437# Restart Claude1438claude chat1439```14401441#### Performance issues / Slow response1442**Symptom**: Operations take longer than expected14431444**Solutions**:14451. **Enable caching** (default, but verify):1446 - Editor caching: 100ms TTL1447 - Audio analysis: 50ms TTL144814492. **Use headless mode** for faster operation:1450 ```json1451 // config.json1452 { "headless": true }1453 ```145414553. **Batch operations**:1456 ```1457 Instead of:1458 - Add drums1459 - Add bass1460 - Add melody14611462 Do:1463 - Generate complete pattern with drums, bass, and melody1464 ```146514664. **Reduce browser overhead**:1467 - Close other browser instances1468 - Disable browser DevTools1469 - Use resource blocking (enabled by default)14701471#### Patterns not saving1472**Symptom**: `save` command fails or patterns don't persist14731474**Solutions**:1475```bash1476# Check patterns directory exists1477ls -la ./patterns14781479# Create manually if needed1480mkdir -p ./patterns14811482# Verify write permissions1483touch ./patterns/test.json1484rm ./patterns/test.json14851486# Check for invalid pattern names1487# Valid: "techno-beat-1", "my_pattern", "track001"1488# Invalid: "pattern/with/slashes", "name:with:colons"1489```14901491### Platform-Specific Issues14921493#### macOS1494```bash1495# Keyboard shortcut uses Meta (Cmd) key1496# Already handled by ControlOrMeta14971498# If Chromium crashes on M1/M2:1499npx playwright install chromium --with-deps1500```15011502#### Linux1503```bash1504# Install system dependencies1505sudo npx playwright install-deps chromium15061507# If running in Docker/headless environment:1508# Ensure config.json has headless: true1509```15101511#### Windows1512```bash1513# Use PowerShell or Git Bash1514# Paths should use forward slashes in config.json15151516# If Chromium doesn't launch:1517npx playwright install chromium1518```15191520### Debugging Tips15211522**Enable Verbose Logging**1523```bash1524# Set environment variable1525DEBUG=* node dist/index.js15261527# Or in Claude:1528You: Enable detailed logging for the next operation1529```15301531**Check Browser State**1532```1533You: Show me the current browser initialization state1534 and any cached patterns15351536Claude: Browser state:1537- Initialized: true1538- Cached patterns: 21539- Undo stack depth: 51540- Last operation: write_pattern (2.5s ago)1541```15421543**Validate Pattern Syntax**1544```1545You: Before playing, validate this pattern syntax:1546 s("bd*4, ~ cp ~ cp")15471548Claude: [Checks syntax]1549Valid Strudel pattern.1550Ready to play.1551```15521553### Getting Help15541555If you encounter issues not covered here:155615571. **Check existing issues**: [GitHub Issues](https://github.com/williamzujkowski/strudel-mcp-server/issues)15582. **Run integration tests**: `npm run test:integration`15593. **Enable debug mode**: `DEBUG=* npm start`15604. **Consult Strudel docs**: [Strudel.cc documentation](https://strudel.cc/learn)15615. **Create new issue**: Include error messages, OS, Node version, and steps to reproduce15621563## π€ Contributing15641565**We need your help!** This project is actively developed and welcomes contributions of all kinds:15661567### Ways to Contribute1568- **Report Bugs**: Found an issue? [Open a bug report](https://github.com/williamzujkowski/strudel-mcp-server/issues/new)1569- **Suggest Features**: Have ideas? [Create a feature request](https://github.com/williamzujkowski/strudel-mcp-server/issues/new)1570- **Improve Docs**: Fix typos, add examples, clarify confusing sections1571- **Write Tests**: Help us reach 80% coverage (currently 78%)1572- **Fix Issues**: Check [open issues](https://github.com/williamzujkowski/strudel-mcp-server/issues) for bugs to fix1573- **Add Features**: Implement new tools or improve existing ones15741575### Quick Start for Contributors15761. Fork the repository15772. Create a feature branch (`git checkout -b feature/amazing-feature`)15783. Make your changes and add tests15794. Ensure tests pass (`npm test`)15805. Commit with clear messages (`git commit -m 'fix: resolve audio analysis bug'`)15816. Push to your fork (`git push origin feature/amazing-feature`)15827. Open a Pull Request15831584**First time contributor?** Look for issues labeled `good-first-issue` or `help-wanted`.15851586### Feedback Welcome1587- Questions? Open a [Discussion](https://github.com/williamzujkowski/strudel-mcp-server/discussions)1588- Found something confusing? Tell us!1589- Have a use case we haven't considered? Share it!15901591We review PRs promptly and welcome contributors of all skill levels. See [DEVELOPMENT.md](DEVELOPMENT.md) for detailed setup instructions.15921593## π License15941595MIT License - see [LICENSE](LICENSE) file15961597## π Acknowledgments15981599- [Strudel.cc](https://strudel.cc) - Amazing live coding environment1600- [TidalCycles](https://tidalcycles.org) - Pattern language inspiration1601- [Anthropic](https://anthropic.com) - Claude AI and MCP protocol1602- [Playwright](https://playwright.dev) - Reliable browser automation16031604---16051606**v2.4.0** - Open Source | Experimental | [Report Issues](https://github.com/williamzujkowski/strudel-mcp-server/issues) | [Contribute](https://github.com/williamzujkowski/strudel-mcp-server/pulls)16071608*This project is under active development. Core features work, but expect bugs and breaking changes. Not recommended for production use.*
Full transparency β inspect the skill content before installing.