@audiolabtools/mcp-server 0.1.1 → 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.
Files changed (3) hide show
  1. package/README.md +32 -23
  2. package/hosted-server.mjs +164 -61
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -3,7 +3,8 @@
3
3
  MCP ([Model Context Protocol](https://modelcontextprotocol.io)) server that gives any
4
4
  MCP-capable AI — Claude Desktop, Claude Code, Cursor, and others — eight audio-analysis
5
5
  tools, backed by the hosted **AudioLab** API. It is a thin HTTP client: **no local audio
6
- engine, no ffmpeg, nothing to compile.**
6
+ engine, no ffmpeg, nothing to compile.** It can analyse a **public URL** or a **local file**
7
+ on your machine.
7
8
 
8
9
  ## Install
9
10
 
@@ -30,25 +31,30 @@ Get a key: sign in at **https://audiolab.tools/account** and generate one (free
30
31
 
31
32
  ## Tools
32
33
 
33
- Every tool takes a **public https URL** to the audio; the API fetches and analyses it
34
- server-side and returns numbers only (nothing is uploaded from your machine).
35
-
36
- | Tool | Input | Returns |
37
- |---|---|---|
38
- | `analyze_loudness` | `{ url }` | Integrated LUFS (EBU R128 / BS.1770-4), true-peak (dBTP), LRA, crest factor, stereo correlation, mono compatibility, tonal balance |
39
- | `check_target` | `{ url, target, lufs?, tp? }` | Pass/fail vs a delivery target (`spotify` / `apple-music` / `youtube` / `tidal` / `amazon-music` / `podcast` / `ebu-broadcast` / `atsc-broadcast`, or `target:"custom"` + `lufs`+`tp`), with per-metric deltas and an ffmpeg loudnorm fix command |
40
- | `analyze_timeseries` | `{ url, waveformPoints? }` | Short-term LUFS over time + downsampled waveform peaks (for graphs/meters) |
41
- | `get_spectrum` | `{ url }` | FFT magnitude data + 7-band energies + dominant band |
42
- | `analyze_voice` | `{ url }` | Voice QA: speech/silence ratio, speaking rate, SNR, noise floor, room echo, sibilance & clipping risk |
43
- | `get_speech_segments` | `{ url }` | Voiced regions with start/end + per-segment RMS (auto-trim, chapters) |
44
- | `index_signal` | `{ url }` | Content-type guess, tags, clipping/silence regions, brightness & dynamics buckets |
45
- | `compare_loudness` | `{ urlA, urlB }` | Runs loudness on both and returns both results for an A/B comparison |
34
+ Every tool takes **one audio source** — a public `url` **or** a local `path`:
35
+
36
+ - `{ url: "https://…" }` — a public https URL the API fetches server-side.
37
+ - `{ path: "./mix.wav" }` — a file on the machine running this server. Files up to **4 MB**
38
+ are sent inline; larger files (up to **50 MB**) upload over a one-shot signed URL, are
39
+ analysed, and are then deleted. *(Local `path` works only in this stdio server, not the
40
+ remote `/mcp` endpoint.)*
41
+
42
+ | Tool | Returns |
43
+ |---|---|
44
+ | `analyze_loudness` | Integrated LUFS (EBU R128 / BS.1770-4), true-peak (dBTP), LRA, crest factor, stereo correlation, mono compatibility, tonal balance |
45
+ | `check_target` | Pass/fail vs a delivery target (`spotify` / `apple-music` / `youtube` / `tidal` / `amazon-music` / `podcast` / `ebu-broadcast` / `atsc-broadcast`, or `target:"custom"` + `lufs`+`tp`), with per-metric deltas and an ffmpeg loudnorm fix command |
46
+ | `analyze_timeseries` | Short-term LUFS over time + downsampled waveform peaks (`waveformPoints?`) |
47
+ | `get_spectrum` | FFT magnitude data + 7-band energies + dominant band |
48
+ | `analyze_voice` | Voice QA: speech/silence ratio, speaking rate, SNR, noise floor, room echo, sibilance & clipping risk |
49
+ | `get_speech_segments` | Voiced regions with start/end + per-segment RMS (auto-trim, chapters) |
50
+ | `index_signal` | Content-type guess, tags, clipping/silence regions, brightness & dynamics buckets |
51
+ | `compare_loudness` | A/B on two sources (`urlA`/`pathA` + `urlB`/`pathB`), returns both results |
46
52
 
47
53
  Example asks to your AI:
48
54
 
49
- - *“Analyze the loudness of https://example.com/track.wav”* → `analyze_loudness`
50
- - *“Does https://example.com/mix.wav pass Spotify?”* → `check_target` with `target:"spotify"`
51
- - *“A/B-compare masterA.wav vs masterB.wav for loudness”* → `compare_loudness`
55
+ - *“Analyze the loudness of https://example.com/track.wav”* → `analyze_loudness` with `url`
56
+ - *“Run loudness on ./master.wav”* → `analyze_loudness` with `path`
57
+ - *“Does ./mix.mp3 pass Spotify?”* → `check_target` with `path` + `target:"spotify"`
52
58
 
53
59
  ## Configuration (env)
54
60
 
@@ -60,20 +66,23 @@ Example asks to your AI:
60
66
 
61
67
  ## Privacy
62
68
 
63
- The tools send the **audio URL** and your **API key** to the AudioLab API (`audiolab.tools`),
64
- which fetches and analyses the audio server-side and returns numbers only — your audio is not
65
- stored (see https://audiolab.tools/privacy). This package has no telemetry and writes nothing
66
- to disk.
69
+ Analysis happens on the AudioLab API, so the audio **does reach `audiolab.tools`** — a `url`
70
+ is fetched server-side, and a local `path` is sent to the API (small files inline; larger
71
+ files via a private one-shot signed upload that is deleted right after analysis). The API
72
+ returns **numbers only** and does not retain your audio (see https://audiolab.tools/privacy).
73
+ This package has no telemetry and writes nothing to disk. If audio must never leave the
74
+ machine, don't use a hosted analyser.
67
75
 
68
76
  ## Limits
69
77
 
78
+ - Local files: up to **50 MB** (host bigger ones at a public URL).
70
79
  - One file per call (agents loop for many); one-shot (no streaming/realtime).
71
- - File-size and rate limits are enforced by the API, per key.
80
+ - Rate and monthly limits are enforced by the API, per key.
72
81
 
73
82
  ## Smoke test
74
83
 
75
84
  ```sh
76
- node hosted-server.mjs --selftest # verifies the 8 tools register + the missing-key guard; no network
85
+ node hosted-server.mjs --selftest # verifies the 8 tools + guards; no network
77
86
  ```
78
87
 
79
88
  ## License
package/hosted-server.mjs CHANGED
@@ -1,14 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  // AudioLab HOSTED-mode MCP server. Exposes the 8 AudioLab tools to any MCP-capable
3
3
  // AI (Claude Desktop / Claude Code, Cursor, etc.) by calling the hosted API at
4
- // audiolab.tools/v1/*. Unlike mcp/server.mjs it contains NO engine code, just HTTP
5
- // calls, so it is safe to distribute publicly without exposing the proprietary engine.
4
+ // audiolab.tools/v1/*. It contains NO engine code, just HTTP calls, so it is safe to
5
+ // distribute publicly without exposing the proprietary engine.
6
6
  //
7
7
  // Two consumers share buildServer():
8
8
  // 1. This file run directly = a stdio server (the npm package @audiolabtools/mcp-server),
9
- // reading the key from AUDIOLAB_API_KEY.
9
+ // reading the key from AUDIOLAB_API_KEY. Started with { local: true } — so it can also
10
+ // analyse a LOCAL file via `{ path }` (small files POST raw; larger files are PUT to
11
+ // storage via a signed URL and analysed by objectPath). Nothing is exposed publicly.
10
12
  // 2. api/mcp.mjs = the remote streamable-HTTP endpoint at /mcp, which passes the
11
- // per-request Bearer key via buildServer({ apiKey }).
13
+ // per-request Bearer key via buildServer({ apiKey }). local defaults to FALSE there —
14
+ // a remote server must NEVER read a path off its own filesystem, so `{ path }` is
15
+ // rejected and only `{ url }` is accepted.
12
16
  //
13
17
  // Requires an API key (self-serve: sign in at https://audiolab.tools/account and generate one).
14
18
  // Config in Claude Desktop's claude_desktop_config.json:
@@ -17,13 +21,21 @@
17
21
  // "env": { "AUDIOLAB_API_KEY": "al_live_yourkey" } } } }
18
22
  //
19
23
  // Env: AUDIOLAB_API_KEY (required at call time for stdio mode), AUDIOLAB_API_BASE
20
- // (default https://audiolab.tools/v1). Smoke test (no network): node mcp/hosted-server.mjs --selftest
24
+ // (default https://audiolab.tools/v1, must be https), AUDIOLAB_TIMEOUT_MS (default 60000).
25
+ // Smoke test (no network): node hosted-server.mjs --selftest
21
26
 
22
27
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
23
28
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
29
+ import { readFile } from 'node:fs/promises';
30
+ import { basename } from 'node:path';
24
31
  import { pathToFileURL } from 'node:url';
25
32
  import { z } from 'zod';
26
33
 
34
+ // Vercel serverless caps a raw request body at ~4.5 MB, so small files POST directly and
35
+ // larger ones go through the signed-URL storage flow. The bucket policy caps at 50 MB.
36
+ const RAW_MAX = 4 * 1024 * 1024;
37
+ const STORAGE_MAX = 50 * 1024 * 1024;
38
+
27
39
  // Read env at CALL time (not module load) so the key can be injected by the MCP host
28
40
  // and so the missing-key guard is testable.
29
41
  const apiBase = () => {
@@ -33,99 +45,185 @@ const apiBase = () => {
33
45
  return base;
34
46
  };
35
47
 
36
- // key defaults to the env var (stdio mode); the remote endpoint passes a per-request key.
37
- export async function call(route, body, key = process.env.AUDIOLAB_API_KEY) {
38
- if (!key) throw new Error('AUDIOLAB_API_KEY is not set. Get a key at https://audiolab.tools/account.');
39
- // Time-box the request so a hung/slow API can't stall the calling agent forever.
40
- const timeoutMs = Number(process.env.AUDIOLAB_TIMEOUT_MS) || 60_000;
48
+ const timeoutMs = () => Number(process.env.AUDIOLAB_TIMEOUT_MS) || 60_000;
49
+
50
+ function requireKey(key) {
51
+ const k = key || process.env.AUDIOLAB_API_KEY;
52
+ if (!k) throw new Error('AUDIOLAB_API_KEY is not set. Get a key at https://audiolab.tools/account.');
53
+ return k;
54
+ }
55
+
56
+ // Guess an audio content-type from a filename extension.
57
+ const CT_BY_EXT = { mp3: 'audio/mpeg', wav: 'audio/wav', flac: 'audio/flac', m4a: 'audio/mp4', mp4: 'audio/mp4', aac: 'audio/aac', ogg: 'audio/ogg', oga: 'audio/ogg', opus: 'audio/opus', webm: 'audio/webm', aiff: 'audio/aiff', aif: 'audio/aiff' };
58
+ const ctForPath = (p) => CT_BY_EXT[String(p).split('.').pop()?.toLowerCase()] || 'application/octet-stream';
59
+
60
+ // Low-level JSON request with a hard timeout. Never echoes an arbitrary upstream body.
61
+ async function request(url, { method = 'POST', headers = {}, body } = {}) {
62
+ const ms = timeoutMs();
41
63
  let res;
42
64
  try {
43
- res = await fetch(`${apiBase()}/${route}`, {
44
- method: 'POST',
45
- headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
46
- body: JSON.stringify(body),
47
- signal: AbortSignal.timeout(timeoutMs),
48
- });
65
+ res = await fetch(url, { method, headers, body, signal: AbortSignal.timeout(ms) });
49
66
  } catch (e) {
50
- if (e?.name === 'TimeoutError') throw new Error(`AudioLab API timed out after ${timeoutMs} ms.`);
67
+ if (e?.name === 'TimeoutError') throw new Error(`AudioLab API timed out after ${ms} ms.`);
51
68
  throw new Error(`Could not reach the AudioLab API: ${String(e?.message || e)}`);
52
69
  }
53
70
  const text = await res.text();
54
71
  let json;
55
- // Parse JSON only; never echo an arbitrary upstream body back to the agent.
56
72
  try { json = JSON.parse(text); }
57
73
  catch { throw new Error(res.ok ? 'AudioLab API returned a non-JSON response.' : `AudioLab API error ${res.status}.`); }
58
74
  if (!res.ok) throw new Error(String(json?.error?.message || json?.error || `API returned ${res.status}`));
59
75
  return json;
60
76
  }
61
77
 
78
+ // key defaults to the env var (stdio mode); the remote endpoint passes a per-request key.
79
+ export async function call(route, body, key = process.env.AUDIOLAB_API_KEY) {
80
+ const k = requireKey(key);
81
+ return request(`${apiBase()}/${route}`, {
82
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${k}` },
83
+ body: JSON.stringify(body),
84
+ });
85
+ }
86
+
87
+ // Small local file → raw audio body straight to /v1 (fast, no storage round-trip).
88
+ // Tool extras (target/lufs/tp/waveformPoints/fileName) ride along as query params.
89
+ async function postRaw(route, buf, ct, extra, key) {
90
+ const k = requireKey(key);
91
+ const qs = new URLSearchParams();
92
+ for (const [name, v] of Object.entries(extra || {})) if (v !== undefined && v !== null && v !== '') qs.set(name, String(v));
93
+ const q = qs.toString();
94
+ return request(`${apiBase()}/${route}${q ? `?${q}` : ''}`, {
95
+ headers: { 'content-type': ct, authorization: `Bearer ${k}` },
96
+ body: buf,
97
+ });
98
+ }
99
+
100
+ // Larger local file → mint a signed upload URL, PUT the bytes to storage, then analyse by
101
+ // objectPath. The objectPath is namespaced to this key server-side; only this key can read it.
102
+ async function postUpload(route, buf, ct, fileName, extra, key) {
103
+ const k = requireKey(key);
104
+ const origin = new URL(apiBase()).origin;
105
+ const mint = await request(`${origin}/api/upload-url`, {
106
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${k}` },
107
+ body: JSON.stringify({ contentType: ct, size: buf.length }),
108
+ });
109
+ if (!mint?.signedUrl || !mint?.objectPath) throw new Error('Could not prepare the upload.');
110
+ let put;
111
+ try {
112
+ put = await fetch(mint.signedUrl, { method: 'PUT', headers: { 'content-type': ct }, body: buf, signal: AbortSignal.timeout(timeoutMs()) });
113
+ } catch (e) {
114
+ if (e?.name === 'TimeoutError') throw new Error(`Upload timed out after ${timeoutMs()} ms.`);
115
+ throw new Error(`Upload to storage failed: ${String(e?.message || e)}`);
116
+ }
117
+ if (!put.ok) throw new Error(`Upload to storage failed (HTTP ${put.status}).`);
118
+ return call(route, { objectPath: mint.objectPath, fileName, ...extra }, k);
119
+ }
120
+
121
+ // Resolve one audio source (url OR local path) to a route call. `local` gates path reads:
122
+ // the remote /mcp endpoint passes local=false and must NEVER touch the server filesystem.
123
+ async function analyzeSource(route, { url, path } = {}, extra = {}, key, local = false) {
124
+ if (url && path) throw new Error('Provide exactly one of url or path, not both.');
125
+ if (path) {
126
+ if (!local) throw new Error('Local file paths are only supported by the local (stdio) MCP server; use a public https url instead.');
127
+ let buf;
128
+ try { buf = await readFile(path); }
129
+ catch (e) { throw new Error(`Could not read local file "${path}": ${e?.code || e?.message || e}`); }
130
+ if (!buf.length) throw new Error('Local file is empty.');
131
+ if (buf.length > STORAGE_MAX) throw new Error(`Local file is ${(buf.length / 1048576).toFixed(1)} MB; max ${STORAGE_MAX / 1048576} MB. Host it at a public https URL for larger files.`);
132
+ const name = basename(path);
133
+ const ct = ctForPath(path);
134
+ return buf.length <= RAW_MAX
135
+ ? postRaw(route, buf, ct, { ...extra, fileName: name }, key) // small → raw POST (no storage)
136
+ : postUpload(route, buf, ct, name, extra, key); // large → signed-URL upload
137
+ }
138
+ if (url) return call(route, { url, ...extra }, key);
139
+ throw new Error('Provide a url (public https) or a path (local file).');
140
+ }
141
+
62
142
  const asContent = (obj) => ({ content: [{ type: 'text', text: JSON.stringify(obj) }] });
63
143
  const wrap = (fn) => async (input) => {
64
144
  try { return asContent(await fn(input)); }
65
145
  catch (e) { return { isError: true, content: [{ type: 'text', text: String(e?.message || e) }] }; }
66
146
  };
67
147
 
68
- const URL_IN = { url: z.string().url().describe('Public https URL to the audio file.') };
148
+ // Input source shape. Remote (url-only) keeps the original required url; local adds an
149
+ // optional path (exactly one of the two). Local-file support only exists in stdio mode.
150
+ const sourceShape = (local) => local
151
+ ? {
152
+ url: z.string().url().optional().describe('Public https URL to the audio file. Provide exactly one of url or path.'),
153
+ path: z.string().optional().describe('Path to a LOCAL audio file on this machine — analysed without hosting it publicly (files up to 4 MB are sent inline; larger ones up to 50 MB upload over a one-shot signed URL). Provide exactly one of url or path.'),
154
+ }
155
+ : { url: z.string().url().describe('Public https URL to the audio file.') };
69
156
 
70
- export function buildServer({ apiKey } = {}) {
71
- const server = new McpServer({ name: 'audiolab', version: '0.1.1' }); // keep in sync with package.json
157
+ export function buildServer({ apiKey, local = false } = {}) {
158
+ const server = new McpServer({ name: 'audiolab', version: '0.2.0' }); // keep in sync with package.json
72
159
  const toolNames = [];
73
160
  const tool = (name, def, handler) => { server.registerTool(name, def, handler); toolNames.push(name); };
74
- // Per-request API key threaded from the transport, so we never race on process.env
75
- // when several requests share one warm serverless instance.
76
- const api = (route, body) => call(route, body, apiKey);
161
+ const src = sourceShape(local);
162
+ const srcDoc = local ? ' Audio source: a public https URL, or a local file path (`path`).' : ' Audio source: public https URL.';
77
163
 
78
164
  tool('analyze_loudness', {
79
165
  title: 'Analyze loudness (MixLab)',
80
- description: 'Loudness and dynamics for a track: integrated LUFS (EBU R128 / BS.1770-4), true-peak (dBTP), loudness range (LRA), crest factor, stereo correlation, mono compatibility, and tonal balance. Audio source: public https URL.',
81
- inputSchema: URL_IN,
82
- }, wrap(({ url }) => api('mixlab/analyze', { url })));
166
+ description: 'Loudness and dynamics for a track: integrated LUFS (EBU R128 / BS.1770-4), true-peak (dBTP), loudness range (LRA), crest factor, stereo correlation, mono compatibility, and tonal balance.' + srcDoc,
167
+ inputSchema: src,
168
+ }, wrap((i) => analyzeSource('mixlab/analyze', i, {}, apiKey, local)));
83
169
 
84
170
  tool('check_target', {
85
171
  title: 'Check audio against a loudness target (Spotify, EBU, etc.)',
86
- description: 'Verify whether audio hits a delivery target (Spotify -14 LUFS / EBU broadcast -23 / podcast -16 / etc.). Returns pass/fail with per-metric deltas and a concrete ffmpeg loudnorm command to fix if failing. Presets: spotify, apple-music, youtube, tidal, amazon-music, podcast, ebu-broadcast, atsc-broadcast; or target="custom" with lufs+tp.',
87
- inputSchema: { ...URL_IN, target: z.string().describe('Preset id or "custom".'), lufs: z.number().optional(), tp: z.number().optional() },
88
- }, wrap(({ url, target, lufs, tp }) => api('mixlab/check-target', { url, target, lufs, tp })));
172
+ description: 'Verify whether audio hits a delivery target (Spotify -14 LUFS / EBU broadcast -23 / podcast -16 / etc.). Returns pass/fail with per-metric deltas and a concrete ffmpeg loudnorm command to fix if failing. Presets: spotify, apple-music, youtube, tidal, amazon-music, podcast, ebu-broadcast, atsc-broadcast; or target="custom" with lufs+tp.' + srcDoc,
173
+ inputSchema: { ...src, target: z.string().describe('Preset id or "custom".'), lufs: z.number().optional(), tp: z.number().optional() },
174
+ }, wrap((i) => analyzeSource('mixlab/check-target', i, { target: i.target, lufs: i.lufs, tp: i.tp }, apiKey, local)));
89
175
 
90
176
  tool('analyze_timeseries', {
91
177
  title: 'Loudness over time (for graphing / visualization)',
92
- description: 'Short-term LUFS samples over time (EBU R128, ~3s window) with their time-base, plus downsampled waveform peaks. Arrays suitable for loudness-over-time charts, level meters, and waveform UIs.',
93
- inputSchema: { ...URL_IN, waveformPoints: z.number().int().positive().optional().describe('Waveform peak count (default 200).') },
94
- }, wrap(({ url, waveformPoints }) => api('mixlab/timeseries', { url, waveformPoints })));
178
+ description: 'Short-term LUFS samples over time (EBU R128, ~3s window) with their time-base, plus downsampled waveform peaks. Arrays suitable for loudness-over-time charts, level meters, and waveform UIs.' + srcDoc,
179
+ inputSchema: { ...src, waveformPoints: z.number().int().positive().optional().describe('Waveform peak count (default 200).') },
180
+ }, wrap((i) => analyzeSource('mixlab/timeseries', i, { waveformPoints: i.waveformPoints }, apiKey, local)));
95
181
 
96
182
  tool('get_spectrum', {
97
183
  title: 'FFT spectrum data',
98
- description: 'Frequency-domain magnitude data (paired frequency/magnitude arrays) plus energies in 7 standard bands (sub/bass/lowMid/mid/highMid/presence/air) and the dominant band. For spectrum-analyzer UIs and tonal-balance analysis.',
99
- inputSchema: URL_IN,
100
- }, wrap(({ url }) => api('mixlab/spectrum', { url })));
184
+ description: 'Frequency-domain magnitude data (paired frequency/magnitude arrays) plus energies in 7 standard bands (sub/bass/lowMid/mid/highMid/presence/air) and the dominant band. For spectrum-analyzer UIs and tonal-balance analysis.' + srcDoc,
185
+ inputSchema: src,
186
+ }, wrap((i) => analyzeSource('mixlab/spectrum', i, {}, apiKey, local)));
101
187
 
102
188
  tool('analyze_voice', {
103
189
  title: 'Analyze voice quality (VoiceLab)',
104
- description: 'Speech-quality QA for a voice recording: speech/silence ratio, speaking-rate label, signal-to-noise, noise floor, room-echo label, sibilance risk, clipping severity. Gates a voice take.',
105
- inputSchema: URL_IN,
106
- }, wrap(({ url }) => api('voicelab/qa', { url })));
190
+ description: 'Speech-quality QA for a voice recording: speech/silence ratio, speaking-rate label, signal-to-noise, noise floor, room-echo label, sibilance risk, clipping severity. Gates a voice take.' + srcDoc,
191
+ inputSchema: src,
192
+ }, wrap((i) => analyzeSource('voicelab/qa', i, {}, apiKey, local)));
107
193
 
108
194
  tool('get_speech_segments', {
109
195
  title: 'Speech segments (VoiceLab)',
110
- description: 'List voiced speech regions with start/end timestamps and per-segment RMS. For auto-trim, chapter generation, and speaker-turn detection. RMS-based voice-activity detection, not speaker diarization.',
111
- inputSchema: URL_IN,
112
- }, wrap(({ url }) => api('voicelab/segments', { url })));
196
+ description: 'List voiced speech regions with start/end timestamps and per-segment RMS. For auto-trim, chapter generation, and speaker-turn detection. RMS-based voice-activity detection, not speaker diarization.' + srcDoc,
197
+ inputSchema: src,
198
+ }, wrap((i) => analyzeSource('voicelab/segments', i, {}, apiKey, local)));
113
199
 
114
200
  tool('index_signal', {
115
201
  title: 'Index a signal (SignalLab)',
116
- description: 'A metadata index for any audio file: content-type guess (voice/music/mixed/noise/silence) with confidence, brightness & dynamics buckets, dominant band, clipping/silence regions, and tag suggestions. For triage or auto-tagging a library.',
117
- inputSchema: URL_IN,
118
- }, wrap(({ url }) => api('signallab/index', { url })));
202
+ description: 'A metadata index for any audio file: content-type guess (voice/music/mixed/noise/silence) with confidence, brightness & dynamics buckets, dominant band, clipping/silence regions, and tag suggestions. For triage or auto-tagging a library.' + srcDoc,
203
+ inputSchema: src,
204
+ }, wrap((i) => analyzeSource('signallab/index', i, {}, apiKey, local)));
119
205
 
206
+ // compare_loudness — two independent sources, each a url or (local only) a path.
207
+ const cmp = local
208
+ ? {
209
+ urlA: z.string().url().optional().describe('First source URL (e.g. master). Provide urlA or pathA.'),
210
+ pathA: z.string().optional().describe('First source as a local file path.'),
211
+ urlB: z.string().url().optional().describe('Second source URL (e.g. reference). Provide urlB or pathB.'),
212
+ pathB: z.string().optional().describe('Second source as a local file path.'),
213
+ }
214
+ : {
215
+ urlA: z.string().url().describe('First source (e.g. master).'),
216
+ urlB: z.string().url().describe('Second source (e.g. reference).'),
217
+ };
120
218
  tool('compare_loudness', {
121
219
  title: 'Compare two tracks (A/B)',
122
- description: 'Run loudness analysis on TWO URLs and return both results for an A/B comparison: master vs reference, before vs after a fix, two encoders, two cuts.',
123
- inputSchema: {
124
- urlA: z.string().url().describe('First source (e.g. master).'),
125
- urlB: z.string().url().describe('Second source (e.g. reference).'),
126
- },
127
- }, wrap(async ({ urlA, urlB }) => {
128
- const [a, b] = await Promise.all([api('mixlab/analyze', { url: urlA }), api('mixlab/analyze', { url: urlB })]);
220
+ description: 'Run loudness analysis on TWO sources and return both results for an A/B comparison: master vs reference, before vs after a fix, two encoders, two cuts.' + srcDoc,
221
+ inputSchema: cmp,
222
+ }, wrap(async (i) => {
223
+ const [a, b] = await Promise.all([
224
+ analyzeSource('mixlab/analyze', { url: i.urlA, path: i.pathA }, {}, apiKey, local),
225
+ analyzeSource('mixlab/analyze', { url: i.urlB, path: i.pathB }, {}, apiKey, local),
226
+ ]);
129
227
  return { a, b };
130
228
  }));
131
229
 
@@ -138,21 +236,26 @@ const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv
138
236
 
139
237
  if (isMain && process.argv.includes('--selftest')) {
140
238
  const assert = (await import('node:assert/strict')).default;
141
- const { toolNames } = buildServer();
142
- assert.deepEqual(
143
- toolNames.slice().sort(),
144
- ['analyze_loudness', 'analyze_timeseries', 'analyze_voice', 'check_target', 'compare_loudness', 'get_spectrum', 'get_speech_segments', 'index_signal'],
145
- 'eight hosted tools registered',
146
- );
239
+ const expected = ['analyze_loudness', 'analyze_timeseries', 'analyze_voice', 'check_target', 'compare_loudness', 'get_spectrum', 'get_speech_segments', 'index_signal'];
240
+ assert.deepEqual(buildServer().toolNames.slice().sort(), expected, 'eight hosted tools (remote / url-only)');
241
+ assert.deepEqual(buildServer({ local: true }).toolNames.slice().sort(), expected, 'eight hosted tools (local / url+path)');
242
+
147
243
  const prev = process.env.AUDIOLAB_API_KEY;
148
244
  delete process.env.AUDIOLAB_API_KEY;
149
245
  await assert.rejects(() => call('mixlab/analyze', { url: 'https://example.com/a.wav' }), /AUDIOLAB_API_KEY/, 'refuses without a key (before any fetch)');
150
- if (prev) process.env.AUDIOLAB_API_KEY = prev;
151
- console.log('selftest ok · 8 hosted tools (API-backed, no engine) + missing-key guard');
246
+
247
+ process.env.AUDIOLAB_API_KEY = 'al_live_selftest';
248
+ // A remote server (local=false) must refuse a path BEFORE any filesystem read.
249
+ await assert.rejects(() => analyzeSource('mixlab/analyze', { path: '/etc/hostname' }, {}, 'al_live_selftest', false), /only supported by the local/, 'remote MCP never reads a server-side path');
250
+ // url + path together is a usage error.
251
+ await assert.rejects(() => analyzeSource('mixlab/analyze', { url: 'https://x/a.wav', path: '/tmp/a.wav' }, {}, 'al_live_selftest', true), /exactly one/, 'url+path together rejected');
252
+ if (prev) process.env.AUDIOLAB_API_KEY = prev; else delete process.env.AUDIOLAB_API_KEY;
253
+
254
+ console.log('selftest ok · 8 tools (remote url-only + local url|path) + missing-key guard + remote-path refusal');
152
255
  process.exit(0);
153
256
  }
154
257
 
155
258
  if (isMain) {
156
- const { server } = buildServer();
259
+ const { server } = buildServer({ local: true });
157
260
  await server.connect(new StdioServerTransport());
158
261
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@audiolabtools/mcp-server",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "MCP server for AudioLab — loudness (EBU R128 / BS.1770-4), true-peak, voice-quality, and signal analysis for AI agents (Claude, Cursor, any MCP client), via the AudioLab hosted API. No local audio engine required.",
5
5
  "type": "module",
6
6
  "bin": {