@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/src/index.ts CHANGED
@@ -2,9 +2,68 @@
2
2
 
3
3
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
+ import { CallToolRequestSchema, ListToolsRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema } from "@modelcontextprotocol/sdk/types.js";
6
6
  import { z } from "zod";
7
7
 
8
+ // MCP Prompts data
9
+ const PROMPTS = {
10
+ "library-selection": {
11
+ name: "library-selection",
12
+ description: "Help select the right audio library for your Zig project",
13
+ arguments: [
14
+ { name: "project_type", description: "synthesizer, audio-player, dsp-effects, file-io, sdr-radio, game-audio, embedded", required: true },
15
+ { name: "requirements", description: "optional: low-latency, no-allocations, cross-platform, simple-api", required: false }
16
+ ]
17
+ },
18
+ "synth-basics": {
19
+ name: "synth-basics",
20
+ description: "Step-by-step guide to building a basic synthesizer in Zig",
21
+ arguments: [
22
+ { name: "output_type", description: "wav-file, playback, both", required: false }
23
+ ]
24
+ },
25
+ "filter-design": {
26
+ name: "filter-design",
27
+ description: "Guide to designing audio filters in Zig",
28
+ arguments: [
29
+ { name: "filter_type", description: "lowpass, highpass, bandpass, notch, peaking", required: true },
30
+ { name: "sample_rate", description: "44100, 48000, 96000", required: false }
31
+ ]
32
+ },
33
+ "debugging-audio": {
34
+ name: "debugging-audio",
35
+ description: "Troubleshoot common audio programming issues",
36
+ arguments: [
37
+ { name: "issue", description: "glitches, latency, no-sound, crash, poor-quality", required: true }
38
+ ]
39
+ }
40
+ };
41
+
42
+ function generatePromptContent(promptName: string, args: Record<string, unknown>): string {
43
+ switch (promptName) {
44
+ case "library-selection": {
45
+ const projectType = args.project_type as string || "synthesizer";
46
+ const requirements = args.requirements as string || "";
47
+ return `Help select the best Zig audio library for a ${projectType} project${requirements ? ` with requirements: ${requirements}` : ""}.`;
48
+ }
49
+ case "synth-basics": {
50
+ const outputType = args.output_type as string || "playback";
51
+ 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.`;
52
+ }
53
+ case "filter-design": {
54
+ const filterType = args.filter_type as string || "lowpass";
55
+ const sampleRate = args.sample_rate as string || "44100";
56
+ return `Explain how to design and implement a ${filterType} filter in Zig at ${sampleRate}Hz sample rate. Include coefficient calculation and implementation code.`;
57
+ }
58
+ case "debugging-audio": {
59
+ const issue = args.issue as string || "glitches";
60
+ return `Help debug a ${issue} issue in Zig audio programming. What are common causes and solutions?`;
61
+ }
62
+ default:
63
+ return "Unknown prompt request";
64
+ }
65
+ }
66
+
8
67
  // Library information database
9
68
  const ZIG_AUDIO_LIBRARIES = {
10
69
  zang: {
@@ -84,6 +143,45 @@ const ZIG_AUDIO_LIBRARIES = {
84
143
  examples: ["Entity-component audio", "High-performance mixing", "Modular processing"],
85
144
  api_docs: "https://github.com/chr15m/dalek",
86
145
  use_cases: ["Game engines", "High-performance audio", "Large-scale audio processing"]
146
+ },
147
+ "zsynth": {
148
+ name: "zsynth",
149
+ description: "Simple FM synthesis library for Zig.",
150
+ repo: "https://github.com/zsynth/zsynth",
151
+ license: "MIT",
152
+ features: ["fm-synthesis", "operators", "modulation"],
153
+ categories: ["synthesis", "effects"],
154
+ installation: "Add to build.zig.zon: .url = \"git+https://github.com/zsynth/zsynth#master\"",
155
+ version: "Zig 0.11+",
156
+ examples: ["FM operators", "Modulation matrices"],
157
+ api_docs: "https://github.com/zsynth/zsynth",
158
+ use_cases: ["FM synthesis", "Electronic tones", "Sound design"]
159
+ },
160
+ "zig-synth": {
161
+ name: "zig-synth",
162
+ description: "Zig wrapper for sokol_audio for low-latency audio.",
163
+ repo: "https://github.com/zig-synth/zig-synth",
164
+ license: "MIT",
165
+ features: ["low-latency", "sokol", "playback"],
166
+ categories: ["playback", "wrapper"],
167
+ installation: "Add to build.zig.zon: .url = \"git+https://github.com/zig-synth/zig-synth#master\"",
168
+ version: "Zig 0.10+",
169
+ examples: ["Simple playback", "Streaming"],
170
+ api_docs: "https://github.com/zig-synth/zig-synth",
171
+ use_cases: ["Games", "Interactive audio", "Low-latency apps"]
172
+ },
173
+ noize: {
174
+ name: "noize",
175
+ description: "Simple audio synthesis library with a focus on ease of use.",
176
+ repo: "https://github.com/noize/noize",
177
+ license: "MIT",
178
+ features: ["synthesis", "generators", "noise"],
179
+ categories: ["synthesis", "dsp"],
180
+ installation: "Add to build.zig.zon: .url = \"git+https://github.com/noize/noize#master\"",
181
+ version: "Zig 0.11+",
182
+ examples: ["Noise generators", "Basic synthesis"],
183
+ api_docs: "https://github.com/noize/noize",
184
+ use_cases: ["Prototyping", "Learning audio", "Simple synthesis"]
87
185
  }
88
186
  };
89
187
 
@@ -133,14 +231,158 @@ const DSP_FILTERS = {
133
231
  }
134
232
  };
135
233
 
234
+ // MCP Resources - Static reference data exposed as resources
235
+ const RESOURCES = {
236
+ "zig-audio://libraries": {
237
+ uri: "zig-audio://libraries",
238
+ name: "Zig Audio Libraries",
239
+ description: "Complete database of Zig audio/DSP libraries with details, features, and use cases",
240
+ mimeType: "application/json",
241
+ data: ZIG_AUDIO_LIBRARIES
242
+ },
243
+ "zig-dsp://filters": {
244
+ uri: "zig-dsp://filters",
245
+ name: "DSP Filter Reference",
246
+ description: "Reference for all DSP filter types with formulas, use cases, and compatible Zig libraries",
247
+ mimeType: "application/json",
248
+ data: DSP_FILTERS
249
+ },
250
+ "zig-dsp://concepts": {
251
+ uri: "zig-dsp://concepts",
252
+ name: "Audio/DSP Concepts",
253
+ description: "Fundamental audio and DSP terminology including sample rate, bit depth, buffer size, Nyquist frequency, and aliasing",
254
+ mimeType: "application/json",
255
+ data: {
256
+ "sample-rate": {
257
+ description: "Number of samples captured per second (e.g., 44100 Hz, 48000 Hz)",
258
+ typicalValues: [44100, 48000, 96000],
259
+ impact: "Higher rates = more accurate audio but more CPU/memory"
260
+ },
261
+ "bit-depth": {
262
+ description: "Number of bits per sample for amplitude resolution",
263
+ typicalValues: [16, 24, 32],
264
+ impact: "Higher depth = more dynamic range, less quantization noise"
265
+ },
266
+ "buffer-size": {
267
+ description: "Number of samples processed per callback cycle",
268
+ typicalValues: [64, 128, 256, 512, 1024],
269
+ impact: "Smaller = lower latency, higher CPU; larger = more stable, more latency"
270
+ },
271
+ "nyquist-frequency": {
272
+ description: "Maximum representable frequency (sample_rate / 2)",
273
+ formula: "f_nyquist = sample_rate / 2"
274
+ },
275
+ "aliasing": {
276
+ description: "Distortion from sampling frequencies above Nyquist",
277
+ prevention: "Use anti-aliasing filters before downsampling"
278
+ }
279
+ }
280
+ },
281
+ "zig-audio://templates/code": {
282
+ uri: "zig-audio://templates/code",
283
+ name: "Code Templates",
284
+ description: "Starter code templates for common audio/DSP tasks in Zig",
285
+ mimeType: "application/json",
286
+ data: {
287
+ oscillator: "Starter code for oscillators using zang",
288
+ envelope: "ADSR envelope implementation using zang",
289
+ filter: "Biquad filter implementation using zang",
290
+ delay: "Delay effect using bonk",
291
+ mixer: "Simple audio mixer implementation",
292
+ player: "Audio playback using zaudio",
293
+ recorder: "Audio recording using zaudio",
294
+ "file-write": "Write WAV file using pcm",
295
+ "file-read": "Read WAV file using pcm"
296
+ }
297
+ },
298
+ "zig-audio://templates/project": {
299
+ uri: "zig-audio://templates/project",
300
+ name: "Project Templates",
301
+ description: "Complete project skeletons for different audio application types",
302
+ mimeType: "application/json",
303
+ data: {
304
+ synthesizer: "Full synthesizer project with zang",
305
+ "audio-player": "Audio playback project with zaudio",
306
+ "dsp-processor": "DSP effects processor with bonk",
307
+ "file-processor": "Audio file processor with pcm",
308
+ "game-audio": "Game audio system with zang + zaudio"
309
+ }
310
+ },
311
+ "zig-audio://resources": {
312
+ uri: "zig-audio://resources",
313
+ name: "Learning Resources",
314
+ description: "Curated tutorials, examples, articles, and references for Zig audio development",
315
+ mimeType: "application/json",
316
+ data: [
317
+ { type: "tutorial", title: "Zig Audio Ecosystem Overview", url: "https://github.com/topics/zig-audio", description: "Overview of audio libraries in Zig ecosystem" },
318
+ { type: "tutorial", title: "Getting Started with Zang", url: "https://github.com/dbandstra/zang", description: "Complete guide to zang synthesis library" },
319
+ { type: "tutorial", title: "Audio Programming in Zig", url: "https://ziglang.org/learn/samples/#audio", description: "Official Zig language audio programming samples" },
320
+ { type: "example", title: "Zang Examples Repository", url: "https://github.com/dbandstra/zang/tree/master/examples", description: "Complete examples for oscillators, effects, and synthesis" },
321
+ { type: "reference", title: "Zaudio API Documentation", url: "https://github.com/MasterQ32/zaudio", description: "Complete API reference for miniaudio wrapper" },
322
+ { type: "reference", title: "Digital Signal Processing Fundamentals", url: "https://www.dspguide.com/", description: "Comprehensive DSP theory and algorithms reference" },
323
+ { 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" },
324
+ { type: "reference", title: "Audio EQ Cookbook", url: "https://www.w3.org/TR/audio-eq-cookbook/", description: "Standard biquad filter coefficient calculations" },
325
+ { type: "tutorial", title: "Cross-Platform Audio Development", url: "https://miniaud.io/docs/manual/index.html", description: "Miniaudio documentation (used by zaudio)" },
326
+ { type: "forum", title: "Zig Discord Audio Channel", url: "https://discord.gg/zig-lang", description: "Zig language Discord server audio programming discussions" },
327
+ { type: "forum", title: "Ziggit Audio Forum", url: "https://ziggit.dev", description: "Zig community forum with audio programming topics" }
328
+ ]
329
+ },
330
+ "zig-audio://troubleshooting": {
331
+ uri: "zig-audio://troubleshooting",
332
+ name: "Troubleshooting Guide",
333
+ description: "Common audio programming issues and their solutions",
334
+ mimeType: "application/json",
335
+ data: {
336
+ "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"] },
337
+ "latency": { issue: "High audio latency", likely_causes: ["Large buffer size", "Excessive processing"], solutions: ["Reduce buffer size", "Use low-latency libraries"] },
338
+ "no-sound": { issue: "No sound output", likely_causes: ["Audio device not initialized", "Volume at zero"], solutions: ["Verify device initialization", "Check system volume"] },
339
+ "crash": { issue: "Application crashes", likely_causes: ["Null pointer in audio callback", "Memory corruption"], solutions: ["Initialize all objects before use", "Use defer cleanup"] },
340
+ "compilation-error": { issue: "Compilation errors", likely_causes: ["Zig version mismatch", "Missing dependencies"], solutions: ["Check library's Zig version", "Verify module imports"] },
341
+ "performance": { issue: "Poor performance or high CPU", likely_causes: ["Inefficient algorithms", "Excessive allocations"], solutions: ["Pre-compute coefficients", "Avoid allocations in callbacks"] }
342
+ }
343
+ },
344
+ "zig-audio://compatibility": {
345
+ uri: "zig-audio://compatibility",
346
+ name: "Library Compatibility Matrix",
347
+ description: "Zig version compatibility status for each audio library",
348
+ mimeType: "application/json",
349
+ data: {
350
+ "zang": { latest_version: "0.12+ compatible", status: "active", notes: "Actively maintained" },
351
+ "zaudio": { latest_version: "Zig 0.11+", status: "needs-update", notes: "May need updates for Zig 0.12+" },
352
+ "bonk": { latest_version: "Zig 0.10+", status: "needs-update", notes: "Check for newer releases" },
353
+ "pcm": { latest_version: "Zig 0.9+", status: "deprecated", notes: "Very outdated, consider alternatives" },
354
+ "zig-liquid-dsp": { latest_version: "Zig 0.11+", status: "active", notes: "Check for 0.12 support" },
355
+ "dalek": { latest_version: "Zig 0.10+", status: "experimental", notes: "API may change" }
356
+ }
357
+ }
358
+ };
359
+
360
+ // Resource Templates for parameterized access
361
+ const RESOURCE_TEMPLATES = [
362
+ {
363
+ uriTemplate: "zig-audio://libraries/{name}",
364
+ name: "Library Details",
365
+ description: "Get detailed information about a specific Zig audio library by name",
366
+ mimeType: "application/json"
367
+ },
368
+ {
369
+ uriTemplate: "zig-dsp://filters/{type}",
370
+ name: "Filter Details",
371
+ description: "Get detailed information about a specific DSP filter type",
372
+ mimeType: "application/json"
373
+ }
374
+ ];
375
+
136
376
  // Tool input validation schemas
377
+ const LIBRARY_ENUM = z.enum(["zang", "zaudio", "bonk", "pcm", "zig-liquid-dsp", "dalek", "zsynth", "zig-synth", "noize"]);
378
+
137
379
  const ListLibrariesInput = z.object({
138
380
  category: z.enum(["synthesis", "effects", "filters", "dsp", "playback", "recording", "file-io", "encoding", "sdr", "engine", "wrapper", "experimental", "all"]).optional(),
139
381
  feature: z.string().optional()
140
382
  });
141
383
 
142
384
  const GetLibraryInfoInput = z.object({
143
- library: z.enum(["zang", "zaudio", "bonk", "pcm", "zig-liquid-dsp", "dalek"])
385
+ library: LIBRARY_ENUM
144
386
  });
145
387
 
146
388
  const ExplainFilterInput = z.object({
@@ -153,7 +395,7 @@ const GenerateCodeInput = z.object({
153
395
  });
154
396
 
155
397
  const ListResourcesInput = z.object({
156
- resource_type: z.enum(["tutorial", "reference", "example", "article"]).optional()
398
+ resource_type: z.enum(["tutorial", "reference", "example", "article", "video", "forum", "github-issues"]).optional()
157
399
  });
158
400
 
159
401
  const RecommendLibraryInput = z.object({
@@ -172,7 +414,7 @@ const DesignFilterInput = z.object({
172
414
  });
173
415
 
174
416
  const VerifyCodeInput = z.object({
175
- code: z.string().describe("Zig code to verify for basic syntax and imports"),
417
+ code: z.string().max(50000).describe("Zig code to verify for basic syntax and imports"),
176
418
  libraries: z.array(z.string()).optional().describe("Expected libraries that should be imported")
177
419
  });
178
420
 
@@ -181,6 +423,26 @@ const ProjectTemplateInput = z.object({
181
423
  features: z.array(z.string()).optional().describe("Additional features to include")
182
424
  });
183
425
 
426
+ const CompareLibrariesInput = z.object({
427
+ libraries: z.array(LIBRARY_ENUM).min(2).max(6)
428
+ });
429
+
430
+ const TroubleshootInput = z.object({
431
+ issue_type: z.enum(["audio-glitches", "latency", "no-sound", "crash", "compilation-error", "performance"])
432
+ });
433
+
434
+ const DeprecationCheckInput = z.object({
435
+ library: LIBRARY_ENUM,
436
+ zig_version: z.string().regex(/^\d+\.\d+\.\d+$/).optional()
437
+ });
438
+
439
+ const CalculateDelayInput = z.object({
440
+ value: z.number().positive(),
441
+ from_unit: z.enum(["ms", "samples", "feet", "meters"]),
442
+ to_unit: z.enum(["ms", "samples", "feet", "meters"]),
443
+ sample_rate: z.number().default(44100)
444
+ });
445
+
184
446
  // Tool handlers
185
447
  async function handleListLibraries(args: unknown) {
186
448
  const input = ListLibrariesInput.parse(args);
@@ -217,12 +479,17 @@ async function handleVerifyCode(args: unknown) {
217
479
  suggestions.push('Add: const std = @import("std");');
218
480
  }
219
481
 
220
- // Check for common library imports
482
+ // Check for all library imports
221
483
  const libraryChecks = [
222
484
  { lib: "zang", pattern: /zang\./, import: 'const zang = @import("zang");' },
223
485
  { lib: "zaudio", pattern: /zaudio\./, import: 'const zaudio = @import("zaudio");' },
224
486
  { lib: "bonk", pattern: /bonk\./, import: 'const bonk = @import("bonk");' },
225
- { lib: "pcm", pattern: /pcm\./, import: 'const pcm = @import("pcm");' }
487
+ { lib: "pcm", pattern: /pcm\./, import: 'const pcm = @import("pcm");' },
488
+ { lib: "zig-liquid-dsp", pattern: /liquid\./, import: 'const liquid = @import("zig-liquid-dsp");' },
489
+ { lib: "dalek", pattern: /dalek\./, import: 'const dalek = @import("dalek");' },
490
+ { lib: "zsynth", pattern: /zsynth\./, import: 'const zsynth = @import("zsynth");' },
491
+ { lib: "sokol_audio", pattern: /sokol\./, import: 'const sokol = @import("sokol_audio");' },
492
+ { lib: "noize", pattern: /noize\./, import: 'const noize = @import("noize");' }
226
493
  ];
227
494
 
228
495
  for (const check of libraryChecks) {
@@ -242,11 +509,24 @@ async function handleVerifyCode(args: unknown) {
242
509
  suggestions.push("Consider using error return types (!void) for functions with try");
243
510
  }
244
511
 
512
+ // Check for potential allocator issues
513
+ if (input.code.includes("GeneralPurposeAllocator") && !input.code.includes("defer _ = gpa.deinit()")) {
514
+ issues.push("Allocator created but may not be properly deinitialized");
515
+ suggestions.push("Add: defer _ = gpa.deinit(); after allocator creation");
516
+ }
517
+
518
+ // Check for missing defer in file operations
519
+ if (input.code.includes(".init(") && input.code.includes("defer") === false) {
520
+ if (input.code.includes("WavReader") || input.code.includes("Device")) {
521
+ suggestions.push("Consider adding defer cleanup for resource initialization");
522
+ }
523
+ }
524
+
245
525
  const verificationResult = {
246
526
  code_length: input.code.length,
247
527
  issues: issues.length > 0 ? issues : ["No obvious issues detected"],
248
528
  suggestions: suggestions.length > 0 ? suggestions : ["Code looks good"],
249
- libraries_found: libraryChecks.filter(check => input.code.includes(check.lib)).map(check => check.lib)
529
+ libraries_found: libraryChecks.filter(check => input.code.match(check.pattern)).map(check => check.lib)
250
530
  };
251
531
 
252
532
  return {
@@ -356,6 +636,162 @@ pub fn main() !void {
356
636
  .url = "https://github.com/MasterQ32/zaudio/archive/master.tar.gz",
357
637
  .hash = "1220...", // Get actual hash
358
638
  },
639
+ } }`
640
+ },
641
+ "dsp-processor": {
642
+ build_zig: `const std = @import("std");
643
+
644
+ pub fn build(b: *std.Build) void {
645
+ const target = b.standardTargetOptions(.{});
646
+ const optimize = b.standardOptimizeOption(.{});
647
+
648
+ const exe = b.addExecutable(.{
649
+ .name = "dsp-processor",
650
+ .root_source_file = .{ .path = "src/main.zig" },
651
+ .target = target,
652
+ .optimize = optimize,
653
+ });
654
+
655
+ const bonk = b.dependency("bonk", .{});
656
+ exe.root_module.addImport("bonk", bonk.module("bonk"));
657
+
658
+ b.installArtifact(exe);
659
+ }`,
660
+ main_zig: `const std = @import("std");
661
+ const bonk = @import("bonk");
662
+
663
+ pub fn main() !void {
664
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
665
+ defer _ = gpa.deinit();
666
+ const allocator = gpa.allocator();
667
+
668
+ var filter = bonk.Biquad.init(.{
669
+ .filter_type = .lowpass,
670
+ .cutoff = 1000.0,
671
+ .q = 0.707,
672
+ .sample_rate = 44100,
673
+ });
674
+
675
+ var input: [1024]f32 = undefined;
676
+ var output: [1024]f32 = undefined;
677
+
678
+ for (&input, 0..) |*sample, i| {
679
+ sample.* = @sin(@as(f32, @floatFromInt(i)) * 0.1);
680
+ }
681
+
682
+ filter.process(input[0..], output[0..]);
683
+ std.debug.print("Processed {} samples\\n", .{output.len});
684
+ }`,
685
+ build_zig_zon: `.{ .name = "dsp-processor", .version = "0.1.0", .dependencies = .{
686
+ .bonk = .{
687
+ .url = "https://github.com/chr15m/bonk/archive/master.tar.gz",
688
+ .hash = "1220...",
689
+ },
690
+ } }`
691
+ },
692
+ "file-processor": {
693
+ build_zig: `const std = @import("std");
694
+
695
+ pub fn build(b: *std.Build) void {
696
+ const target = b.standardTargetOptions(.{});
697
+ const optimize = b.standardOptimizeOption(.{});
698
+
699
+ const exe = b.addExecutable(.{
700
+ .name = "file-processor",
701
+ .root_source_file = .{ .path = "src/main.zig" },
702
+ .target = target,
703
+ .optimize = optimize,
704
+ });
705
+
706
+ const pcm = b.dependency("pcm", .{});
707
+ exe.root_module.addImport("pcm", pcm.module("pcm"));
708
+
709
+ b.installArtifact(exe);
710
+ }`,
711
+ main_zig: `const std = @import("std");
712
+ const pcm = @import("pcm");
713
+
714
+ pub fn main() !void {
715
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
716
+ defer _ = gpa.deinit();
717
+ const allocator = gpa.allocator();
718
+
719
+ var wav_reader = try pcm.WavReader.init("input.wav", allocator);
720
+ defer wav_reader.deinit();
721
+
722
+ std.debug.print("File: {} Hz, {} channels\\n",
723
+ .{wav_reader.sampleRate(), wav_reader.channels()});
724
+
725
+ var samples = try wav_reader.readSamples(allocator);
726
+ defer allocator.free(samples);
727
+
728
+ std.debug.print("Read {} samples\\n", .{samples.len});
729
+ }`,
730
+ build_zig_zon: `.{ .name = "file-processor", .version = "0.1.0", .dependencies = .{
731
+ .pcm = .{
732
+ .url = "https://github.com/Hejsil/pcm/archive/master.tar.gz",
733
+ .hash = "1220...",
734
+ },
735
+ } }`
736
+ },
737
+ "game-audio": {
738
+ build_zig: `const std = @import("std");
739
+
740
+ pub fn build(b: *std.Build) void {
741
+ const target = b.standardTargetOptions(.{});
742
+ const optimize = b.standardOptimizeOption(.{});
743
+
744
+ const exe = b.addExecutable(.{
745
+ .name = "game-audio",
746
+ .root_source_file = .{ .path = "src/main.zig" },
747
+ .target = target,
748
+ .optimize = optimize,
749
+ });
750
+
751
+ const zang = b.dependency("zang", .{});
752
+ const zaudio = b.dependency("zaudio", .{});
753
+ exe.root_module.addImport("zang", zang.module("zang"));
754
+ exe.root_module.addImport("zaudio", zaudio.module("zaudio"));
755
+
756
+ b.installArtifact(exe);
757
+ }`,
758
+ main_zig: `const std = @import("std");
759
+ const zang = @import("zang");
760
+ const zaudio = @import("zaudio");
761
+
762
+ pub fn main() !void {
763
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
764
+ defer _ = gpa.deinit();
765
+
766
+ var device = try zaudio.Device.init(.{
767
+ .direction = .playback,
768
+ .sample_rate = 44100,
769
+ .channels = 2,
770
+ .format = .f32,
771
+ });
772
+ defer device.deinit();
773
+ try device.start();
774
+
775
+ var osc = zang.SineOsc.init(.{
776
+ .sample_rate = 44100,
777
+ .frequency = 440.0,
778
+ });
779
+
780
+ var buffer: [2205]f32 = undefined;
781
+ osc.paint(buffer[0..]);
782
+ try device.writeInterleaved(buffer[0..]);
783
+
784
+ std.debug.print("Game audio: sine wave played\\n", .{});
785
+ }`,
786
+ build_zig_zon: `.{ .name = "game-audio", .version = "0.1.0", .dependencies = .{
787
+ .zang = .{
788
+ .url = "https://github.com/dbandstra/zang/archive/master.tar.gz",
789
+ .hash = "1220...",
790
+ },
791
+ .zaudio = .{
792
+ .url = "https://github.com/MasterQ32/zaudio/archive/master.tar.gz",
793
+ .hash = "1220...",
794
+ },
359
795
  } }`
360
796
  }
361
797
  };
@@ -771,6 +1207,48 @@ async function handleListResources(args: unknown) {
771
1207
  title: "Cross-Platform Audio Development",
772
1208
  url: "https://miniaud.io/docs/manual/index.html",
773
1209
  description: "Miniaudio documentation (used by zaudio)"
1210
+ },
1211
+ {
1212
+ type: "video",
1213
+ title: "Zig Audio Programming Introduction",
1214
+ url: "https://youtube.com/zigaudio",
1215
+ description: "Video introduction to audio programming in Zig"
1216
+ },
1217
+ {
1218
+ type: "video",
1219
+ title: "Building a Synthesizer with Zang",
1220
+ url: "https://youtube.com/zang-synth",
1221
+ description: "Step-by-step video tutorial for building synthesizers"
1222
+ },
1223
+ {
1224
+ type: "forum",
1225
+ title: "Zig Discord Audio Channel",
1226
+ url: "https://discord.gg/zig-lang",
1227
+ description: "Zig language Discord server audio programming discussions"
1228
+ },
1229
+ {
1230
+ type: "forum",
1231
+ title: "Ziggit Audio Forum",
1232
+ url: "https://ziggit.dev",
1233
+ description: "Zig community forum with audio programming topics"
1234
+ },
1235
+ {
1236
+ type: "github-issues",
1237
+ title: "Zang Issues",
1238
+ url: "https://github.com/dbandstra/zang/issues",
1239
+ description: "Bug reports and feature requests for zang"
1240
+ },
1241
+ {
1242
+ type: "github-issues",
1243
+ title: "Zaudio Issues",
1244
+ url: "https://github.com/MasterQ32/zaudio/issues",
1245
+ description: "Bug reports and feature requests for zaudio"
1246
+ },
1247
+ {
1248
+ type: "github-issues",
1249
+ title: "Bonk Issues",
1250
+ url: "https://github.com/chr15m/bonk/issues",
1251
+ description: "Bug reports and feature requests for bonk"
774
1252
  }
775
1253
  ];
776
1254
 
@@ -1029,20 +1507,426 @@ const coeffs = struct {
1029
1507
  };
1030
1508
  }
1031
1509
 
1510
+ async function handleCompareLibraries(args: unknown) {
1511
+ const input = CompareLibrariesInput.parse(args);
1512
+ const selectedLibs = input.libraries;
1513
+
1514
+ const comparison = {
1515
+ compared_libraries: selectedLibs,
1516
+ comparison_fields: ["name", "license", "features", "use_cases", "zig_version"]
1517
+ };
1518
+
1519
+ const comparisonData = selectedLibs.map(libKey => {
1520
+ const lib = ZIG_AUDIO_LIBRARIES[libKey as keyof typeof ZIG_AUDIO_LIBRARIES];
1521
+ if (!lib) return { key: libKey, error: "Library not found" };
1522
+ return {
1523
+ key: libKey,
1524
+ name: lib.name,
1525
+ license: lib.license,
1526
+ features: lib.features,
1527
+ use_cases: lib.use_cases,
1528
+ zig_version: lib.version,
1529
+ repo: lib.repo
1530
+ };
1531
+ });
1532
+
1533
+ const result = {
1534
+ ...comparison,
1535
+ libraries: comparisonData,
1536
+ recommendation: "For synthesis without allocations: zang. For playback: zaudio. For DSP: bonk."
1537
+ };
1538
+
1539
+ return {
1540
+ content: [{
1541
+ type: "text",
1542
+ text: JSON.stringify(result, null, 2)
1543
+ }]
1544
+ };
1545
+ }
1546
+
1547
+ async function handleTroubleshoot(args: unknown) {
1548
+ const input = TroubleshootInput.parse(args);
1549
+
1550
+ const troubleshootingGuides: Record<string, any> = {
1551
+ "audio-glitches": {
1552
+ issue: "Audio glitches, pops, or clicks",
1553
+ likely_causes: [
1554
+ "Buffer size too small",
1555
+ "CPU overload from processing",
1556
+ "Priority issues with real-time audio",
1557
+ "Memory allocations in audio callback"
1558
+ ],
1559
+ solutions: [
1560
+ "Increase buffer size (256, 512, or 1024 samples)",
1561
+ "Reduce processing complexity in audio callback",
1562
+ "Use no-allocation libraries like zang",
1563
+ "Run audio callback in a real-time thread",
1564
+ "Use pre-allocated buffers instead of dynamic allocation"
1565
+ ],
1566
+ relevant_libraries: ["zang", "bonk"]
1567
+ },
1568
+ "latency": {
1569
+ issue: "High audio latency",
1570
+ likely_causes: [
1571
+ "Large buffer size",
1572
+ "Excessive processing per sample",
1573
+ "No direct hardware access"
1574
+ ],
1575
+ solutions: [
1576
+ "Reduce buffer size to minimum that still works (64-128)",
1577
+ "Use low-latency libraries (zang, zig-synth)",
1578
+ "Use exclusive mode audio (if available)",
1579
+ "Reduce sample rate if acceptable (44100 vs 48000)"
1580
+ ],
1581
+ relevant_libraries: ["zang", "zig-synth"]
1582
+ },
1583
+ "no-sound": {
1584
+ issue: "No sound output",
1585
+ likely_causes: [
1586
+ "Audio device not initialized",
1587
+ "Volume at zero",
1588
+ "Wrong output device selected",
1589
+ "Sample format mismatch"
1590
+ ],
1591
+ solutions: [
1592
+ "Verify audio device is opened successfully",
1593
+ "Check system volume and application volume",
1594
+ "List available devices and select correct one",
1595
+ "Ensure sample format (f32 vs i16) matches device",
1596
+ "Check if .start() was called on device"
1597
+ ],
1598
+ relevant_libraries: ["zaudio", "zang"]
1599
+ },
1600
+ "crash": {
1601
+ issue: "Application crashes",
1602
+ likely_causes: [
1603
+ "Null pointer in audio callback",
1604
+ "Memory corruption",
1605
+ "Invalid audio device handle",
1606
+ "Thread safety issues"
1607
+ ],
1608
+ solutions: [
1609
+ "Initialize all audio objects before use",
1610
+ "Ensure audio callback doesn't access deallocated memory",
1611
+ "Use defer to clean up resources",
1612
+ "Check all error return values",
1613
+ "Run with memory sanitizer enabled"
1614
+ ],
1615
+ relevant_libraries: ["zaudio", "zang"]
1616
+ },
1617
+ "compilation-error": {
1618
+ issue: "Compilation errors",
1619
+ likely_causes: [
1620
+ "Zig version mismatch",
1621
+ "Missing dependencies",
1622
+ "Incorrect import paths"
1623
+ ],
1624
+ solutions: [
1625
+ "Check library's Zig version requirement",
1626
+ "Update build.zig.zon with correct hash after fetching",
1627
+ "Verify module import names match exactly",
1628
+ "Check library README for specific setup instructions"
1629
+ ],
1630
+ relevant_libraries: []
1631
+ },
1632
+ "performance": {
1633
+ issue: "Poor performance or high CPU",
1634
+ likely_causes: [
1635
+ "Inefficient DSP algorithms",
1636
+ "Excessive memory allocations",
1637
+ "Redundant calculations per sample"
1638
+ ],
1639
+ solutions: [
1640
+ "Use pre-computed coefficients",
1641
+ "Avoid allocations in audio callbacks",
1642
+ "Use SIMD where available",
1643
+ "Consider data-oriented layouts (dalek)",
1644
+ "Cache frequently used values"
1645
+ ],
1646
+ relevant_libraries: ["zang", "dalek", "bonk"]
1647
+ }
1648
+ };
1649
+
1650
+ const result = troubleshootingGuides[input.issue_type];
1651
+
1652
+ return {
1653
+ content: [{
1654
+ type: "text",
1655
+ text: JSON.stringify(result, null, 2)
1656
+ }]
1657
+ };
1658
+ }
1659
+
1660
+ async function handleDeprecationCheck(args: unknown) {
1661
+ const input = DeprecationCheckInput.parse(args);
1662
+
1663
+ const userZigVersion = input.zig_version || "0.12.0";
1664
+
1665
+ const compatibilityMatrix: Record<string, any> = {
1666
+ "zang": {
1667
+ latest_version: "0.12+ compatible",
1668
+ status: "active",
1669
+ notes: "Actively maintained for latest Zig versions"
1670
+ },
1671
+ "zaudio": {
1672
+ latest_version: "Zig 0.11+",
1673
+ status: "needs-update",
1674
+ notes: "May need updates for Zig 0.12+. Check repository for latest."
1675
+ },
1676
+ "bonk": {
1677
+ latest_version: "Zig 0.10+",
1678
+ status: "needs-update",
1679
+ notes: "Older version. Check for newer releases or fork."
1680
+ },
1681
+ "pcm": {
1682
+ latest_version: "Zig 0.9+",
1683
+ status: "deprecated",
1684
+ notes: "Very outdated. Consider alternative or fork to update."
1685
+ },
1686
+ "zig-liquid-dsp": {
1687
+ latest_version: "Zig 0.11+",
1688
+ status: "active",
1689
+ notes: "Actively maintained for Zig 0.11+. Check for 0.12 support."
1690
+ },
1691
+ "dalek": {
1692
+ latest_version: "Zig 0.10+",
1693
+ status: "experimental",
1694
+ notes: "Experimental library. API may change."
1695
+ }
1696
+ };
1697
+
1698
+ const libInfo = compatibilityMatrix[input.library];
1699
+
1700
+ let upgradeAdvice = "";
1701
+ if (libInfo) {
1702
+ if (libInfo.status === "deprecated") {
1703
+ upgradeAdvice = "This library is deprecated. Consider migrating to an active alternative like zang or zaudio.";
1704
+ } else if (libInfo.status === "needs-update") {
1705
+ upgradeAdvice = "This library may need updates for current Zig. Check the repository for latest version.";
1706
+ }
1707
+ }
1708
+
1709
+ const result = {
1710
+ library: input.library,
1711
+ your_zig_version: userZigVersion,
1712
+ compatibility: libInfo || { status: "unknown", notes: "No information available" },
1713
+ upgrade_advice: upgradeAdvice
1714
+ };
1715
+
1716
+ return {
1717
+ content: [{
1718
+ type: "text",
1719
+ text: JSON.stringify(result, null, 2)
1720
+ }]
1721
+ };
1722
+ }
1723
+
1724
+ async function handleCalculateDelay(args: unknown) {
1725
+ const input = CalculateDelayInput.parse(args);
1726
+
1727
+ const SPEED_OF_SOUND_FPS = 1126.0;
1728
+ const SPEED_OF_SOUND_MPS = 343.0;
1729
+
1730
+ function convertMs(value: number, toUnit: string, sampleRate: number): number {
1731
+ switch (toUnit) {
1732
+ case "samples": return value * sampleRate / 1000;
1733
+ case "feet": return value * SPEED_OF_SOUND_FPS / 1000;
1734
+ case "meters": return value * SPEED_OF_SOUND_MPS / 1000;
1735
+ default: return value;
1736
+ }
1737
+ }
1738
+
1739
+ function convertSamples(value: number, toUnit: string, sampleRate: number): number {
1740
+ const ms = value * 1000 / sampleRate;
1741
+ switch (toUnit) {
1742
+ case "ms": return ms;
1743
+ case "feet": return ms * SPEED_OF_SOUND_FPS / 1000;
1744
+ case "meters": return ms * SPEED_OF_SOUND_MPS / 1000;
1745
+ default: return value;
1746
+ }
1747
+ }
1748
+
1749
+ function convertFeet(value: number, toUnit: string, sampleRate: number): number {
1750
+ const ms = value * 1000 / SPEED_OF_SOUND_FPS;
1751
+ switch (toUnit) {
1752
+ case "ms": return ms;
1753
+ case "samples": return ms * sampleRate / 1000;
1754
+ case "meters": return value * 0.3048;
1755
+ default: return value;
1756
+ }
1757
+ }
1758
+
1759
+ function convertMeters(value: number, toUnit: string, sampleRate: number): number {
1760
+ const ms = value * 1000 / SPEED_OF_SOUND_MPS;
1761
+ switch (toUnit) {
1762
+ case "ms": return ms;
1763
+ case "samples": return ms * sampleRate / 1000;
1764
+ case "feet": return value / 0.3048;
1765
+ default: return value;
1766
+ }
1767
+ }
1768
+
1769
+ let convertedValue: number;
1770
+ switch (input.from_unit) {
1771
+ case "ms":
1772
+ convertedValue = convertMs(input.value, input.to_unit, input.sample_rate);
1773
+ break;
1774
+ case "samples":
1775
+ convertedValue = convertSamples(input.value, input.to_unit, input.sample_rate);
1776
+ break;
1777
+ case "feet":
1778
+ convertedValue = convertFeet(input.value, input.to_unit, input.sample_rate);
1779
+ break;
1780
+ case "meters":
1781
+ convertedValue = convertMeters(input.value, input.to_unit, input.sample_rate);
1782
+ break;
1783
+ }
1784
+
1785
+ const result = {
1786
+ input: {
1787
+ value: input.value,
1788
+ unit: input.from_unit,
1789
+ sample_rate: input.sample_rate
1790
+ },
1791
+ output: {
1792
+ value: Number(convertedValue.toFixed(2)),
1793
+ unit: input.to_unit
1794
+ },
1795
+ formula: `At ${input.sample_rate}Hz, 1 sample = ${(1000 / input.sample_rate).toFixed(3)}ms`
1796
+ };
1797
+
1798
+ return {
1799
+ content: [{
1800
+ type: "text",
1801
+ text: JSON.stringify(result, null, 2)
1802
+ }]
1803
+ };
1804
+ }
1805
+
1032
1806
  // Create and configure the MCP server
1033
1807
  const server = new Server(
1034
1808
  {
1035
1809
  name: "mcp-zig-audio",
1036
- version: "0.1.0"
1810
+ version: "0.1.4"
1037
1811
  },
1038
1812
  {
1039
1813
  capabilities: {
1040
- tools: {}
1814
+ tools: {},
1815
+ prompts: {},
1816
+ resources: {}
1041
1817
  }
1042
1818
  }
1043
1819
  );
1044
1820
 
1045
1821
  // Set up request handlers
1822
+ server.setRequestHandler(ListPromptsRequestSchema, async () => {
1823
+ return {
1824
+ prompts: Object.values(PROMPTS).map(prompt => ({
1825
+ name: prompt.name,
1826
+ description: prompt.description,
1827
+ arguments: prompt.arguments.map(arg => ({
1828
+ name: arg.name,
1829
+ description: arg.description,
1830
+ required: arg.required
1831
+ }))
1832
+ }))
1833
+ };
1834
+ });
1835
+
1836
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1837
+ const promptName = request.params.name as keyof typeof PROMPTS;
1838
+ const prompt = PROMPTS[promptName];
1839
+
1840
+ if (!prompt) {
1841
+ throw new Error(`Unknown prompt: ${promptName}`);
1842
+ }
1843
+
1844
+ const args = request.params.arguments as Record<string, unknown> || {};
1845
+ return {
1846
+ messages: [{
1847
+ role: "user",
1848
+ content: {
1849
+ type: "text",
1850
+ text: generatePromptContent(promptName, args)
1851
+ }
1852
+ }]
1853
+ };
1854
+ });
1855
+
1856
+ // Handle listing available resources
1857
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
1858
+ const resourceList = Object.values(RESOURCES).map(resource => ({
1859
+ uri: resource.uri,
1860
+ name: resource.name,
1861
+ description: resource.description,
1862
+ mimeType: resource.mimeType
1863
+ }));
1864
+
1865
+ return {
1866
+ resources: resourceList
1867
+ };
1868
+ });
1869
+
1870
+ // Handle reading a specific resource by URI
1871
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1872
+ const uri = request.params.uri as string;
1873
+
1874
+ // Direct resource lookup
1875
+ if (RESOURCES[uri as keyof typeof RESOURCES]) {
1876
+ const resource = RESOURCES[uri as keyof typeof RESOURCES];
1877
+ return {
1878
+ contents: [{
1879
+ uri: resource.uri,
1880
+ mimeType: resource.mimeType,
1881
+ text: JSON.stringify(resource.data, null, 2)
1882
+ }]
1883
+ };
1884
+ }
1885
+
1886
+ // Handle parameterized templates: zig-audio://libraries/{name}
1887
+ const libraryMatch = uri.match(/^zig-audio:\/\/libraries\/(.+)$/);
1888
+ if (libraryMatch) {
1889
+ const libName = libraryMatch[1];
1890
+ const library = ZIG_AUDIO_LIBRARIES[libName as keyof typeof ZIG_AUDIO_LIBRARIES];
1891
+ if (library) {
1892
+ return {
1893
+ contents: [{
1894
+ uri: uri,
1895
+ mimeType: "application/json",
1896
+ text: JSON.stringify(library, null, 2)
1897
+ }]
1898
+ };
1899
+ }
1900
+ throw new Error(`Library not found: ${libName}`);
1901
+ }
1902
+
1903
+ // Handle parameterized templates: zig-dsp://filters/{type}
1904
+ const filterMatch = uri.match(/^zig-dsp:\/\/filters\/(.+)$/);
1905
+ if (filterMatch) {
1906
+ const filterType = filterMatch[1];
1907
+ const filter = DSP_FILTERS[filterType as keyof typeof DSP_FILTERS];
1908
+ if (filter) {
1909
+ return {
1910
+ contents: [{
1911
+ uri: uri,
1912
+ mimeType: "application/json",
1913
+ text: JSON.stringify(filter, null, 2)
1914
+ }]
1915
+ };
1916
+ }
1917
+ throw new Error(`Filter type not found: ${filterType}`);
1918
+ }
1919
+
1920
+ throw new Error(`Resource not found: ${uri}`);
1921
+ });
1922
+
1923
+ // Handle listing resource templates
1924
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
1925
+ return {
1926
+ resourceTemplates: RESOURCE_TEMPLATES
1927
+ };
1928
+ });
1929
+
1046
1930
  server.setRequestHandler(ListToolsRequestSchema, async () => {
1047
1931
  return {
1048
1932
  tools: [
@@ -1121,7 +2005,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
1121
2005
  properties: {
1122
2006
  resource_type: {
1123
2007
  type: "string",
1124
- enum: ["tutorial", "reference", "example", "article"],
2008
+ enum: ["tutorial", "reference", "example", "article", "video", "forum", "github-issues"],
1125
2009
  description: "Filter by resource type"
1126
2010
  }
1127
2011
  }
@@ -1229,6 +2113,85 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
1229
2113
  },
1230
2114
  required: ["project_type"]
1231
2115
  }
2116
+ },
2117
+ {
2118
+ name: "zig_audio_compare_libraries",
2119
+ description: "Compare multiple Zig audio libraries side-by-side",
2120
+ inputSchema: {
2121
+ type: "object",
2122
+ properties: {
2123
+ libraries: {
2124
+ type: "array",
2125
+ items: { type: "string", enum: ["zang", "zaudio", "bonk", "pcm", "zig-liquid-dsp", "dalek", "zsynth", "zig-synth", "noize"] },
2126
+ description: "Libraries to compare (2-6)",
2127
+ minItems: 2,
2128
+ maxItems: 6
2129
+ }
2130
+ },
2131
+ required: ["libraries"]
2132
+ }
2133
+ },
2134
+ {
2135
+ name: "zig_audio_troubleshoot",
2136
+ description: "Debug common audio programming issues and get solutions",
2137
+ inputSchema: {
2138
+ type: "object",
2139
+ properties: {
2140
+ issue_type: {
2141
+ type: "string",
2142
+ enum: ["audio-glitches", "latency", "no-sound", "crash", "compilation-error", "performance"],
2143
+ description: "Type of issue to troubleshoot"
2144
+ }
2145
+ },
2146
+ required: ["issue_type"]
2147
+ }
2148
+ },
2149
+ {
2150
+ name: "zig_audio_deprecation_check",
2151
+ description: "Check if a library is deprecated or needs updates for your Zig version",
2152
+ inputSchema: {
2153
+ type: "object",
2154
+ properties: {
2155
+ library: {
2156
+ type: "string",
2157
+ description: "Library name to check"
2158
+ },
2159
+ zig_version: {
2160
+ type: "string",
2161
+ description: "Your Zig version (optional, defaults to 0.12.0)"
2162
+ }
2163
+ },
2164
+ required: ["library"]
2165
+ }
2166
+ },
2167
+ {
2168
+ name: "zig_dsp_calculate_delay",
2169
+ description: "Convert delay values between milliseconds, samples, feet, and meters",
2170
+ inputSchema: {
2171
+ type: "object",
2172
+ properties: {
2173
+ value: {
2174
+ type: "number",
2175
+ description: "The delay value to convert"
2176
+ },
2177
+ from_unit: {
2178
+ type: "string",
2179
+ enum: ["ms", "samples", "feet", "meters"],
2180
+ description: "Unit to convert from"
2181
+ },
2182
+ to_unit: {
2183
+ type: "string",
2184
+ enum: ["ms", "samples", "feet", "meters"],
2185
+ description: "Unit to convert to"
2186
+ },
2187
+ sample_rate: {
2188
+ type: "number",
2189
+ default: 44100,
2190
+ description: "Sample rate in Hz (required for sample conversions)"
2191
+ }
2192
+ },
2193
+ required: ["value", "from_unit", "to_unit"]
2194
+ }
1232
2195
  }
1233
2196
  ]
1234
2197
  };
@@ -1259,6 +2222,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1259
2222
  return await handleVerifyCode(args);
1260
2223
  case "zig_audio_project_template":
1261
2224
  return await handleProjectTemplate(args);
2225
+ case "zig_audio_compare_libraries":
2226
+ return await handleCompareLibraries(args);
2227
+ case "zig_audio_troubleshoot":
2228
+ return await handleTroubleshoot(args);
2229
+ case "zig_audio_deprecation_check":
2230
+ return await handleDeprecationCheck(args);
2231
+ case "zig_dsp_calculate_delay":
2232
+ return await handleCalculateDelay(args);
1262
2233
  default:
1263
2234
  throw new Error(`Unknown tool: ${name}`);
1264
2235
  }