24 KiB
GAJ3T.MusicGen.Riff-Groove-Builder
Current status: published win-x64 MCP MIDI/fallback slice; application acceptance pending
A .NET 10 console application for a local, stdio MCP workflow that turns supported musical descriptions into MIDI. Evidence-backed native instrument files remain blocked on authorized codecs/fixtures.
The executable implements UTF-8 newline-delimited JSON-RPC and the
MCP 2025-11-25 initialization lifecycle, ping, tool discovery/call
infrastructure and per-request cancellation. Its production registry exposes
exactly list_instrument_profiles and generate_project.
Generation supports explicit AGLP/AGM/AGT/AME documented Lead profiles and
ABJ Sustain-only Bass, with real Standard
MIDI, including honestly reported MIDI fallback for unavailable native writers.
It fails unavailable mappings, missing explicit selections and unsupported ABJ
PalmMute rather than dropping roles or substituting Sustain. Core
provides instrument-neutral exact-rational composition models, validation and
deterministic planning for a documented bounded English subset.
Stdout contains protocol messages only; diagnostics go to stderr. Empty stdin
followed by EOF exits silently. Malformed input now returns explicit errors
instead of being discarded. See the protocol contract
for lifecycle, framing limits, errors and unsupported features.
There are no HTTP listeners, containers, audio, playback/device APIs, or external LLM calls. Native AGP/SDP support is not implemented. Five documentation-backed default mappings exist; no installed plugin or Cubase acceptance is claimed.
The Release Windows x64 self-contained, single-file executable is available
locally in artifacts\publish\win-x64. See local deployment
for the reproducible publish command, copyable VS Code stdio configuration,
explicit tool/profile arguments, extraction facts and the actual published-RPC
generated artifacts\examples\ame-lead-example.mid. Isolated/executable-only
launch and MIDI read-back pass on the SDK machine; a runtime-free Windows host
and all licensed-application/native acceptance remain pending.
See the text-description contract for
accepted grammar, explicit-only role/drum-subset selection, defaults and limits.
In-process callers use DescriptionParser.Parse then
CompositionPlanner.Plan(parsed.Description), or CompositionPlanner.Plan(text);
CompositionValidator.Validate also checks manually constructed models.
Failures carry actionable diagnostics and no partial composition. Logical
drum voices and articulation intentions do not imply verified product mappings.
The full documented four-bar example spans 15,360 ticks at 960 PPQ with
32 lead notes, four sustained bass notes and 48 drum hits.
Core also provides generic immutable profile validation and typed MIDI
event-intention planning (InstrumentProfileValidator.Validate,
ArticulationPlanner.Plan): keyswitch/velocity/CC combinations, explicit state,
shared lead-in, deterministic ordering and complete failure diagnostics.
These are not MIDI files or DryWetMIDI events. Generation has separate embedded
identity and versioned mapping catalogs. InstrumentCatalog.LoadEmbedded()
declares seven targets; InstrumentProfileCatalog.LoadEmbedded().Profiles is
five Documented profiles: four Lead guitars and Sustain-only Ample Bass J.
Synthetic profiles exist only in tests, requiring explicit test-only opt-in.
See the mapping contract. Infrastructure tests
do not close full Step 4: AMR/SD3 remain unavailable, ABJ PalmMute is unsupported, and installed-product
mapping/application acceptance remains unverified.
The accepted generic Step 4 infrastructure now feeds Step 5's actual type-1 MIDI writer, tested with synthetic profiles and actual write/read-back of all admitted documented profiles. This sequencing does not waive production mapping, native-format or application acceptance gates.
MCP profile discovery and generation
Initialize the process using MCP 2025-11-25, send notifications/initialized,
then use tools/list for the strict input/output schemas. Call
list_instrument_profiles with {} or {"role":"lead"} (bass/drums also
filter). Discovery returns all matching declared identities, admitted profiles,
source evidence, immutable compatibility notes and actual format capabilities.
Two unmapped identities stay visible; native writers are unavailable and all
application compatibility is unverified.
Example tools/call params (JSON, not an executable/CLI generation command):
{
"name": "generate_project",
"arguments": {
"description": "palm-muted eighth-note lead",
"outputDirectory": "D:\\MusicGenOutputs",
"projectName": "my-riff",
"formats": ["mid"],
"profiles": {
"lead": "ample-aglp-documented-defaults-2026-10-20"
},
"fallbackToMidi": false
}
}
This produces one actual D:\MusicGenOutputs\my-riff.mid and status:"complete",
with a source-only Documented compatibility warning. AME can be selected using
ample-ame-documented-defaults-2026-10-20. No role has an automatic profile
default. Missing/wrong-role/unavailable mappings and profiles for unselected
roles fail the whole request; the supported grammar is unchanged.
For an explicitly selected Lead+Bass arrangement, use e.g.
"description":"palm-muted eighth-note lead and sustained bass" with
"profiles":{"lead":"ample-agm-documented-defaults-2026-10-20","bass":"ample-abj-documented-defaults-2026-10-20"}.
One combined MIDI contains Lead channel 0 and Bass channel 1 with a shared
120-tick lead-in. Each selected role still requires an explicit profile ID.
ABJ exposes Sustain only; palm-muted bass fails unsupported_articulation.
AMR/SD3 are not substitutes or inferred defaults.
- Omitted formats mean applicable native formats plus MIDI: Lead-only requests
default to
["agp","mid"], not SDP. Explicit inapplicable formats fail. fallbackToMididefaults to true. Requesting applicable native output yieldsstatus:"fallback"and one combined real.mid, with per-target reasons and warnings. An explicitly requested MIDI file is reused, never duplicated or renamed.agp/.sdp. With fallback disabled, native requests fail preflight. MIDI-only requests work even with fallback disabled.- Results include interpreted settings/defaults, actual paths/byte counts,
per-role/per-format targets, warnings/errors and 960-PPQ lead-in timing.
MCP text content exactly matches
structuredContent;isErroris true only for failed generation results. Invalid JSON contract arguments use-32602. - Output directories are explicit absolute paths. Safe stems, semantic/profile/ format preflight and no-overwrite staging protect existing output, including races. Invalid input, MIDI limits, I/O errors and cancellation are not fallback triggers. No native placeholder files are written.
- Parsing/planning and synchronous file/library work run off the transport reader. Pings and cancellation remain responsive. DryWetMIDI serialization itself is synchronous/non-interruptible; cancellation is checked around it and before publication. Cancellation racing after publication does not undo the file. Empty directories created by a failed write may remain; unrelated files and directories are never recursively removed.
- Keep stdin open until responses arrive. EOF cancels active work; piping an entire generation conversation and immediately closing stdin is not a reliable generation client.
See the protocol/tool contract for failure fields/codes, exact schemas and scope boundaries.
Declared targets and honest mapping availability
| Instrument ID | Code | Product | Existing role |
|---|---|---|---|
ample-abj |
ABJ | Ample Bass J | Bass |
ample-aglp |
AGLP | Ample Guitar LP | Lead |
ample-agm |
AGM | Ample Guitar M | Lead |
ample-agt |
AGT | Ample Guitar T | Lead |
ample-ame |
AME | Ample Metal Eclipse | Lead |
ample-amr |
AMR | Ample Metal Ray5 | Bass |
toontrack-sd3 |
SD3 | Superior Drummer 3 | Drums |
ABJ, AGLP, AGM, AGT and AME report profile_available; AMR and SD3 remain
mapping_unavailable. Availability means an admitted Documented or Verified map,
not native-format support, plugin installation or application acceptance.
Documented means published mapping facts; Verified remains application-tested.
Production rejects Synthetic and Unverified. Select(role, profileId) preserves explicit role/profile
selection; SelectInstrument(role, instrumentId, profileId?) never substitutes
another instrument and requires a profile ID when multiple versions exist.
Acoustic/electric guitars share the existing Lead slot; no extra roles or patterns.
To add another target with the existing mechanisms, add a definition to
Generation\Instruments\instruments.json and, only after evidence review, its
versioned profiles to Generation\Profiles\instrument-profiles.json, bound by
required instrumentId and matching product name/role. Rebuild/publish to embed
changes. No product subclass, product switch, planner change, runtime profile
directory or VST scanning/loading is involved. See the mapping contract for
official documentation links, strict data validation and the admission procedure.
The explicit IDs are ample-aglp-documented-defaults-2026-10-20,
ample-agm-documented-defaults-2026-10-20, ample-agt-documented-defaults-2026-10-20,
ample-ame-documented-defaults-2026-10-20 and
ample-abj-documented-defaults-2026-10-20; none is an automatic role default.
Official non-versioned manuals and vendor demo MIDI anchor Sustain 24/PM 26,
AGLP range 40-86, AGM/AGT 40-84 and AME 36-84. AGLP/AGM/AGT Sustain accepts
musical velocities 1-126, AME 64-126, and PM 1-127. AGT uses the genuine named
A6=105 tab-play anchor, not a direct Sustain/PM performance or guessed label.
The official ABJ/ABP-shared demo anchors ABJ Sustain 24, range 35-76, musical
velocities 1-125; PM and accents 126-127 are rejected. Unsupported layers fail,
never clamp. Shared applicability is vendor-listed, not an ABJ-named performance.
The profiles disclose unknown installed versions separately from source/mapping
revisions. Immutable compatibility notes require default tuning/mapping/velocity
settings, instrument mode and MIDI Guitar mode off. Route Lead channel 0 to the
isolated product, and Bass channel 1 to ABJ. Initial articulation is unknown: explicitly pulse only the
first requested state, avoiding combined Sustain/PM switches.
The 120-tick advance/30-tick pulse at 960 PPQ is a deterministic writer policy,
not a certified plugin minimum. Sources, revision hashes, limitations and
the exact missing facts for other targets are in the mapping contract.
In-process Standard MIDI generation
Generation.Midi.MidiEventBuilder.Build(plannedEvent, cancellationToken)
translates a typed intention without assigning its absolute tick as a delta.
MidiFileBuilder.Build(composition, eventPlan, cancellationToken) validates the
composition/plan agreement and returns a DryWetMIDI MidiFile. The writer
reuses that builder; callers need not build a second copy first.
After explicitly selecting evidence-backed profiles and obtaining a successful
ArticulationPlanner.Plan result:
// composition and eventPlan are the matching validated Core results.
MidiFileWriter.WriteFile(absoluteMidiPath, composition, eventPlan, cancellationToken);
// Alternative: a caller-owned writable stream (also supports non-seekable streams).
using var stream = new MemoryStream();
MidiFileWriter.Write(stream, composition, eventPlan, cancellationToken);
// stream remains open; position is after the written data.
These APIs are in GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Midi.
There are no usable production profile defaults today; synthetic factories and
uses of the planner's explicit opt-in remain in tests. Neither writer nor server
invents synthetic profiles.
Invalid input/unsupported format values throw actionable exceptions; I/O
failures and cancellation propagate, not successful fallback results.
Output is SMF type 1, 960 PPQ, with Conductor then selected Lead,
Bass, Drums tracks, in that order. Tempo/meter stay at tick zero even with
a shared lead-in. Event channels, absolute pitches, velocities, CCs, explicit
note-offs (release velocity zero) and stable same-tick ordering are preserved.
Every track has exactly one End-of-Track at the plan's global EndTick,
including trailing rests and later switch release/reset tails.
- BPM converts to integer microseconds/quarter by nearest-integer,
midpoint-away-from-zero rounding (
123 BPM -> 487805,512 -> 117188). The unrounded quotient must be in 1..16777215, as Core already requires. - DryWetMIDI 8.0.3 takes the actual denominator, not its exponent. Its byte API supports powers of two through 128, verified by read-back. Core-valid /256 is rejected clearly, not wrapped, changed or removed from Core.
- Absolute-to-delta arithmetic is checked. Every gap must fit SMF's four-byte
VLQ, 0..268435455. Because the conductor has no events between tick zero
and its end marker, global
EndTickalso cannot exceed that value. No filler events or nonstandard five-byte deltas are inserted. The library itself accepts larger deltas, so the builder enforces this limit. - The pinned library creates End-of-Track internally. The builder reads a
library-generated empty track with
EndOfTrackStoringPolicy.Store, inserts events before its retained marker, and sets that marker's delta. Read-back tests also useStore; the library's default reader otherwise omits markers.
Write borrows the stream and is not transactional: a failed/cancelled call
may leave partial or complete bytes; the caller manages position, rollback and
disposal. WriteFile requires an explicit fully qualified destination filename
and an existing parent directory. It creates a uniquely named request-owned
.riffgroove-*.stage file beside the destination with CreateNew, serializes
and closes it, then moves with no overwrite, including late collisions.
It never deletes/replaces a pre-existing destination. Failure/cancellation
removes only its own staging file; cleanup failure throws AggregateException
with the original error, cleanup error and remaining staging path.
If serialization/cancellation and stage-stream closing both fail, both errors
are also retained in an aggregate rather than hiding the first error.
Cancellation is checked through event translation, before/after the library's synchronous serialization, and before publication. That synchronous library call is not interruptible; cancellation observed afterward prevents file publication. Publication is the commit point; a token signalled after the final check/during a successful move does not roll back a completed file. This is single-file staging, not crash-durability or multi-format transactional output. The combined multi-track arrangement is not a single-track Riffer export, AGP/SDP serialization, or proof of real plugin/Cubase import compatibility.
Prerequisites
- .NET SDK 10.0.400, as selected by
global.json.latestPatchpermits later patches in the same SDK feature band, not a different major/minor/feature band. - Access to the official NuGet feed for the initial dependency restore.
- The initial validation environment is Windows x64. No other deployment target or runtime-free deployment has been validated.
If dotnet is not on PowerShell's PATH but the standard Windows installation
exists, prepend its directory for the current shell only:
$env:PATH = 'C:\Program Files\dotnet;' + $env:PATH
dotnet --list-sdks
This does not install or modify machine-wide tooling.
Restore, build, and test
From the repository root:
dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx
dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore
dotnet publish .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\GAJ3T.MusicGen.RiffGrooveBuilder.Server.csproj -p:PublishProfile=win-x64 -o .\artifacts\publish\win-x64
dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build
dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode
Keep every project's generated packages.lock.json and the server's separate
publication packages.win-x64.lock.json in source control. Use
--locked-mode when verifying that restored dependencies match those locks.
Package versions are centralized as exact ranges in Directory.Packages.props:
| Package | Version | Use |
|---|---|---|
| Melanchall.DryWetMidi | 8.0.3 | All MIDI construction/serialization and semantic file read-back |
| xunit | 2.9.3 | Tests only |
| xunit.runner.visualstudio | 4.0.1 | Private test adapter |
| Microsoft.NET.Test.Sdk | 18.11.0 | Private test infrastructure |
These stable versions were checked against official NuGet version indexes and
package manifests. No separate coverage package is referenced; any
Microsoft.CodeCoverage lock entry is a transitive dependency of the test SDK.
To exercise a pre-initialization ping manually from PowerShell:
'{"jsonrpc":"2.0","id":1,"method":"ping"}' | & .\src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\bin\Release\net10.0\GAJ3T.MusicGen.RiffGrooveBuilder.Server.exe
$LASTEXITCODE
The server returns {"jsonrpc":"2.0","id":1,"result":{}}; the subsequent
shell command should print 0. An empty stream has no response; a blank
line is a malformed JSON frame and returns a parse error.
Project layout and boundaries
GAJ3T.MusicGen.RiffGrooveBuilder.slnx
src\
GAJ3T.MusicGen.RiffGrooveBuilder.Core\ # Dependency-free composition, articulation and generation DTOs
GAJ3T.MusicGen.RiffGrooveBuilder.Generation\ # Text/profile/MIDI service, safe writer and embedded catalogs
GAJ3T.MusicGen.RiffGrooveBuilder.Server\ # Stdio protocol, MCP session and two production tools
tests\
GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\ # Core + Generation + Server
GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\ # Composition/articulation pipeline + real Server process
docs\
local-deployment.md
format-compatibility.md
mcp-protocol.md
text-description-contract.md
articulation-mappings.md
prompts\
plan.md
step_1.md
report_1.md
step_2.md
report_2.md
step_3.md
report_3.md
step_4.md
report_4.md
All five projects target net10.0, use Microsoft.NET.Sdk, and inherit nullable
analysis, implicit usings, warnings-as-errors, and package lock-file generation.
Only Server is an executable.
Unit tests retain compiled .NET 10 assembly/dependency smoke checks, and cover bounded framing, strict UTF-8, JSON-RPC envelopes/errors/IDs, lifecycle state, typed synthetic tool schemas/results, overlapping handlers, cancellation, duplicate active IDs, admission bounds and actual I/O failure propagation. Synthetic tools exist only in test assemblies, never in the production registry. Composition units cover rational timing/overflow, grammar, defaults/conflicts, selected roles, exact patterns, range/extent validation, determinism and the 100,000 combined generated-note/hit limit (including its exact boundary).
Integration tests launch the actual built Server apphost with redirected
streams, the MCP handshake, malformed input/recovery, UTF-8 and size limits,
LF/CRLF, final non-newline frames, EOF, a bounded timeout, and process-owned
cleanup. A build target copies the Server's complete output next to the tests,
so locating its executable is independent of the test runner's current
directory. Cases run both beside the tests and in an existing unrelated OS
directory (Environment.SystemDirectory on Windows), without creating or
modifying files outside the checkout. Output/error streams are drained
concurrently; successful runs require exit code zero, valid JSON-RPC output
lines and empty or explicitly expected diagnostic-only stderr.
Additional in-process integration tests exercise the real Core parser/planner/
validator pipeline, including all roles, selected subsets, non-4/4 denominator
beats and explicit failures. New subprocess generation tests call the actual
production tools using all five admitted capabilities, including explicit
Lead+Bass arrangements, from an unrelated cwd, reopen
RPC-returned MIDI paths with DryWetMIDI, compare metadata/notes/switches/end
markers, and cover native fallback, invalid requests, missing selected mappings,
no overwrite, cancellation and protocol-only stdout.
Synthetic articulation unit/pipeline tests cover profile validation, keyswitch/
velocity/CC rules and combinations, state conflicts/transitions, exact timing,
shared multi-role lead-in, event pairing/order, final releases, immutable results,
malformed catalogs, documented admission and truthful partial availability. Data-only test
fixtures prove additional identities and multiple mapping/product versions
through the same selection/planner APIs. Their test Verified flags exercise
catalog admission, not real-world verification; fixtures are never shipped.
MIDI unit tests cover metadata rounding/limits, denominator 128/256, VLQ
boundaries, event semantics/order/pairing, borrowed streams, no-overwrite races,
owned-stage cleanup and cancellation. Actual file integration tests reuse the
existing synthetic pipeline profiles: all three roles, selected subsets, 3/8,
1,000 repeated 7/8 bars without drift, rests and later control tails. Files are
written beneath test-owned checkout directories, read with DryWetMIDI and
removed; unrelated-cwd output uses an explicit absolute destination.
Documented-profile tests additionally write/read all five profiles through the
actual MIDI writer, covering first Sustain/PM selection, repeated latches,
transitions and numeric pitch/velocity boundaries without combined/stuck switches.
Actual built and published subprocess RPC tests generate complete Lead+Bass
arrangements and one combined fallback artifact, with no stuck notes or role
substitution. These are source/format checks, not real VST or Cubase runs.
Native compatibility evidence required
See the compatibility inventory. No exact installed product versions, native fixtures, template/redistribution permission, native schemas or import acceptance have been supplied for the six requested Ample products, Superior Drummer 3, or Cubase. Documentation research now establishes the five bounded default capabilities above, not installation facts. Folder screenshots identify requested targets, not installed versions, filesystem paths or verified maps. Articulations must be verified independently per product.
Before native writers/application-verified profiles, obtain authorized minimal native fixtures, exact product/version and SD3 library/map settings, supported extension and import workflow confirmation, and verified MIDI note/keyswitch/CC/velocity/ timing/channel/state rules. Later application-level acceptance must record actual successful plugin and Cubase imports.
DryWetMIDI's Standard MIDI support is not proof of AGP or SDP compatibility. Requested extensions remain unverified for the owner's exact products, and MIDI fallback would not satisfy the full native requirement. These evidence gates block later implementation/acceptance, not generic instrument-neutral planning. Passing generic Step 4/5 tests does not satisfy the production mapping exit gate for all requested products. Documented-default source readiness is distinct from real plugin compatibility; native implementation and real application acceptance remain blocked/pending. The supported MIDI/fallback public-tool slice is implemented and published for Windows x64; runtime-free deployment acceptance is still pending.