agentleFS
raulkiviraulkivi/sheet-music-mcp/pitch-mcp/CLAUDE.md

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

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
  1. Very specific:

    Integration tests: must be @pytest.mark.integration.

    line 91
  2. Very specific:

    sounddevice streams fail at runtime: if libportaudio2 is absent.

    line 119
  3. Very specific:

    Never open a score path yourself.

    line 134
  4. Very specific:

    start_practice must not leave an orphan: If start_monitoring raises, _discard removes the session and calls stop().

    line 148
  5. Distinctive:

    When you finish work or reach a milestone, update:

    line 193

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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 CI

Install dependencies: uv sync


Key Files

FilePurpose
src/pitch_mcp/server.pyMCP tool definitions and handlers
src/pitch_mcp/presenter.pystructuredContent + output schemas for the Practice Coach tools
src/pitch_mcp/health.pyHealth 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.pySession management, offline/real-time orchestration, AudioSource (SoundDeviceSource, PushedChunkSource), PitchFrames (no MCP imports)
src/pitch_mcp/pitch_detector.pylibrosa pYIN backend (+ optional crepe)
src/pitch_mcp/aligner.pyDTW (dtaidistance) alignment, accuracy classification
src/pitch_mcp/utils.pyNote sequence extraction, metronome map, Hz↔note conversion
docs/HANDOVER.mdStatus, remaining work, definition of done
docs/PLAN.mdArchitecture decisions and rationale
docs/requirements.mdFunctional/non-functional requirements
docs/architecture.mdComponent diagram and data-flow

Implemented Tools

ToolPhaseDescription
analyze_recordingAPre-recorded WAV + MusicXML (musicxml or musicxml_path, optional measures) → per-note accuracy report + highlights
load_scoreBLoad MusicXML (musicxml or musicxml_path, optional measures) into a session, return session_id
start_practiceW3load_score + start_monitoring in one call (part, tempo_bpm, measures); no orphan session if the mic fails
describe_scoreW2Shared core tool: title, key, tempo, parts with IDs and ranges, without loading a session
start_monitoringBOpen 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_positionBCurrent measure/beat/pitch/accuracy from active session
stop_monitoringBStop stream, return summary (with highlights), clean up session (timed_out: true if the idle timeout closed it); JSON text only, no structuredContent
list_sessionsBOpen sessions: part, state (loaded/monitoring), idle seconds; JSON text only, no structuredContent
get_score_for_sessionAppsApp-only: the session's MusicXML for the Practice Coach (session_id only, no paths)
push_audio_chunkAppsApp-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: libportaudio2 required 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 — use uv sync or uv add
  • engine.py must not import from mcp — 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.Queue only

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

  • crepe fails to build under uv (missing pkg_resources) — keep as manual opt-in only; do not add it to default dependencies.
  • aubio has no Python 3.13 wheel and requires libportaudio2 + libsamplerate — use librosa instead for all pitch detection.
  • sounddevice streams fail at runtime if libportaudio2 is 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. Use threading.Lock to 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 Reaper daemon thread (started by the first load_score) calls registry.reap(clock()) every 30 s and closes sessions idle longer than PITCH_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 for stop_monitoring (timed_out: true). Test with an injected fake clock and reap(now), never with real waits; tests/conftest.py stops the reaper thread at the end of the run.
  • Score paths go through the core. server._reference_score() calls sheet_music_mcp_core.references.load_score() (read roots: SHEET_MUSIC_OUTPUT_ROOT, client MCP roots, SHEET_MUSIC_INPUT_ROOTS), then the same validate_musicxml() inline text gets. Never open a score path yourself. The core function is imported as read_score because engine.load_score (the session tool) has the same name. audio_path is deliberately not confined (Wave 2 decision W2-3). The schemas carry both anyOf (part / part_id) and oneOf (musicxml / musicxml_path) at the top level.
  • analyze_recording accepts 16-bit PCM WAV only. Reject MP3/FLAC with UNSUPPORTED_FORMAT.
  • measures cuts the score in the engine (_select / ScoreSession.__init__: core select_measures(text, measures) before extract_part_notes). The timeline starts at 0 s at start; measures keep printed numbers; measure_count counts from start (bar 1 without measures). The server passes measures only 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 with number=None and numberSounding set; _build_metronome_map uses number, else numberSounding, else 120. Without that, a cut score (or any score with only <sound tempo>) silently ran at 120 BPM.
  • start_practice must not leave an orphan. If start_monitoring raises, _discard removes the session and calls stop(). A stream that opened but failed to start is closed by SoundDeviceSource.start() itself before it raises. Tests fake sounddevice via sys.modules (tests/test_practice.py); never open a real mic.
  • Highlights take both result shapes. Offline results use expected, live history expected_note and has one entry per frame; aligner.highlights merges 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 with start(sink) / stop() / close(); the default is the module factory engine.server_mic_source (SoundDeviceSource, which owns the stream, the queue and the worker). start_monitoring(..., source="pushed") opens engine.pushed_source() (PushedChunkSource) instead. The server-mic call stays session.start(tempo_bpm=...) with no source keyword, so fakes of ScoreSession.start written for it keep working. Tests inject a recording source or PushedChunkSource(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_chunk reply already reflects its chunk, and nothing can pile up. Limits: 8 000–48 000 Hz, a chunk at most int(rate * 1.25) * 2 bytes (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.py pins E2–A5 within 3 cents.
  • The Practice Coach declares permissions={"microphone": {}} on PRACTICE_COACH; the registry sends it as the resource's _meta.ui.permissions.microphone in resources/list and resources/read (pinned in tests/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:

  1. docs/HANDOVER.md — check off done items, add new gotchas
  2. docs/PLAN.md — check off phase items, note changed decisions
  3. docs/requirements.md — update if behaviour changed
  4. docs/architecture.md — update if implementation changed

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.