mcp-speechmatics-transcribe 0.1.3 → 0.1.5

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/README.md CHANGED
@@ -28,7 +28,7 @@ Logins are optional. Keep credentials outside the repository.
28
28
  "mcpServers": {
29
29
  "mcp-speechmatics-transcribe": {
30
30
  "command": "npx",
31
- "args": ["-y", "--prefer-online", "mcp-speechmatics-transcribe@latest", "mcp"],
31
+ "args": ["-y", "--prefer-online", "mcp-speechmatics-transcribe@latest"],
32
32
  "env": {
33
33
  "SPEECHMATICS_TOKENS": "YOUR_API_TOKEN"
34
34
  }
@@ -38,14 +38,44 @@ Logins are optional. Keep credentials outside the repository.
38
38
  ```
39
39
 
40
40
  On Windows, clients that require an executable path can use npx.cmd.
41
- For a local env file, insert --env-file and its absolute path before mcp.
42
- Restart the MCP server to pick up a new package version. Allow enough tool time for
41
+ For a local env file, append --env-file and its absolute path.
42
+ With no file argument, the command starts the MCP server; the explicit mcp subcommand
43
+ remains supported. MCP is a thin adapter: it obtains tool definitions from the CLI
44
+ at startup and on every tools/list request, then forwards each tools/call to a
45
+ separate CLI process. An npx-managed installation resolves the latest published CLI
46
+ through npx, reusing npm's cache. Local launches, including npm scripts, use the CLI
47
+ from the same installation through the current Node.js executable. Ambiguous
48
+ launches use the same-installation CLI.
49
+ Changes detected during discovery emit notifications/tools/list_changed. Clients
50
+ must request the tool list to discover updates; no background polling is performed.
51
+ In-flight calls continue with their starting version. The CLI inherits the
52
+ environment and selected env-file path; execution arguments travel over stdin.
53
+ CLI startup or network failures are reported without stopping an established MCP
54
+ connection. Startup discovery must succeed before the MCP connection is initialized.
55
+ Allow enough tool time for npm startup,
43
56
  uploads and processing; the built-in API timeout is 900 seconds.
44
57
 
45
58
  The transcribe tool requires an absolute file path. Optional parameters are model,
46
59
  language, disableDiarization, audioEvents, convertToMp3, and timeoutSeconds.
47
60
  Missing credentials are reported when the tool is called; tool discovery remains available.
48
61
 
62
+ ## Machine-readable CLI
63
+
64
+ `--tool-manifest` prints a JSON document containing `protocol: 1`,
65
+ `serverInfo`, and `tools` with MCP-compatible names, descriptions, and JSON Schemas.
66
+ It does not require API credentials. `--execute-tool` reads one JSON request from
67
+ stdin and prints one MCP-compatible tool result to stdout:
68
+
69
+ ```json
70
+ {"protocol":1,"name":"transcribe","arguments":{"file":"/path/to/recording.mp3"}}
71
+ ```
72
+
73
+ Execution validates arguments against the same definitions used by the manifest.
74
+ Tool failures return `isError: true` and text content. Human-facing file commands
75
+ retain their existing output and exit-code behavior. Internal `--worker` remains
76
+ an alias for execution. CLI and MCP are distributed together in the same package;
77
+ the adapter contains no transcription-specific schemas or execution logic.
78
+
49
79
  ## Configuration
50
80
 
51
81
  Invocation arguments override process environment, followed by the selected env file
@@ -111,7 +141,7 @@ match the package version. npm publishing uses GitHub OIDC after a trusted
111
141
  publisher is configured for this repository and release.yml.
112
142
 
113
143
  For the first publication, authenticate with npm login and publish the checked archive
114
- from work/releases/ using npm publish with --access public.
144
+ from .tmp/releases/ using npm publish with --access public.
115
145
  The release workflow publishes stable versions under latest and prereleases under next.
116
146
 
117
147
  ## License
package/cli.js CHANGED
@@ -11,7 +11,9 @@ const program = new Command()
11
11
  .version(version)
12
12
  .description("Transcribe audio and video files to JSON, WebVTT, and Markdown.")
13
13
  .option("--env-file <path>", "Load an explicit .env file (also supported through SPEECHMATICS_ENV_FILE)")
14
- .argument("<file>", "Path to an audio or video file")
14
+ .option("--tool-manifest", "Print tool names, descriptions, and JSON Schemas as JSON")
15
+ .option("--execute-tool", "Execute a JSON tool request read from stdin")
16
+ .argument("[file]", "Path to an audio or video file")
15
17
  .addOption(new Option("--model <model>", `Model (default: ${defaults.model})`).choices(optionFields.model.options))
16
18
  .option("--language <code>", `Language (default: ${defaults.language}); use multi with multilingual models`)
17
19
  .addOption(new Option("--diarization <mode>", `Diarization (default: ${defaults.diarization})`).choices(optionFields.diarization.options))
@@ -25,7 +27,21 @@ const program = new Command()
25
27
  const { envFile } = program.opts();
26
28
  if (envFile) process.env.SPEECHMATICS_ENV_FILE = resolve(envFile);
27
29
  })
28
- .action(async (file, { envFile, ...options }) => {
30
+ .action(async (file, { envFile, toolManifest, executeTool, ...options }) => {
31
+ if (toolManifest) {
32
+ const { getToolManifest } = await import("./modules/tools.js");
33
+ console.log(JSON.stringify(await getToolManifest()));
34
+ return;
35
+ }
36
+ if (executeTool) {
37
+ const { serveExecution } = await import("./modules/cli-protocol.js");
38
+ await serveExecution();
39
+ return;
40
+ }
41
+ if (!file) {
42
+ await import("./mcp.js");
43
+ return;
44
+ }
29
45
  try {
30
46
  console.log(JSON.stringify(await transcribe(file, options), null, 2));
31
47
  } catch (error) {
@@ -38,4 +54,9 @@ program.command("mcp")
38
54
  .description("Start the MCP server over stdio")
39
55
  .action(async () => { await import("./mcp.js"); });
40
56
 
41
- await program.parseAsync();
57
+ if (process.argv.length === 3 && process.argv[2] === "--worker") {
58
+ const { serveExecution } = await import("./modules/cli-protocol.js");
59
+ await serveExecution();
60
+ } else {
61
+ await program.parseAsync();
62
+ }
package/mcp.js CHANGED
@@ -1,43 +1,27 @@
1
- import { McpServer } from "@modelcontextprotocol/server";
1
+ import { Server } from "@modelcontextprotocol/server";
2
2
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
- import { z } from "zod";
4
- import { readFile } from "node:fs/promises";
5
- import { optionFields } from "./modules/options.js";
6
- import { loadConfig } from "./modules/config.js";
7
- import { transcribe } from "./modules/transcribe.js";
3
+ import { runCli } from "./modules/cli-process.js";
8
4
 
9
- const { options: configuredDefaults } = await loadConfig({}, { requireTokens: false });
10
- const { version } = JSON.parse(await readFile(new URL("./package.json", import.meta.url), "utf8"));
11
-
12
- function createServer() {
13
- const description = "Transcribe local audio and video files through the Speechmatics Batch API.";
14
- const server = new McpServer({
15
- name: "mcp-speechmatics-transcribe",
16
- title: "Speechmatics Transcribe",
17
- version,
18
- description,
19
- }, { instructions: description });
20
- server.registerTool("transcribe", {
21
- description: `${description} Return paths to raw JSON, segments, WebVTT subtitles, and Markdown.`,
22
- inputSchema: z.strictObject({
23
- file: z.string().min(1).describe("Absolute path to a local audio or video file."),
24
- model: optionFields.model.optional().describe(`Configured default: ${configuredDefaults.model}. enhanced: highest accuracy for a selected language. standard: faster processing and archival transcription. melia-1: MULTILANGUAGE, language switching within recordings. oak-1: MULTILANGUAGE, healthcare recordings. Use language=multi for melia-1 and oak-1; neither supports audio events.`),
25
- language: optionFields.language.optional().describe(`Configured default: ${configuredDefaults.language}. Language code such as pl or en for enhanced/standard. Use multi for MULTILANGUAGE models melia-1 and oak-1.`),
26
- disableDiarization: z.boolean().optional().describe(`Configured speaker diarization: ${configuredDefaults.diarization === "none" ? "disabled" : "enabled"}. Set true to disable it. Omit or pass false to use the server setting.`),
27
- audioEvents: optionFields.audioEvents.optional().describe(`Configured default: ${configuredDefaults.audioEvents}. Detect laughter, music, and applause with Standard/Enhanced. Automatically disabled for melia-1/oak-1. Set false to disable.`),
28
- convertToMp3: optionFields.convertToMp3.optional().describe(`Configured default: ${configuredDefaults.convertToMp3}. Convert non-MP3 files with system FFmpeg before uploading.`),
29
- timeoutSeconds: optionFields.timeoutSeconds.optional().describe(`Configured default: ${configuredDefaults.timeoutSeconds} seconds. Upload and API processing timeout, independent of recording duration.`),
30
- }),
31
- }, async ({ file, disableDiarization, ...options }) => {
5
+ async function createServer() {
6
+ let manifest = await runCli("--tool-manifest");
7
+ const server = new Server(manifest.serverInfo, {
8
+ instructions: manifest.serverInfo.description,
9
+ capabilities: { tools: { listChanged: true } },
10
+ });
11
+ server.setRequestHandler("tools/list", async () => {
12
+ const latest = await runCli("--tool-manifest");
13
+ const changed = JSON.stringify(latest.tools) !== JSON.stringify(manifest.tools);
14
+ manifest = latest;
15
+ if (changed) await server.sendToolListChanged();
16
+ return { tools: manifest.tools };
17
+ });
18
+ server.setRequestHandler("tools/call", async ({ params }) => {
32
19
  try {
33
- const result = await transcribe(file, {
34
- ...options,
35
- ...(disableDiarization && { diarization: "none" }),
20
+ return await runCli("--execute-tool", {
21
+ protocol: 1, name: params.name, arguments: params.arguments ?? {},
36
22
  });
37
- return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
38
23
  } catch (error) {
39
- const result = error.result ?? { message: error.message };
40
- return { isError: true, content: [{ type: "text", text: JSON.stringify(result) }] };
24
+ return { isError: true, content: [{ type: "text", text: JSON.stringify({ message: error.message }) }] };
41
25
  }
42
26
  });
43
27
  return server;
@@ -0,0 +1,63 @@
1
+ import { spawn } from "node:child_process";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ // Keep arguments and credentials on stdin/environment, outside the shell command.
6
+ export function runCli(mode, request) {
7
+ return new Promise((done, reject) => {
8
+ 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
+ },
31
+ });
32
+ let output = "";
33
+ child.stdout.setEncoding("utf8");
34
+ child.stdout.on("data", (chunk) => {
35
+ output += chunk;
36
+ if (output.length > 1024 * 1024) {
37
+ child.kill();
38
+ reject(new Error("CLI process response exceeded 1 MiB."));
39
+ }
40
+ });
41
+ child.on("error", reject);
42
+ child.stdin.on("error", reject);
43
+ child.on("close", (code, signal) => {
44
+ if (code !== 0) {
45
+ reject(new Error(`CLI process exited with ${signal ?? code}.`));
46
+ return;
47
+ }
48
+ try {
49
+ const result = JSON.parse(output);
50
+ if (mode === "--tool-manifest") {
51
+ if (result.protocol !== 1 || !Array.isArray(result.tools) || !result.serverInfo) throw new Error("Invalid tool manifest.");
52
+ } else if (!Array.isArray(result?.content)) {
53
+ throw new Error("Missing tool content.");
54
+ }
55
+ done(result);
56
+ } catch {
57
+ reject(new Error("CLI process returned an invalid response. Check npm connectivity and the published package version."));
58
+ }
59
+ });
60
+ child.stdin.end(request ? JSON.stringify(request) : undefined);
61
+ });
62
+ }
63
+
@@ -0,0 +1,21 @@
1
+ import { executeTool } from "./tools.js";
2
+
3
+ export async function serveExecution() {
4
+ try {
5
+ let input = "";
6
+ process.stdin.setEncoding("utf8");
7
+ for await (const chunk of process.stdin) {
8
+ input += chunk;
9
+ if (input.length > 1024 * 1024) throw new Error("Worker request exceeded 1 MiB.");
10
+ }
11
+ const request = JSON.parse(input);
12
+ if (request.protocol !== 1) throw new Error("Unsupported worker protocol.");
13
+ const result = await executeTool(request.name, request.arguments);
14
+ process.stdout.write(JSON.stringify(result) + "\n");
15
+ } catch (error) {
16
+ process.stdout.write(JSON.stringify({
17
+ isError: true,
18
+ content: [{ type: "text", text: JSON.stringify(error.result ?? { message: error.message }) }],
19
+ }) + "\n");
20
+ }
21
+ }
@@ -0,0 +1,60 @@
1
+ import { z } from "zod";
2
+ import { optionFields } from "./options.js";
3
+ import { transcribe } from "./transcribe.js";
4
+ import { loadConfig } from "./config.js";
5
+ import { readFile } from "node:fs/promises";
6
+
7
+ export const description = "Transcribe local audio and video files through the Speechmatics Batch API.";
8
+
9
+ export function createTools(configuredDefaults) {
10
+ return {
11
+ transcribe: {
12
+ definition: {
13
+ description: `${description} Return paths to raw JSON, segments, WebVTT subtitles, and Markdown.`,
14
+ inputSchema: z.strictObject({
15
+ file: z.string().min(1).describe("Absolute path to a local audio or video file."),
16
+ model: optionFields.model.optional().describe(`Configured default: ${configuredDefaults.model}. enhanced: highest accuracy for a selected language. standard: faster processing and archival transcription. melia-1: MULTILANGUAGE, language switching within recordings. oak-1: MULTILANGUAGE, healthcare recordings. Use language=multi for melia-1 and oak-1; neither supports audio events.`),
17
+ language: optionFields.language.optional().describe(`Configured default: ${configuredDefaults.language}. Language code such as pl or en for enhanced/standard. Use multi for MULTILANGUAGE models melia-1 and oak-1.`),
18
+ disableDiarization: z.boolean().optional().describe(`Configured speaker diarization: ${configuredDefaults.diarization === "none" ? "disabled" : "enabled"}. Set true to disable it. Omit or pass false to use the server setting.`),
19
+ audioEvents: optionFields.audioEvents.optional().describe(`Configured default: ${configuredDefaults.audioEvents}. Detect laughter, music, and applause with Standard/Enhanced. Automatically disabled for melia-1/oak-1. Set false to disable.`),
20
+ convertToMp3: optionFields.convertToMp3.optional().describe(`Configured default: ${configuredDefaults.convertToMp3}. Convert non-MP3 files with system FFmpeg before uploading.`),
21
+ timeoutSeconds: optionFields.timeoutSeconds.optional().describe(`Configured default: ${configuredDefaults.timeoutSeconds} seconds. Upload and API processing timeout, independent of recording duration.`),
22
+ }),
23
+ },
24
+ execute: async ({ file, disableDiarization, ...options }) => {
25
+ try {
26
+ const result = await transcribe(file, {
27
+ ...options,
28
+ ...(disableDiarization && { diarization: "none" }),
29
+ });
30
+ return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
31
+ } catch (error) {
32
+ const result = error.result ?? { message: error.message };
33
+ return { isError: true, content: [{ type: "text", text: JSON.stringify(result) }] };
34
+ }
35
+ },
36
+ },
37
+ };
38
+ }
39
+
40
+ export async function executeTool(name, args) {
41
+ const { options } = await loadConfig({}, { requireTokens: false });
42
+ const tools = createTools(options);
43
+ if (!Object.hasOwn(tools, name)) throw new Error("Unknown tool: " + name);
44
+ const tool = tools[name];
45
+ return tool.execute(tool.definition.inputSchema.parse(args));
46
+ }
47
+
48
+ export async function getToolManifest() {
49
+ const { options } = await loadConfig({}, { requireTokens: false });
50
+ const { name, version } = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
51
+ return {
52
+ protocol: 1,
53
+ serverInfo: { name, version, title: "Speechmatics Transcribe", description },
54
+ tools: Object.entries(createTools(options)).map(([toolName, { definition }]) => ({
55
+ ...definition,
56
+ name: toolName,
57
+ inputSchema: z.toJSONSchema(definition.inputSchema, { target: "draft-7" }),
58
+ })),
59
+ };
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-speechmatics-transcribe",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Transcribe audio and video files with Speechmatics through a CLI and MCP server.",
5
5
  "type": "module",
6
6
  "license": "MIT",