sheet-music-mcp / pitch-mcp
CLAUDE.md4 starsChanged 2 months agoMITView on GitHub
Last changed: 2026-11-26 · Source: https://github.com/raulkivi/sheet-music-mcp Real-time pitch detection from microphone input compared against a reference MusicXML score. Reports current score position (measure + beat), pitch accuracy in cents, and sharp/flat/on-pitch status while a singer sings. Status: Phase A (offline analysis) + Phase B (real-time, audio-driven position tracking) complete, plus UX Wave 2 (score references: musicxml_path, describe_score) and UX Wave 3 (measures ranges, start_practice, highlights), the MCP Apps Practice Coach (server microphone; structuredContent, app-only get_score_for_session; page in ui/apps/practice-coach/, see requirements…
- Installs packages
In this repository7 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- comparer-mcp/CLAUDE.mdCLAUDE.md
- musicxml-abc-mcp/CLAUDE.mdCLAUDE.md
- omr-mcp/CLAUDE.mdCLAUDE.md
- render-mcp/CLAUDE.mdCLAUDE.md
- synth-mcp/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
The file
We split this CLAUDE.md into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 91
Integration tests: must be @pytest.mark.integration.
- Very specific: line 119
sounddevicestreams fail at runtime: if libportaudio2 is absent. - Very specific: line 134
Never open a score path yourself.
- Very specific: line 148
start_practicemust not leave an orphan: If start_monitoring raises, _discard removes the session and calls stop(). - Distinctive: line 193
When you finish work or reach a milestone, update:
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
pitch-mcp — Claude Code Instructions
Last changed: 2026-11-26 · Source: https://github.com/raulkivi/sheet-music-mcp
What This Server Does
Real-time pitch detection from microphone input compared against a reference MusicXML score. Reports current score position (measure + beat), pitch accuracy in cents, and sharp/flat/on-pitch status while a singer sings.
Status: Phase A (offline analysis) + Phase B (real-time, audio-driven position tracking)
complete, plus UX Wave 2 (score references: musicxml_path, describe_score) and UX Wave 3
(measures ranges, start_practice, highlights), the MCP Apps Practice Coach (server
microphone; structuredContent, app-only get_score_for_session; page in ui/apps/practice-coach/,
see requirements IR-5b), the Setup Doctor (health_check), and the server side of a browser-microphone
mode (start_monitoring source: "pushed", app-only push_audio_chunk; no page uses it yet).
509 unit (+2 skipped) tests; 16 integration tests (-m integration: 4 offline analysis, 12
synth-to-pitch round trip that need a soundfont and synth-mcp's venv); 2 manual mic tests
(-m manual) require real hardware.
Running Tests
# From this directory
VIRTUAL_ENV= .venv/bin/pytest tests/ -v # 509 unit tests (integration/manual skipped by default)
VIRTUAL_ENV= .venv/bin/pytest tests/ -v -m integration # offline analysis + synth round trip (needs SYNTH_SOUNDFONT_PATH)
VIRTUAL_ENV= .venv/bin/pytest tests/ -v -m manual # real mic tests — skip in CIInstall dependencies: uv sync
Key Files
| File | Purpose |
src/pitch_mcp/server.py | MCP tool definitions and handlers |
src/pitch_mcp/presenter.py | structuredContent + output schemas for the Practice Coach tools |
src/pitch_mcp/health.py | Health checks mapped to the shared report (core health) |
src/pitch_mcp/ui/assets/ | practice-coach.html, setup-doctor.html; built by ui/ (npm run copy-assets), gitignored |
src/pitch_mcp/engine.py | Session management, offline/real-time orchestration, AudioSource (SoundDeviceSource, PushedChunkSource), PitchFrames (no MCP imports) |
src/pitch_mcp/pitch_detector.py | librosa pYIN backend (+ optional crepe) |
src/pitch_mcp/aligner.py | DTW (dtaidistance) alignment, accuracy classification |
src/pitch_mcp/utils.py | Note sequence extraction, metronome map, Hz↔note conversion |
docs/HANDOVER.md | Status, remaining work, definition of done |
docs/PLAN.md | Architecture decisions and rationale |
docs/requirements.md | Functional/non-functional requirements |
docs/architecture.md | Component diagram and data-flow |
Implemented Tools
| Tool | Phase | Description |
analyze_recording | A | Pre-recorded WAV + MusicXML (musicxml or musicxml_path, optional measures) → per-note accuracy report + highlights |
load_score | B | Load MusicXML (musicxml or musicxml_path, optional measures) into a session, return session_id |
start_practice | W3 | load_score + start_monitoring in one call (part, tempo_bpm, measures); no orphan session if the mic fails |
describe_score | W2 | Shared core tool: title, key, tempo, parts with IDs and ranges, without loading a session |
start_monitoring | B | Open mic stream for a session (JSON text only, no structuredContent); source: "pushed" takes browser audio instead (option B; the page does not use it yet) |
get_current_position | B | Current measure/beat/pitch/accuracy from active session |
stop_monitoring | B | Stop stream, return summary (with highlights), clean up session (timed_out: true if the idle timeout closed it); JSON text only, no structuredContent |
list_sessions | B | Open sessions: part, state (loaded/monitoring), idle seconds; JSON text only, no structuredContent |
get_score_for_session | Apps | App-only: the session's MusicXML for the Practice Coach (session_id only, no paths) |
push_audio_chunk | Apps | App-only: {session_id, pcm_b64, sample_rate} (16-bit LE mono PCM) for a pushed session → position snapshot |
list_capabilities | — | Server metadata, pitch backend version |
health_check | — | Runtime dependency status; structuredContent health report, linked to ui://pitch/setup-doctor |
Environment
- Primary pitch backend:
librosa.pyin— pure Python, no system deps, excellent for voice - Real-time (Phase B):
sounddevice+ YIN autocorrelation in worker thread, or audio the Practice Coach pushes from the browser (no PortAudio needed) - System dep:
libportaudio2required at runtime for real-time streams (Phase B only) Offline analysis (Phase A /analyze_recording) has no system deps. - MXL fixtures:
../omr-mcp/test_samples/pdmx_satb_samples/mxl/(10 SATB files)
Hard Rules
- Never
pip install— useuv syncoruv add engine.pymust not import frommcp— keeps it unit-testable- All tool handlers must be
async def - All errors →
{"error": "...", "error_code": "..."}(codes:FILE_NOT_FOUND,UNSUPPORTED_FORMAT,INVALID_INPUT,PROCESSING_FAILED,INVALID_PARAMETER,SESSION_NOT_FOUND) - Integration tests must be
@pytest.mark.integration; manual mic tests@pytest.mark.manual - Audio callback must never do I/O or locking — queue chunks to a
queue.Queueonly
MCP Server Startup Pattern
import asyncio
import mcp.server.stdio
async def _run():
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await app.run(read_stream, write_stream, app.create_initialization_options())
asyncio.run(_run())run_server() does not exist in the installed MCP SDK — use the context manager above.
Known Gotchas
crepefails to build under uv (missingpkg_resources) — keep as manual opt-in only; do not add it to default dependencies.aubiohas no Python 3.13 wheel and requireslibportaudio2+libsamplerate— uselibrosainstead for all pitch detection.sounddevicestreams fail at runtime iflibportaudio2is absent. Phase B real-time features simply won't work on machines without it; Phase A is unaffected.- This is the only stateful server. Sessions are held in the module-level
SessionRegistry(engine._registry), which has its own lock. Usethreading.Lockto protect shared state accessed by the worker thread and tool handlers. Never do I/O or take a lock inside the audio callback — only queue chunks. - Idle sessions are reaped. A
Reaperdaemon thread (started by the firstload_score) callsregistry.reap(clock())every 30 s and closes sessions idle longer thanPITCH_SESSION_IDLE_MINUTES(default 10,0= off, read once at import). Activity = creation,start_monitoring,get_current_position. Timed-out summaries are kept 1 h forstop_monitoring(timed_out: true). Test with an injected fake clock andreap(now), never with real waits;tests/conftest.pystops the reaper thread at the end of the run. - Score paths go through the core.
server._reference_score()callssheet_music_mcp_core.references.load_score()(read roots:SHEET_MUSIC_OUTPUT_ROOT, client MCP roots,SHEET_MUSIC_INPUT_ROOTS), then the samevalidate_musicxml()inline text gets. Never open a score path yourself. The core function is imported asread_scorebecauseengine.load_score(the session tool) has the same name.audio_pathis deliberately not confined (Wave 2 decision W2-3). The schemas carry bothanyOf(part/part_id) andoneOf(musicxml/musicxml_path) at the top level. analyze_recordingaccepts 16-bit PCM WAV only. Reject MP3/FLAC withUNSUPPORTED_FORMAT.measurescuts the score in the engine (_select/ScoreSession.__init__: coreselect_measures(text, measures)beforeextract_part_notes). The timeline starts at 0 s atstart; measures keep printed numbers;measure_countcounts fromstart(bar 1 withoutmeasures). The server passesmeasuresonly when given (_measures(arguments)), so existing engine calls and fakes are untouched.- Cut scores carry the tempo as a bare
<sound tempo>. music21 reads that as a MetronomeMark withnumber=NoneandnumberSoundingset;_build_metronome_mapusesnumber, elsenumberSounding, else 120. Without that, a cut score (or any score with only<sound tempo>) silently ran at 120 BPM. start_practicemust not leave an orphan. Ifstart_monitoringraises,_discardremoves the session and callsstop(). A stream that opened but failed to start is closed bySoundDeviceSource.start()itself before it raises. Tests fakesounddeviceviasys.modules(tests/test_practice.py); never open a real mic.- Highlights take both result shapes. Offline results use
expected, live historyexpected_noteand has one entry per frame;aligner.highlightsmerges consecutive entries with the same (measure, beat, pitch) into one note with the median cents. - Audio comes through an
AudioSource.ScoreSession.start(tempo_bpm, source=None)takes any object withstart(sink)/stop()/close(); the default is the module factoryengine.server_mic_source(SoundDeviceSource, which owns the stream, the queue and the worker).start_monitoring(..., source="pushed")opensengine.pushed_source()(PushedChunkSource) instead. The server-mic call stayssession.start(tempo_bpm=...)with nosourcekeyword, so fakes ofScoreSession.startwritten for it keep working. Tests inject a recording source orPushedChunkSource(clock=FakeClock())(tests/test_audio_source.py,tests/test_pushed_audio.py). - Pushed audio is analysed on the handler's thread, not queued: the
push_audio_chunkreply already reflects its chunk, and nothing can pile up. Limits: 8 000–48 000 Hz, a chunk at mostint(rate * 1.25) * 2bytes (checked on the base64 length before decoding), 25 pushes per second per session. Never persist pushed audio;stop()replaces the analysis window. - The live YIN must interpolate at the dip's minimum. It used to interpolate at the first lag
below the threshold and read every note ~40 cents flat;
test_audio_source.pypins E2–A5 within 3 cents. - The Practice Coach declares
permissions={"microphone": {}}onPRACTICE_COACH; the registry sends it as the resource's_meta.ui.permissions.microphoneinresources/listandresources/read(pinned intests/test_practice_coach.py). - Accuracy thresholds: on_pitch = ±25 cents; sharp = >+25 cents; flat = <−25 cents.
Claude Desktop Config
{
"mcpServers": {
"pitch": {
"command": "uv",
"args": ["--directory", "/path/to/pitch-mcp", "run", "pitch-mcp"]
}
}
}Document Update Policy
When you finish work or reach a milestone, update:
docs/HANDOVER.md— check off done items, add new gotchasdocs/PLAN.md— check off phase items, note changed decisionsdocs/requirements.md— update if behaviour changeddocs/architecture.md— update if implementation changed
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

