8.3 KiB
Step 2: Implement stdio JSON-RPC and the MCP lifecycle
Objective and prerequisites
Step 1 has been reviewed and accepted: Release build and all eight scaffold tests pass. Read the approved plan, the Step 1 report, and existing source/tests before editing.
Implement a protocol-correct .NET 10 stdio MCP server, targeting version
2025-11-25. This step is transport/lifecycle/registry infrastructure only.
Stop before composition, real instrument profiles, generation tools or writers.
Do not create later prompts, modify orchestrator prompts/plan, commit, or delegate.
Files to create or modify
src\GAJ3T.MusicGen.RiffGrooveBuilder.Server\
Program.cs
Protocol\StdioTransport.cs
Protocol\JsonRpcDispatcher.cs
Protocol\McpSession.cs
Protocol\JsonRpcError.cs
Tools\McpToolRegistry.cs
Tools\McpToolDefinition.cs
tests\GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests\
GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.csproj
Protocol\StdioTransportTests.cs
Protocol\JsonRpcDispatcherTests.cs
Protocol\McpSessionTests.cs
tests\GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests\
Stdio\ProcessStartupTests.cs
Stdio\McpProtocolTests.cs
README.md
docs\mcp-protocol.md
prompts\report_2.md
Small directly necessary protocol/test helper files are allowed. Prefer simple typed contracts over a generic framework. Add a Server project reference to UnitTests if needed. No new package is required; use System.Text.Json and BCL. Refresh generated lock files only if the project reference change requires it.
Protocol requirements
Transport
- UTF-8, newline-delimited JSON-RPC, never
Content-Lengthframing. Serialized JSON strings may contain escaped newlines, not literal message framing newlines. Accept LF and CRLF. Flush each completed output message. - Stdout contains only complete protocol messages. Serialize writes so overlapping request work cannot interleave JSON. Diagnostics use stderr.
- Bound incoming messages while reading, not only after allocating an unbounded line. Use a documented internal limit (1 MiB is acceptable). Reject an oversized frame with an explicit bounded diagnostic/protocol error, resynchronize at its newline, and test continued operation.
- Reject invalid UTF-8 without silently substituting characters. Handle a final nonempty frame at EOF explicitly and test the documented behavior.
- EOF and Ctrl+C shut down cleanly, cancelling outstanding work and disposing only owned resources. An empty stdin stream produces no output.
JSON-RPC
- Require
jsonrpc: "2.0"and a string method for inbound requests/notifications. Validate params shape against the method. Preserve supported string/integer request IDs in responses; do not coerce strings to numbers. - Reject malformed JSON with -32700, invalid envelopes/batch arrays with -32600, unknown request methods with -32601, invalid method/tool parameters with -32602, and unexpected internal failures with -32603.
- Error response
idis null when no valid request ID can be identified. Never answer a valid notification, including unknown notifications. - Do not process JSON-RPC batches as a supported MCP feature.
- An exception boundary may report unexpected per-request failures explicitly, log details to stderr and return -32603. Do not suppress exceptions into success results or hide actual I/O failures.
Lifecycle
- Support
initialize,notifications/initialized,ping,tools/list,tools/call, andnotifications/cancelled. - Validate initialization fields per the MCP specification. Return serverInfo, supported protocolVersion and only implemented capabilities.
- Negotiate version: echo
2025-11-25when requested; otherwise return2025-11-25as the server's supported alternative. Do not claim support for other protocol versions. - Enforce initialization state and reject inappropriate requests with explicit errors. Permit ping per lifecycle rules. Reject repeated initialization.
- Use stdin closure for shutdown, not an invented
shutdownmethod. - Ignore/log unsupported notifications without replying.
- Track outstanding request IDs and propagate valid cancellation notifications to the matching active request; cancellation is not cancellation of the whole server. Keep reading notifications while a handler is awaiting work.
- Keep lifecycle changes/registry access safe when work overlaps. Distinguish requests with different ID types. Do not let duplicate active IDs cancel or replace unrelated work.
Tool registry
- Implement registration/lookup and schema serialization for tool definitions.
- Production registry is initially empty:
tools/listreturnstools: []. Do not advertise placeholder profile/generation tools. - An unknown tool is a protocol/tool-selection error, not a fake successful call.
- Provide a bounded typed handler boundary supporting input validation,
structuredContent plus text content, expected tool errors (
isError: true), and cancellation. Synthetic test-only tools can exercise these paths. - Do not implement MCP resources, prompts, sampling, logging RPCs, task APIs, HTTP, composition, or real generation in this step.
Use the primary MCP sources referenced in the plan to resolve protocol details. Document supported/unsupported methods and capability/version behavior.
Required tests
Unit tests
Cover:
- LF/CRLF framing, escaped newline content, UTF-8/non-ASCII content, invalid UTF-8, empty EOF and the documented non-newline final-frame behavior.
- Message size at/over the limit, resynchronization, complete serialized output.
- Valid string/integer IDs, malformed JSON, invalid envelopes/IDs, batch rejection, unknown methods and invalid params.
- Notifications produce no response, even unknown ones.
- Initialization success, unsupported-version negotiation, premature requests, initialized transition, repeated initialization and ping.
- Empty production registry; test-only registered tool discovery/calls and schema/content agreement; unknown tool and handler validation failures.
- A cancellable synthetic handler cancelled while awaiting work, unrelated request survival, and overlapping response serialization.
Retain the meaningful framework/dependency scaffold unit tests.
Real-process integration tests
- Update the prior input-discard startup test: only empty EOF remains silently successful. Non-JSON input must now yield a parse error, not be discarded.
- Launch the real Server apphost, negotiate initialization, send
notifications/initialized, list empty tools, ping, and close stdin. - Assert response IDs, MCP version/capabilities, per-line valid JSON, no notification reply, empty or diagnostic-only stderr, and exit code zero.
- Exercise malformed input followed by a valid request on the same connection, unknown method/tool, invalid arguments, and an unrelated working directory.
- Include timeout-bounded cleanup and concurrent draining of stdout/stderr. Never kill by process name or leave a helper running.
Validation and acceptance
Run targeted protocol tests during development, then:
dotnet build .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-restore
dotnet test .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx -c Release --no-build
dotnet restore .\GAJ3T.MusicGen.RiffGrooveBuilder.slnx --locked-mode
If changed manifests make assets stale, restore after the manifest change.
The installed SDK is at C:\Program Files\dotnet\dotnet.exe; use a process-local
PATH adjustment if needed. The editor test tool failed discovery in Step 1;
CLI xUnit execution is the verified fallback, not a skipped test.
Exit criteria: actual stdio MCP lifecycle works, all tests pass including retained scaffold coverage, no non-protocol stdout, no unimplemented tools advertised, documentation matches behavior, and no scope expansion.
Mandatory worker report
When complete, write your end-of-step report to ./prompts/report_2.md including: what was implemented, test results (pass/fail with details), any issues encountered, and whether you're ready for the next step
Put the entire report inside exactly one plain triple-backtick fence, with no outside content. Include changed files, exact commands/exit codes, test counts, protocol limits and decisions, any skipped checks, issues/blockers, and explicit Step 2 readiness. Native compatibility remains unverified and outside this step. Stop after writing the report.