mcp-speechmatics-transcribe 0.1.6 → 0.1.8

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/.env.example CHANGED
@@ -14,3 +14,8 @@ SPEECHMATICS_AUDIO_EVENTS=true
14
14
  SPEECHMATICS_CONVERT_TO_MP3=false
15
15
  # Upload and processing timeout, independent of recording duration.
16
16
  SPEECHMATICS_TIMEOUT_SECONDS=900
17
+ # Shared MCP discovery cache lifetime in milliseconds; 0 disables caching.
18
+ SPEECHMATICS_DISCOVERY_CACHE_TTL_MS=600000
19
+ # Additional comma-separated environment names omitted from the cache key.
20
+ # CODEX_TOOL_CALL_ID is always omitted from the key and still passed to the CLI.
21
+ SPEECHMATICS_DISCOVERY_CACHE_KEY_EXCLUDE=
package/README.md CHANGED
@@ -80,7 +80,8 @@ the adapter contains no transcription-specific schemas or execution logic.
80
80
 
81
81
  The read-only `token_status` tool checks all configured tokens through the EU1
82
82
  Batch usage endpoint. Optional `since` and `until` dates use YYYY-MM-DD; the default
83
- start is the first day of the current UTC month. Results identify each key by its
83
+ start is the first day of the current UTC month and the default end is today in UTC,
84
+ explicitly including the current day's usage. Results identify each key by its
84
85
  configured login or a masked token. Excluded keys return `excluded` without an API
85
86
  request. Successful requests return `active` and the API's usage fields directly;
86
87
  failures return `error` with available HTTP details. Short anonymous tokens are fully
@@ -133,13 +134,36 @@ the existing output format. Unknown speaker labels and event types are preserved
133
134
  Audio events appear in Markdown and WebVTT at confidence >=0.90.
134
135
 
135
136
  The shared transcription/logs.json records status, elapsed time, job ID, and
136
- token SHA-256. Token rotation skips credentials disabled after authentication,
137
+ token SHA-256. Tokens are selected in round-robin order across transcription
138
+ requests. Token rotation skips credentials disabled after authentication,
137
139
  entitlement, or exhausted-account-limit errors. HTTP 429 rate limits alone do not
138
140
  disable a token. API errors are returned to the caller.
139
141
 
140
142
  Audio is uploaded to Speechmatics in EU1. Transcription usage is billed by Speechmatics.
141
143
  An API timeout can leave a remote job running; its ID is retained when available.
142
144
 
145
+ ## MCP discovery cache
146
+
147
+ MCP discovery is shared across processes in the operating system temporary
148
+ directory under `transcription/discovery/`. Its default lifetime is 10 minutes
149
+ from a successful refresh; cache hits do not extend it. Set
150
+ `SPEECHMATICS_DISCOVERY_CACHE_TTL_MS` to change the lifetime, or `0` to disable it.
151
+ Tool descriptions reflect the defaults captured during that refresh. Environment
152
+ changes create a different cache entry; edits inside an env file take effect on
153
+ the next refresh or after invalidation.
154
+
155
+ Cache filenames hash the CLI command, arguments, working directory, and complete
156
+ effective environment. `CODEX_TOOL_CALL_ID` is excluded from the hash; additional
157
+ names can be listed in `SPEECHMATICS_DISCOVERY_CACHE_KEY_EXCLUDE`. These exclusions
158
+ never remove variables from the CLI environment. Windows environment names are
159
+ case-insensitive. Exclude only transient values that do not affect discovery.
160
+
161
+ Only validated tool definitions and server identity are cached, with timestamps
162
+ and an opaque hash. Environment values, credentials, session state, and tool-call
163
+ results are not stored. Expired or damaged entries are refreshed, and tool-list
164
+ change notifications invalidate the cache. Warm discovery and legacy MCP ping
165
+ do not start a CLI process. Actual tool calls always delegate to the CLI.
166
+
143
167
  ## Development and releases
144
168
 
145
169
  ```sh
package/mcp.js CHANGED
@@ -1,25 +1,56 @@
1
- import { Server } from "@modelcontextprotocol/server";
2
- import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
- import { runCli } from "./modules/cli-process.js";
1
+ import { Server, PROTOCOL_VERSION_META_KEY } from "@modelcontextprotocol/server";
2
+ import { serveStdio, StdioServerTransport } from "@modelcontextprotocol/server/stdio";
3
+ import { runCli, resolveCliLaunch } from "./modules/cli-process.js";
4
+ import { createDiscoveryCache } from "./modules/discovery-cache.js";
4
5
 
5
- async function createServer() {
6
- let manifest = await runCli("--tool-manifest");
6
+ const launch = resolveCliLaunch();
7
+ const discovery = createDiscoveryCache(launch, () => runCli("--tool-manifest", undefined, { launch }));
8
+ let era;
9
+ let invalidation = Promise.resolve();
10
+ class LocalTransport extends StdioServerTransport {
11
+ async start() {
12
+ const dispatch = this.onmessage;
13
+ this.onmessage = (message, extra) => {
14
+ const modern = message.params?._meta && Object.hasOwn(message.params._meta, PROTOCOL_VERSION_META_KEY);
15
+ if (era !== "modern" && !modern && message.jsonrpc === "2.0" && message.method === "ping"
16
+ && (typeof message.id === "string" || typeof message.id === "number")) {
17
+ this.send({ jsonrpc: "2.0", id: message.id, result: {} }).catch((error) => this.onerror?.(error));
18
+ return;
19
+ }
20
+ if (message.method === "notifications/tools/list_changed" && message.id === undefined) {
21
+ invalidation = discovery.invalidate();
22
+ return;
23
+ }
24
+ dispatch?.(message, extra);
25
+ };
26
+ return super.start();
27
+ }
28
+ }
29
+
30
+ async function createServer(context) {
31
+ era = context.era;
32
+ await invalidation;
33
+ let manifest = await discovery.get();
7
34
  const server = new Server(manifest.serverInfo, {
8
35
  instructions: manifest.serverInfo.description,
9
36
  capabilities: { tools: { listChanged: true } },
10
37
  });
11
38
  server.setRequestHandler("tools/list", async () => {
12
- const latest = await runCli("--tool-manifest");
39
+ await invalidation;
40
+ const latest = await discovery.get();
13
41
  const changed = JSON.stringify(latest.tools) !== JSON.stringify(manifest.tools);
14
42
  manifest = latest;
15
- if (changed) await server.sendToolListChanged();
43
+ if (changed) {
44
+ await discovery.invalidate();
45
+ await server.sendToolListChanged();
46
+ }
16
47
  return { tools: manifest.tools };
17
48
  });
18
- server.setRequestHandler("tools/call", async ({ params }) => {
49
+ server.setRequestHandler("tools/call", async ({ params }, context) => {
19
50
  try {
20
51
  return await runCli("--execute-tool", {
21
52
  protocol: 1, name: params.name, arguments: params.arguments ?? {},
22
- });
53
+ }, { signal: context?.mcpReq.signal });
23
54
  } catch (error) {
24
55
  return { isError: true, content: [{ type: "text", text: JSON.stringify({ message: error.message }) }] };
25
56
  }
@@ -27,4 +58,4 @@ async function createServer() {
27
58
  return server;
28
59
  }
29
60
 
30
- serveStdio(createServer);
61
+ serveStdio(createServer, { transport: new LocalTransport() });
@@ -1,34 +1,42 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawn, execFile } from "node:child_process";
2
2
  import { resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
5
  // Keep arguments and credentials on stdin/environment, outside the shell command.
6
- export function runCli(mode, request) {
6
+ export function resolveCliLaunch() {
7
+ const modulePath = fileURLToPath(import.meta.url);
8
+ const cachedPackage = /[\\/]_npx[\\/][^\\/]+[\\/]node_modules[\\/]mcp-speechmatics-transcribe[\\/]/i.test(modulePath);
9
+ const npmExec = process.env.npm_command === "exec"
10
+ || (!process.env.npm_command && process.env.npm_lifecycle_event === "npx");
11
+ const useNpx = cachedPackage && npmExec;
12
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^npm_config_(package|call)$/i.test(key)));
13
+ env.SPEECHMATICS_ENV_FILE = process.env.SPEECHMATICS_ENV_FILE
14
+ ? resolve(process.env.SPEECHMATICS_ENV_FILE) : fileURLToPath(new URL("../.env", import.meta.url));
15
+ return {
16
+ command: useNpx ? "npx" : process.execPath,
17
+ args: useNpx ? ["-y", "--prefer-online", "--package=mcp-speechmatics-transcribe@latest", "--", "mcp-speechmatics-transcribe"]
18
+ : [fileURLToPath(new URL("../cli.js", import.meta.url))],
19
+ cwd: process.cwd(), env, shell: useNpx && process.platform === "win32",
20
+ };
21
+ }
22
+
23
+ export function runCli(mode, request, { launch = resolveCliLaunch(), signal } = {}) {
7
24
  return new Promise((done, reject) => {
8
25
  if (!["--tool-manifest", "--execute-tool"].includes(mode)) throw new Error("Unsupported CLI mode.");
9
- const modulePath = fileURLToPath(import.meta.url);
10
- const cachedPackage = /[\\/]_npx[\\/][^\\/]+[\\/]node_modules[\\/]mcp-speechmatics-transcribe[\\/]/i.test(modulePath);
11
- const npmExec = process.env.npm_command === "exec"
12
- || (!process.env.npm_command && process.env.npm_lifecycle_event === "npx");
13
- const useNpx = cachedPackage && npmExec;
14
- const launchArgs = useNpx
15
- ? ["-y", "--prefer-online", "--package=mcp-speechmatics-transcribe@latest", "--", "mcp-speechmatics-transcribe", mode]
16
- : [fileURLToPath(new URL("../cli.js", import.meta.url)), mode];
17
- const windowsShell = useNpx && process.platform === "win32";
18
- const environment = Object.fromEntries(Object.entries(process.env)
19
- .filter(([key]) => !/^npm_config_(package|call)$/i.test(key)));
20
- const command = useNpx ? "npx" : process.execPath;
21
- const child = spawn(windowsShell ? command + " " + launchArgs.join(" ") : command, windowsShell ? [] : launchArgs, {
22
- shell: windowsShell,
23
- windowsHide: true,
24
- stdio: ["pipe", "pipe", "inherit"],
25
- env: {
26
- ...environment,
27
- SPEECHMATICS_ENV_FILE: process.env.SPEECHMATICS_ENV_FILE
28
- ? resolve(process.env.SPEECHMATICS_ENV_FILE)
29
- : fileURLToPath(new URL("../.env", import.meta.url)),
30
- },
26
+ signal?.throwIfAborted();
27
+ const launchArgs = [...launch.args, mode];
28
+ const child = spawn(launch.shell ? launch.command + " " + launchArgs.join(" ") : launch.command, launch.shell ? [] : launchArgs, {
29
+ shell: launch.shell, cwd: launch.cwd, windowsHide: true,
30
+ stdio: ["pipe", "pipe", "inherit"], env: launch.env,
31
31
  });
32
+ const abort = () => {
33
+ if (launch.shell && process.platform === "win32" && child.pid) {
34
+ execFile("taskkill", ["/PID", String(child.pid), "/T", "/F"], { windowsHide: true }, () => {});
35
+ } else child.kill();
36
+ reject(new DOMException("CLI operation was cancelled.", "AbortError"));
37
+ };
38
+ signal?.addEventListener("abort", abort, { once: true });
39
+ if (signal?.aborted) abort();
32
40
  let output = "";
33
41
  child.stdout.setEncoding("utf8");
34
42
  child.stdout.on("data", (chunk) => {
@@ -40,6 +48,7 @@ export function runCli(mode, request) {
40
48
  });
41
49
  child.on("error", reject);
42
50
  child.stdin.on("error", reject);
51
+ child.once("close", () => signal?.removeEventListener("abort", abort));
43
52
  child.on("close", (code, signal) => {
44
53
  if (code !== 0) {
45
54
  reject(new Error(`CLI process exited with ${signal ?? code}.`));
@@ -0,0 +1,70 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { z } from "zod";
6
+
7
+ const object = z.record(z.string(), z.json());
8
+ const manifestSchema = z.object({
9
+ protocol: z.literal(1),
10
+ serverInfo: z.object({ name: z.string().min(1), version: z.string().min(1), title: z.string().optional(), description: z.string().optional() }).strict(),
11
+ tools: z.array(z.object({
12
+ name: z.string().min(1), title: z.string().optional(), description: z.string().optional(),
13
+ inputSchema: object.refine((value) => value.type === "object"),
14
+ outputSchema: object.optional(),
15
+ annotations: z.object({ title: z.string().optional(), readOnlyHint: z.boolean().optional(), destructiveHint: z.boolean().optional(), idempotentHint: z.boolean().optional(), openWorldHint: z.boolean().optional() }).strict().optional(),
16
+ }).strict()).refine((tools) => new Set(tools.map((tool) => tool.name)).size === tools.length),
17
+ }).strict();
18
+
19
+ export function discoveryKey(launch, platform = process.platform) {
20
+ const normalize = (key) => platform === "win32" ? key.toUpperCase() : key;
21
+ const excluded = new Set(["CODEX_TOOL_CALL_ID", ...(launch.env.SPEECHMATICS_DISCOVERY_CACHE_KEY_EXCLUDE ?? "").split(",").map((key) => key.trim()).filter(Boolean)].map(normalize));
22
+ const env = Object.entries(launch.env).map(([key, value]) => [normalize(key), value])
23
+ .filter(([key]) => !excluded.has(key)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
24
+ return createHash("sha256").update(JSON.stringify({ version: 1, command: launch.command, args: launch.args, cwd: launch.cwd, shell: launch.shell, env })).digest("hex");
25
+ }
26
+
27
+ export function createDiscoveryCache(launch, load, { directory = join(tmpdir(), "transcription", "discovery"), now = Date.now } = {}) {
28
+ const raw = launch.env.SPEECHMATICS_DISCOVERY_CACHE_TTL_MS ?? "600000";
29
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error("SPEECHMATICS_DISCOVERY_CACHE_TTL_MS must be a nonnegative integer.");
30
+ const ttl = Number(raw), key = discoveryKey(launch), file = join(directory, key + ".json");
31
+ let pending, generation = 0;
32
+ const invalidate = async () => { generation++; await rm(file, { force: true }).catch(() => {}); };
33
+ return {
34
+ file, invalidate,
35
+ async get() {
36
+ if (ttl) {
37
+ try {
38
+ const bytes = await readFile(file);
39
+ if (bytes.length > 1024 * 1024) throw new Error("Oversized cache.");
40
+ const entry = JSON.parse(bytes);
41
+ if (entry.version !== 1 || entry.key !== key || !Number.isFinite(entry.createdAt) || !Number.isFinite(entry.expiresAt)
42
+ || entry.createdAt > now() || entry.expiresAt <= now() || entry.expiresAt - entry.createdAt > ttl) throw new Error("Expired cache.");
43
+ return manifestSchema.parse(entry.manifest);
44
+ } catch { /* Invalid or unavailable cache entries are misses. */ }
45
+ }
46
+ if (pending) return pending;
47
+ const revision = generation;
48
+ pending = (async () => {
49
+ const manifest = manifestSchema.parse(await load());
50
+ const serialized = JSON.stringify(manifest);
51
+ const privateValues = Object.entries(launch.env).filter(([name]) => /token|secret|password|session|CODEX_TOOL_CALL_ID/i.test(name))
52
+ .flatMap(([name, value]) => /SPEECHMATICS_TOKENS/i.test(name)
53
+ ? [value, ...value.split(",").flatMap((entry) => entry.includes(":") ? [entry.slice(entry.indexOf(":") + 1)] : [entry])]
54
+ : [value]).filter((value) => value.length >= 8);
55
+ if (ttl && revision === generation && !privateValues.some((value) => serialized.includes(value))) {
56
+ const temporary = file + "." + randomUUID() + ".tmp";
57
+ try {
58
+ await mkdir(directory, { recursive: true, mode: 0o700 });
59
+ const createdAt = now();
60
+ await writeFile(temporary, JSON.stringify({ version: 1, key, createdAt, expiresAt: createdAt + ttl, manifest }), { mode: 0o600 });
61
+ if (revision === generation) await rename(temporary, file);
62
+ } catch { /* Discovery remains available when the cache is unwritable. */ }
63
+ finally { await rm(temporary, { force: true }).catch(() => {}); }
64
+ }
65
+ return manifest;
66
+ })();
67
+ try { return await pending; } finally { pending = undefined; }
68
+ },
69
+ };
70
+ }
@@ -3,8 +3,11 @@ import { loadConfig } from "./config.js";
3
3
  import { readLog } from "./history.js";
4
4
  import { ApiError, getUsage } from "./speechmatics.js";
5
5
 
6
- export async function tokenStatus({ since = new Date().toISOString().slice(0, 7) + "-01", until } = {}) {
7
- if (until && until < since) throw new Error("until must be on or after since.");
6
+ export async function tokenStatus({ since, until } = {}) {
7
+ const today = new Date().toISOString().slice(0, 10);
8
+ since ??= today.slice(0, 7) + "-01";
9
+ until ??= today;
10
+ if (until < since) throw new Error("until must be on or after since.");
8
11
  const { tokens } = await loadConfig();
9
12
  const excluded = new Set((await readLog())
10
13
  .filter((entry) => entry.tokenDisabled)
package/modules/tools.js CHANGED
@@ -40,7 +40,7 @@ export function createTools(configuredDefaults) {
40
40
  description: "Check configured tokens and read Batch usage from Speechmatics. Excluded tokens are reported without API requests. Identity is the configured login or a masked token. API access does not guarantee funds for transcription. Usage is returned in the API's scope, not attributed exclusively to a key. This read-only check does not change rotation, exclusions, or logs.",
41
41
  inputSchema: z.strictObject({
42
42
  since: z.iso.date().optional().describe("Inclusive start date YYYY-MM-DD. Defaults to the first day of the current UTC month."),
43
- until: z.iso.date().optional().describe("Inclusive end date YYYY-MM-DD. Omit to use the API's current end date."),
43
+ until: z.iso.date().optional().describe("Inclusive end date YYYY-MM-DD. Defaults explicitly to today in UTC, including the current day's usage."),
44
44
  }),
45
45
  annotations: { readOnlyHint: true },
46
46
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-speechmatics-transcribe",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Transcribe audio and video files with Speechmatics through a CLI and MCP server.",
5
5
  "type": "module",
6
6
  "license": "MIT",