17 KiB
Stdio MCP protocol and generation tools (Steps 2/8)
Scope and negotiation
The .NET 10 Server apphost implements a small local stdio MCP server using
System.Text.Json and the BCL. It supports only MCP 2025-11-25. An
initialize request for that version is echoed; any other string version
receives 2025-11-25 as the supported alternative. A client that cannot use
this version should disconnect. No network connection is made.
The only advertised capability is tools: { "listChanged": false }. The
production registry contains exactly list_instrument_profiles and
generate_project. No fake profiles, native writers or synthetic test tools
are advertised. Server identity is
GAJ3T.MusicGen.RiffGrooveBuilder, implementation version 0.2.0.
Framing and ownership
- Messages are strict UTF-8 JSON, delimited by LF or CRLF, not
Content-Lengthframing. A BOM is not removed. Invalid UTF-8 produces-32700, never replacement characters. JSON strings can contain escaped\n; a literal newline terminates the frame. - The production limit is 1,048,576 UTF-8 bytes per incoming frame, excluding
its LF or CRLF terminator. Exactly the limit is accepted. Reading uses a
fixed limit-plus-one frame buffer and a 4 KiB read buffer: an oversized
message is drained without accumulating its remainder. At its newline (or
EOF), one bounded
-32600response withid: nulland a fixed stderr diagnostic is emitted, then processing resumes at the next frame. - JSON parsing also applies
System.Text.Json's default maximum nesting depth of 64. Exceeding it returns a parse error. - An empty stream produces nothing. A nonempty final frame at EOF is processed
once, even without a trailing newline. A blank line is an empty JSON frame
and returns
-32700. An incomplete final JSON document returns-32700. - Every output is a complete compact JSON-RPC object followed by LF and a flush. A write lock prevents concurrent responses from interleaving. A write already in progress is not truncated by request cancellation.
- The transport borrows its streams; the entry point owns/disposes the streams it opens. It never disposes the caller's diagnostic writer.
- EOF or Ctrl+C cancels active work and awaits its cancellation/cleanup. There
is no
shutdownRPC. Fatal input/output failures are written to stderr and exit with code 1; normal EOF/cancellation exits with code 0. Per-request unexpected failures return-32603and diagnostic details only on stderr.
Methods and lifecycle
| Method | Behavior |
|---|---|
initialize |
Request, once only. Requires object params containing string protocolVersion, object capabilities, and clientInfo with string name and version. Optional known metadata/capability fields are type-checked, including icons and nested client capability objects. Unknown client capability keys are allowed but never used. Successful initialization waits for notifications/initialized. |
notifications/initialized |
Notification with omitted or empty object params (optional object _meta). Transitions an initialized session to ready. Out-of-order, repeated or invalid notifications are ignored with a diagnostic and no response. |
ping |
Request allowed before, during and after initialization. Omitted/empty object params, optional _meta; returns {}. |
tools/list |
Requires ready state. Omitted/empty object params, optional _meta; returns the two production tools in stable name order with input/output schemas. No pagination cursor is issued; any supplied cursor is rejected. |
tools/call |
Requires ready state and object params with string name, optional object arguments (defaults to {}), optional _meta. Unknown tool or invalid arguments return -32602. |
notifications/cancelled |
Validates requestId and optional string reason. Cancels only the matching active request, never initialize or the server. Malformed, unknown or completed IDs are ignored. Reasons are not echoed. No notification response; a cancelled request normally has no response either. |
Fixed method params reject unknown members (including task augmentation);
_meta accepts extension fields, and request _meta.progressToken, if present,
must be a string or number. Client capabilities and implementation metadata
are not fetched or acted on. Tools cannot run before the complete handshake.
Known tool requests in the wrong state return -32002. Repeated initialization
returns -32002. Unknown request methods always return -32601, including
request-shaped notification methods.
Valid notifications never receive a response, including unsupported methods and requests mistakenly sent without an ID. Unsupported notifications are ignored with a fixed diagnostic; they cannot initialize or invoke a tool. Malformed envelopes are invalid requests, not valid notifications.
Resources, prompts, sampling, elicitation, logging RPCs, progress emission, task APIs, HTTP, server-initiated requests, and list-change notifications are not implemented or advertised.
JSON-RPC validation and errors
Requests/notifications require jsonrpc: "2.0" and a string method. Requests
use a string or signed 64-bit integer ID. String and numeric IDs are distinct;
responses preserve their values and types, not necessarily JSON escape spelling.
Null, boolean, fractional/exponent/decimal numeric IDs and integers outside
Int64 are unsupported. An unambiguous valid ID is preserved on an invalid
envelope; otherwise error id is null. Duplicate envelope member names and
batch arrays are rejected; MCP batch execution is not supported.
| Code | Meaning |
|---|---|
-32700 |
Malformed JSON, blank frame, or invalid UTF-8 |
-32600 |
Invalid envelope/ID, batch, duplicate active request ID, oversized frame |
-32601 |
Unknown request method |
-32602 |
Invalid method params, unknown tool, invalid typed/semantic tool arguments or cursor |
-32603 |
Unexpected handler/result-serialization failure |
-32002 |
Inappropriate lifecycle state |
-32000 |
Request admission limit reached |
There are at most 64 active requests. Excess requests get an explicit
bounded error without blocking notification dispatch. The ID table never
replaces an active request: a duplicate receives -32600 without cancelling or
overwriting the original. Async tool work does not block reading cancellation
or unrelated requests. Responses may complete out of order. Once a response
write has started, cancellation may race with its delivery; clients must
tolerate a late response. Registry snapshots and lifecycle/ID state are
synchronized.
Typed tool boundary
Registration is internal application setup, not a user plugin/RPC feature. Register uniquely named definitions before creating the session; the session freezes the registry and does not emit list-change notifications.
McpToolDefinition<TInput,TOutput> uses non-null object DTO contracts. The same
strict camel-case serializer options generate output/default input JSON Schemas
with the .NET JSON Schema exporter (default JSON Schema 2020-12), deserialize
arguments and serialize results. Required constructor members, non-nullable
properties, types, duplicate properties and unknown members are validated.
Optional semantic validation raises McpToolInputException for -32602.
Enums serialize as camel-case strings, never integers. Production tools supply
explicit constrained input schemas, matching validators (including exact enum
case, non-null optional inputs, uniqueness and nested profiles), and a small
output-schema refinement for successful versus failed generation.
This remains a typed boundary, not a general-purpose arbitrary JSON Schema
engine; domain constraints are enforced by the registered validator/handler.
Handlers accept a request-scoped CancellationToken and must honor it and
clean up owned resources. They return McpToolOutcome<TOutput>: the emitted
object contains structuredContent, an identical serialized JSON text block
in content, and isError. Expected execution failures explicitly return a
typed schema-conforming outcome with isError: true; unexpected exceptions
never become successful tool results.
Production tools (Step 8)
list_instrument_profiles
The optional role is exactly lead, bass or drums. Omit it for all;
explicit null, integers, other casing and unknown fields are invalid params.
Output includes:
instruments: stableid,vendor,productCode,displayName,role,documentationUrl,availability(profile_available/mapping_unavailable).profiles:id,instrumentId, role/product/version/mapping revision,playableRange(absolute minimum/maximum pitches), zero-basedchannel,articulations(mechanisms, velocity constraints, behavior, explicit switch/ controller/voice data),evidence,compatibilityNotes,nativeFormats, andnativeStatus:"unverified".formats:midhaswriterStatus:"implemented";agp/sdphavewriterStatus:"unavailable". EachapplicationStatusisunverified.
Seven declared identities and five Documented profiles are currently exposed: AGLP/AGM/AGT/AME Lead Sustain/PalmMute, ABJ Bass Sustain only. AMR and SD3 have no admitted map. ABJ discovery advertises one articulation, musical velocities 1-125 and zero-based channel 1; Lead uses channel 0. Documented means source-backed, not installed/application-verified; no synthetic/test fixture is exposed. Native format applicability is not writer availability or application acceptance. The embedded catalog is independent of cwd; runtime profile/VST loading is absent.
generate_project
| Input | Contract |
|---|---|
description |
Required string, 1..16384 characters; the bounded grammar applies |
outputDirectory |
Required nonempty string; explicit absolute filesystem directory, no traversal/device syntax |
projectName |
Required nonempty safe filename stem; no separators, traversal, reserved devices, alternate streams, trailing dot/space |
formats |
Optional nonempty unique array of exact strings agp, sdp, mid; omit for applicable native formats plus MIDI |
profiles |
Optional fixed object with optional nonempty string lead, bass, drums profile IDs; every selected role needs an explicit matching admitted ID |
fallbackToMidi |
Optional boolean, defaults true |
All fixed request/nested objects reject unknown/duplicate members. Supplied null
fields are not accepted. There is no automatic profile default or substitution.
Only explicitly selected roles are resolved; profiles for unselected roles fail.
Text that omits roles still follows the grammar's three-role default and fails
missing explicit Lead/Bass selections and unavailable Drums instead of silently
removing them. Missing Bass selection now returns no_default_profile, not
mapping_unavailable; unmapped Drums still returns mapping_unavailable.
Explicit ABJ PalmMute fails unsupported_articulation, never Sustain fallback.
Role-to-instrument binding is resolved from the admitted profile, not user folders.
The structured result has all of these required keys:
status: complete | fallback | failed
interpretedComposition: { tempoBpm, meter, key, bars, roles, defaultsApplied } | null
artifacts: [{ format, roles, absolutePath, byteCount, profileIds }]
targets: [{
role, instrumentId, profileId, requestedFormat, outcome,
artifactPaths, reasonCode, message
}]
warnings: [{ code, message, role, requestedFormat }]
errors: [{ code, message, field, role }]
timing: { ticksPerQuarterNote, leadInTicks } | null
Enums are strings (target outcome: written, fallback, failed). Nullable
identity/reason/diagnostic fields are serialized explicitly as null, not omitted.
Early failures have null interpreted composition/timing. Other failures can retain
successful interpretation/planning details. The advertised conditional output
schema allows null composition/timing only for failed, requires nonempty
artifacts/targets and empty errors for success, and no artifacts plus nonempty
errors for failure. Artifact byte counts and absolute paths describe real,
nonempty files. Every applicable role/requested-format pair has a target; combined
MIDI targets share one path. Inapplicable requested formats instead fail globally.
Structured content is repeated byte-for-byte as serialized JSON in one text block;
isError is true only for failed, false for complete and fallback.
agp applies to selected Lead/Bass; sdp to selected Drums. Lead-only omitted
formats therefore mean AGP+MIDI, not SDP. Explicit inapplicable formats fail.
Both native writers are absent: applicable native requests with fallback enabled
write exactly one <projectName>.mid for the complete selected event plan.
An explicit MIDI request reuses that artifact. Each native target reports
native_writer_unavailable, and a warning discloses unverified compatibility.
There are no native files/placeholders/renamed MIDI files. With fallback disabled,
native requests fail before directory creation/output; MIDI-only still succeeds.
Every selected Documented mapping produces a warning containing source-only
status and the exact version/configuration/routing/timing compatibility notes.
Expected domain failures return status:"failed", no artifacts, actionable
errors and failed targets with no usable paths. Codes include
no_default_profile (with available IDs), unknown_profile,
profile_role_mismatch, unselected_role_profile, mapping_unavailable,
inapplicable_format, native_fallback_disabled, invalid_formats,
invalid_output_path, parser/planner diagnostics, midi_not_supported,
output_exists, and output_io_error. Contract/JSON violations use -32602
instead. Invalid mappings/text, MIDI limitations, I/O, cancellation and unexpected
exceptions never trigger native fallback. Unexpected failures use the existing
logged -32603 boundary, with details on stderr only.
Semantic/profile/native-format and shared MIDI meter/extent preflight occur before directory creation. Generation calls the real staged no-overwrite MIDI writer; early existence checks are not the race-safety mechanism. Only this request's staging file is cleaned on failure/cancellation; existing destinations, other requests' files and unrelated files are preserved. A created directory may remain empty after an I/O failure. Cleanup/close failures retain aggregate diagnostics and any remaining staging path at the logged error boundary.
Generation runs on a thread-pool worker, including text planning, profile/event planning and synchronous filesystem/DryWetMIDI work. The reader stays available for ping and cancellation; deterministic blocked-work unit tests verify this even when tiny real requests finish too quickly. Cancellation propagates without a tool response and is checked before publication. The library's synchronous serialization has no cancellation API; a token cannot interrupt that call but observed cancellation afterward prevents publication and cleans staging. Publication is the commit point; cancellation racing after the last check/move does not roll back the committed file. EOF cancels active requests: clients must keep stdin open and wait for responses before closing it.
Validation and primary references
Unit tests cover framing at/over the limit, strict UTF-8/EOF, serialized flushed writes, envelopes and error codes, negotiation/state, schemas/results, test-only handlers, cancellation with unrelated work surviving, duplicate typed IDs, admission limits and fatal I/O. Real-apphost tests cover handshake, notification silence, malformed-frame recovery, unknown methods/tools, invalid params, LF/CRLF, Unicode IDs, exact-limit/oversized/invalid-UTF-8 frames and final frames at EOF from both test-output and unrelated working directories. Production-tool tests add strict schemas versus serialized results, discovery/ filtering, real RPC-generated MIDI read-back for all five admitted capabilities and complete Lead+Bass arrangements, native fallback and disabled fallback, selected-role/mapping failures, collisions, responsive ping/cancellation and unchanged stdout purity. All subprocess tests concurrently drain stdout/stderr and enforce bounded, process-owned cleanup. Lifetime-token cancellation (the Ctrl+C code path) is unit-tested; sending an actual interactive Windows console Ctrl+C event is not an automated apphost test.
Primary MCP 2025-11-25 sources:
Native compatibility and full product readiness remain unverified; see the evidence inventory. Publication and actual plugin/Cubase acceptance belong to later steps.