pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! ツールの処理の本体(`do_check`・`do_edit_timbre`・`do_describe`・`do_build`・`do_render`・`do_measure_tone`・`do_get_tones`・`do_format`)。
//!
//! MCP の口(`router`)から呼ぶ。非同期の口と分けて同期の関数にしてあるのは、テストから
//! 直接呼べるようにするため(返事の JSON の形は `tests` と `tests/mcp_protocol.rs` が見張る)。
//! MML にエラーがあっても検査の結果は「答え」なので、`check_mml` は `is_error` にしない。

use super::*;

// ---- ツール(処理の本体は同期の関数。テストしやすいように分けてある) -------------

impl PikoServer {
    pub fn do_check(&self, args: &MmlArgs) -> CallToolResult {
        match compile(
            &args.mml,
            args.dialect.as_deref(),
            args.includes.as_ref(),
            &self.config.tones,
            &self.i18n,
        ) {
            // 検査の結果は「答え」なので、MML にエラーがあっても is_error にはしない
            Ok(c) => CallToolResult::structured(report_json(&c.check, vec![])),
            Err(e) => e,
        }
    }

    /// `format_mml`:MML を整形して返す(`mml` が整形後の全文、`changed` が変わったか)。整形そのものは
    /// `pikopiko::composer::edit::format`(CLI の `fmt` と同じ。展開後の曲が前後で同じになることを確かめる)。
    /// 誤りのある曲は整形せず、診断つきのツールのエラー。`width` が範囲の外ならツールのエラー。
    pub fn do_format(&self, args: &FormatArgs) -> CallToolResult {
        use pikopiko::composer::edit::{format, FormatOptions};
        const MAX_WIDTH: u32 = 1000;
        let width = args.width.unwrap_or(100);
        if width > MAX_WIDTH {
            return tool_error(self.tr(
                "mcp-tool-bad-width",
                &[("value", width.to_string()), ("max", MAX_WIDTH.to_string())],
            ));
        }
        let check = match self.compile_song(
            &args.mml,
            args.dialect.as_deref(),
            args.includes.as_ref(),
            "mcp-tool-what-format",
        ) {
            Ok((_, check)) => check,
            Err(e) => return e,
        };
        let dialect = match resolve_dialect(args.dialect.as_deref(), &self.i18n) {
            Ok(d) => d,
            Err(e) => return e,
        };
        let sources = pikopiko::compiler::include::Sources::new(
            args.includes
                .iter()
                .flatten()
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        let loader =
            pikopiko::synth::tones::user::WithLibraries::new(Some(&sources), &self.config.tones);
        let opts = CompileOptions {
            dialect,
            synths: pikopiko::synth::all(),
            include: Some(&loader),
            ..Default::default()
        };
        let fmt = FormatOptions {
            width: width as usize,
            normalize: args.normalize.unwrap_or(false),
        };
        match format(&args.mml, &fmt, &opts) {
            Ok(text) => {
                let changed = text != args.mml;
                CallToolResult::structured(report_json(
                    &check,
                    vec![("mml", Value::String(text)), ("changed", json!(changed))],
                ))
            }
            Err(diags) => {
                let check = CheckReport::new(diags)
                    .in_lang(self.i18n.lang())
                    .with_messages(|d| self.i18n.diagnostic(d));
                failed(&check, "mcp-tool-what-format", &self.i18n)
            }
        }
    }

    /// `edit_timbre`:置き場所の一覧を返すか、差し替え → つまみ → パラメータの順に書き換えた MML を返す。
    ///
    /// 書き換えた結果は検査の報告と一緒に返す(`mml` が新しい全文、`timbre` が直した場所の今の音色)。
    /// 名前の誤り(場所・プリセット・つまみ・パラメータ)は、使える名前を添えたツールのエラーにする。
    pub fn do_edit_timbre(&self, args: &EditTimbreArgs) -> CallToolResult {
        use pikopiko::composer::edit::{self, TimbreTarget};
        let (song, check) = match self.compile_song(
            &args.mml,
            args.dialect.as_deref(),
            args.includes.as_ref(),
            "mcp-tool-what-edit-timbre",
        ) {
            Ok(v) => v,
            Err(e) => return e,
        };
        let spec = pikopiko::synth::find(pikopiko::synth::all(), &song.synth.name)
            .unwrap_or(&pikopiko::synth::BASIC);
        // compile と同じ設定(方言・音源・共有の定義)で書き換える
        let dialect = match resolve_dialect(args.dialect.as_deref(), &self.i18n) {
            Ok(d) => d,
            Err(e) => return e,
        };
        let sources = pikopiko::compiler::include::Sources::new(
            args.includes
                .iter()
                .flatten()
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        let loader =
            pikopiko::synth::tones::user::WithLibraries::new(Some(&sources), &self.config.tones);
        let opts = CompileOptions {
            dialect,
            synths: pikopiko::synth::all(),
            include: Some(&loader),
            ..Default::default()
        };
        let name_of = |t: &TimbreTarget| match t {
            TimbreTarget::Track(n) => n.clone(),
            TimbreTarget::Macro(n) => format!("${n}"),
        };
        let timbre_json = |t: &edit::Timbre| {
            let params: Map<String, Value> = t
                .params
                .iter()
                .map(|(k, v)| (k.clone(), json!(v)))
                .collect();
            json!({ "target": name_of(&t.target), "tone": t.tone, "params": params, "macros": t.macros })
        };
        let list = edit::timbres(&args.mml, &opts);
        let Some(target_name) = args.target.as_deref() else {
            let all: Vec<Value> = list.iter().map(timbre_json).collect();
            return CallToolResult::structured(report_json(
                &check,
                vec![("synth", json!(spec.name)), ("timbres", Value::Array(all))],
            ));
        };
        let target = match target_name.strip_prefix('$') {
            Some(m) => TimbreTarget::Macro(m.to_string()),
            None => TimbreTarget::Track(target_name.to_string()),
        };
        if !list.iter().any(|t| t.target == target) {
            let names: Vec<String> = list.iter().map(|t| name_of(&t.target)).collect();
            return tool_error(self.tr(
                "mcp-tool-unknown-target",
                &[("name", target_name.into()), ("names", names.join(", "))],
            ));
        }
        let names = |it: &mut dyn Iterator<Item = &'static str>| it.collect::<Vec<_>>().join(", ");
        let mut text = args.mml.clone();
        let invalid = |diags: Vec<pikopiko::Diagnostic>| {
            let check = CheckReport::new(diags)
                .in_lang(self.i18n.lang())
                .with_messages(|d| self.i18n.diagnostic(d));
            let message = self.tr("mcp-tool-edit-timbre-invalid", &[]);
            CallToolResult::structured_error(report_json(
                &check,
                vec![("error", Value::String(message))],
            ))
        };
        if let Some(p) = args.preset.as_deref() {
            let Some(preset) = spec.preset(p) else {
                return tool_error(self.tr(
                    "mcp-tool-unknown-preset",
                    &[
                        ("name", p.into()),
                        ("synth", spec.name.into()),
                        ("names", names(&mut spec.presets.iter().map(|x| x.name))),
                    ],
                ));
            };
            text = match edit::replace_timbre(&text, &target, preset.body, &opts) {
                Ok(t) => t,
                Err(d) => return invalid(d),
            };
        }
        let mut changes: Vec<(&str, u32)> = Vec::new();
        if let Some(knobs) = &args.knobs {
            let base = edit::timbres(&text, &opts)
                .into_iter()
                .find(|t| t.target == target)
                .map(|t| t.params)
                .unwrap_or_default();
            let max = pikopiko::synth::KNOB_STEPS;
            for (k, &steps) in knobs {
                let Some(knob) = spec.knob(k) else {
                    return tool_error(self.tr(
                        "mcp-tool-unknown-knob",
                        &[
                            ("name", k.clone()),
                            ("synth", spec.name.into()),
                            ("names", names(&mut spec.knobs.iter().map(|x| x.name))),
                        ],
                    ));
                };
                if !(-max..=max).contains(&steps) {
                    return tool_error(self.tr(
                        "mcp-tool-bad-knob-steps",
                        &[
                            ("name", k.clone()),
                            ("value", steps.to_string()),
                            ("max", max.to_string()),
                        ],
                    ));
                }
                changes.extend(knob.values(spec, steps, &base));
            }
        }
        if let Some(params) = &args.params {
            for (name, &value) in params {
                let Some(info) = spec.params.iter().find(|p| p.name == name) else {
                    return tool_error(self.tr(
                        "mcp-tool-unknown-param",
                        &[
                            ("name", name.clone()),
                            ("synth", spec.name.into()),
                            ("names", names(&mut spec.params.iter().map(|x| x.name))),
                        ],
                    ));
                };
                changes.push((info.name, value));
            }
        }
        if !changes.is_empty() {
            text = match edit::set_timbre_params(&text, &target, &changes, &opts) {
                Ok(t) => t,
                Err(d) => return invalid(d),
            };
        }
        let (_, diags) = pikopiko::compile_with(&text, &opts);
        let check = CheckReport::new(diags)
            .in_lang(self.i18n.lang())
            .with_messages(|d| self.i18n.diagnostic(d));
        let now = edit::timbres(&text, &opts)
            .into_iter()
            .find(|t| t.target == target)
            .map(|t| timbre_json(&t))
            .unwrap_or(Value::Null);
        CallToolResult::structured(report_json(
            &check,
            vec![("mml", Value::String(text)), ("timbre", now)],
        ))
    }

    pub fn do_describe(&self, args: &MmlArgs) -> CallToolResult {
        let (song, check) = match self.compile_song(
            &args.mml,
            args.dialect.as_deref(),
            args.includes.as_ref(),
            "mcp-tool-what-describe",
        ) {
            Ok(v) => v,
            Err(e) => return e,
        };
        let info = serde_json::to_value(pikopiko::describe_with(&song, pikopiko::synth::all()))
            .unwrap_or(Value::Null);
        CallToolResult::structured(report_json(&check, vec![("info", info)]))
    }

    pub fn do_build(&self, args: &BuildArgs) -> CallToolResult {
        let (song, check) = match self.compile_song(
            &args.mml,
            args.dialect.as_deref(),
            args.includes.as_ref(),
            "mcp-tool-what-build",
        ) {
            Ok(v) => v,
            Err(e) => return e,
        };
        let (bytes, stats) = match pikopiko::export::binary::encode_with_stats(&song) {
            Ok(r) => r,
            Err(e) => {
                let e = self.i18n.error(&e);
                return tool_error(self.tr("mcp-tool-encode-failed", &[("error", e)]));
            }
        };
        let mut binary = Map::new();
        binary.insert("format".into(), json!(bytes[0] >> 4));
        binary.insert(
            "sizes".into(),
            serde_json::to_value(BuildSizes::new(&song, &stats)).unwrap_or(Value::Null),
        );
        let style = match args.inline.as_deref() {
            Some(name) => match crate::inline::Inline::from_name(name) {
                Some(s) => Some(s),
                None => {
                    return tool_error(self.tr(
                        "mcp-tool-bad-inline",
                        &[
                            ("value", name.to_string()),
                            ("names", crate::inline::NAMES.join(", ")),
                        ],
                    ))
                }
            },
            None => args
                .include_hex
                .unwrap_or(false)
                .then_some(crate::inline::Inline::Hex),
        };
        if let Some(style) = style {
            let limit = self.config.max_inline;
            if bytes.len() <= limit {
                let text = style.render(&bytes);
                if style == crate::inline::Inline::Hex {
                    // 以前の欄(`hex`)も残す
                    binary.insert("hex".into(), Value::String(text.clone()));
                }
                binary.insert(
                    "inline".into(),
                    json!({ "format": style.name(), "bytes": bytes.len(), "text": text }),
                );
            } else {
                let note = self.tr(
                    "mcp-tool-hex-omitted",
                    &[
                        ("bytes", bytes.len().to_string()),
                        ("max", limit.to_string()),
                    ],
                );
                if style == crate::inline::Inline::Hex {
                    binary.insert("hex_omitted".into(), Value::String(note.clone()));
                }
                binary.insert("inline_omitted".into(), Value::String(note));
            }
        }
        CallToolResult::structured(report_json(&check, vec![("binary", Value::Object(binary))]))
    }

    pub fn do_render(&self, args: &RenderArgs) -> CallToolResult {
        let sample_rate = args.sample_rate.unwrap_or(44_100);
        if !SAMPLE_RATE_RANGE.contains(&sample_rate) {
            let (lo, hi) = (SAMPLE_RATE_RANGE.start(), SAMPLE_RATE_RANGE.end());
            return tool_error(self.tr(
                "mcp-tool-bad-sample-rate",
                &[
                    ("value", sample_rate.to_string()),
                    ("min", lo.to_string()),
                    ("max", hi.to_string()),
                ],
            ));
        }
        let loops = args.loops.unwrap_or(0);
        if loops > MAX_LOOPS {
            return tool_error(self.tr(
                "mcp-tool-bad-loops",
                &[("value", loops.to_string()), ("max", MAX_LOOPS.to_string())],
            ));
        }
        if let Some(n) = &args.name {
            if !valid_file_name(n) {
                return tool_error(self.tr("mcp-tool-bad-name", &[]));
            }
        }
        let eq = match args.eq.as_deref().map(|e| crate::eq::parse(e, sample_rate)) {
            None => None,
            Some(Ok(eq)) => Some(eq),
            Some(Err(crate::eq::EqTextError::Item(item))) => {
                return tool_error(self.tr(
                    "mcp-tool-bad-eq",
                    &[("item", item), ("names", crate::eq::names())],
                ));
            }
            Some(Err(crate::eq::EqTextError::TooMany)) => {
                return tool_error(self.tr(
                    "mcp-tool-eq-too-many",
                    &[("max", pikopiko::runtime::output::MAX_BANDS.to_string())],
                ));
            }
        };
        let vgm = match args.format.as_deref() {
            None | Some("wav") => None,
            Some("vgm") => Some(false),
            Some("vgz") => Some(true),
            Some(f) => {
                return tool_error(
                    self.tr("mcp-tool-unknown-render-format", &[("name", f.to_string())]),
                );
            }
        };
        let (song, check) = match self.compile_song(
            &args.mml,
            args.dialect.as_deref(),
            args.includes.as_ref(),
            "mcp-tool-what-render",
        ) {
            Ok(v) => v,
            Err(e) => return e,
        };
        if let Some(gzip) = vgm {
            return self.do_render_vgm(args, &song, &check, gzip);
        }
        let info = pikopiko::describe(&song);
        let looped = info.duration_secs - info.loop_secs.unwrap_or(0.0);
        let total_secs = info.duration_secs + f64::from(loops) * looped;
        if total_secs > self.config.max_render_secs {
            let max = self.config.max_render_secs;
            return tool_error(self.tr(
                "mcp-tool-too-long",
                &[
                    ("secs", format!("{total_secs:.1}")),
                    ("max", format!("{max:.0}")),
                ],
            ));
        }
        let synth = pikopiko::synth::create(
            pikopiko::synth::all(),
            &song.synth,
            sample_rate,
            song.tracks.len(),
        );
        let mut samples = pikopiko::render_to_vec_looped_with(&song, sample_rate, synth, loops);
        if let Some(eq) = eq {
            pikopiko::runtime::output::OutputEq::new(eq).process_block(&mut samples);
        }
        let stats = audio_stats(&samples, sample_rate);
        let wav = pikopiko::export::wav::encode_pcm16_with_meta(&samples, sample_rate, &song.meta);

        let sample_rate_bytes = sample_rate.to_le_bytes();
        let loops_bytes = loops.to_le_bytes();
        let name = args.name.clone().unwrap_or_else(|| {
            // 共有の定義(includes)も入力に含める。渡していなければ MML だけから作った名前
            let mut parts: Vec<&[u8]> = vec![
                args.mml.as_bytes(),
                args.dialect.as_deref().unwrap_or("").as_bytes(),
                &sample_rate_bytes,
                &loops_bytes,
            ];
            for (k, v) in args.includes.iter().flatten() {
                parts.push(k.as_bytes());
                parts.push(v.as_bytes());
            }
            // EQ を渡したときだけ足す(渡さない呼び出しは今までと同じ名前のまま)
            if let Some(e) = &args.eq {
                parts.push(b"eq");
                parts.push(e.as_bytes());
            }
            let h = fnv1a(&parts);
            format!("render-{h:016x}")
        });
        // ファイルを書かない設定(HTTP):音は結果に埋めるので、大きすぎれば短くしてもらう
        if !self.config.write_files && wav.len() > AUDIO_EMBED_LIMIT {
            return tool_error(self.tr(
                "mcp-tool-audio-too-big",
                &[
                    ("bytes", wav.len().to_string()),
                    ("max", AUDIO_EMBED_LIMIT.to_string()),
                ],
            ));
        }
        let path = if self.config.write_files {
            let path = self.config.out_dir.join(format!("{name}.wav"));
            if let Err(e) = std::fs::create_dir_all(&self.config.out_dir)
                .and_then(|()| std::fs::write(&path, &wav))
            {
                return tool_error(self.tr(
                    "mcp-tool-write-failed",
                    &[
                        ("path", path.display().to_string()),
                        ("error", self.i18n.io_error(&e)),
                    ],
                ));
            }
            // Windows で `\\?\C:\…` の形にならないよう、canonicalize ではなく絶対パスにする
            Some(std::path::absolute(&path).unwrap_or(path))
        } else {
            None
        };

        // ファイルを書かないときは、指定がなくても音を埋める(返す方法がほかにない)
        let want_audio = args.include_audio.unwrap_or(!self.config.write_files);
        let embed = want_audio && wav.len() <= AUDIO_EMBED_LIMIT;
        let mut render = Map::new();
        if let Some(path) = &path {
            render.insert("path".into(), json!(path.display().to_string()));
        }
        render.insert("bytes".into(), json!(wav.len()));
        render.insert("sample_rate".into(), json!(sample_rate));
        render.insert("loops".into(), json!(loops));
        if let Some(e) = &args.eq {
            render.insert("eq".into(), json!(e));
        }
        render.insert("frames".into(), json!(samples.len()));
        render.insert(
            "duration_secs".into(),
            json!(samples.len() as f64 / f64::from(sample_rate)),
        );
        render.insert(
            "stats".into(),
            serde_json::to_value(&stats).unwrap_or(Value::Null),
        );
        // 区間(`@mark`、なければ 8 小節)ごとの音量・帯域・広がりと、音量差などの注意
        render.insert(
            "sections".into(),
            serde_json::to_value(pikopiko::report::song::analyze(
                &song,
                &samples,
                sample_rate,
            ))
            .unwrap_or(Value::Null),
        );
        render.insert("audio_embedded".into(), json!(embed));
        if want_audio && !embed {
            render.insert(
                "audio_omitted".into(),
                Value::String(self.tr(
                    "mcp-tool-audio-omitted",
                    &[
                        ("bytes", wav.len().to_string()),
                        ("max", AUDIO_EMBED_LIMIT.to_string()),
                    ],
                )),
            );
        }
        let mut result = CallToolResult::structured(report_json(
            &check,
            vec![("render", Value::Object(render))],
        ));
        if embed {
            result
                .content
                .push(ContentBlock::audio(base64(&wav), "audio/wav"));
        }
        result
    }

    /// `render_mml` の `format` が `vgm`・`vgz` のとき。曲を VGM(AY-3-8912 / YM2149 の
    /// レジスタの書き込みの記録)にしてサーバーのフォルダーに書く。音は作らないので `stats` は返さない。
    /// `gzip` なら `.vgz`。VGM の機能がないビルドと、レジスタを持たない音源の曲はツールのエラー。
    #[cfg(feature = "vgm")]
    fn do_render_vgm(
        &self,
        args: &RenderArgs,
        song: &pikopiko::Song,
        check: &pikopiko::report::CheckReport,
        gzip: bool,
    ) -> CallToolResult {
        use std::io::Write;
        let info = pikopiko::describe(song);
        let max = self.config.max_render_secs;
        if info.duration_secs > max {
            return tool_error(self.tr(
                "mcp-tool-too-long",
                &[
                    ("secs", format!("{:.1}", info.duration_secs)),
                    ("max", format!("{max:.0}")),
                ],
            ));
        }
        let bytes = match pikopiko::export::vgm::encode_vgm(song) {
            Ok(b) => b,
            Err(e) => {
                return tool_error(
                    self.tr("mcp-tool-vgm-failed", &[("error", self.i18n.error(&e))]),
                );
            }
        };
        let ext = if gzip { "vgz" } else { "vgm" };
        let bytes = if gzip {
            let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
            match enc.write_all(&bytes).and_then(|()| enc.finish()) {
                Ok(b) => b,
                Err(e) => {
                    return tool_error(
                        self.tr("mcp-tool-vgm-failed", &[("error", self.i18n.io_error(&e))]),
                    );
                }
            }
        } else {
            bytes
        };
        let name = args.name.clone().unwrap_or_else(|| {
            let mut parts: Vec<&[u8]> = vec![
                args.mml.as_bytes(),
                args.dialect.as_deref().unwrap_or("").as_bytes(),
                ext.as_bytes(),
            ];
            for (k, v) in args.includes.iter().flatten() {
                parts.push(k.as_bytes());
                parts.push(v.as_bytes());
            }
            format!("render-{:016x}", fnv1a(&parts))
        });
        let mut render = Map::new();
        if self.config.write_files {
            let path = self.config.out_dir.join(format!("{name}.{ext}"));
            if let Err(e) = std::fs::create_dir_all(&self.config.out_dir)
                .and_then(|()| std::fs::write(&path, &bytes))
            {
                return tool_error(self.tr(
                    "mcp-tool-write-failed",
                    &[
                        ("path", path.display().to_string()),
                        ("error", self.i18n.io_error(&e)),
                    ],
                ));
            }
            let path = std::path::absolute(&path).unwrap_or(path);
            render.insert("path".into(), json!(path.display().to_string()));
        } else {
            // ファイルを書かないときは Base64 で埋める(大きすぎればツールのエラー)
            if bytes.len() > AUDIO_EMBED_LIMIT {
                return tool_error(self.tr(
                    "mcp-tool-audio-too-big",
                    &[
                        ("bytes", bytes.len().to_string()),
                        ("max", AUDIO_EMBED_LIMIT.to_string()),
                    ],
                ));
            }
            render.insert("base64".into(), json!(base64(&bytes)));
        }
        render.insert("bytes".into(), json!(bytes.len()));
        render.insert("format".into(), json!(ext));
        render.insert("duration_secs".into(), json!(info.duration_secs));
        CallToolResult::structured(report_json(check, vec![("render", Value::Object(render))]))
    }

    /// VGM の機能がないビルド:`format` が `vgm`・`vgz` ならツールのエラー。
    #[cfg(not(feature = "vgm"))]
    fn do_render_vgm(
        &self,
        _args: &RenderArgs,
        _song: &pikopiko::Song,
        _check: &pikopiko::report::CheckReport,
        _gzip: bool,
    ) -> CallToolResult {
        tool_error(self.tr("mcp-tool-vgm-unavailable", &[]))
    }

    /// 使える音源の一覧。`only` があればその音源だけ(名前か別名。なければ名前の一覧つきの誤り)。
    pub fn do_list_synths(&self, args: &ListSynthsArgs) -> CallToolResult {
        let all = pikopiko::synth::all();
        let one;
        let synths: &[&pikopiko::synth::SynthSpec] = match &args.only {
            None => all,
            Some(name) => match pikopiko::synth::find(all, name) {
                Some(spec) => {
                    one = [spec];
                    &one
                }
                None => {
                    let names: Vec<&str> = all.iter().map(|s| s.name).collect();
                    return tool_error(self.tr(
                        "mcp-tool-unknown-synth",
                        &[("name", name.clone()), ("names", names.join(", "))],
                    ));
                }
            },
        };
        // 音源の説明は言語に合わせる(`mcp.ftl` に同じキーがあればそちら)
        let i18n = &self.i18n;
        let synths = synth_catalog_with(synths, i18n.lang(), &mut |k| i18n.override_text(k));
        let mut out = json!({ "synths": serde_json::to_value(synths).unwrap_or(Value::Null) });
        // 利用者の音色集(`--tones`)。`library` と同じ形の項目に `source: "user"` を付けて並べる
        if !self.config.tones.is_empty() && args.only.is_none() {
            let lang = i18n.lang();
            let mut mine: Vec<Value> = Vec::new();
            for lib in &self.config.tones {
                for k in &lib.kinds {
                    let description =
                        pikopiko::synth::tones::user::pick_description(&k.description, lang);
                    for t in k.tones() {
                        mine.push(json!({
                            "name": t.name,
                            "kind": t.kind,
                            "file": format!("@{}/{}", lib.name, k.name),
                            "description": description,
                            "synth": lib.synth,
                            "source": "user",
                        }));
                    }
                }
            }
            out["user_library"] = Value::Array(mine);
        }
        CallToolResult::structured(out)
    }

    /// `get_tones` で利用者の音色集(`--tones`。`@名前/種類`)を引く。その名前の音色集がなければ `None`
    /// (組み込みを引く)。名前はあるが種類がなければ、ある種類を添えたツールのエラー。
    fn user_tones(&self, file: &str) -> Option<CallToolResult> {
        let (lib, kind) = file.strip_prefix('@')?.split_once('/')?;
        let lib = self.config.tones.iter().find(|l| l.name == lib)?;
        // 組み込みと同じ名前の音色集は組み込みが優先される(読み込みと同じ約束)
        if lib.clashes(pikopiko::synth::all()) {
            return None;
        }
        let Some(k) = lib.kind(kind) else {
            let names: Vec<String> = lib
                .kinds
                .iter()
                .map(|k| format!("@{}/{}", lib.name, k.name))
                .collect();
            return Some(tool_error(self.tr(
                "mcp-tool-unknown-library",
                &[("name", file.to_string()), ("names", names.join(", "))],
            )));
        };
        let description =
            pikopiko::synth::tones::user::pick_description(&k.description, self.i18n.lang());
        let tones: Vec<Value> = k
            .tones()
            .iter()
            .map(|t| {
                json!({
                    "name": t.name,
                    "kind": t.kind,
                    "file": file,
                    "body": t.body,
                    "description": description,
                })
            })
            .collect();
        Some(CallToolResult::structured(json!({
            "file": file,
            "kind": k.name,
            "synth": lib.synth,
            "source": "user",
            "text": k.text,
            "tones": tones,
        })))
    }

    /// `get_tones`:組み込みの音色集の 1 ファイルの本文(`text`)と、`#include` すると呼べる音色
    /// (`tones`:名前・種類・中身・説明。まとめて読むファイルは中の `#include` をたどった全部)。
    /// 知らない名前は、ある音色集の名前を添えたツールのエラー。説明と本文のコメントの行は表示の言語
    /// (本文のコメントは `library::file_text`。音色の行は曲で読むものと同じ)。
    pub fn do_get_tones(&self, args: &GetTonesArgs) -> CallToolResult {
        use pikopiko::synth::tones as library;
        if let Some(r) = self.user_tones(&args.file) {
            return r;
        }
        let found = args
            .file
            .strip_prefix('@')
            .and_then(|p| p.split_once('/'))
            .and_then(|(synth, name)| {
                let spec = pikopiko::synth::find(pikopiko::synth::all(), synth)?;
                Some((spec, spec.tone_file(name)?, library::tones_in(spec, name)?))
            });
        let Some((spec, file, tones)) = found else {
            let names: Vec<String> = pikopiko::synth::all()
                .iter()
                .flat_map(|s| {
                    s.tone_files
                        .iter()
                        .map(move |f| format!("@{}/{}", s.library_prefix(), f.name))
                })
                .collect();
            return tool_error(self.tr(
                "mcp-tool-unknown-library",
                &[("name", args.file.clone()), ("names", names.join(", "))],
            ));
        };
        let lang = self.i18n.lang();
        let tones: Vec<Value> = tones
            .iter()
            .map(|t| {
                let description = self
                    .i18n
                    .override_text(&t.text_key())
                    .unwrap_or_else(|| spec.library_description(t.name, lang).to_string());
                json!({
                    "name": t.name,
                    "kind": t.kind,
                    "file": t.path(),
                    "body": t.body,
                    "description": description,
                })
            })
            .collect();
        CallToolResult::structured(json!({
            "file": format!("@{}/{}", spec.library_prefix(), file.name),
            "kind": file.kind,
            "text": library::file_text(spec, file, lang),
            "tones": tones,
        }))
    }

    /// `measure_tone`:音色を試聴フレーズで鳴らして測る。結果(`tone`)と、試聴のファイル(`format` で
    /// WAV か MP3)の場所を返す。知らない形式は、使える形式を添えたツールのエラー。
    ///
    /// 解析は `compile_song` で行う(音色に誤りがあれば、ほかのツールと同じ診断つきのエラーになる。
    /// 位置は試聴フレーズの曲の中の位置で、`tone.mml` で確かめられる)。知らない種類は、使える種類を
    /// 添えたツールのエラー。
    pub fn do_measure_tone(&self, args: &MeasureToneArgs) -> CallToolResult {
        use pikopiko::report::tone;
        let Some(category) = tone::Category::from_name(&args.category) else {
            let names: Vec<&str> = tone::ALL.iter().map(|c| c.name()).collect();
            return tool_error(self.tr(
                "mcp-tool-unknown-category",
                &[("name", args.category.clone()), ("names", names.join(", "))],
            ));
        };
        if let Some(n) = &args.name {
            if !valid_file_name(n) {
                return tool_error(self.tr("mcp-tool-bad-name", &[]));
            }
        }
        use crate::audio_file::{encode, AudioFormat, EncodeError};
        let format = match args.format.as_deref() {
            None => AudioFormat::Wav,
            Some(f) => match AudioFormat::from_name(f) {
                Some(format) => format,
                None => {
                    return tool_error(
                        self.tr("mcp-tool-unknown-format", &[("name", f.to_string())]),
                    )
                }
            },
        };
        let synth = args.synth.as_deref().unwrap_or("va");
        let spec = pikopiko::synth::find(pikopiko::synth::all(), synth);
        // 音色集の音色を名前で呼んでいれば、読み込みの行を足す(`$kawaii_pluck` だけでも測れる)
        let mml = match spec {
            Some(spec) => pikopiko::synth::tones::audition_mml_for(spec, category, &args.timbre),
            None => tone::audition_mml(category, synth, &args.timbre),
        };
        let (song, check) = match self.compile_song(&mml, None, None, "mcp-tool-what-measure-tone")
        {
            Ok(v) => v,
            Err(e) => return e,
        };
        // 参照音を先に読む(読めなければ鳴らす前に止める)
        let reference = match &args.reference {
            Some(name) => match self.read_reference(name, args) {
                Ok(m) => Some(m),
                Err(e) => return e,
            },
            None => None,
        };
        const RATE: u32 = 44_100;
        let options = tone::AuditionOptions::default().with_alias(args.alias.unwrap_or(false));
        let mut report = tone::report_with(category, &song, mml, RATE, options);
        // 似すぎの判定:同じ種類の音色集の音色とプリセットのうち近い 3 つ
        if let Some(spec) = spec {
            pikopiko::synth::tones::compare(&mut report, spec, RATE, 3);
        }
        let name = args.name.clone().unwrap_or_else(|| {
            let h = fnv1a(&[report.mml.as_bytes()]);
            format!("tone-{h:016x}")
        });
        let path = self
            .config
            .out_dir
            .join(format!("{name}.{}", format.extension()));
        let bytes = match encode(&report.samples, RATE, format) {
            Ok(b) => b,
            Err(e) => {
                let key = match e {
                    EncodeError::Mp3Unavailable => "mcp-tool-mp3-unavailable",
                    EncodeError::Mp3Failed => "mcp-tool-mp3-failed",
                };
                return tool_error(self.tr(key, &[("path", path.display().to_string())]));
            }
        };
        if let Err(e) = std::fs::create_dir_all(&self.config.out_dir)
            .and_then(|()| std::fs::write(&path, &bytes))
        {
            return tool_error(self.tr(
                "mcp-tool-write-failed",
                &[
                    ("path", path.display().to_string()),
                    ("error", self.i18n.io_error(&e)),
                ],
            ));
        }
        let path = std::path::absolute(&path).unwrap_or(path);
        let mut fields = vec![
            ("tone", serde_json::to_value(&report).unwrap_or(Value::Null)),
            ("path", json!(path.display().to_string())),
        ];
        if let Some(m) = &reference {
            let c = tone::compare_audition(&report, m);
            fields.push(("reference", serde_json::to_value(m).unwrap_or(Value::Null)));
            fields.push((
                "comparison",
                serde_json::to_value(&c).unwrap_or(Value::Null),
            ));
        }
        CallToolResult::structured(report_json(&check, fields))
    }

    /// `measure_tone` の参照音を読んで測る。読めるのは参照音のフォルダー([`Config::ref_dir`])の
    /// 直下のファイルだけ:名前に区切り文字・`..`・ドライブの印があれば拒否し、フォルダーの指定が
    /// なければエラーにする。誤りはツールのエラー(表示の言語の文)。
    fn read_reference(
        &self,
        name: &str,
        args: &MeasureToneArgs,
    ) -> Result<pikopiko::report::tone::ToneMetrics, CallToolResult> {
        use crate::reference::{measure_reference, Cut, ReferenceError, WavError};
        let Some(dir) = &self.config.ref_dir else {
            return Err(tool_error(self.tr("mcp-tool-ref-no-dir", &[])));
        };
        let plain = !name.is_empty()
            && name != "."
            && name != ".."
            && !name.contains(['/', '\\', ':'])
            && std::path::Path::new(name).components().count() == 1;
        if !plain {
            return Err(tool_error(
                self.tr("mcp-tool-ref-bad-name", &[("name", name.to_string())]),
            ));
        }
        let bytes = std::fs::read(dir.join(name)).map_err(|e| {
            tool_error(self.tr(
                "mcp-tool-ref-read",
                &[
                    ("name", name.to_string()),
                    ("error", self.i18n.io_error(&e)),
                ],
            ))
        })?;
        let cut = Cut {
            from: args.reference_from,
            to: args.reference_to,
            release: args.reference_release,
            note: args.reference_note.clone(),
        };
        measure_reference(&bytes, &cut).map_err(|e| {
            let n = ("name", name.to_string());
            tool_error(match e {
                ReferenceError::Wav(WavError::NotWav) => self.tr("mcp-tool-ref-not-wav", &[n]),
                ReferenceError::Wav(WavError::Truncated) => self.tr("mcp-tool-ref-truncated", &[n]),
                ReferenceError::Wav(WavError::Unsupported { format, bits }) => self.tr(
                    "mcp-tool-ref-unsupported",
                    &[
                        n,
                        ("format", format.to_string()),
                        ("bits", bits.to_string()),
                    ],
                ),
                ReferenceError::BadNote(note) => self.tr("mcp-tool-ref-note", &[("note", note)]),
                ReferenceError::BadRange => self.tr("mcp-tool-ref-range", &[]),
            })
        })
    }
}