summaryrefslogtreecommitdiff
path: root/src/mml_composemusic_mcp/server.py
blob: f0c8bd1f50c961d52b942706c790be00cd592d17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# MCP server exposing compose_mml tool.

import argparse
import json
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path

from fastmcp import FastMCP
from fastmcp.tools import ToolResult
from fastmcp.utilities.types import Audio
from mcp.types import TextContent

from .ir import ErrorCode, ErrorDetail, ErrorPhase, NoteSequence
from .lexer import tokenize
from .parser_ppmck import parse_ppmck
from .parser_pyxel import parse_pyxel
from .semantic_ppmck import analyze_ppmck
from .semantic_pyxel import analyze_pyxel
from .synthesizer import build_channel_summary, synthesize, write_wav
from .templates import TEMPLATES, get_template

mcp = FastMCP("mml-composemusic-mcp")
OUTPUT_DIR = Path("./data")


@dataclass(frozen=True)
class ToolExecution:
    """Internal result kept separate from the public MCP payload."""

    result: dict
    is_error: bool = False
    wav_path: Path | None = None


def _is_error(errors: list[ErrorDetail]) -> bool:
    return any(e.severity == "error" for e in errors)


def _create_output_directory() -> Path:
    """Create and return a unique timestamped output directory.

    Format: YYYYMMDD_HHMMSS_mmm
    If the millisecond is already in use, advance the timestamp until a free
    directory can be created. Exclusive creation also handles concurrent calls.
    """
    now = datetime.now()
    for offset_ms in range(1000):
        candidate_time = now + timedelta(milliseconds=offset_ms)
        timestamp = candidate_time.strftime("%Y%m%d_%H%M%S_%f")[:-3]
        output_dir = OUTPUT_DIR / timestamp
        try:
            output_dir.mkdir(parents=True, exist_ok=False)
            return output_dir
        except FileExistsError:
            continue
    raise RuntimeError("一意な出力ディレクトリを作成できませんでした。")


def _split_errors(errors: list[ErrorDetail]) -> tuple[list[dict], list[dict]]:
    errs = [e.to_dict() for e in errors if e.severity == "error"]
    warns = [e.to_dict() for e in errors if e.severity == "warning"]
    return errs, warns


def _internal_error_execution() -> ToolExecution:
    """Build a path-free MCP tool error for unexpected failures."""
    return ToolExecution(
        {
            "success": False,
            "audio": None,
            "duration_sec": 0,
            "note_sequence": None,
            "validation": {
                "errors": [
                    {
                        "code": ErrorCode.RUNTIME_INTERNAL_ERROR.value,
                        "phase": ErrorPhase.RUNTIME.value,
                        "line": 0,
                        "column": 0,
                        "message": "内部エラーが発生しました。",
                        "severity": "error",
                        "hint": "MMLの内容を確認の上、再度お試しください。",
                    }
                ],
                "warnings": [],
            },
        },
        is_error=True,
    )


def _parse_mml(mml: str, mode: str) -> tuple[dict | None, list[ErrorDetail]]:
    """Run lexer, parser, and semantic analyzer for the given mode."""
    tokens = tokenize(mml, mode)

    if mode == "ppmck":
        program, errors = parse_ppmck(mml, tokens)
        if not _is_error(errors):
            note_sequence, semantic_errors = analyze_ppmck(mml, program)
            errors.extend(semantic_errors)
    elif mode == "pyxel":
        program, errors = parse_pyxel(mml, tokens)
        if not _is_error(errors):
            note_sequence, semantic_errors = analyze_pyxel(mml, program)
            errors.extend(semantic_errors)
    else:
        errors = [
            ErrorDetail(
                code=ErrorCode.VALIDATION_INVALID_MODE,
                phase=ErrorPhase.API,
                line=0,
                column=0,
                message=f"未知のモード '{mode}' です。",
                severity="error",
                hint="mode は 'ppmck' または 'pyxel' を指定してください。",
            )
        ]
        note_sequence = None

    if _is_error(errors):
        note_sequence = None
    return (note_sequence.to_dict() if note_sequence else None), errors


def _execute_compose_mml(
    action: str,
    mml: str = "",
    mode: str = "",
    template: str = "basic",
    sample_rate: int = 44100,
    normalize: bool = True,
) -> ToolExecution:
    """Execute a request without exposing internal file paths."""
    if action == "template":
        if mode not in ("ppmck", "pyxel"):
            mode = "ppmck"
        if template not in TEMPLATES[mode]:
            template = "basic"
        mml_text, description = get_template(mode, template)
        return ToolExecution({"mml": mml_text, "description": description})

    if action in ("compose", "validate"):
        if not mml or not mode:
            return ToolExecution(
                {
                    "success": False,
                    "valid": False,
                    "note_sequence": None,
                    "validation": {
                        "errors": [
                            {
                                "code": ErrorCode.VALIDATION_MISSING_PARAMETER.value,
                                "phase": ErrorPhase.API.value,
                                "line": 0,
                                "column": 0,
                                "message": "mml と mode は compose/validate の必須パラメータです。",
                                "severity": "error",
                                "hint": "mml に MML 文字列、mode に 'ppmck' または 'pyxel' を指定してください。",
                            }
                        ],
                        "warnings": [],
                    },
                },
                is_error=True,
            )
        try:
            note_sequence_dict, errors = _parse_mml(mml, mode)
            errors_list, warnings_list = _split_errors(errors)
            if action == "validate":
                return ToolExecution(
                    {
                        "valid": not _is_error(errors),
                        "errors": errors_list,
                        "warnings": warnings_list,
                        "note_sequence": note_sequence_dict,
                        "channel_summary": build_channel_summary(note_sequence_dict)
                        if note_sequence_dict
                        else [],
                    },
                    is_error=mode not in ("ppmck", "pyxel"),
                )
            # compose
            if _is_error(errors):
                return ToolExecution(
                    {
                        "success": False,
                        "audio": None,
                        "duration_sec": 0,
                        "note_sequence": note_sequence_dict,
                        "validation": {
                            "errors": errors_list,
                            "warnings": warnings_list,
                        },
                    },
                    is_error=True,
                )

            ns = _dict_to_note_sequence(note_sequence_dict)
            try:
                wave_data, duration, synth_errors = synthesize(
                    ns, mode, sample_rate, normalize
                )
            except Exception:
                return ToolExecution(
                    {
                        "success": False,
                        "audio": None,
                        "duration_sec": 0,
                        "note_sequence": note_sequence_dict,
                        "validation": {
                            "errors": [
                                {
                                    "code": ErrorCode.RUNTIME_SYNTHESIS_FAILED.value,
                                    "phase": ErrorPhase.RUNTIME.value,
                                    "line": 0,
                                    "column": 0,
                                    "message": "音声合成中にエラーが発生しました。",
                                    "severity": "error",
                                    "hint": "MMLの内容を確認の上、再度お試しください。問題が続く場合は、短いMMLから試してください。",
                                }
                            ],
                            "warnings": warnings_list,
                        },
                    },
                    is_error=True,
                )
            errors.extend(synth_errors)
            errors_list, warnings_list = _split_errors(errors)
            if _is_error(errors):
                return ToolExecution(
                    {
                        "success": False,
                        "audio": None,
                        "duration_sec": 0,
                        "note_sequence": note_sequence_dict,
                        "validation": {
                            "errors": errors_list,
                            "warnings": warnings_list,
                        },
                    },
                    is_error=True,
                )
            output_dir = _create_output_directory()
            wav_path = output_dir / "output.wav"
            wav_errors = write_wav(wav_path, wave_data, sample_rate)
            errors.extend(wav_errors)
            if not _is_error(errors):
                try:
                    (output_dir / "output.mml").write_text(mml, encoding="utf-8")
                except Exception:
                    errors.append(
                        ErrorDetail(
                            code=ErrorCode.RUNTIME_MML_WRITE_FAILED,
                            phase=ErrorPhase.RUNTIME,
                            line=0,
                            column=0,
                            message="MMLファイルの出力に失敗しました。",
                            severity="error",
                            hint="出力先を確認してください。",
                        )
                    )
            errors_list, warnings_list = _split_errors(errors)
            failed = _is_error(errors)
            result = {
                "success": not failed,
                "audio": None
                if failed
                else {
                    "mime_type": "audio/wav",
                    "size_bytes": wav_path.stat().st_size,
                    "sample_rate": sample_rate,
                },
                "duration_sec": duration,
                "note_sequence": note_sequence_dict,
                "validation": {"errors": errors_list, "warnings": warnings_list},
            }
            return ToolExecution(
                result,
                is_error=failed,
                wav_path=None if failed else wav_path,
            )
        except Exception:
            return _internal_error_execution()

    return ToolExecution(
        {
            "success": False,
            "validation": {
                "errors": [
                    {
                        "code": ErrorCode.VALIDATION_INVALID_ACTION.value,
                        "phase": ErrorPhase.API.value,
                        "line": 0,
                        "column": 0,
                        "message": f"未知の action '{action}' です。",
                        "severity": "error",
                        "hint": "action は 'compose', 'validate', 'template' のいずれかを指定してください。",
                    }
                ],
                "warnings": [],
            },
        },
        is_error=True,
    )


def _build_tool_result(execution: ToolExecution) -> ToolResult:
    """Convert an internal execution result to the public MCP response."""
    result = execution.result
    if "wav_path" in result:
        raise ValueError("Internal paths must not be included in MCP results")
    if "success" in result and result["success"] is execution.is_error:
        raise ValueError("success and is_error are inconsistent")
    if execution.is_error and execution.wav_path is not None:
        raise ValueError("Error results must not contain audio")

    content = [
        TextContent(
            type="text",
            text=json.dumps(result, ensure_ascii=False),
        )
    ]
    if execution.wav_path is not None:
        content.append(Audio(path=execution.wav_path).to_audio_content())

    return ToolResult(
        content=content,
        structured_content=result,
        is_error=execution.is_error,
    )


@mcp.tool(name="compose_mml", output_schema=None)
def compose_mml(
    action: str,
    mml: str = "",
    mode: str = "",
    template: str = "basic",
    sample_rate: int = 44100,
    normalize: bool = True,
) -> ToolResult:
    """Compose, validate, or generate templates for retro chiptune-style MML."""
    try:
        execution = _execute_compose_mml(
            action=action,
            mml=mml,
            mode=mode,
            template=template,
            sample_rate=sample_rate,
            normalize=normalize,
        )
        return _build_tool_result(execution)
    except Exception:
        return _build_tool_result(_internal_error_execution())


def _dict_to_note_sequence(data: dict) -> NoteSequence:
    from .ir import (
        ChannelSequence,
        DetuneEvent,
        DutyEnvelopeEvent,
        DutyEvent,
        EnvelopeEvent,
        GlideEvent,
        LfoEvent,
        NoteEnvEvent,
        NoteEvent,
        NoteSequence,
        PitchEnvEvent,
        QuantizeEvent,
        RelativeVolumeEvent,
        RepeatEvent,
        RestEvent,
        SweepEvent,
        TempoEvent,
        VibratoEvent,
        VolumeEnvelopeEvent,
        VolumeEvent,
    )

    ns = NoteSequence(
        version=data["version"],
        bpm=data["bpm"],
        ticks_per_quarter=data["ticks_per_quarter"],
        mode=data.get("mode", "ppmck"),
        definitions=data.get("definitions", {}),
        channels={},
    )
    for name, ch_data in data["channels"].items():
        ch = ChannelSequence(
            channel_type=ch_data["channel_type"],
            events=[],
            total_ticks=ch_data["total_ticks"],
        )
        for ev in ch_data["events"]:
            ev_type = ev["type"]
            if ev_type == "note":
                ch.events.append(NoteEvent(**ev))
            elif ev_type == "rest":
                ch.events.append(RestEvent(**ev))
            elif ev_type == "volume":
                ch.events.append(VolumeEvent(**ev))
            elif ev_type == "duty":
                ch.events.append(DutyEvent(**ev))
            elif ev_type == "tempo":
                ch.events.append(TempoEvent(**ev))
            elif ev_type == "repeat":
                ch.events.append(RepeatEvent(**ev))
            elif ev_type == "envelope":
                ch.events.append(EnvelopeEvent(**ev))
            elif ev_type == "quantize":
                ch.events.append(QuantizeEvent(**ev))
            elif ev_type == "detune":
                ch.events.append(DetuneEvent(**ev))
            elif ev_type == "sweep":
                ch.events.append(SweepEvent(**ev))
            elif ev_type == "rel_volume":
                ch.events.append(RelativeVolumeEvent(**ev))
            elif ev_type == "vol_envelope":
                ch.events.append(VolumeEnvelopeEvent(**ev))
            elif ev_type == "duty_envelope":
                ch.events.append(DutyEnvelopeEvent(**ev))
            elif ev_type == "lfo":
                ch.events.append(LfoEvent(**ev))
            elif ev_type == "pitch_envelope":
                ch.events.append(PitchEnvEvent(**ev))
            elif ev_type == "note_envelope":
                ch.events.append(NoteEnvEvent(**ev))
            elif ev_type == "vibrato":
                ch.events.append(VibratoEvent(**ev))
            elif ev_type == "glide":
                ch.events.append(GlideEvent(**ev))
        ns.channels[name] = ch
    return ns


def main() -> None:
    parser = argparse.ArgumentParser(description="MML Compose MCP Server")
    parser.add_argument(
        "--output-dir",
        type=str,
        default="./data",
        help="Directory to store generated WAV files (default: ./data)",
    )
    parser.add_argument(
        "--transport",
        type=str,
        default="stdio",
        choices=["stdio", "http", "sse", "streamable-http"],
        help="MCP transport (default: stdio)",
    )
    parser.add_argument(
        "--host",
        type=str,
        default="127.0.0.1",
        help="Host to bind for HTTP-based transports (default: 127.0.0.1)",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=8080,
        help="Port to bind for HTTP-based transports (default: 8080)",
    )
    args = parser.parse_args()
    global OUTPUT_DIR
    OUTPUT_DIR = Path(args.output_dir)
    if args.transport == "stdio":
        mcp.run(transport="stdio")
    else:
        mcp.run(
            transport=args.transport,
            host=args.host,
            port=args.port,
        )


if __name__ == "__main__":
    main()