Skip to main content
Glama
README.md
# aimusic-studio

**A MIDI workspace an AI agent and a human can drive together.**

The agent talks to you in your terminal. This gives it a window: a multi-track
timeline, a piano roll you can actually edit, velocity, track filters, a theory
layer, and a two-way channel so it knows what you just changed.

![piano roll + velocity + multi-track timeline](docs/screenshot.png)

![grand staff notation view](docs/score.png)

```bash
# straight from GitHub (works now)
pip install "git+https://github.com/AxelBeary/aimusic-studio"

# or, once it is on PyPI:
pip install aimusic-studio

aimusic-studio --root ~/Music/project
```

That's it. No Node, no bundler, no build step. It opens a browser tab.

---

## Why this exists

Coding agents got Cursor. Music agents got nothing — you either write a score in
code and *hope*, or you use a DAW that has no idea an agent exists.

Two things are missing, and they're different problems:

| Problem | Solution |
|---|---|
| The agent can't *show* you what it did | this window |
| You can't *tell* the agent what you just changed | this window, read back by tools |

## What it does

### See
- multi-track timeline with one lane per track
- piano roll with a real keyboard column and bar numbers from the MIDI time signature
- **bars follow time-signature changes** (4/4 → 3/4 is drawn at the right place)
- velocity lane, one bar per note
- track list with instrument names, note counts, volume/pan readout

### Edit notes
- drag a note to move (pitch + time), drag its right edge to resize
- **double-click empty space** (or use the pencil tool) to add a note
- **right-click** a note, or Delete, to remove notes
- Shift+click / drag to multi-select; move a whole selection at once
- drag velocity bars up/down; paint several at once
- copy / paste / duplicate, undo / redo (snapshot based, 40 steps)
- grid snap: off, 1/64 … 1/2, bar — computed in **ticks** through the tempo map,
  so a piece with tempo changes still snaps musically

### Edit in bulk (one click each)
transpose ±1 / ±8va · quantize (position, duration, velocity) · legato ·
staccato · fixed length · humanize · reverse · velocity ramp up/down ·
scale velocity · swing 50%/100% · snap to scale · insert/delete a time range

### Tracks
- mute / solo (affects display, export and the re-rendered preview)
- show / hide, rename, change GM program
- filter by instrument: pick a GM category or a specific program, or search by name
- drum tracks are recognised from channel 10 and labelled `Drums`
- **mixer**: per-track volume / pan (written back as CC7/CC10), mute, solo,
  and "listen to the mix" (renders from MIDI with those settings)

### Controller lanes (automation)
- a lane switch under the roll: **velocity, CC1 modulation, CC2 breath,
  CC7 volume, CC10 pan, CC11 expression, CC64 sustain, CC71 resonance,
  CC74 brightness, pitch bend**
- click empty space to add a point, drag to shape, right-click to delete
- written back to the MIDI as real CC / pitch-wheel events; external
  controllers' CC messages land in the selected lane while you play

### Record & play
- **metronome** that follows the tempo map (accent on bar starts)
- **Web MIDI input**: connect a keyboard, hear it through WebAudio, and
  **record** what you play into the current track (grid-snapped)
- **tempo / time signature / markers** editor — writes back to the MIDI
- **version history**: every save is recorded per root piece; reopen any version
- **stem export**: one WAV per track plus a mixdown, respecting mute/solo/volume
- **real-time preview**: a WebAudio synth plays the whole arrangement immediately
  (simple triangle voices — for checking, not for listening)

### Arrangement (clips & sections)
- **clips**: box-select a range, "用选区建 Clip" stamps a coloured block on the
  timeline lane; drag the block to move its notes, right-click to drop the block
  (notes stay), double-click to rename
- **sections**: named ranges with a role (intro / verse / chorus / bridge / outro),
  drawn across the ruler; a panel lists and deletes them
- clips and sections live in the project file, not in the MIDI

### Drum grid
- for drum tracks (channel 10): a 16th-note step grid over two bars (or the loop
  region) — click to toggle a hit, one row per GM drum key

### Waveform
- the audio file's envelope is drawn behind the timeline, so you can see the
  song's shape while you edit the MIDI
- decoded in the browser (mp3 / ogg / wav / flac), with a server-side WAV
  fallback for headless use

### Score view
- toggle **乐谱** for a grand staff (treble above C4, bass below) with barlines,
  measure numbers, accidentals, ledger lines, stems and simple beams
- it is a *reading* view built from the same document — no music-font engine,
  no ties/dots/tuplets; edits still happen in the piano roll

### Theory
- scale snapping (15 scales) so "write it in C lydian" is an operation, not a wish
- key detection (Krumhansl-Schmuckler) shown in the hint bar
- insert a chord at the playhead: `Cmaj7`, `Am7`, `F#dim` …
- 7 diatonic triads with roman numerals (used by the chord helper)

### Save — safely
- every write goes to **a new file** under `.aimusic-studio/edits/`
- **your source MIDI is never opened for writing.** Not configurable.
- one all-or-nothing patch: unknown note ids are rejected as a whole, so a
  half-applied file can never happen
- optimistic locking: if the file changed since you loaded it, the save is
  refused (409) instead of silently overwriting someone else's work
- the window notices when the file changes on disk and reloads itself when you
  have nothing unsaved

### Agent integration
- same operation layer behind the browser, the CLI and MCP
- 18 MCP tools (act + read + hear)
- a chat pane in the window, for when you want to work full-screen

---

## Install

```bash
pip install aimusic-studio

# optional: rendered preview needs FluidSynth + a SoundFont
export AIMUSIC_SOUNDFONT=/path/to/GM.sf2
export AIMUSIC_FLUIDSYNTH=/usr/bin/fluidsynth
```

Python 3.10+. Only hard dependency is `mido`. `numpy` (optional) makes the
audio-alignment estimate faster; without it there is a slower fallback.

Preview degrades gracefully: without a soundfont the editor works, the preview
button explains what is missing.

## Use

```bash
aimusic-studio                      # discover ./music or cwd, open the window
aimusic-studio --root D:/scores     # point at a library
aimusic-studio --midi sketch.mid    # one file
aimusic-studio check                # diagnose the environment
```

`--root` works before *or* after the subcommand. MSYS paths (`/e/music`) work on Windows.

### CLI verbs

| Command | Direction | Meaning |
|---|---|---|
| `open [--say TEXT]` | — | start the server, open the browser |
| `serve` | — | server only, no browser |
| `say TEXT` | agent → window | post a message into the chat pane |
| `listen [--wait N]` | window → agent | block until the human speaks |
| `sel` | window → agent | read the human's latest selection |
| `edits` | window → agent | read **unsaved** changes the human made |
| `show PIECE` | agent → window | switch the displayed piece |
| `pieces` | — | list what was discovered |
| `info PIECE` | — | tracks, instruments, note counts (JSON) |
| `notes PIECE [filters]` | — | list notes as JSON |
| `ops` | — | every transform, one line each |
| `instruments [--search X]` | — | GM programs / drum keys |
| `apply PIECE --op X --param k=v` | — | transform + write a new MIDI |
| `add PIECE --track N --pitch P --tick T --dur D` | — | add one note |
| `delete PIECE --ids 0:12,0:15` | — | delete notes by id |
| `set-track PIECE --index N [--name/--program/--volume/--pan]` | — | track properties |
| `cc PIECE --track N --controller C --points 0:0,480:64` | — | replace one CC / pitch-bend lane |
| `meta PIECE --tempo 0:90 --marker 0:intro` | — | replace tempo / time signatures / markers |
| `history PIECE` | — | saved-version history |
| `stems PIECE` | — | one WAV per track + mixdown |
| `offset PIECE [--force]` | — | estimate audio ↔ MIDI time offset |
| `mcp` | — | run as an MCP stdio server |
| `check` | — | self-diagnose |

Filters (`notes` / `apply`): `--track`, `--program`, `--category`,
`--name-contains`, `--pitch-lo/--pitch-hi`, `--tick-lo/--tick-hi`,
`--vel-lo/--vel-hi`.

```bash
# write the whole string section up an octave, into a new file
aimusic-studio apply song --op transpose --param semitones=12 --category Strings

# quantize track 0 to 16ths, then swing it
aimusic-studio apply song --op quantize --param grid_ticks=120 --track 0
aimusic-studio apply song --op swing --param grid_ticks=120 --param strength=0.6
```

---

## Wiring into an agent

### MCP (any host)

**DSH** — edit `~/.dsh/profiles/desktop/cordis.patch.yml`:

```yaml
- insert:
    - id: mcp-aimusic
      name: "@deepseek-ai/dsh-mcp-client"
      disabled: false
      config:
        serverName: aimusic
        transport: stdio
        command: "python"
        args: ["-m", "studio.cli", "mcp", "--root", "D:/music"]
        toolCallTimeoutMs: 300000
        startupTimeoutMs: 60000
        failOnStartupError: false
```

⚠️ It must be an `insert:` block. A bare top-level entry only *overrides* an
existing entry — it will silently never mount.

**Claude Code**

```bash
claude mcp add aimusic -- python -m studio.cli mcp --root D:/music
```

**opencode** — `opencode.json`, V2 shape:

```json
{ "mcp": { "servers": { "aimusic": {
  "type": "local",
  "command": ["python", "-m", "studio.cli", "mcp", "--root", "D:/music"]
} } } }
```

### MCP tools

| Tool | Purpose |
|---|---|
| `open_window` | start the server and open the browser |
| `say` / `listen` | talk into the chat pane / block until the human speaks |
| `show_piece` / `list_pieces` | switch / enumerate |
| `get_piece` | tracks, instruments, counts, warnings |
| `read_notes` | notes as JSON with filters |
| `list_ops` / `list_instruments` | discoverable vocabulary |
| `apply_op` | transform selected notes → new file |
| `add_notes` / `delete_notes` | note-level writes → new file |
| `set_track` | rename / program / channel / volume / pan |
| `save_patch` | low-level all-or-nothing patch |
| `read_selection` | what the human selected |
| `read_pending_edits` | what the human dragged, unsaved |
| `set_cc` | replace a CC / pitch-bend lane → new file |
| `edit_meta` | replace tempo map / time signatures / markers → new file |
| `history` | saved versions of a piece |
| `render_stems` | per-track WAVs + mixdown |
| `offset` | audio ↔ MIDI alignment in seconds |
| `quick_preview` | render a preview WAV |

---

## What this is not (and why)

The architecture is a local Python process + a browser tab with zero build step.
That buys "pip install and go", and it costs three things on purpose:

- **No plugin hosting (VST/AU/CLAP).** That needs a native host and a process
  bridge; it is not a feature you can bolt onto a stdlib HTTP server.
- **No low-latency audio recording / monitoring.** Recording a microphone
  properly needs an audio device with sub-10 ms buffering, not HTTP + WebAudio.
- **No sample-accurate real-time engine.** Playback either follows your rendered
  WAV, or the built-in WebAudio synth (good enough to check notes, not to mix).

Everything else in the DAW scorecard — editing, arrangement clips, CC lanes,
tempo/keys, mixer, stems, versions, notation, metronome, MIDI in/out — is here.

## Architecture, and why it's shaped this way

```
   your agent (DSH / Claude Code / Cursor / a script)
        │                                    ▲
        │ MCP tools / CLI                    │ read_selection
        │ (act)                              │ read_pending_edits
        ▼                                    │
   ┌─────────────────────────────────────────────────┐
   │  aimusic-studio                                 │
   │  local HTTP server  ←→  self-contained web UI   │
   │  ops.py  ← one operation layer →  3 faces       │
   │  mido / FluidSynth / WebAudio  ←→  .aimusic-studio/ │
   └─────────────────────────────────────────────────┘
```

Layers, in dependency order:

```
config → library → midi → instruments
                     ↓
          edit (patch writer) ← transform ← theory
                     ↓
                    ops  →  engine (CLI/MCP)
                     ↓
                  server  →  web/app.js
```

**One operation layer, three faces.** Transpose in the browser, in the CLI and
through MCP all call `studio.transform`. If each face re-implemented it, they
would drift. This is the single most important structural decision in the package.

Three questions answered with evidence, not taste:

**1. Why not just MCP?**
MCP has no path for the human to speak unprompted. Its `elicitation` feature is
`Server -> Client -> User -> Client -> Server` — the user can only answer a
question the server is *currently asking*. Verified against the 2025-06-18 spec's
message-flow diagram. So a pull channel (the mailbox) is still needed.

**2. Why not AG-UI?**
AG-UI is the right protocol for this layer — it explicitly owns Agent↔User while
MCP owns Agent↔Tools. But it's a wire format, not a product: *you* still write
the application. Adopted its one directly useful idea — shared state converging
through single-note changes — without the runtime.

**3. Why not a DSH plugin?**
Because then Claude Code users can't use it. The plugin is twelve lines of YAML
(this README shows them); it isn't an architecture.

**Reused, not rebuilt:** `mido` (MIDI), FluidSynth (render), MCP (tools),
WebAudio (audition), GM tables (one module), Krumhansl-Schmuckler (key
detection), RFC 6902 patch semantics (convergence).

**Deliberately hand-rolled:** the piano-roll canvas. The best npm options
(`@audio-ui/react`, MIT) need React plus a build step, which turns
"`pip install` and go" into "`npm install && npm run build`". If you're already
running a bundler, that library is the first thing worth swapping in.

### One bug worth knowing about

The first version of the save path edited MIDI **delta-times**. Delta-times are
relative, so nudging one note shifted everything after it — editing 3 notes
rewrote 87. The fix is to flatten each track to absolute ticks, edit, then
recompute deltas. There is a regression test for exactly this.

## Keyboard

| Key | Action |
|---|---|
| Space | play / pause |
| Home | back to start |
| F | fit the whole piece |
| L | loop the selection |
| Q | quantize to the current grid |
| 1–7 | switch grid (1/64 … bar) |
| ↑ / ↓ | transpose a semitone |
| Shift+↑ / ↓ | transpose an octave |
| Ctrl+A | select all |
| Ctrl+C / V | copy / paste |
| Ctrl+D | duplicate in place |
| Ctrl+E | export selection as .mid |
| Delete | delete selected notes |
| Ctrl+Z / Ctrl+Shift+Z | undo / redo |
| R | record from MIDI input into the current track |
| M | metronome on / off |
| Esc | clear selection |
| Alt+drag | temporarily ignore snap |

## Development

```bash
pip install -e .[dev]
python -m pytest tests/ -q          # python side, no browser needed
node --check web/app.js             # JS syntax
node tools/e2e.mjs http://127.0.0.1:8770/   # real browser smoke (needs msedge)
```

## Safety

- source files are opened read-only, always
- edits go to a timestamped copy; nothing is overwritten
- a save is refused if the file changed underneath you (optimistic lock)
- the server binds `127.0.0.1` only
- the mailbox lives in memory; restarting clears it
- no telemetry, no network calls except what you configure

## License

MIT — see [LICENSE](LICENSE).