synth-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- synth_mcp/__init__.py +1 -0
- synth_mcp/engine.py +273 -0
- synth_mcp/server.py +234 -0
- synth_mcp/utils.py +61 -0
- synth_mcp-0.1.0.dist-info/METADATA +26 -0
- synth_mcp-0.1.0.dist-info/RECORD +8 -0
- synth_mcp-0.1.0.dist-info/WHEEL +4 -0
- synth_mcp-0.1.0.dist-info/entry_points.txt +2 -0
synth_mcp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
synth_mcp/engine.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core synthesis engine for synth-mcp.
|
|
3
|
+
|
|
4
|
+
No MCP SDK imports here — this module is independently unit-testable.
|
|
5
|
+
|
|
6
|
+
Pipeline:
|
|
7
|
+
MusicXML string
|
|
8
|
+
→ parse_parts() → list of part metadata dicts
|
|
9
|
+
→ extract_midi() → MIDI bytes
|
|
10
|
+
→ synthesize_midi() → WAV file at output_path, returns duration (seconds)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import copy
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import tempfile
|
|
17
|
+
import wave
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ProcessingError(Exception):
|
|
25
|
+
"""Raised when a synthesis step fails in an expected, reportable way."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str, error_code: str = "PROCESSING_FAILED"):
|
|
28
|
+
super().__init__(message)
|
|
29
|
+
self.error_code = error_code
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------------------------------------------------------------------------
|
|
33
|
+
# Step 1 — parse parts
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
def parse_parts(musicxml_str: str) -> list[dict]:
|
|
37
|
+
"""Parse a MusicXML string and return metadata for each voice part.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
List of dicts: [{"id": "P1", "name": "Soprano", "measure_count": 32}, ...]
|
|
41
|
+
|
|
42
|
+
Raises:
|
|
43
|
+
ProcessingError: on parse failure or empty score.
|
|
44
|
+
"""
|
|
45
|
+
try:
|
|
46
|
+
import music21.converter # noqa: F401 — verify availability
|
|
47
|
+
except ImportError as e:
|
|
48
|
+
raise ProcessingError(f"music21 is not available: {e}", "PROCESSING_FAILED")
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
import music21
|
|
52
|
+
score = music21.converter.parseData(musicxml_str, format="musicxml")
|
|
53
|
+
except Exception as e:
|
|
54
|
+
raise ProcessingError(f"Failed to parse MusicXML: {e}", "INVALID_INPUT")
|
|
55
|
+
|
|
56
|
+
parts = list(score.parts)
|
|
57
|
+
if not parts:
|
|
58
|
+
raise ProcessingError(
|
|
59
|
+
"No parts found in score. Verify the MusicXML contains <part> elements.",
|
|
60
|
+
"INVALID_INPUT",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
result = []
|
|
64
|
+
for part in parts:
|
|
65
|
+
measure_count = len(list(part.getElementsByClass("Measure")))
|
|
66
|
+
result.append(
|
|
67
|
+
{
|
|
68
|
+
"id": part.id,
|
|
69
|
+
"name": part.partName or part.id,
|
|
70
|
+
"measure_count": measure_count,
|
|
71
|
+
}
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return result
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------------------
|
|
78
|
+
# Step 2 — extract MIDI
|
|
79
|
+
# ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
def extract_midi(
|
|
82
|
+
musicxml_str: str,
|
|
83
|
+
part_ids: Optional[list[str]],
|
|
84
|
+
tempo_factor: float,
|
|
85
|
+
) -> bytes:
|
|
86
|
+
"""Export selected parts of a MusicXML score to MIDI bytes.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
musicxml_str: MusicXML document as a string.
|
|
90
|
+
part_ids: Part IDs to include; None means all parts.
|
|
91
|
+
tempo_factor: Tempo multiplier applied to all MetronomeMarks (0.25–4.0).
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
Raw MIDI file bytes.
|
|
95
|
+
|
|
96
|
+
Raises:
|
|
97
|
+
ProcessingError: on parse error, invalid part ID, or MIDI export failure.
|
|
98
|
+
"""
|
|
99
|
+
try:
|
|
100
|
+
import music21
|
|
101
|
+
import music21.converter
|
|
102
|
+
import music21.midi.translate
|
|
103
|
+
import music21.stream
|
|
104
|
+
import music21.tempo
|
|
105
|
+
except ImportError as e:
|
|
106
|
+
raise ProcessingError(f"music21 is not available: {e}", "PROCESSING_FAILED")
|
|
107
|
+
|
|
108
|
+
try:
|
|
109
|
+
score = music21.converter.parseData(musicxml_str, format="musicxml")
|
|
110
|
+
except Exception as e:
|
|
111
|
+
raise ProcessingError(f"Failed to parse MusicXML: {e}", "INVALID_INPUT")
|
|
112
|
+
|
|
113
|
+
all_parts = list(score.parts)
|
|
114
|
+
if not all_parts:
|
|
115
|
+
raise ProcessingError("No parts found in score", "INVALID_INPUT")
|
|
116
|
+
|
|
117
|
+
# Validate and filter by part_ids
|
|
118
|
+
if part_ids is not None:
|
|
119
|
+
available_ids = {p.id for p in all_parts}
|
|
120
|
+
invalid = [pid for pid in part_ids if pid not in available_ids]
|
|
121
|
+
if invalid:
|
|
122
|
+
raise ProcessingError(
|
|
123
|
+
f"Invalid part IDs: {invalid}. Valid IDs: {sorted(available_ids)}",
|
|
124
|
+
"INVALID_PARAMETER",
|
|
125
|
+
)
|
|
126
|
+
selected = [p for p in all_parts if p.id in part_ids]
|
|
127
|
+
else:
|
|
128
|
+
selected = all_parts
|
|
129
|
+
|
|
130
|
+
# Build a new score from deep-copied parts so we don't mutate the original
|
|
131
|
+
new_score = music21.stream.Score()
|
|
132
|
+
for part in selected:
|
|
133
|
+
new_score.append(copy.deepcopy(part))
|
|
134
|
+
|
|
135
|
+
# Apply tempo factor to all MetronomeMarks
|
|
136
|
+
if tempo_factor != 1.0:
|
|
137
|
+
marks = list(new_score.recurse().getElementsByClass(music21.tempo.MetronomeMark))
|
|
138
|
+
if marks:
|
|
139
|
+
for mm in marks:
|
|
140
|
+
if mm.number is not None:
|
|
141
|
+
mm.number = mm.number * tempo_factor
|
|
142
|
+
else:
|
|
143
|
+
# No explicit tempo — insert a scaled default (120 BPM) at measure 1
|
|
144
|
+
first_part = new_score.parts[0]
|
|
145
|
+
measures = list(first_part.getElementsByClass("Measure"))
|
|
146
|
+
if measures:
|
|
147
|
+
mm = music21.tempo.MetronomeMark(number=120.0 * tempo_factor)
|
|
148
|
+
measures[0].insert(0, mm)
|
|
149
|
+
|
|
150
|
+
# Export to MIDI bytes via a temp file
|
|
151
|
+
try:
|
|
152
|
+
midi_file = music21.midi.translate.streamToMidiFile(new_score)
|
|
153
|
+
with tempfile.NamedTemporaryFile(suffix=".mid", delete=False) as f:
|
|
154
|
+
tmp_path = f.name
|
|
155
|
+
try:
|
|
156
|
+
midi_file.open(tmp_path, "wb")
|
|
157
|
+
midi_file.write()
|
|
158
|
+
midi_file.close()
|
|
159
|
+
with open(tmp_path, "rb") as f:
|
|
160
|
+
return f.read()
|
|
161
|
+
finally:
|
|
162
|
+
Path(tmp_path).unlink(missing_ok=True)
|
|
163
|
+
except Exception as e:
|
|
164
|
+
raise ProcessingError(f"Failed to export MIDI: {e}", "PROCESSING_FAILED")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---------------------------------------------------------------------------
|
|
168
|
+
# Step 3 — synthesize to WAV
|
|
169
|
+
# ---------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
def synthesize_midi(midi_bytes: bytes, output_path: str) -> float:
|
|
172
|
+
"""Render MIDI bytes to a WAV file using the FluidSynth CLI.
|
|
173
|
+
|
|
174
|
+
The soundfont is read from the SYNTH_SOUNDFONT_PATH environment variable.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
midi_bytes: Raw MIDI file bytes.
|
|
178
|
+
output_path: Destination path for the WAV file.
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
Duration of the rendered audio in seconds.
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
ProcessingError: if the soundfont is missing, FluidSynth is unavailable,
|
|
185
|
+
or rendering fails.
|
|
186
|
+
"""
|
|
187
|
+
soundfont_path = os.environ.get("SYNTH_SOUNDFONT_PATH", "")
|
|
188
|
+
if not soundfont_path:
|
|
189
|
+
raise ProcessingError(
|
|
190
|
+
"Soundfont not configured. Set SYNTH_SOUNDFONT_PATH to an SF2 file path. "
|
|
191
|
+
"Download MuseScore General from "
|
|
192
|
+
"https://musescore.org/en/handbook/soundfonts-and-sfz-files",
|
|
193
|
+
"PROCESSING_FAILED",
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
if not Path(soundfont_path).exists():
|
|
197
|
+
raise ProcessingError(
|
|
198
|
+
f"Soundfont file not found: {soundfont_path!r}. "
|
|
199
|
+
"Update SYNTH_SOUNDFONT_PATH to a valid SF2 file path.",
|
|
200
|
+
"PROCESSING_FAILED",
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
# Verify the pyfluidsynth binding (catches a missing C library early)
|
|
204
|
+
try:
|
|
205
|
+
import fluidsynth
|
|
206
|
+
except (ImportError, OSError) as e:
|
|
207
|
+
raise ProcessingError(
|
|
208
|
+
f"FluidSynth library not available: {e}. "
|
|
209
|
+
"Install libfluidsynth-dev (Linux) or brew install fluid-synth (macOS)",
|
|
210
|
+
"PROCESSING_FAILED",
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# Write MIDI bytes to a temp file for the player
|
|
214
|
+
with tempfile.NamedTemporaryFile(suffix=".mid", delete=False) as f:
|
|
215
|
+
f.write(midi_bytes)
|
|
216
|
+
tmp_midi = f.name
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
Path(output_path).parent.mkdir(parents=True, exist_ok=True)
|
|
220
|
+
|
|
221
|
+
fs = fluidsynth.Synth(
|
|
222
|
+
gain=0.5,
|
|
223
|
+
samplerate=44100,
|
|
224
|
+
**{
|
|
225
|
+
"audio.driver": "file",
|
|
226
|
+
"audio.file.name": output_path,
|
|
227
|
+
"audio.file.type": "wav",
|
|
228
|
+
"player.timing-source": "sample",
|
|
229
|
+
"synth.lock-memory": 0,
|
|
230
|
+
},
|
|
231
|
+
)
|
|
232
|
+
try:
|
|
233
|
+
sfid = fs.sfload(soundfont_path)
|
|
234
|
+
if sfid == fluidsynth.FLUID_FAILED:
|
|
235
|
+
raise ProcessingError(
|
|
236
|
+
f"Failed to load soundfont: {soundfont_path!r}",
|
|
237
|
+
"PROCESSING_FAILED",
|
|
238
|
+
)
|
|
239
|
+
fs.sfont_select(0, sfid)
|
|
240
|
+
fs.start(driver="file")
|
|
241
|
+
status = fs.play_midi_file(tmp_midi)
|
|
242
|
+
if status == fluidsynth.FLUID_FAILED:
|
|
243
|
+
raise ProcessingError("FluidSynth MIDI player failed to start", "PROCESSING_FAILED")
|
|
244
|
+
fluidsynth.fluid_player_join(fs.player)
|
|
245
|
+
finally:
|
|
246
|
+
fs.delete()
|
|
247
|
+
|
|
248
|
+
if not Path(output_path).exists():
|
|
249
|
+
raise ProcessingError(
|
|
250
|
+
"Synthesis completed but did not produce an output WAV file.",
|
|
251
|
+
"PROCESSING_FAILED",
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
return _get_wav_duration(output_path)
|
|
255
|
+
|
|
256
|
+
except ProcessingError:
|
|
257
|
+
raise
|
|
258
|
+
except Exception as e:
|
|
259
|
+
raise ProcessingError(f"Synthesis failed: {e}", "PROCESSING_FAILED")
|
|
260
|
+
finally:
|
|
261
|
+
Path(tmp_midi).unlink(missing_ok=True)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# ---------------------------------------------------------------------------
|
|
265
|
+
# Helpers
|
|
266
|
+
# ---------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
def _get_wav_duration(wav_path: str) -> float:
|
|
269
|
+
"""Return the duration of a WAV file in seconds."""
|
|
270
|
+
with wave.open(wav_path, "r") as wf:
|
|
271
|
+
frames = wf.getnframes()
|
|
272
|
+
rate = wf.getframerate()
|
|
273
|
+
return frames / rate if rate > 0 else 0.0
|
synth_mcp/server.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import mcp.server.stdio
|
|
7
|
+
from mcp.server import Server
|
|
8
|
+
from mcp.types import TextContent, Tool
|
|
9
|
+
|
|
10
|
+
from .engine import ProcessingError, extract_midi, parse_parts, synthesize_midi
|
|
11
|
+
from .utils import generate_output_path, validate_musicxml, validate_tempo_factor
|
|
12
|
+
|
|
13
|
+
logging.basicConfig(level=logging.INFO)
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
app = Server("synth-mcp")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@app.list_tools()
|
|
20
|
+
async def list_tools():
|
|
21
|
+
return [
|
|
22
|
+
Tool(
|
|
23
|
+
name="get_parts",
|
|
24
|
+
description="List all voice parts available in a MusicXML score",
|
|
25
|
+
inputSchema={
|
|
26
|
+
"type": "object",
|
|
27
|
+
"properties": {
|
|
28
|
+
"musicxml": {
|
|
29
|
+
"type": "string",
|
|
30
|
+
"description": "MusicXML document as a string",
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"required": ["musicxml"],
|
|
34
|
+
},
|
|
35
|
+
),
|
|
36
|
+
Tool(
|
|
37
|
+
name="synthesize",
|
|
38
|
+
description=(
|
|
39
|
+
"Synthesize audio from a MusicXML score. "
|
|
40
|
+
"Optionally select specific voice parts and adjust the tempo."
|
|
41
|
+
),
|
|
42
|
+
inputSchema={
|
|
43
|
+
"type": "object",
|
|
44
|
+
"properties": {
|
|
45
|
+
"musicxml": {
|
|
46
|
+
"type": "string",
|
|
47
|
+
"description": "MusicXML document as a string",
|
|
48
|
+
},
|
|
49
|
+
"part_ids": {
|
|
50
|
+
"type": "array",
|
|
51
|
+
"items": {"type": "string"},
|
|
52
|
+
"description": "Part IDs to include (default: all parts)",
|
|
53
|
+
},
|
|
54
|
+
"tempo_factor": {
|
|
55
|
+
"type": "number",
|
|
56
|
+
"description": (
|
|
57
|
+
"Tempo multiplier: 1.0 = score tempo, 0.75 = 75% speed. "
|
|
58
|
+
"Valid range: 0.25–4.0. Default: 1.0"
|
|
59
|
+
),
|
|
60
|
+
},
|
|
61
|
+
"output_path": {
|
|
62
|
+
"type": "string",
|
|
63
|
+
"description": "Path to write WAV file (auto-generated if omitted)",
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
"required": ["musicxml"],
|
|
67
|
+
},
|
|
68
|
+
),
|
|
69
|
+
Tool(
|
|
70
|
+
name="list_capabilities",
|
|
71
|
+
description="List supported formats and available tools for this synthesis server",
|
|
72
|
+
inputSchema={
|
|
73
|
+
"type": "object",
|
|
74
|
+
"properties": {},
|
|
75
|
+
"required": [],
|
|
76
|
+
},
|
|
77
|
+
),
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _error(message: str, code: str) -> list[TextContent]:
|
|
82
|
+
return [TextContent(type="text", text=json.dumps({"error": message, "error_code": code}))]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@app.call_tool()
|
|
86
|
+
async def call_tool(name: str, arguments: dict):
|
|
87
|
+
if name == "get_parts":
|
|
88
|
+
musicxml = arguments.get("musicxml", "")
|
|
89
|
+
|
|
90
|
+
ok, err = validate_musicxml(musicxml)
|
|
91
|
+
if not ok:
|
|
92
|
+
return _error(err, "INVALID_INPUT")
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
parts = parse_parts(musicxml)
|
|
96
|
+
return [TextContent(type="text", text=json.dumps({"parts": parts}, indent=2))]
|
|
97
|
+
except ProcessingError as e:
|
|
98
|
+
return _error(str(e), e.error_code)
|
|
99
|
+
except Exception as e:
|
|
100
|
+
logger.error("get_parts unexpected error: %s", e)
|
|
101
|
+
return _error(f"Unexpected error: {e}", "PROCESSING_FAILED")
|
|
102
|
+
|
|
103
|
+
elif name == "synthesize":
|
|
104
|
+
musicxml = arguments.get("musicxml", "")
|
|
105
|
+
part_ids = arguments.get("part_ids") # None → all parts
|
|
106
|
+
tempo_factor = arguments.get("tempo_factor", 1.0)
|
|
107
|
+
output_path = arguments.get("output_path")
|
|
108
|
+
|
|
109
|
+
ok, err = validate_musicxml(musicxml)
|
|
110
|
+
if not ok:
|
|
111
|
+
return _error(err, "INVALID_INPUT")
|
|
112
|
+
|
|
113
|
+
ok, err = validate_tempo_factor(tempo_factor)
|
|
114
|
+
if not ok:
|
|
115
|
+
return _error(err, "INVALID_PARAMETER")
|
|
116
|
+
|
|
117
|
+
if part_ids is not None and not isinstance(part_ids, list):
|
|
118
|
+
return _error("part_ids must be a list of strings", "INVALID_PARAMETER")
|
|
119
|
+
|
|
120
|
+
resolved_output = generate_output_path(output_path)
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
midi_bytes = extract_midi(musicxml, part_ids, tempo_factor)
|
|
124
|
+
except ProcessingError as e:
|
|
125
|
+
return _error(str(e), e.error_code)
|
|
126
|
+
except Exception as e:
|
|
127
|
+
logger.error("extract_midi unexpected error: %s", e)
|
|
128
|
+
return _error(f"MIDI extraction failed: {e}", "PROCESSING_FAILED")
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
duration = synthesize_midi(midi_bytes, resolved_output)
|
|
132
|
+
except ProcessingError as e:
|
|
133
|
+
return _error(str(e), e.error_code)
|
|
134
|
+
except Exception as e:
|
|
135
|
+
logger.error("synthesize_midi unexpected error: %s", e)
|
|
136
|
+
return _error(f"Synthesis failed: {e}", "PROCESSING_FAILED")
|
|
137
|
+
|
|
138
|
+
# Resolve the list of included part IDs for the response
|
|
139
|
+
if part_ids is not None:
|
|
140
|
+
parts_included = part_ids
|
|
141
|
+
else:
|
|
142
|
+
try:
|
|
143
|
+
parts_included = [p["id"] for p in parse_parts(musicxml)]
|
|
144
|
+
except Exception:
|
|
145
|
+
parts_included = []
|
|
146
|
+
|
|
147
|
+
return [
|
|
148
|
+
TextContent(
|
|
149
|
+
type="text",
|
|
150
|
+
text=json.dumps(
|
|
151
|
+
{
|
|
152
|
+
"audio_path": resolved_output,
|
|
153
|
+
"format": "wav",
|
|
154
|
+
"duration_seconds": round(duration, 2),
|
|
155
|
+
"parts_included": parts_included,
|
|
156
|
+
"tempo_factor": tempo_factor,
|
|
157
|
+
},
|
|
158
|
+
indent=2,
|
|
159
|
+
),
|
|
160
|
+
)
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
elif name == "list_capabilities":
|
|
164
|
+
soundfont_path = os.environ.get("SYNTH_SOUNDFONT_PATH", "")
|
|
165
|
+
soundfont_loaded = bool(soundfont_path) and os.path.exists(soundfont_path)
|
|
166
|
+
|
|
167
|
+
fluidsynth_available = True
|
|
168
|
+
try:
|
|
169
|
+
import fluidsynth # noqa: F401
|
|
170
|
+
except (ImportError, OSError):
|
|
171
|
+
fluidsynth_available = False
|
|
172
|
+
|
|
173
|
+
backend_version = "unknown"
|
|
174
|
+
try:
|
|
175
|
+
import subprocess
|
|
176
|
+
r = subprocess.run(
|
|
177
|
+
["fluidsynth", "--version"],
|
|
178
|
+
capture_output=True,
|
|
179
|
+
text=True,
|
|
180
|
+
timeout=5,
|
|
181
|
+
)
|
|
182
|
+
# FluidSynth prints e.g. "FluidSynth version 2.3.4\n..."
|
|
183
|
+
first_line = (r.stdout + r.stderr).strip().split("\n")[0]
|
|
184
|
+
backend_version = first_line.replace("FluidSynth version ", "").strip() or "unknown"
|
|
185
|
+
except Exception:
|
|
186
|
+
pass
|
|
187
|
+
|
|
188
|
+
result = {
|
|
189
|
+
"server": "synth-mcp",
|
|
190
|
+
"version": "0.1.0",
|
|
191
|
+
"input_formats": ["musicxml"],
|
|
192
|
+
"output_formats": ["wav"],
|
|
193
|
+
"tools": ["get_parts", "synthesize", "list_capabilities"],
|
|
194
|
+
"backend": "fluidsynth",
|
|
195
|
+
"backend_version": backend_version,
|
|
196
|
+
"soundfont_loaded": soundfont_loaded,
|
|
197
|
+
"soundfont_path": soundfont_path if soundfont_loaded else None,
|
|
198
|
+
"fluidsynth_available": fluidsynth_available,
|
|
199
|
+
}
|
|
200
|
+
return [TextContent(type="text", text=json.dumps(result, indent=2))]
|
|
201
|
+
|
|
202
|
+
raise ValueError(f"Unknown tool: {name}")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def main():
|
|
206
|
+
"""Entry point for synth-mcp."""
|
|
207
|
+
soundfont_path = os.environ.get("SYNTH_SOUNDFONT_PATH", "")
|
|
208
|
+
if not soundfont_path:
|
|
209
|
+
logger.warning(
|
|
210
|
+
"SYNTH_SOUNDFONT_PATH is not set — synthesis will fail. "
|
|
211
|
+
"Download an SF2 soundfont and set the variable before calling synthesize."
|
|
212
|
+
)
|
|
213
|
+
elif not os.path.exists(soundfont_path):
|
|
214
|
+
logger.warning("Soundfont not found at %r — synthesis will fail.", soundfont_path)
|
|
215
|
+
else:
|
|
216
|
+
logger.info("Soundfont: %s", soundfont_path)
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
import fluidsynth # noqa: F401
|
|
220
|
+
logger.info("FluidSynth library available")
|
|
221
|
+
except (ImportError, OSError) as e:
|
|
222
|
+
logger.warning("FluidSynth library not available: %s", e)
|
|
223
|
+
|
|
224
|
+
logger.info("Starting synth-mcp server…")
|
|
225
|
+
|
|
226
|
+
async def _run():
|
|
227
|
+
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
|
228
|
+
await app.run(read_stream, write_stream, app.create_initialization_options())
|
|
229
|
+
|
|
230
|
+
asyncio.run(_run())
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
if __name__ == "__main__":
|
|
234
|
+
main()
|
synth_mcp/utils.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import xml.etree.ElementTree as ET
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
SYNTH_OUTPUT_DIR = "/tmp/synth-mcp"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_musicxml(musicxml_str: str) -> tuple[bool, str]:
|
|
12
|
+
"""Validate a MusicXML string.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
(True, "") if valid, (False, error_message) if invalid.
|
|
16
|
+
"""
|
|
17
|
+
if not musicxml_str or not musicxml_str.strip():
|
|
18
|
+
return False, "MusicXML string is empty"
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
root = ET.fromstring(musicxml_str)
|
|
22
|
+
except ET.ParseError as e:
|
|
23
|
+
return False, f"Invalid XML: {e}"
|
|
24
|
+
|
|
25
|
+
tag = root.tag.split("}")[-1] if "}" in root.tag else root.tag
|
|
26
|
+
if tag not in ("score-partwise", "score-timewise"):
|
|
27
|
+
return False, (
|
|
28
|
+
f"Not a MusicXML score: root element is <{tag}>, "
|
|
29
|
+
"expected <score-partwise> or <score-timewise>"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
return True, ""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def validate_tempo_factor(tempo_factor: float) -> tuple[bool, str]:
|
|
36
|
+
"""Validate a tempo factor value (must be in range 0.25–4.0).
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
(True, "") if valid, (False, error_message) if invalid.
|
|
40
|
+
"""
|
|
41
|
+
if not isinstance(tempo_factor, (int, float)):
|
|
42
|
+
return False, f"tempo_factor must be a number, got {type(tempo_factor).__name__}"
|
|
43
|
+
|
|
44
|
+
if tempo_factor < 0.25 or tempo_factor > 4.0:
|
|
45
|
+
return False, (
|
|
46
|
+
f"tempo_factor must be between 0.25 and 4.0, got {tempo_factor}. "
|
|
47
|
+
"Values below 1.0 slow the tempo; values above 1.0 speed it up."
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
return True, ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def generate_output_path(output_path: str | None) -> str:
|
|
54
|
+
"""Return output_path if provided, otherwise generate one in SYNTH_OUTPUT_DIR."""
|
|
55
|
+
if output_path:
|
|
56
|
+
return output_path
|
|
57
|
+
|
|
58
|
+
output_dir = Path(SYNTH_OUTPUT_DIR)
|
|
59
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
61
|
+
return str(output_dir / f"output_{timestamp}.wav")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: synth-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server that synthesizes audio from MusicXML with selectable voice parts and tempo control
|
|
5
|
+
Project-URL: Homepage, https://github.com/raulkivi/music-assistant
|
|
6
|
+
Project-URL: Repository, https://github.com/raulkivi/music-assistant
|
|
7
|
+
Project-URL: Bug Tracker, https://github.com/raulkivi/music-assistant/issues
|
|
8
|
+
Author-email: Raul Kivi <raulkivi@users.noreply.github.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
Keywords: audio,choir,fluidsynth,mcp,music,musicxml,synthesis
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: MIDI
|
|
19
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Sound Synthesis
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Requires-Dist: mcp>=1.0.0
|
|
22
|
+
Requires-Dist: music21>=9.0.0
|
|
23
|
+
Requires-Dist: pyfluidsynth>=1.3.0
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
synth_mcp/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
synth_mcp/engine.py,sha256=geNCVrtT_qet2VROKyGKTjY7e7tMdM5OYi2lk1oFIfc,9282
|
|
3
|
+
synth_mcp/server.py,sha256=q63oq1U0seNz-K6ZrAYoSNHMJoJWOfnfGJmWyyDgn9Y,8192
|
|
4
|
+
synth_mcp/utils.py,sha256=cZ-bnjI6BFSZjqQxVSYurSuAEYXieZhE-xp8OLNdzAc,1918
|
|
5
|
+
synth_mcp-0.1.0.dist-info/METADATA,sha256=A6rzEGrmIK5wIm4NNV5or1JKv5TxpgZHr6L9tu1_69o,1199
|
|
6
|
+
synth_mcp-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
7
|
+
synth_mcp-0.1.0.dist-info/entry_points.txt,sha256=J0BXB2Z8Y-WgnkrMxEDaJAMu6taAGM3BUqO5EpEgbUc,52
|
|
8
|
+
synth_mcp-0.1.0.dist-info/RECORD,,
|