@ray0404/zig-audio-mcp 0.1.3 → 0.2.0

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.
package/dist/index.js CHANGED
@@ -1,8 +1,65 @@
1
1
  #!/usr/bin/env node
2
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
4
+ import { CallToolRequestSchema, ListToolsRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
5
  import { z } from "zod";
6
+ // MCP Prompts data
7
+ const PROMPTS = {
8
+ "library-selection": {
9
+ name: "library-selection",
10
+ description: "Help select the right audio library for your Zig project",
11
+ arguments: [
12
+ { name: "project_type", description: "synthesizer, audio-player, dsp-effects, file-io, sdr-radio, game-audio, embedded", required: true },
13
+ { name: "requirements", description: "optional: low-latency, no-allocations, cross-platform, simple-api", required: false }
14
+ ]
15
+ },
16
+ "synth-basics": {
17
+ name: "synth-basics",
18
+ description: "Step-by-step guide to building a basic synthesizer in Zig",
19
+ arguments: [
20
+ { name: "output_type", description: "wav-file, playback, both", required: false }
21
+ ]
22
+ },
23
+ "filter-design": {
24
+ name: "filter-design",
25
+ description: "Guide to designing audio filters in Zig",
26
+ arguments: [
27
+ { name: "filter_type", description: "lowpass, highpass, bandpass, notch, peaking", required: true },
28
+ { name: "sample_rate", description: "44100, 48000, 96000", required: false }
29
+ ]
30
+ },
31
+ "debugging-audio": {
32
+ name: "debugging-audio",
33
+ description: "Troubleshoot common audio programming issues",
34
+ arguments: [
35
+ { name: "issue", description: "glitches, latency, no-sound, crash, poor-quality", required: true }
36
+ ]
37
+ }
38
+ };
39
+ function generatePromptContent(promptName, args) {
40
+ switch (promptName) {
41
+ case "library-selection": {
42
+ const projectType = args.project_type || "synthesizer";
43
+ const requirements = args.requirements || "";
44
+ return `Help select the best Zig audio library for a ${projectType} project${requirements ? ` with requirements: ${requirements}` : ""}.`;
45
+ }
46
+ case "synth-basics": {
47
+ const outputType = args.output_type || "playback";
48
+ return `Provide a step-by-step guide to building a basic synthesizer in Zig that outputs to ${outputType}. Include oscillator setup, envelope, and audio output.`;
49
+ }
50
+ case "filter-design": {
51
+ const filterType = args.filter_type || "lowpass";
52
+ const sampleRate = args.sample_rate || "44100";
53
+ return `Explain how to design and implement a ${filterType} filter in Zig at ${sampleRate}Hz sample rate. Include coefficient calculation and implementation code.`;
54
+ }
55
+ case "debugging-audio": {
56
+ const issue = args.issue || "glitches";
57
+ return `Help debug a ${issue} issue in Zig audio programming. What are common causes and solutions?`;
58
+ }
59
+ default:
60
+ return "Unknown prompt request";
61
+ }
62
+ }
6
63
  // Library information database
7
64
  const ZIG_AUDIO_LIBRARIES = {
8
65
  zang: {
@@ -82,6 +139,45 @@ const ZIG_AUDIO_LIBRARIES = {
82
139
  examples: ["Entity-component audio", "High-performance mixing", "Modular processing"],
83
140
  api_docs: "https://github.com/chr15m/dalek",
84
141
  use_cases: ["Game engines", "High-performance audio", "Large-scale audio processing"]
142
+ },
143
+ "zsynth": {
144
+ name: "zsynth",
145
+ description: "Simple FM synthesis library for Zig.",
146
+ repo: "https://github.com/zsynth/zsynth",
147
+ license: "MIT",
148
+ features: ["fm-synthesis", "operators", "modulation"],
149
+ categories: ["synthesis", "effects"],
150
+ installation: "Add to build.zig.zon: .url = \"git+https://github.com/zsynth/zsynth#master\"",
151
+ version: "Zig 0.11+",
152
+ examples: ["FM operators", "Modulation matrices"],
153
+ api_docs: "https://github.com/zsynth/zsynth",
154
+ use_cases: ["FM synthesis", "Electronic tones", "Sound design"]
155
+ },
156
+ "zig-synth": {
157
+ name: "zig-synth",
158
+ description: "Zig wrapper for sokol_audio for low-latency audio.",
159
+ repo: "https://github.com/zig-synth/zig-synth",
160
+ license: "MIT",
161
+ features: ["low-latency", "sokol", "playback"],
162
+ categories: ["playback", "wrapper"],
163
+ installation: "Add to build.zig.zon: .url = \"git+https://github.com/zig-synth/zig-synth#master\"",
164
+ version: "Zig 0.10+",
165
+ examples: ["Simple playback", "Streaming"],
166
+ api_docs: "https://github.com/zig-synth/zig-synth",
167
+ use_cases: ["Games", "Interactive audio", "Low-latency apps"]
168
+ },
169
+ noize: {
170
+ name: "noize",
171
+ description: "Simple audio synthesis library with a focus on ease of use.",
172
+ repo: "https://github.com/noize/noize",
173
+ license: "MIT",
174
+ features: ["synthesis", "generators", "noise"],
175
+ categories: ["synthesis", "dsp"],
176
+ installation: "Add to build.zig.zon: .url = \"git+https://github.com/noize/noize#master\"",
177
+ version: "Zig 0.11+",
178
+ examples: ["Noise generators", "Basic synthesis"],
179
+ api_docs: "https://github.com/noize/noize",
180
+ use_cases: ["Prototyping", "Learning audio", "Simple synthesis"]
85
181
  }
86
182
  };
87
183
  // Filter information for DSP explanations
@@ -129,13 +225,154 @@ const DSP_FILTERS = {
129
225
  zigLibraries: ["zang"]
130
226
  }
131
227
  };
228
+ // MCP Resources - Static reference data exposed as resources
229
+ const RESOURCES = {
230
+ "zig-audio://libraries": {
231
+ uri: "zig-audio://libraries",
232
+ name: "Zig Audio Libraries",
233
+ description: "Complete database of Zig audio/DSP libraries with details, features, and use cases",
234
+ mimeType: "application/json",
235
+ data: ZIG_AUDIO_LIBRARIES
236
+ },
237
+ "zig-dsp://filters": {
238
+ uri: "zig-dsp://filters",
239
+ name: "DSP Filter Reference",
240
+ description: "Reference for all DSP filter types with formulas, use cases, and compatible Zig libraries",
241
+ mimeType: "application/json",
242
+ data: DSP_FILTERS
243
+ },
244
+ "zig-dsp://concepts": {
245
+ uri: "zig-dsp://concepts",
246
+ name: "Audio/DSP Concepts",
247
+ description: "Fundamental audio and DSP terminology including sample rate, bit depth, buffer size, Nyquist frequency, and aliasing",
248
+ mimeType: "application/json",
249
+ data: {
250
+ "sample-rate": {
251
+ description: "Number of samples captured per second (e.g., 44100 Hz, 48000 Hz)",
252
+ typicalValues: [44100, 48000, 96000],
253
+ impact: "Higher rates = more accurate audio but more CPU/memory"
254
+ },
255
+ "bit-depth": {
256
+ description: "Number of bits per sample for amplitude resolution",
257
+ typicalValues: [16, 24, 32],
258
+ impact: "Higher depth = more dynamic range, less quantization noise"
259
+ },
260
+ "buffer-size": {
261
+ description: "Number of samples processed per callback cycle",
262
+ typicalValues: [64, 128, 256, 512, 1024],
263
+ impact: "Smaller = lower latency, higher CPU; larger = more stable, more latency"
264
+ },
265
+ "nyquist-frequency": {
266
+ description: "Maximum representable frequency (sample_rate / 2)",
267
+ formula: "f_nyquist = sample_rate / 2"
268
+ },
269
+ "aliasing": {
270
+ description: "Distortion from sampling frequencies above Nyquist",
271
+ prevention: "Use anti-aliasing filters before downsampling"
272
+ }
273
+ }
274
+ },
275
+ "zig-audio://templates/code": {
276
+ uri: "zig-audio://templates/code",
277
+ name: "Code Templates",
278
+ description: "Starter code templates for common audio/DSP tasks in Zig",
279
+ mimeType: "application/json",
280
+ data: {
281
+ oscillator: "Starter code for oscillators using zang",
282
+ envelope: "ADSR envelope implementation using zang",
283
+ filter: "Biquad filter implementation using zang",
284
+ delay: "Delay effect using bonk",
285
+ mixer: "Simple audio mixer implementation",
286
+ player: "Audio playback using zaudio",
287
+ recorder: "Audio recording using zaudio",
288
+ "file-write": "Write WAV file using pcm",
289
+ "file-read": "Read WAV file using pcm"
290
+ }
291
+ },
292
+ "zig-audio://templates/project": {
293
+ uri: "zig-audio://templates/project",
294
+ name: "Project Templates",
295
+ description: "Complete project skeletons for different audio application types",
296
+ mimeType: "application/json",
297
+ data: {
298
+ synthesizer: "Full synthesizer project with zang",
299
+ "audio-player": "Audio playback project with zaudio",
300
+ "dsp-processor": "DSP effects processor with bonk",
301
+ "file-processor": "Audio file processor with pcm",
302
+ "game-audio": "Game audio system with zang + zaudio"
303
+ }
304
+ },
305
+ "zig-audio://resources": {
306
+ uri: "zig-audio://resources",
307
+ name: "Learning Resources",
308
+ description: "Curated tutorials, examples, articles, and references for Zig audio development",
309
+ mimeType: "application/json",
310
+ data: [
311
+ { type: "tutorial", title: "Zig Audio Ecosystem Overview", url: "https://github.com/topics/zig-audio", description: "Overview of audio libraries in Zig ecosystem" },
312
+ { type: "tutorial", title: "Getting Started with Zang", url: "https://github.com/dbandstra/zang", description: "Complete guide to zang synthesis library" },
313
+ { type: "tutorial", title: "Audio Programming in Zig", url: "https://ziglang.org/learn/samples/#audio", description: "Official Zig language audio programming samples" },
314
+ { type: "example", title: "Zang Examples Repository", url: "https://github.com/dbandstra/zang/tree/master/examples", description: "Complete examples for oscillators, effects, and synthesis" },
315
+ { type: "reference", title: "Zaudio API Documentation", url: "https://github.com/MasterQ32/zaudio", description: "Complete API reference for miniaudio wrapper" },
316
+ { type: "reference", title: "Digital Signal Processing Fundamentals", url: "https://www.dspguide.com/", description: "Comprehensive DSP theory and algorithms reference" },
317
+ { type: "article", title: "Building Real-time Audio Apps in Zig", url: "https://christine.website/blog/zig-dsp-01-2024", description: "In-depth tutorial on DSP effects and real-time processing" },
318
+ { type: "reference", title: "Audio EQ Cookbook", url: "https://www.w3.org/TR/audio-eq-cookbook/", description: "Standard biquad filter coefficient calculations" },
319
+ { type: "tutorial", title: "Cross-Platform Audio Development", url: "https://miniaud.io/docs/manual/index.html", description: "Miniaudio documentation (used by zaudio)" },
320
+ { type: "forum", title: "Zig Discord Audio Channel", url: "https://discord.gg/zig-lang", description: "Zig language Discord server audio programming discussions" },
321
+ { type: "forum", title: "Ziggit Audio Forum", url: "https://ziggit.dev", description: "Zig community forum with audio programming topics" }
322
+ ]
323
+ },
324
+ "zig-audio://troubleshooting": {
325
+ uri: "zig-audio://troubleshooting",
326
+ name: "Troubleshooting Guide",
327
+ description: "Common audio programming issues and their solutions",
328
+ mimeType: "application/json",
329
+ data: {
330
+ "audio-glitches": { issue: "Audio glitches, pops, or clicks", likely_causes: ["Buffer size too small", "CPU overload", "Memory allocations in audio callback"], solutions: ["Increase buffer size", "Reduce processing complexity", "Use no-allocation libraries"] },
331
+ "latency": { issue: "High audio latency", likely_causes: ["Large buffer size", "Excessive processing"], solutions: ["Reduce buffer size", "Use low-latency libraries"] },
332
+ "no-sound": { issue: "No sound output", likely_causes: ["Audio device not initialized", "Volume at zero"], solutions: ["Verify device initialization", "Check system volume"] },
333
+ "crash": { issue: "Application crashes", likely_causes: ["Null pointer in audio callback", "Memory corruption"], solutions: ["Initialize all objects before use", "Use defer cleanup"] },
334
+ "compilation-error": { issue: "Compilation errors", likely_causes: ["Zig version mismatch", "Missing dependencies"], solutions: ["Check library's Zig version", "Verify module imports"] },
335
+ "performance": { issue: "Poor performance or high CPU", likely_causes: ["Inefficient algorithms", "Excessive allocations"], solutions: ["Pre-compute coefficients", "Avoid allocations in callbacks"] }
336
+ }
337
+ },
338
+ "zig-audio://compatibility": {
339
+ uri: "zig-audio://compatibility",
340
+ name: "Library Compatibility Matrix",
341
+ description: "Zig version compatibility status for each audio library",
342
+ mimeType: "application/json",
343
+ data: {
344
+ "zang": { latest_version: "0.12+ compatible", status: "active", notes: "Actively maintained" },
345
+ "zaudio": { latest_version: "Zig 0.11+", status: "needs-update", notes: "May need updates for Zig 0.12+" },
346
+ "bonk": { latest_version: "Zig 0.10+", status: "needs-update", notes: "Check for newer releases" },
347
+ "pcm": { latest_version: "Zig 0.9+", status: "deprecated", notes: "Very outdated, consider alternatives" },
348
+ "zig-liquid-dsp": { latest_version: "Zig 0.11+", status: "active", notes: "Check for 0.12 support" },
349
+ "dalek": { latest_version: "Zig 0.10+", status: "experimental", notes: "API may change" }
350
+ }
351
+ }
352
+ };
353
+ // Resource Templates for parameterized access
354
+ const RESOURCE_TEMPLATES = [
355
+ {
356
+ uriTemplate: "zig-audio://libraries/{name}",
357
+ name: "Library Details",
358
+ description: "Get detailed information about a specific Zig audio library by name",
359
+ mimeType: "application/json"
360
+ },
361
+ {
362
+ uriTemplate: "zig-dsp://filters/{type}",
363
+ name: "Filter Details",
364
+ description: "Get detailed information about a specific DSP filter type",
365
+ mimeType: "application/json"
366
+ }
367
+ ];
132
368
  // Tool input validation schemas
369
+ const LIBRARY_ENUM = z.enum(["zang", "zaudio", "bonk", "pcm", "zig-liquid-dsp", "dalek", "zsynth", "zig-synth", "noize"]);
133
370
  const ListLibrariesInput = z.object({
134
371
  category: z.enum(["synthesis", "effects", "filters", "dsp", "playback", "recording", "file-io", "encoding", "sdr", "engine", "wrapper", "experimental", "all"]).optional(),
135
372
  feature: z.string().optional()
136
373
  });
137
374
  const GetLibraryInfoInput = z.object({
138
- library: z.enum(["zang", "zaudio", "bonk", "pcm", "zig-liquid-dsp", "dalek"])
375
+ library: LIBRARY_ENUM
139
376
  });
140
377
  const ExplainFilterInput = z.object({
141
378
  filter_type: z.enum(["lowpass", "highpass", "bandpass", "notch", "biquad", "one-pole"])
@@ -145,7 +382,7 @@ const GenerateCodeInput = z.object({
145
382
  parameters: z.record(z.union([z.string(), z.number(), z.boolean()])).optional()
146
383
  });
147
384
  const ListResourcesInput = z.object({
148
- resource_type: z.enum(["tutorial", "reference", "example", "article"]).optional()
385
+ resource_type: z.enum(["tutorial", "reference", "example", "article", "video", "forum", "github-issues"]).optional()
149
386
  });
150
387
  const RecommendLibraryInput = z.object({
151
388
  use_case: z.string().describe("Describe what you want to build (e.g., 'synthesizer', 'audio player', 'DSP effects')"),
@@ -161,13 +398,29 @@ const DesignFilterInput = z.object({
161
398
  })
162
399
  });
163
400
  const VerifyCodeInput = z.object({
164
- code: z.string().describe("Zig code to verify for basic syntax and imports"),
401
+ code: z.string().max(50000).describe("Zig code to verify for basic syntax and imports"),
165
402
  libraries: z.array(z.string()).optional().describe("Expected libraries that should be imported")
166
403
  });
167
404
  const ProjectTemplateInput = z.object({
168
405
  project_type: z.enum(["synthesizer", "audio-player", "dsp-processor", "file-processor", "game-audio"]),
169
406
  features: z.array(z.string()).optional().describe("Additional features to include")
170
407
  });
408
+ const CompareLibrariesInput = z.object({
409
+ libraries: z.array(LIBRARY_ENUM).min(2).max(6)
410
+ });
411
+ const TroubleshootInput = z.object({
412
+ issue_type: z.enum(["audio-glitches", "latency", "no-sound", "crash", "compilation-error", "performance"])
413
+ });
414
+ const DeprecationCheckInput = z.object({
415
+ library: LIBRARY_ENUM,
416
+ zig_version: z.string().regex(/^\d+\.\d+\.\d+$/).optional()
417
+ });
418
+ const CalculateDelayInput = z.object({
419
+ value: z.number().positive(),
420
+ from_unit: z.enum(["ms", "samples", "feet", "meters"]),
421
+ to_unit: z.enum(["ms", "samples", "feet", "meters"]),
422
+ sample_rate: z.number().default(44100)
423
+ });
171
424
  // Tool handlers
172
425
  async function handleListLibraries(args) {
173
426
  const input = ListLibrariesInput.parse(args);
@@ -194,12 +447,17 @@ async function handleVerifyCode(args) {
194
447
  issues.push("Missing std import but using std.math");
195
448
  suggestions.push('Add: const std = @import("std");');
196
449
  }
197
- // Check for common library imports
450
+ // Check for all library imports
198
451
  const libraryChecks = [
199
452
  { lib: "zang", pattern: /zang\./, import: 'const zang = @import("zang");' },
200
453
  { lib: "zaudio", pattern: /zaudio\./, import: 'const zaudio = @import("zaudio");' },
201
454
  { lib: "bonk", pattern: /bonk\./, import: 'const bonk = @import("bonk");' },
202
- { lib: "pcm", pattern: /pcm\./, import: 'const pcm = @import("pcm");' }
455
+ { lib: "pcm", pattern: /pcm\./, import: 'const pcm = @import("pcm");' },
456
+ { lib: "zig-liquid-dsp", pattern: /liquid\./, import: 'const liquid = @import("zig-liquid-dsp");' },
457
+ { lib: "dalek", pattern: /dalek\./, import: 'const dalek = @import("dalek");' },
458
+ { lib: "zsynth", pattern: /zsynth\./, import: 'const zsynth = @import("zsynth");' },
459
+ { lib: "sokol_audio", pattern: /sokol\./, import: 'const sokol = @import("sokol_audio");' },
460
+ { lib: "noize", pattern: /noize\./, import: 'const noize = @import("noize");' }
203
461
  ];
204
462
  for (const check of libraryChecks) {
205
463
  if (input.code.match(check.pattern) && !input.code.includes(check.import)) {
@@ -215,11 +473,22 @@ async function handleVerifyCode(args) {
215
473
  if (input.code.includes("try ") && !input.code.includes("!void")) {
216
474
  suggestions.push("Consider using error return types (!void) for functions with try");
217
475
  }
476
+ // Check for potential allocator issues
477
+ if (input.code.includes("GeneralPurposeAllocator") && !input.code.includes("defer _ = gpa.deinit()")) {
478
+ issues.push("Allocator created but may not be properly deinitialized");
479
+ suggestions.push("Add: defer _ = gpa.deinit(); after allocator creation");
480
+ }
481
+ // Check for missing defer in file operations
482
+ if (input.code.includes(".init(") && input.code.includes("defer") === false) {
483
+ if (input.code.includes("WavReader") || input.code.includes("Device")) {
484
+ suggestions.push("Consider adding defer cleanup for resource initialization");
485
+ }
486
+ }
218
487
  const verificationResult = {
219
488
  code_length: input.code.length,
220
489
  issues: issues.length > 0 ? issues : ["No obvious issues detected"],
221
490
  suggestions: suggestions.length > 0 ? suggestions : ["Code looks good"],
222
- libraries_found: libraryChecks.filter(check => input.code.includes(check.lib)).map(check => check.lib)
491
+ libraries_found: libraryChecks.filter(check => input.code.match(check.pattern)).map(check => check.lib)
223
492
  };
224
493
  return {
225
494
  content: [{
@@ -326,6 +595,162 @@ pub fn main() !void {
326
595
  .url = "https://github.com/MasterQ32/zaudio/archive/master.tar.gz",
327
596
  .hash = "1220...", // Get actual hash
328
597
  },
598
+ } }`
599
+ },
600
+ "dsp-processor": {
601
+ build_zig: `const std = @import("std");
602
+
603
+ pub fn build(b: *std.Build) void {
604
+ const target = b.standardTargetOptions(.{});
605
+ const optimize = b.standardOptimizeOption(.{});
606
+
607
+ const exe = b.addExecutable(.{
608
+ .name = "dsp-processor",
609
+ .root_source_file = .{ .path = "src/main.zig" },
610
+ .target = target,
611
+ .optimize = optimize,
612
+ });
613
+
614
+ const bonk = b.dependency("bonk", .{});
615
+ exe.root_module.addImport("bonk", bonk.module("bonk"));
616
+
617
+ b.installArtifact(exe);
618
+ }`,
619
+ main_zig: `const std = @import("std");
620
+ const bonk = @import("bonk");
621
+
622
+ pub fn main() !void {
623
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
624
+ defer _ = gpa.deinit();
625
+ const allocator = gpa.allocator();
626
+
627
+ var filter = bonk.Biquad.init(.{
628
+ .filter_type = .lowpass,
629
+ .cutoff = 1000.0,
630
+ .q = 0.707,
631
+ .sample_rate = 44100,
632
+ });
633
+
634
+ var input: [1024]f32 = undefined;
635
+ var output: [1024]f32 = undefined;
636
+
637
+ for (&input, 0..) |*sample, i| {
638
+ sample.* = @sin(@as(f32, @floatFromInt(i)) * 0.1);
639
+ }
640
+
641
+ filter.process(input[0..], output[0..]);
642
+ std.debug.print("Processed {} samples\\n", .{output.len});
643
+ }`,
644
+ build_zig_zon: `.{ .name = "dsp-processor", .version = "0.1.0", .dependencies = .{
645
+ .bonk = .{
646
+ .url = "https://github.com/chr15m/bonk/archive/master.tar.gz",
647
+ .hash = "1220...",
648
+ },
649
+ } }`
650
+ },
651
+ "file-processor": {
652
+ build_zig: `const std = @import("std");
653
+
654
+ pub fn build(b: *std.Build) void {
655
+ const target = b.standardTargetOptions(.{});
656
+ const optimize = b.standardOptimizeOption(.{});
657
+
658
+ const exe = b.addExecutable(.{
659
+ .name = "file-processor",
660
+ .root_source_file = .{ .path = "src/main.zig" },
661
+ .target = target,
662
+ .optimize = optimize,
663
+ });
664
+
665
+ const pcm = b.dependency("pcm", .{});
666
+ exe.root_module.addImport("pcm", pcm.module("pcm"));
667
+
668
+ b.installArtifact(exe);
669
+ }`,
670
+ main_zig: `const std = @import("std");
671
+ const pcm = @import("pcm");
672
+
673
+ pub fn main() !void {
674
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
675
+ defer _ = gpa.deinit();
676
+ const allocator = gpa.allocator();
677
+
678
+ var wav_reader = try pcm.WavReader.init("input.wav", allocator);
679
+ defer wav_reader.deinit();
680
+
681
+ std.debug.print("File: {} Hz, {} channels\\n",
682
+ .{wav_reader.sampleRate(), wav_reader.channels()});
683
+
684
+ var samples = try wav_reader.readSamples(allocator);
685
+ defer allocator.free(samples);
686
+
687
+ std.debug.print("Read {} samples\\n", .{samples.len});
688
+ }`,
689
+ build_zig_zon: `.{ .name = "file-processor", .version = "0.1.0", .dependencies = .{
690
+ .pcm = .{
691
+ .url = "https://github.com/Hejsil/pcm/archive/master.tar.gz",
692
+ .hash = "1220...",
693
+ },
694
+ } }`
695
+ },
696
+ "game-audio": {
697
+ build_zig: `const std = @import("std");
698
+
699
+ pub fn build(b: *std.Build) void {
700
+ const target = b.standardTargetOptions(.{});
701
+ const optimize = b.standardOptimizeOption(.{});
702
+
703
+ const exe = b.addExecutable(.{
704
+ .name = "game-audio",
705
+ .root_source_file = .{ .path = "src/main.zig" },
706
+ .target = target,
707
+ .optimize = optimize,
708
+ });
709
+
710
+ const zang = b.dependency("zang", .{});
711
+ const zaudio = b.dependency("zaudio", .{});
712
+ exe.root_module.addImport("zang", zang.module("zang"));
713
+ exe.root_module.addImport("zaudio", zaudio.module("zaudio"));
714
+
715
+ b.installArtifact(exe);
716
+ }`,
717
+ main_zig: `const std = @import("std");
718
+ const zang = @import("zang");
719
+ const zaudio = @import("zaudio");
720
+
721
+ pub fn main() !void {
722
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
723
+ defer _ = gpa.deinit();
724
+
725
+ var device = try zaudio.Device.init(.{
726
+ .direction = .playback,
727
+ .sample_rate = 44100,
728
+ .channels = 2,
729
+ .format = .f32,
730
+ });
731
+ defer device.deinit();
732
+ try device.start();
733
+
734
+ var osc = zang.SineOsc.init(.{
735
+ .sample_rate = 44100,
736
+ .frequency = 440.0,
737
+ });
738
+
739
+ var buffer: [2205]f32 = undefined;
740
+ osc.paint(buffer[0..]);
741
+ try device.writeInterleaved(buffer[0..]);
742
+
743
+ std.debug.print("Game audio: sine wave played\\n", .{});
744
+ }`,
745
+ build_zig_zon: `.{ .name = "game-audio", .version = "0.1.0", .dependencies = .{
746
+ .zang = .{
747
+ .url = "https://github.com/dbandstra/zang/archive/master.tar.gz",
748
+ .hash = "1220...",
749
+ },
750
+ .zaudio = .{
751
+ .url = "https://github.com/MasterQ32/zaudio/archive/master.tar.gz",
752
+ .hash = "1220...",
753
+ },
329
754
  } }`
330
755
  }
331
756
  };
@@ -729,6 +1154,48 @@ async function handleListResources(args) {
729
1154
  title: "Cross-Platform Audio Development",
730
1155
  url: "https://miniaud.io/docs/manual/index.html",
731
1156
  description: "Miniaudio documentation (used by zaudio)"
1157
+ },
1158
+ {
1159
+ type: "video",
1160
+ title: "Zig Audio Programming Introduction",
1161
+ url: "https://youtube.com/zigaudio",
1162
+ description: "Video introduction to audio programming in Zig"
1163
+ },
1164
+ {
1165
+ type: "video",
1166
+ title: "Building a Synthesizer with Zang",
1167
+ url: "https://youtube.com/zang-synth",
1168
+ description: "Step-by-step video tutorial for building synthesizers"
1169
+ },
1170
+ {
1171
+ type: "forum",
1172
+ title: "Zig Discord Audio Channel",
1173
+ url: "https://discord.gg/zig-lang",
1174
+ description: "Zig language Discord server audio programming discussions"
1175
+ },
1176
+ {
1177
+ type: "forum",
1178
+ title: "Ziggit Audio Forum",
1179
+ url: "https://ziggit.dev",
1180
+ description: "Zig community forum with audio programming topics"
1181
+ },
1182
+ {
1183
+ type: "github-issues",
1184
+ title: "Zang Issues",
1185
+ url: "https://github.com/dbandstra/zang/issues",
1186
+ description: "Bug reports and feature requests for zang"
1187
+ },
1188
+ {
1189
+ type: "github-issues",
1190
+ title: "Zaudio Issues",
1191
+ url: "https://github.com/MasterQ32/zaudio/issues",
1192
+ description: "Bug reports and feature requests for zaudio"
1193
+ },
1194
+ {
1195
+ type: "github-issues",
1196
+ title: "Bonk Issues",
1197
+ url: "https://github.com/chr15m/bonk/issues",
1198
+ description: "Bug reports and feature requests for bonk"
732
1199
  }
733
1200
  ];
734
1201
  let filtered = resources;
@@ -956,16 +1423,387 @@ const coeffs = struct {
956
1423
  }]
957
1424
  };
958
1425
  }
1426
+ async function handleCompareLibraries(args) {
1427
+ const input = CompareLibrariesInput.parse(args);
1428
+ const selectedLibs = input.libraries;
1429
+ const comparison = {
1430
+ compared_libraries: selectedLibs,
1431
+ comparison_fields: ["name", "license", "features", "use_cases", "zig_version"]
1432
+ };
1433
+ const comparisonData = selectedLibs.map(libKey => {
1434
+ const lib = ZIG_AUDIO_LIBRARIES[libKey];
1435
+ if (!lib)
1436
+ return { key: libKey, error: "Library not found" };
1437
+ return {
1438
+ key: libKey,
1439
+ name: lib.name,
1440
+ license: lib.license,
1441
+ features: lib.features,
1442
+ use_cases: lib.use_cases,
1443
+ zig_version: lib.version,
1444
+ repo: lib.repo
1445
+ };
1446
+ });
1447
+ const result = {
1448
+ ...comparison,
1449
+ libraries: comparisonData,
1450
+ recommendation: "For synthesis without allocations: zang. For playback: zaudio. For DSP: bonk."
1451
+ };
1452
+ return {
1453
+ content: [{
1454
+ type: "text",
1455
+ text: JSON.stringify(result, null, 2)
1456
+ }]
1457
+ };
1458
+ }
1459
+ async function handleTroubleshoot(args) {
1460
+ const input = TroubleshootInput.parse(args);
1461
+ const troubleshootingGuides = {
1462
+ "audio-glitches": {
1463
+ issue: "Audio glitches, pops, or clicks",
1464
+ likely_causes: [
1465
+ "Buffer size too small",
1466
+ "CPU overload from processing",
1467
+ "Priority issues with real-time audio",
1468
+ "Memory allocations in audio callback"
1469
+ ],
1470
+ solutions: [
1471
+ "Increase buffer size (256, 512, or 1024 samples)",
1472
+ "Reduce processing complexity in audio callback",
1473
+ "Use no-allocation libraries like zang",
1474
+ "Run audio callback in a real-time thread",
1475
+ "Use pre-allocated buffers instead of dynamic allocation"
1476
+ ],
1477
+ relevant_libraries: ["zang", "bonk"]
1478
+ },
1479
+ "latency": {
1480
+ issue: "High audio latency",
1481
+ likely_causes: [
1482
+ "Large buffer size",
1483
+ "Excessive processing per sample",
1484
+ "No direct hardware access"
1485
+ ],
1486
+ solutions: [
1487
+ "Reduce buffer size to minimum that still works (64-128)",
1488
+ "Use low-latency libraries (zang, zig-synth)",
1489
+ "Use exclusive mode audio (if available)",
1490
+ "Reduce sample rate if acceptable (44100 vs 48000)"
1491
+ ],
1492
+ relevant_libraries: ["zang", "zig-synth"]
1493
+ },
1494
+ "no-sound": {
1495
+ issue: "No sound output",
1496
+ likely_causes: [
1497
+ "Audio device not initialized",
1498
+ "Volume at zero",
1499
+ "Wrong output device selected",
1500
+ "Sample format mismatch"
1501
+ ],
1502
+ solutions: [
1503
+ "Verify audio device is opened successfully",
1504
+ "Check system volume and application volume",
1505
+ "List available devices and select correct one",
1506
+ "Ensure sample format (f32 vs i16) matches device",
1507
+ "Check if .start() was called on device"
1508
+ ],
1509
+ relevant_libraries: ["zaudio", "zang"]
1510
+ },
1511
+ "crash": {
1512
+ issue: "Application crashes",
1513
+ likely_causes: [
1514
+ "Null pointer in audio callback",
1515
+ "Memory corruption",
1516
+ "Invalid audio device handle",
1517
+ "Thread safety issues"
1518
+ ],
1519
+ solutions: [
1520
+ "Initialize all audio objects before use",
1521
+ "Ensure audio callback doesn't access deallocated memory",
1522
+ "Use defer to clean up resources",
1523
+ "Check all error return values",
1524
+ "Run with memory sanitizer enabled"
1525
+ ],
1526
+ relevant_libraries: ["zaudio", "zang"]
1527
+ },
1528
+ "compilation-error": {
1529
+ issue: "Compilation errors",
1530
+ likely_causes: [
1531
+ "Zig version mismatch",
1532
+ "Missing dependencies",
1533
+ "Incorrect import paths"
1534
+ ],
1535
+ solutions: [
1536
+ "Check library's Zig version requirement",
1537
+ "Update build.zig.zon with correct hash after fetching",
1538
+ "Verify module import names match exactly",
1539
+ "Check library README for specific setup instructions"
1540
+ ],
1541
+ relevant_libraries: []
1542
+ },
1543
+ "performance": {
1544
+ issue: "Poor performance or high CPU",
1545
+ likely_causes: [
1546
+ "Inefficient DSP algorithms",
1547
+ "Excessive memory allocations",
1548
+ "Redundant calculations per sample"
1549
+ ],
1550
+ solutions: [
1551
+ "Use pre-computed coefficients",
1552
+ "Avoid allocations in audio callbacks",
1553
+ "Use SIMD where available",
1554
+ "Consider data-oriented layouts (dalek)",
1555
+ "Cache frequently used values"
1556
+ ],
1557
+ relevant_libraries: ["zang", "dalek", "bonk"]
1558
+ }
1559
+ };
1560
+ const result = troubleshootingGuides[input.issue_type];
1561
+ return {
1562
+ content: [{
1563
+ type: "text",
1564
+ text: JSON.stringify(result, null, 2)
1565
+ }]
1566
+ };
1567
+ }
1568
+ async function handleDeprecationCheck(args) {
1569
+ const input = DeprecationCheckInput.parse(args);
1570
+ const userZigVersion = input.zig_version || "0.12.0";
1571
+ const compatibilityMatrix = {
1572
+ "zang": {
1573
+ latest_version: "0.12+ compatible",
1574
+ status: "active",
1575
+ notes: "Actively maintained for latest Zig versions"
1576
+ },
1577
+ "zaudio": {
1578
+ latest_version: "Zig 0.11+",
1579
+ status: "needs-update",
1580
+ notes: "May need updates for Zig 0.12+. Check repository for latest."
1581
+ },
1582
+ "bonk": {
1583
+ latest_version: "Zig 0.10+",
1584
+ status: "needs-update",
1585
+ notes: "Older version. Check for newer releases or fork."
1586
+ },
1587
+ "pcm": {
1588
+ latest_version: "Zig 0.9+",
1589
+ status: "deprecated",
1590
+ notes: "Very outdated. Consider alternative or fork to update."
1591
+ },
1592
+ "zig-liquid-dsp": {
1593
+ latest_version: "Zig 0.11+",
1594
+ status: "active",
1595
+ notes: "Actively maintained for Zig 0.11+. Check for 0.12 support."
1596
+ },
1597
+ "dalek": {
1598
+ latest_version: "Zig 0.10+",
1599
+ status: "experimental",
1600
+ notes: "Experimental library. API may change."
1601
+ }
1602
+ };
1603
+ const libInfo = compatibilityMatrix[input.library];
1604
+ let upgradeAdvice = "";
1605
+ if (libInfo) {
1606
+ if (libInfo.status === "deprecated") {
1607
+ upgradeAdvice = "This library is deprecated. Consider migrating to an active alternative like zang or zaudio.";
1608
+ }
1609
+ else if (libInfo.status === "needs-update") {
1610
+ upgradeAdvice = "This library may need updates for current Zig. Check the repository for latest version.";
1611
+ }
1612
+ }
1613
+ const result = {
1614
+ library: input.library,
1615
+ your_zig_version: userZigVersion,
1616
+ compatibility: libInfo || { status: "unknown", notes: "No information available" },
1617
+ upgrade_advice: upgradeAdvice
1618
+ };
1619
+ return {
1620
+ content: [{
1621
+ type: "text",
1622
+ text: JSON.stringify(result, null, 2)
1623
+ }]
1624
+ };
1625
+ }
1626
+ async function handleCalculateDelay(args) {
1627
+ const input = CalculateDelayInput.parse(args);
1628
+ const SPEED_OF_SOUND_FPS = 1126.0;
1629
+ const SPEED_OF_SOUND_MPS = 343.0;
1630
+ function convertMs(value, toUnit, sampleRate) {
1631
+ switch (toUnit) {
1632
+ case "samples": return value * sampleRate / 1000;
1633
+ case "feet": return value * SPEED_OF_SOUND_FPS / 1000;
1634
+ case "meters": return value * SPEED_OF_SOUND_MPS / 1000;
1635
+ default: return value;
1636
+ }
1637
+ }
1638
+ function convertSamples(value, toUnit, sampleRate) {
1639
+ const ms = value * 1000 / sampleRate;
1640
+ switch (toUnit) {
1641
+ case "ms": return ms;
1642
+ case "feet": return ms * SPEED_OF_SOUND_FPS / 1000;
1643
+ case "meters": return ms * SPEED_OF_SOUND_MPS / 1000;
1644
+ default: return value;
1645
+ }
1646
+ }
1647
+ function convertFeet(value, toUnit, sampleRate) {
1648
+ const ms = value * 1000 / SPEED_OF_SOUND_FPS;
1649
+ switch (toUnit) {
1650
+ case "ms": return ms;
1651
+ case "samples": return ms * sampleRate / 1000;
1652
+ case "meters": return value * 0.3048;
1653
+ default: return value;
1654
+ }
1655
+ }
1656
+ function convertMeters(value, toUnit, sampleRate) {
1657
+ const ms = value * 1000 / SPEED_OF_SOUND_MPS;
1658
+ switch (toUnit) {
1659
+ case "ms": return ms;
1660
+ case "samples": return ms * sampleRate / 1000;
1661
+ case "feet": return value / 0.3048;
1662
+ default: return value;
1663
+ }
1664
+ }
1665
+ let convertedValue;
1666
+ switch (input.from_unit) {
1667
+ case "ms":
1668
+ convertedValue = convertMs(input.value, input.to_unit, input.sample_rate);
1669
+ break;
1670
+ case "samples":
1671
+ convertedValue = convertSamples(input.value, input.to_unit, input.sample_rate);
1672
+ break;
1673
+ case "feet":
1674
+ convertedValue = convertFeet(input.value, input.to_unit, input.sample_rate);
1675
+ break;
1676
+ case "meters":
1677
+ convertedValue = convertMeters(input.value, input.to_unit, input.sample_rate);
1678
+ break;
1679
+ }
1680
+ const result = {
1681
+ input: {
1682
+ value: input.value,
1683
+ unit: input.from_unit,
1684
+ sample_rate: input.sample_rate
1685
+ },
1686
+ output: {
1687
+ value: Number(convertedValue.toFixed(2)),
1688
+ unit: input.to_unit
1689
+ },
1690
+ formula: `At ${input.sample_rate}Hz, 1 sample = ${(1000 / input.sample_rate).toFixed(3)}ms`
1691
+ };
1692
+ return {
1693
+ content: [{
1694
+ type: "text",
1695
+ text: JSON.stringify(result, null, 2)
1696
+ }]
1697
+ };
1698
+ }
959
1699
  // Create and configure the MCP server
960
1700
  const server = new Server({
961
1701
  name: "mcp-zig-audio",
962
- version: "0.1.0"
1702
+ version: "0.1.4"
963
1703
  }, {
964
1704
  capabilities: {
965
- tools: {}
1705
+ tools: {},
1706
+ prompts: {},
1707
+ resources: {}
966
1708
  }
967
1709
  });
968
1710
  // Set up request handlers
1711
+ server.setRequestHandler(ListPromptsRequestSchema, async () => {
1712
+ return {
1713
+ prompts: Object.values(PROMPTS).map(prompt => ({
1714
+ name: prompt.name,
1715
+ description: prompt.description,
1716
+ arguments: prompt.arguments.map(arg => ({
1717
+ name: arg.name,
1718
+ description: arg.description,
1719
+ required: arg.required
1720
+ }))
1721
+ }))
1722
+ };
1723
+ });
1724
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1725
+ const promptName = request.params.name;
1726
+ const prompt = PROMPTS[promptName];
1727
+ if (!prompt) {
1728
+ throw new Error(`Unknown prompt: ${promptName}`);
1729
+ }
1730
+ const args = request.params.arguments || {};
1731
+ return {
1732
+ messages: [{
1733
+ role: "user",
1734
+ content: {
1735
+ type: "text",
1736
+ text: generatePromptContent(promptName, args)
1737
+ }
1738
+ }]
1739
+ };
1740
+ });
1741
+ // Handle listing available resources
1742
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
1743
+ const resourceList = Object.values(RESOURCES).map(resource => ({
1744
+ uri: resource.uri,
1745
+ name: resource.name,
1746
+ description: resource.description,
1747
+ mimeType: resource.mimeType
1748
+ }));
1749
+ return {
1750
+ resources: resourceList
1751
+ };
1752
+ });
1753
+ // Handle reading a specific resource by URI
1754
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1755
+ const uri = request.params.uri;
1756
+ // Direct resource lookup
1757
+ if (RESOURCES[uri]) {
1758
+ const resource = RESOURCES[uri];
1759
+ return {
1760
+ contents: [{
1761
+ uri: resource.uri,
1762
+ mimeType: resource.mimeType,
1763
+ text: JSON.stringify(resource.data, null, 2)
1764
+ }]
1765
+ };
1766
+ }
1767
+ // Handle parameterized templates: zig-audio://libraries/{name}
1768
+ const libraryMatch = uri.match(/^zig-audio:\/\/libraries\/(.+)$/);
1769
+ if (libraryMatch) {
1770
+ const libName = libraryMatch[1];
1771
+ const library = ZIG_AUDIO_LIBRARIES[libName];
1772
+ if (library) {
1773
+ return {
1774
+ contents: [{
1775
+ uri: uri,
1776
+ mimeType: "application/json",
1777
+ text: JSON.stringify(library, null, 2)
1778
+ }]
1779
+ };
1780
+ }
1781
+ throw new Error(`Library not found: ${libName}`);
1782
+ }
1783
+ // Handle parameterized templates: zig-dsp://filters/{type}
1784
+ const filterMatch = uri.match(/^zig-dsp:\/\/filters\/(.+)$/);
1785
+ if (filterMatch) {
1786
+ const filterType = filterMatch[1];
1787
+ const filter = DSP_FILTERS[filterType];
1788
+ if (filter) {
1789
+ return {
1790
+ contents: [{
1791
+ uri: uri,
1792
+ mimeType: "application/json",
1793
+ text: JSON.stringify(filter, null, 2)
1794
+ }]
1795
+ };
1796
+ }
1797
+ throw new Error(`Filter type not found: ${filterType}`);
1798
+ }
1799
+ throw new Error(`Resource not found: ${uri}`);
1800
+ });
1801
+ // Handle listing resource templates
1802
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
1803
+ return {
1804
+ resourceTemplates: RESOURCE_TEMPLATES
1805
+ };
1806
+ });
969
1807
  server.setRequestHandler(ListToolsRequestSchema, async () => {
970
1808
  return {
971
1809
  tools: [
@@ -1044,7 +1882,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
1044
1882
  properties: {
1045
1883
  resource_type: {
1046
1884
  type: "string",
1047
- enum: ["tutorial", "reference", "example", "article"],
1885
+ enum: ["tutorial", "reference", "example", "article", "video", "forum", "github-issues"],
1048
1886
  description: "Filter by resource type"
1049
1887
  }
1050
1888
  }
@@ -1152,6 +1990,85 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
1152
1990
  },
1153
1991
  required: ["project_type"]
1154
1992
  }
1993
+ },
1994
+ {
1995
+ name: "zig_audio_compare_libraries",
1996
+ description: "Compare multiple Zig audio libraries side-by-side",
1997
+ inputSchema: {
1998
+ type: "object",
1999
+ properties: {
2000
+ libraries: {
2001
+ type: "array",
2002
+ items: { type: "string", enum: ["zang", "zaudio", "bonk", "pcm", "zig-liquid-dsp", "dalek", "zsynth", "zig-synth", "noize"] },
2003
+ description: "Libraries to compare (2-6)",
2004
+ minItems: 2,
2005
+ maxItems: 6
2006
+ }
2007
+ },
2008
+ required: ["libraries"]
2009
+ }
2010
+ },
2011
+ {
2012
+ name: "zig_audio_troubleshoot",
2013
+ description: "Debug common audio programming issues and get solutions",
2014
+ inputSchema: {
2015
+ type: "object",
2016
+ properties: {
2017
+ issue_type: {
2018
+ type: "string",
2019
+ enum: ["audio-glitches", "latency", "no-sound", "crash", "compilation-error", "performance"],
2020
+ description: "Type of issue to troubleshoot"
2021
+ }
2022
+ },
2023
+ required: ["issue_type"]
2024
+ }
2025
+ },
2026
+ {
2027
+ name: "zig_audio_deprecation_check",
2028
+ description: "Check if a library is deprecated or needs updates for your Zig version",
2029
+ inputSchema: {
2030
+ type: "object",
2031
+ properties: {
2032
+ library: {
2033
+ type: "string",
2034
+ description: "Library name to check"
2035
+ },
2036
+ zig_version: {
2037
+ type: "string",
2038
+ description: "Your Zig version (optional, defaults to 0.12.0)"
2039
+ }
2040
+ },
2041
+ required: ["library"]
2042
+ }
2043
+ },
2044
+ {
2045
+ name: "zig_dsp_calculate_delay",
2046
+ description: "Convert delay values between milliseconds, samples, feet, and meters",
2047
+ inputSchema: {
2048
+ type: "object",
2049
+ properties: {
2050
+ value: {
2051
+ type: "number",
2052
+ description: "The delay value to convert"
2053
+ },
2054
+ from_unit: {
2055
+ type: "string",
2056
+ enum: ["ms", "samples", "feet", "meters"],
2057
+ description: "Unit to convert from"
2058
+ },
2059
+ to_unit: {
2060
+ type: "string",
2061
+ enum: ["ms", "samples", "feet", "meters"],
2062
+ description: "Unit to convert to"
2063
+ },
2064
+ sample_rate: {
2065
+ type: "number",
2066
+ default: 44100,
2067
+ description: "Sample rate in Hz (required for sample conversions)"
2068
+ }
2069
+ },
2070
+ required: ["value", "from_unit", "to_unit"]
2071
+ }
1155
2072
  }
1156
2073
  ]
1157
2074
  };
@@ -1180,6 +2097,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1180
2097
  return await handleVerifyCode(args);
1181
2098
  case "zig_audio_project_template":
1182
2099
  return await handleProjectTemplate(args);
2100
+ case "zig_audio_compare_libraries":
2101
+ return await handleCompareLibraries(args);
2102
+ case "zig_audio_troubleshoot":
2103
+ return await handleTroubleshoot(args);
2104
+ case "zig_audio_deprecation_check":
2105
+ return await handleDeprecationCheck(args);
2106
+ case "zig_dsp_calculate_delay":
2107
+ return await handleCalculateDelay(args);
1183
2108
  default:
1184
2109
  throw new Error(`Unknown tool: ${name}`);
1185
2110
  }