1use super::*;
8
9impl PikoServer {
12 pub fn do_check(&self, args: &MmlArgs) -> CallToolResult {
13 match compile(
14 &args.mml,
15 args.dialect.as_deref(),
16 args.includes.as_ref(),
17 &self.config.tones,
18 &self.i18n,
19 ) {
20 Ok(c) => CallToolResult::structured(report_json(&c.check, vec![])),
22 Err(e) => e,
23 }
24 }
25
26 pub fn do_format(&self, args: &FormatArgs) -> CallToolResult {
30 use pikopiko::composer::edit::{format, FormatOptions};
31 const MAX_WIDTH: u32 = 1000;
32 let width = args.width.unwrap_or(100);
33 if width > MAX_WIDTH {
34 return tool_error(self.tr(
35 "mcp-tool-bad-width",
36 &[("value", width.to_string()), ("max", MAX_WIDTH.to_string())],
37 ));
38 }
39 let check = match self.compile_song(
40 &args.mml,
41 args.dialect.as_deref(),
42 args.includes.as_ref(),
43 "mcp-tool-what-format",
44 ) {
45 Ok((_, check)) => check,
46 Err(e) => return e,
47 };
48 let dialect = match resolve_dialect(args.dialect.as_deref(), &self.i18n) {
49 Ok(d) => d,
50 Err(e) => return e,
51 };
52 let sources = pikopiko::compiler::include::Sources::new(
53 args.includes
54 .iter()
55 .flatten()
56 .map(|(k, v)| (k.clone(), v.clone())),
57 );
58 let loader =
59 pikopiko::synth::tones::user::WithLibraries::new(Some(&sources), &self.config.tones);
60 let opts = CompileOptions {
61 dialect,
62 synths: pikopiko::synth::all(),
63 include: Some(&loader),
64 ..Default::default()
65 };
66 let fmt = FormatOptions {
67 width: width as usize,
68 normalize: args.normalize.unwrap_or(false),
69 };
70 match format(&args.mml, &fmt, &opts) {
71 Ok(text) => {
72 let changed = text != args.mml;
73 CallToolResult::structured(report_json(
74 &check,
75 vec![("mml", Value::String(text)), ("changed", json!(changed))],
76 ))
77 }
78 Err(diags) => {
79 let check = CheckReport::new(diags)
80 .in_lang(self.i18n.lang())
81 .with_messages(|d| self.i18n.diagnostic(d));
82 failed(&check, "mcp-tool-what-format", &self.i18n)
83 }
84 }
85 }
86
87 pub fn do_edit_timbre(&self, args: &EditTimbreArgs) -> CallToolResult {
92 use pikopiko::composer::edit::{self, TimbreTarget};
93 let (song, check) = match self.compile_song(
94 &args.mml,
95 args.dialect.as_deref(),
96 args.includes.as_ref(),
97 "mcp-tool-what-edit-timbre",
98 ) {
99 Ok(v) => v,
100 Err(e) => return e,
101 };
102 let spec = pikopiko::synth::find(pikopiko::synth::all(), &song.synth.name)
103 .unwrap_or(&pikopiko::synth::BASIC);
104 let dialect = match resolve_dialect(args.dialect.as_deref(), &self.i18n) {
106 Ok(d) => d,
107 Err(e) => return e,
108 };
109 let sources = pikopiko::compiler::include::Sources::new(
110 args.includes
111 .iter()
112 .flatten()
113 .map(|(k, v)| (k.clone(), v.clone())),
114 );
115 let loader =
116 pikopiko::synth::tones::user::WithLibraries::new(Some(&sources), &self.config.tones);
117 let opts = CompileOptions {
118 dialect,
119 synths: pikopiko::synth::all(),
120 include: Some(&loader),
121 ..Default::default()
122 };
123 let name_of = |t: &TimbreTarget| match t {
124 TimbreTarget::Track(n) => n.clone(),
125 TimbreTarget::Macro(n) => format!("${n}"),
126 };
127 let timbre_json = |t: &edit::Timbre| {
128 let params: Map<String, Value> = t
129 .params
130 .iter()
131 .map(|(k, v)| (k.clone(), json!(v)))
132 .collect();
133 json!({ "target": name_of(&t.target), "tone": t.tone, "params": params, "macros": t.macros })
134 };
135 let list = edit::timbres(&args.mml, &opts);
136 let Some(target_name) = args.target.as_deref() else {
137 let all: Vec<Value> = list.iter().map(timbre_json).collect();
138 return CallToolResult::structured(report_json(
139 &check,
140 vec![("synth", json!(spec.name)), ("timbres", Value::Array(all))],
141 ));
142 };
143 let target = match target_name.strip_prefix('$') {
144 Some(m) => TimbreTarget::Macro(m.to_string()),
145 None => TimbreTarget::Track(target_name.to_string()),
146 };
147 if !list.iter().any(|t| t.target == target) {
148 let names: Vec<String> = list.iter().map(|t| name_of(&t.target)).collect();
149 return tool_error(self.tr(
150 "mcp-tool-unknown-target",
151 &[("name", target_name.into()), ("names", names.join(", "))],
152 ));
153 }
154 let names = |it: &mut dyn Iterator<Item = &'static str>| it.collect::<Vec<_>>().join(", ");
155 let mut text = args.mml.clone();
156 let invalid = |diags: Vec<pikopiko::Diagnostic>| {
157 let check = CheckReport::new(diags)
158 .in_lang(self.i18n.lang())
159 .with_messages(|d| self.i18n.diagnostic(d));
160 let message = self.tr("mcp-tool-edit-timbre-invalid", &[]);
161 CallToolResult::structured_error(report_json(
162 &check,
163 vec![("error", Value::String(message))],
164 ))
165 };
166 if let Some(p) = args.preset.as_deref() {
167 let Some(preset) = spec.preset(p) else {
168 return tool_error(self.tr(
169 "mcp-tool-unknown-preset",
170 &[
171 ("name", p.into()),
172 ("synth", spec.name.into()),
173 ("names", names(&mut spec.presets.iter().map(|x| x.name))),
174 ],
175 ));
176 };
177 text = match edit::replace_timbre(&text, &target, preset.body, &opts) {
178 Ok(t) => t,
179 Err(d) => return invalid(d),
180 };
181 }
182 let mut changes: Vec<(&str, u32)> = Vec::new();
183 if let Some(knobs) = &args.knobs {
184 let base = edit::timbres(&text, &opts)
185 .into_iter()
186 .find(|t| t.target == target)
187 .map(|t| t.params)
188 .unwrap_or_default();
189 let max = pikopiko::synth::KNOB_STEPS;
190 for (k, &steps) in knobs {
191 let Some(knob) = spec.knob(k) else {
192 return tool_error(self.tr(
193 "mcp-tool-unknown-knob",
194 &[
195 ("name", k.clone()),
196 ("synth", spec.name.into()),
197 ("names", names(&mut spec.knobs.iter().map(|x| x.name))),
198 ],
199 ));
200 };
201 if !(-max..=max).contains(&steps) {
202 return tool_error(self.tr(
203 "mcp-tool-bad-knob-steps",
204 &[
205 ("name", k.clone()),
206 ("value", steps.to_string()),
207 ("max", max.to_string()),
208 ],
209 ));
210 }
211 changes.extend(knob.values(spec, steps, &base));
212 }
213 }
214 if let Some(params) = &args.params {
215 for (name, &value) in params {
216 let Some(info) = spec.params.iter().find(|p| p.name == name) else {
217 return tool_error(self.tr(
218 "mcp-tool-unknown-param",
219 &[
220 ("name", name.clone()),
221 ("synth", spec.name.into()),
222 ("names", names(&mut spec.params.iter().map(|x| x.name))),
223 ],
224 ));
225 };
226 changes.push((info.name, value));
227 }
228 }
229 if !changes.is_empty() {
230 text = match edit::set_timbre_params(&text, &target, &changes, &opts) {
231 Ok(t) => t,
232 Err(d) => return invalid(d),
233 };
234 }
235 let (_, diags) = pikopiko::compile_with(&text, &opts);
236 let check = CheckReport::new(diags)
237 .in_lang(self.i18n.lang())
238 .with_messages(|d| self.i18n.diagnostic(d));
239 let now = edit::timbres(&text, &opts)
240 .into_iter()
241 .find(|t| t.target == target)
242 .map(|t| timbre_json(&t))
243 .unwrap_or(Value::Null);
244 CallToolResult::structured(report_json(
245 &check,
246 vec![("mml", Value::String(text)), ("timbre", now)],
247 ))
248 }
249
250 pub fn do_describe(&self, args: &MmlArgs) -> CallToolResult {
251 let (song, check) = match self.compile_song(
252 &args.mml,
253 args.dialect.as_deref(),
254 args.includes.as_ref(),
255 "mcp-tool-what-describe",
256 ) {
257 Ok(v) => v,
258 Err(e) => return e,
259 };
260 let info = serde_json::to_value(pikopiko::describe_with(&song, pikopiko::synth::all()))
261 .unwrap_or(Value::Null);
262 CallToolResult::structured(report_json(&check, vec![("info", info)]))
263 }
264
265 pub fn do_build(&self, args: &BuildArgs) -> CallToolResult {
266 let (song, check) = match self.compile_song(
267 &args.mml,
268 args.dialect.as_deref(),
269 args.includes.as_ref(),
270 "mcp-tool-what-build",
271 ) {
272 Ok(v) => v,
273 Err(e) => return e,
274 };
275 let (bytes, stats) = match pikopiko::export::binary::encode_with_stats(&song) {
276 Ok(r) => r,
277 Err(e) => {
278 let e = self.i18n.error(&e);
279 return tool_error(self.tr("mcp-tool-encode-failed", &[("error", e)]));
280 }
281 };
282 let mut binary = Map::new();
283 binary.insert("format".into(), json!(bytes[0] >> 4));
284 binary.insert(
285 "sizes".into(),
286 serde_json::to_value(BuildSizes::new(&song, &stats)).unwrap_or(Value::Null),
287 );
288 let style = match args.inline.as_deref() {
289 Some(name) => match crate::inline::Inline::from_name(name) {
290 Some(s) => Some(s),
291 None => {
292 return tool_error(self.tr(
293 "mcp-tool-bad-inline",
294 &[
295 ("value", name.to_string()),
296 ("names", crate::inline::NAMES.join(", ")),
297 ],
298 ))
299 }
300 },
301 None => args
302 .include_hex
303 .unwrap_or(false)
304 .then_some(crate::inline::Inline::Hex),
305 };
306 if let Some(style) = style {
307 let limit = self.config.max_inline;
308 if bytes.len() <= limit {
309 let text = style.render(&bytes);
310 if style == crate::inline::Inline::Hex {
311 binary.insert("hex".into(), Value::String(text.clone()));
313 }
314 binary.insert(
315 "inline".into(),
316 json!({ "format": style.name(), "bytes": bytes.len(), "text": text }),
317 );
318 } else {
319 let note = self.tr(
320 "mcp-tool-hex-omitted",
321 &[
322 ("bytes", bytes.len().to_string()),
323 ("max", limit.to_string()),
324 ],
325 );
326 if style == crate::inline::Inline::Hex {
327 binary.insert("hex_omitted".into(), Value::String(note.clone()));
328 }
329 binary.insert("inline_omitted".into(), Value::String(note));
330 }
331 }
332 CallToolResult::structured(report_json(&check, vec![("binary", Value::Object(binary))]))
333 }
334
335 pub fn do_render(&self, args: &RenderArgs) -> CallToolResult {
336 let sample_rate = args.sample_rate.unwrap_or(44_100);
337 if !SAMPLE_RATE_RANGE.contains(&sample_rate) {
338 let (lo, hi) = (SAMPLE_RATE_RANGE.start(), SAMPLE_RATE_RANGE.end());
339 return tool_error(self.tr(
340 "mcp-tool-bad-sample-rate",
341 &[
342 ("value", sample_rate.to_string()),
343 ("min", lo.to_string()),
344 ("max", hi.to_string()),
345 ],
346 ));
347 }
348 let loops = args.loops.unwrap_or(0);
349 if loops > MAX_LOOPS {
350 return tool_error(self.tr(
351 "mcp-tool-bad-loops",
352 &[("value", loops.to_string()), ("max", MAX_LOOPS.to_string())],
353 ));
354 }
355 if let Some(n) = &args.name {
356 if !valid_file_name(n) {
357 return tool_error(self.tr("mcp-tool-bad-name", &[]));
358 }
359 }
360 let eq = match args.eq.as_deref().map(|e| crate::eq::parse(e, sample_rate)) {
361 None => None,
362 Some(Ok(eq)) => Some(eq),
363 Some(Err(crate::eq::EqTextError::Item(item))) => {
364 return tool_error(self.tr(
365 "mcp-tool-bad-eq",
366 &[("item", item), ("names", crate::eq::names())],
367 ));
368 }
369 Some(Err(crate::eq::EqTextError::TooMany)) => {
370 return tool_error(self.tr(
371 "mcp-tool-eq-too-many",
372 &[("max", pikopiko::runtime::output::MAX_BANDS.to_string())],
373 ));
374 }
375 };
376 let vgm = match args.format.as_deref() {
377 None | Some("wav") => None,
378 Some("vgm") => Some(false),
379 Some("vgz") => Some(true),
380 Some(f) => {
381 return tool_error(
382 self.tr("mcp-tool-unknown-render-format", &[("name", f.to_string())]),
383 );
384 }
385 };
386 let (song, check) = match self.compile_song(
387 &args.mml,
388 args.dialect.as_deref(),
389 args.includes.as_ref(),
390 "mcp-tool-what-render",
391 ) {
392 Ok(v) => v,
393 Err(e) => return e,
394 };
395 if let Some(gzip) = vgm {
396 return self.do_render_vgm(args, &song, &check, gzip);
397 }
398 let info = pikopiko::describe(&song);
399 let looped = info.duration_secs - info.loop_secs.unwrap_or(0.0);
400 let total_secs = info.duration_secs + f64::from(loops) * looped;
401 if total_secs > self.config.max_render_secs {
402 let max = self.config.max_render_secs;
403 return tool_error(self.tr(
404 "mcp-tool-too-long",
405 &[
406 ("secs", format!("{total_secs:.1}")),
407 ("max", format!("{max:.0}")),
408 ],
409 ));
410 }
411 let synth = pikopiko::synth::create(
412 pikopiko::synth::all(),
413 &song.synth,
414 sample_rate,
415 song.tracks.len(),
416 );
417 let mut samples = pikopiko::render_to_vec_looped_with(&song, sample_rate, synth, loops);
418 if let Some(eq) = eq {
419 pikopiko::runtime::output::OutputEq::new(eq).process_block(&mut samples);
420 }
421 let stats = audio_stats(&samples, sample_rate);
422 let wav = pikopiko::export::wav::encode_pcm16_with_meta(&samples, sample_rate, &song.meta);
423
424 let sample_rate_bytes = sample_rate.to_le_bytes();
425 let loops_bytes = loops.to_le_bytes();
426 let name = args.name.clone().unwrap_or_else(|| {
427 let mut parts: Vec<&[u8]> = vec![
429 args.mml.as_bytes(),
430 args.dialect.as_deref().unwrap_or("").as_bytes(),
431 &sample_rate_bytes,
432 &loops_bytes,
433 ];
434 for (k, v) in args.includes.iter().flatten() {
435 parts.push(k.as_bytes());
436 parts.push(v.as_bytes());
437 }
438 if let Some(e) = &args.eq {
440 parts.push(b"eq");
441 parts.push(e.as_bytes());
442 }
443 let h = fnv1a(&parts);
444 format!("render-{h:016x}")
445 });
446 if !self.config.write_files && wav.len() > AUDIO_EMBED_LIMIT {
448 return tool_error(self.tr(
449 "mcp-tool-audio-too-big",
450 &[
451 ("bytes", wav.len().to_string()),
452 ("max", AUDIO_EMBED_LIMIT.to_string()),
453 ],
454 ));
455 }
456 let path = if self.config.write_files {
457 let path = self.config.out_dir.join(format!("{name}.wav"));
458 if let Err(e) = std::fs::create_dir_all(&self.config.out_dir)
459 .and_then(|()| std::fs::write(&path, &wav))
460 {
461 return tool_error(self.tr(
462 "mcp-tool-write-failed",
463 &[
464 ("path", path.display().to_string()),
465 ("error", self.i18n.io_error(&e)),
466 ],
467 ));
468 }
469 Some(std::path::absolute(&path).unwrap_or(path))
471 } else {
472 None
473 };
474
475 let want_audio = args.include_audio.unwrap_or(!self.config.write_files);
477 let embed = want_audio && wav.len() <= AUDIO_EMBED_LIMIT;
478 let mut render = Map::new();
479 if let Some(path) = &path {
480 render.insert("path".into(), json!(path.display().to_string()));
481 }
482 render.insert("bytes".into(), json!(wav.len()));
483 render.insert("sample_rate".into(), json!(sample_rate));
484 render.insert("loops".into(), json!(loops));
485 if let Some(e) = &args.eq {
486 render.insert("eq".into(), json!(e));
487 }
488 render.insert("frames".into(), json!(samples.len()));
489 render.insert(
490 "duration_secs".into(),
491 json!(samples.len() as f64 / f64::from(sample_rate)),
492 );
493 render.insert(
494 "stats".into(),
495 serde_json::to_value(&stats).unwrap_or(Value::Null),
496 );
497 render.insert(
499 "sections".into(),
500 serde_json::to_value(pikopiko::report::song::analyze(
501 &song,
502 &samples,
503 sample_rate,
504 ))
505 .unwrap_or(Value::Null),
506 );
507 render.insert("audio_embedded".into(), json!(embed));
508 if want_audio && !embed {
509 render.insert(
510 "audio_omitted".into(),
511 Value::String(self.tr(
512 "mcp-tool-audio-omitted",
513 &[
514 ("bytes", wav.len().to_string()),
515 ("max", AUDIO_EMBED_LIMIT.to_string()),
516 ],
517 )),
518 );
519 }
520 let mut result = CallToolResult::structured(report_json(
521 &check,
522 vec![("render", Value::Object(render))],
523 ));
524 if embed {
525 result
526 .content
527 .push(ContentBlock::audio(base64(&wav), "audio/wav"));
528 }
529 result
530 }
531
532 #[cfg(feature = "vgm")]
536 fn do_render_vgm(
537 &self,
538 args: &RenderArgs,
539 song: &pikopiko::Song,
540 check: &pikopiko::report::CheckReport,
541 gzip: bool,
542 ) -> CallToolResult {
543 use std::io::Write;
544 let info = pikopiko::describe(song);
545 let max = self.config.max_render_secs;
546 if info.duration_secs > max {
547 return tool_error(self.tr(
548 "mcp-tool-too-long",
549 &[
550 ("secs", format!("{:.1}", info.duration_secs)),
551 ("max", format!("{max:.0}")),
552 ],
553 ));
554 }
555 let bytes = match pikopiko::export::vgm::encode_vgm(song) {
556 Ok(b) => b,
557 Err(e) => {
558 return tool_error(
559 self.tr("mcp-tool-vgm-failed", &[("error", self.i18n.error(&e))]),
560 );
561 }
562 };
563 let ext = if gzip { "vgz" } else { "vgm" };
564 let bytes = if gzip {
565 let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
566 match enc.write_all(&bytes).and_then(|()| enc.finish()) {
567 Ok(b) => b,
568 Err(e) => {
569 return tool_error(
570 self.tr("mcp-tool-vgm-failed", &[("error", self.i18n.io_error(&e))]),
571 );
572 }
573 }
574 } else {
575 bytes
576 };
577 let name = args.name.clone().unwrap_or_else(|| {
578 let mut parts: Vec<&[u8]> = vec![
579 args.mml.as_bytes(),
580 args.dialect.as_deref().unwrap_or("").as_bytes(),
581 ext.as_bytes(),
582 ];
583 for (k, v) in args.includes.iter().flatten() {
584 parts.push(k.as_bytes());
585 parts.push(v.as_bytes());
586 }
587 format!("render-{:016x}", fnv1a(&parts))
588 });
589 let mut render = Map::new();
590 if self.config.write_files {
591 let path = self.config.out_dir.join(format!("{name}.{ext}"));
592 if let Err(e) = std::fs::create_dir_all(&self.config.out_dir)
593 .and_then(|()| std::fs::write(&path, &bytes))
594 {
595 return tool_error(self.tr(
596 "mcp-tool-write-failed",
597 &[
598 ("path", path.display().to_string()),
599 ("error", self.i18n.io_error(&e)),
600 ],
601 ));
602 }
603 let path = std::path::absolute(&path).unwrap_or(path);
604 render.insert("path".into(), json!(path.display().to_string()));
605 } else {
606 if bytes.len() > AUDIO_EMBED_LIMIT {
608 return tool_error(self.tr(
609 "mcp-tool-audio-too-big",
610 &[
611 ("bytes", bytes.len().to_string()),
612 ("max", AUDIO_EMBED_LIMIT.to_string()),
613 ],
614 ));
615 }
616 render.insert("base64".into(), json!(base64(&bytes)));
617 }
618 render.insert("bytes".into(), json!(bytes.len()));
619 render.insert("format".into(), json!(ext));
620 render.insert("duration_secs".into(), json!(info.duration_secs));
621 CallToolResult::structured(report_json(check, vec![("render", Value::Object(render))]))
622 }
623
624 #[cfg(not(feature = "vgm"))]
626 fn do_render_vgm(
627 &self,
628 _args: &RenderArgs,
629 _song: &pikopiko::Song,
630 _check: &pikopiko::report::CheckReport,
631 _gzip: bool,
632 ) -> CallToolResult {
633 tool_error(self.tr("mcp-tool-vgm-unavailable", &[]))
634 }
635
636 pub fn do_list_synths(&self, args: &ListSynthsArgs) -> CallToolResult {
638 let all = pikopiko::synth::all();
639 let one;
640 let synths: &[&pikopiko::synth::SynthSpec] = match &args.only {
641 None => all,
642 Some(name) => match pikopiko::synth::find(all, name) {
643 Some(spec) => {
644 one = [spec];
645 &one
646 }
647 None => {
648 let names: Vec<&str> = all.iter().map(|s| s.name).collect();
649 return tool_error(self.tr(
650 "mcp-tool-unknown-synth",
651 &[("name", name.clone()), ("names", names.join(", "))],
652 ));
653 }
654 },
655 };
656 let i18n = &self.i18n;
658 let synths = synth_catalog_with(synths, i18n.lang(), &mut |k| i18n.override_text(k));
659 let mut out = json!({ "synths": serde_json::to_value(synths).unwrap_or(Value::Null) });
660 if !self.config.tones.is_empty() && args.only.is_none() {
662 let lang = i18n.lang();
663 let mut mine: Vec<Value> = Vec::new();
664 for lib in &self.config.tones {
665 for k in &lib.kinds {
666 let description =
667 pikopiko::synth::tones::user::pick_description(&k.description, lang);
668 for t in k.tones() {
669 mine.push(json!({
670 "name": t.name,
671 "kind": t.kind,
672 "file": format!("@{}/{}", lib.name, k.name),
673 "description": description,
674 "synth": lib.synth,
675 "source": "user",
676 }));
677 }
678 }
679 }
680 out["user_library"] = Value::Array(mine);
681 }
682 CallToolResult::structured(out)
683 }
684
685 fn user_tones(&self, file: &str) -> Option<CallToolResult> {
688 let (lib, kind) = file.strip_prefix('@')?.split_once('/')?;
689 let lib = self.config.tones.iter().find(|l| l.name == lib)?;
690 if lib.clashes(pikopiko::synth::all()) {
692 return None;
693 }
694 let Some(k) = lib.kind(kind) else {
695 let names: Vec<String> = lib
696 .kinds
697 .iter()
698 .map(|k| format!("@{}/{}", lib.name, k.name))
699 .collect();
700 return Some(tool_error(self.tr(
701 "mcp-tool-unknown-library",
702 &[("name", file.to_string()), ("names", names.join(", "))],
703 )));
704 };
705 let description =
706 pikopiko::synth::tones::user::pick_description(&k.description, self.i18n.lang());
707 let tones: Vec<Value> = k
708 .tones()
709 .iter()
710 .map(|t| {
711 json!({
712 "name": t.name,
713 "kind": t.kind,
714 "file": file,
715 "body": t.body,
716 "description": description,
717 })
718 })
719 .collect();
720 Some(CallToolResult::structured(json!({
721 "file": file,
722 "kind": k.name,
723 "synth": lib.synth,
724 "source": "user",
725 "text": k.text,
726 "tones": tones,
727 })))
728 }
729
730 pub fn do_get_tones(&self, args: &GetTonesArgs) -> CallToolResult {
735 use pikopiko::synth::tones as library;
736 if let Some(r) = self.user_tones(&args.file) {
737 return r;
738 }
739 let found = args
740 .file
741 .strip_prefix('@')
742 .and_then(|p| p.split_once('/'))
743 .and_then(|(synth, name)| {
744 let spec = pikopiko::synth::find(pikopiko::synth::all(), synth)?;
745 Some((spec, spec.tone_file(name)?, library::tones_in(spec, name)?))
746 });
747 let Some((spec, file, tones)) = found else {
748 let names: Vec<String> = pikopiko::synth::all()
749 .iter()
750 .flat_map(|s| {
751 s.tone_files
752 .iter()
753 .map(move |f| format!("@{}/{}", s.library_prefix(), f.name))
754 })
755 .collect();
756 return tool_error(self.tr(
757 "mcp-tool-unknown-library",
758 &[("name", args.file.clone()), ("names", names.join(", "))],
759 ));
760 };
761 let lang = self.i18n.lang();
762 let tones: Vec<Value> = tones
763 .iter()
764 .map(|t| {
765 let description = self
766 .i18n
767 .override_text(&t.text_key())
768 .unwrap_or_else(|| spec.library_description(t.name, lang).to_string());
769 json!({
770 "name": t.name,
771 "kind": t.kind,
772 "file": t.path(),
773 "body": t.body,
774 "description": description,
775 })
776 })
777 .collect();
778 CallToolResult::structured(json!({
779 "file": format!("@{}/{}", spec.library_prefix(), file.name),
780 "kind": file.kind,
781 "text": library::file_text(spec, file, lang),
782 "tones": tones,
783 }))
784 }
785
786 pub fn do_measure_tone(&self, args: &MeasureToneArgs) -> CallToolResult {
793 use pikopiko::report::tone;
794 let Some(category) = tone::Category::from_name(&args.category) else {
795 let names: Vec<&str> = tone::ALL.iter().map(|c| c.name()).collect();
796 return tool_error(self.tr(
797 "mcp-tool-unknown-category",
798 &[("name", args.category.clone()), ("names", names.join(", "))],
799 ));
800 };
801 if let Some(n) = &args.name {
802 if !valid_file_name(n) {
803 return tool_error(self.tr("mcp-tool-bad-name", &[]));
804 }
805 }
806 use crate::audio_file::{encode, AudioFormat, EncodeError};
807 let format = match args.format.as_deref() {
808 None => AudioFormat::Wav,
809 Some(f) => match AudioFormat::from_name(f) {
810 Some(format) => format,
811 None => {
812 return tool_error(
813 self.tr("mcp-tool-unknown-format", &[("name", f.to_string())]),
814 )
815 }
816 },
817 };
818 let synth = args.synth.as_deref().unwrap_or("va");
819 let spec = pikopiko::synth::find(pikopiko::synth::all(), synth);
820 let mml = match spec {
822 Some(spec) => pikopiko::synth::tones::audition_mml_for(spec, category, &args.timbre),
823 None => tone::audition_mml(category, synth, &args.timbre),
824 };
825 let (song, check) = match self.compile_song(&mml, None, None, "mcp-tool-what-measure-tone")
826 {
827 Ok(v) => v,
828 Err(e) => return e,
829 };
830 let reference = match &args.reference {
832 Some(name) => match self.read_reference(name, args) {
833 Ok(m) => Some(m),
834 Err(e) => return e,
835 },
836 None => None,
837 };
838 const RATE: u32 = 44_100;
839 let options = tone::AuditionOptions::default().with_alias(args.alias.unwrap_or(false));
840 let mut report = tone::report_with(category, &song, mml, RATE, options);
841 if let Some(spec) = spec {
843 pikopiko::synth::tones::compare(&mut report, spec, RATE, 3);
844 }
845 let name = args.name.clone().unwrap_or_else(|| {
846 let h = fnv1a(&[report.mml.as_bytes()]);
847 format!("tone-{h:016x}")
848 });
849 let path = self
850 .config
851 .out_dir
852 .join(format!("{name}.{}", format.extension()));
853 let bytes = match encode(&report.samples, RATE, format) {
854 Ok(b) => b,
855 Err(e) => {
856 let key = match e {
857 EncodeError::Mp3Unavailable => "mcp-tool-mp3-unavailable",
858 EncodeError::Mp3Failed => "mcp-tool-mp3-failed",
859 };
860 return tool_error(self.tr(key, &[("path", path.display().to_string())]));
861 }
862 };
863 if let Err(e) = std::fs::create_dir_all(&self.config.out_dir)
864 .and_then(|()| std::fs::write(&path, &bytes))
865 {
866 return tool_error(self.tr(
867 "mcp-tool-write-failed",
868 &[
869 ("path", path.display().to_string()),
870 ("error", self.i18n.io_error(&e)),
871 ],
872 ));
873 }
874 let path = std::path::absolute(&path).unwrap_or(path);
875 let mut fields = vec![
876 ("tone", serde_json::to_value(&report).unwrap_or(Value::Null)),
877 ("path", json!(path.display().to_string())),
878 ];
879 if let Some(m) = &reference {
880 let c = tone::compare_audition(&report, m);
881 fields.push(("reference", serde_json::to_value(m).unwrap_or(Value::Null)));
882 fields.push((
883 "comparison",
884 serde_json::to_value(&c).unwrap_or(Value::Null),
885 ));
886 }
887 CallToolResult::structured(report_json(&check, fields))
888 }
889
890 fn read_reference(
894 &self,
895 name: &str,
896 args: &MeasureToneArgs,
897 ) -> Result<pikopiko::report::tone::ToneMetrics, CallToolResult> {
898 use crate::reference::{measure_reference, Cut, ReferenceError, WavError};
899 let Some(dir) = &self.config.ref_dir else {
900 return Err(tool_error(self.tr("mcp-tool-ref-no-dir", &[])));
901 };
902 let plain = !name.is_empty()
903 && name != "."
904 && name != ".."
905 && !name.contains(['/', '\\', ':'])
906 && std::path::Path::new(name).components().count() == 1;
907 if !plain {
908 return Err(tool_error(
909 self.tr("mcp-tool-ref-bad-name", &[("name", name.to_string())]),
910 ));
911 }
912 let bytes = std::fs::read(dir.join(name)).map_err(|e| {
913 tool_error(self.tr(
914 "mcp-tool-ref-read",
915 &[
916 ("name", name.to_string()),
917 ("error", self.i18n.io_error(&e)),
918 ],
919 ))
920 })?;
921 let cut = Cut {
922 from: args.reference_from,
923 to: args.reference_to,
924 release: args.reference_release,
925 note: args.reference_note.clone(),
926 };
927 measure_reference(&bytes, &cut).map_err(|e| {
928 let n = ("name", name.to_string());
929 tool_error(match e {
930 ReferenceError::Wav(WavError::NotWav) => self.tr("mcp-tool-ref-not-wav", &[n]),
931 ReferenceError::Wav(WavError::Truncated) => self.tr("mcp-tool-ref-truncated", &[n]),
932 ReferenceError::Wav(WavError::Unsupported { format, bits }) => self.tr(
933 "mcp-tool-ref-unsupported",
934 &[
935 n,
936 ("format", format.to_string()),
937 ("bits", bits.to_string()),
938 ],
939 ),
940 ReferenceError::BadNote(note) => self.tr("mcp-tool-ref-note", &[("note", note)]),
941 ReferenceError::BadRange => self.tr("mcp-tool-ref-range", &[]),
942 })
943 })
944 }
945}