# Step 2: Typed domain models and MCP tool contracts ## Objective and prerequisites Step 1 has been reviewed and accepted: its persistent report was read and all six foundation/distribution tests independently passed. Implement Step 2 of the approved plan, not server behavior, generation, mapping data, or native writers. Read `prompts/plan.md`, `prompts/report_1.md`, and the current package/tooling. Keep the reviewed public MCP contract consistent with Section 7 of the plan. Do not delegate, commit, generate later prompts, or fabricate compatibility data. ## Owned files - Create `src/riff_groove_builder/schemas.py`. - Create `src/riff_groove_builder/errors.py`. - Create `tests/unit/test_schemas.py` and `tests/unit/test_errors.py`. - Create `tests/integration/test_contracts.py`. - Update `docs/architecture.md` with the implemented contracts. - Update `README.md` only where needed for accurate validation instructions. - Update `pyproject.toml` only if a directly used test/type dependency is needed; install only after its manifest change. - Write `prompts/report_2.md`. Keep existing foundation tests intact. Explain any additional directly necessary file. Do not change Step 1's report or the approved plan. ## Implementation details 1. Use Pydantic v2 typed models and a small explicit domain-error hierarchy. Reject unknown fields and invalid input with actionable messages. 2. Implement request and response models for exactly `list_instrument_profiles` and `generate_music` as specified by the approved plan, including the explicit success/error output-schema branches. Empty list-profile input accepts only an empty object. Expose reusable JSON Schema helpers/constants as appropriate; Step 3 must not duplicate the contract. 3. Preserve absent override fields as absent/None. Text inference, default musical intent resolution, and choosing a production profile are later work. Enforce cross-field constraints when sufficient fields are explicitly known, and clearly define which checks require resolved intent later. 4. Strictly validate numeric inputs: reject booleans as integers/numbers, non-finite values, out-of-range values, duplicate enum-list members, empty arrays, unsupported fields, and invalid part/format/profile combinations. Accept valid integer or fractional BPM values within the proposed limits. 5. Validate safe basenames, including Windows reserved device names, path separators/traversal, trailing dots/spaces, length, and the approved ASCII grammar. Filesystem root/link resolution is future service work. 6. Parse/normalize the documented key grammar for pitch classes (including conventional sharps/flats) plus major/minor. Reject unsupported modes, malformed accidentals, or contradictory key strings; test normalization. 7. Define the internal intent, score, logical-note, instrument-profile summary, and scheduled-event structures needed by the plan. Avoid speculative native fields. Define exact rational beat positions/durations using Fraction or an equally explicit rational representation; do not accumulate float timing. 8. Document the representation and units. MIDI channel numbers are 0-15; notes and CC payloads are 0-127; musical note-on velocity is 1-127; event ticks are nonnegative integers. Separate keyswitch events from musical-note roles. Intensity, if normalized to 0-1, is finite and validated rather than clamped. 9. Keep event payloads type-safe: prefer small discriminated event models or explicit valid combinations over a bag of optional/Any fields. Model stable event ordering metadata without implementing the scheduler in this step. 10. Make shared timeline/part invariants enforceable: nonempty selected parts, valid meter, unique part tracks, positive duration, valid note/event ranges. Distinguish logical musical range checks from future verified profile checks. 11. Define GenerationResult and GenerationError types matching the plan. Validate feasible result invariants (status/warnings, artifact parts/formats, positive sizes, and end >= start) without inventing fake files or inspecting disk. Runtime existence, publication, and full output coverage belong to Step 9. 12. Provide specific named domain exceptions/codes, including invalid requests, unsupported descriptions/articulations, missing profiles, unavailable native formats, output collision/IO, and serialization errors. Keep public messages actionable without exposing stack traces/private file content. 13. Keep package imports side-effect-free and dependency direction simple. No placeholders pretending to generate files, real production profiles, parser/composer, filesystem publication, or proprietary codecs. ## Required unit tests - Every generate_music parameter at valid and invalid boundaries. - Strict numeric types, NaN/infinity, duplicate/empty lists, invalid enums, unknown fields, bad profile-part associations, incompatible explicit formats. - Optional parts/formats/overrides remain unresolved when omitted. - Safe basenames including case-insensitive Windows reserved names and traversal. - Keys, meter, seed, exact rational timing, duration/intensity, event payloads, note/channel/controller ranges, and malformed combinations. - Empty list-profile input/output and valid/unavailable profile summaries. - Valid success/fallback/error results and invalid claimed result combinations. - Domain error codes and stable, useful public details. ## Required integration tests - Representative requests for each part and combined parts validate and JSON-round-trip without losing optional-field semantics. - Published input/output schemas are valid JSON Schemas and agree with the typed models for representative accepted/rejected payloads. - Valid success and error branches round-trip through their published schema. - Logical score/event structures preserve rational timing exactly in documented serialization, without depending on a production instrument map. - The existing foundation/distribution tests still pass. If importing jsonschema directly in tests, declare it directly as a development dependency rather than depending implicitly on the MCP SDK's transitive package. Use repository-standard typing without broad ignores or Any casts. ## Verification and acceptance Run focused new tests, existing relevant tests, Ruff lint/format checks, and strict mypy. Do not claim an unavailable editor test runner passed; use the known working `.venv\Scripts\python.exe -m pytest` fallback when necessary. Run the distribution test if package/dependency configuration changes. Acceptance requires one authoritative, strict, serializable contract ready for the Step 3 server and Step 4 MIDI writer. No real mapping/native evidence is required for purely synthetic model tests, and none may be invented. ## Required 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 The report must be entirely inside exactly one plain triple-backtick fence. Include changed files, model/schema design decisions, exact validation commands and pass/fail/skip counts, unresolved limits, and whether Step 3 is ready. Do not claim any server, generated music, or target application compatibility.