### Development CLI Commands Source: https://github.com/speechify-ai/cli/blob/main/README.md Standard commands for installing dependencies, building the project, running tests, linting, and generating documentation. Also includes an example of executing the built binary. ```bash pnpm install pnpm build # tsup → dist/bin.js (executable, shebang'd) pnpm typecheck pnpm test # includes the docs drift guard pnpm lint # biome pnpm docs:generate # rewrite llms.txt, llms-full.txt and docs/ from the CLI node dist/bin.js whoami ``` -------------------------------- ### CLI usage examples for mcp Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-mcp.md Common commands for running the MCP relay and installing configurations into AI clients. ```bash speechify mcp # relay to the hosted server over stdio speechify mcp --url https://staging.example.com/mcp speechify mcp --accept-alpha # error: alpha_flag_removed (exit 78) speechify mcp install --all speechify mcp install --print # print the canonical config block ``` -------------------------------- ### runMcpInstall(opts: McpInstallOptions) Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Orchestrates the installation of the MCP server configuration into various supported clients. It supports printing configurations, installing into all detected clients, or installing into specific named clients. ```APIDOC ## runMcpInstall ### Description Orchestrates the installation of the MCP server configuration into various supported clients. It supports printing configurations, installing into all detected clients, or installing into specific named clients. ### Parameters - **opts** (McpInstallOptions) - Required - Configuration options including target clients, API keys, and execution modes (--print, --all, --client). ### Throws - **no_clients** (65) - Thrown when --all is used but no client marker is found. - **unknown_client** (65) - Thrown when --client names an ID outside of supported CLIENT_IDS. - **no_target** (65) - Thrown when neither --client nor --all is provided. ``` -------------------------------- ### Install and manage MCP configuration Source: https://github.com/speechify-ai/cli/blob/main/README.md Use the install command to automatically configure your AI clients or print the necessary configuration block. ```bash speechify mcp install --all # every detected client speechify mcp install --print # print the config block, write nothing ``` -------------------------------- ### playAudio usage example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/audio-play.md Example showing how to call playAudio and handle the PlaybackUnavailableError. ```ts import { playAudio, PlaybackUnavailableError } from "./audio/play.js"; try { await playAudio("narration.mp3"); } catch (err) { if (err instanceof PlaybackUnavailableError) { console.warn(err.message); // "No audio player found. Install ffmpeg …" } else { throw err; } } ``` -------------------------------- ### Configuration Management Example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/configFile.md Demonstrates the basic workflow of writing, reading, and clearing the configuration. ```ts import { readConfigFile, writeConfigFile, clearConfigFile } from "./configFile.js"; await writeConfigFile({ api_key: "sk_…", base_url: "https://api.speechify.ai" }); const stored = await readConfigFile(); // { api_key?, api_version?, base_url? } | undefined await clearConfigFile(); // true when anything was removed ``` -------------------------------- ### Usage of speechify mcp install Source: https://github.com/speechify-ai/cli/blob/main/docs/mcp-install.md The basic command syntax for installing the MCP relay. ```bash speechify mcp install [options] ``` -------------------------------- ### Runtime Usage Example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/runtime.md Example of using outputMode and detectAgent to determine runtime behavior. ```ts import { outputMode, detectAgent } from "./runtime.js"; const mode = await outputMode({ json: process.argv.includes("--json") }); const agent = await detectAgent(); // { isAgent, name? } — cached for the process lifetime console.log(mode, agent); ``` -------------------------------- ### speechify mcp install Source: https://github.com/speechify-ai/cli/blob/main/docs/mcp-install.md Installs the MCP relay into local AI clients. Users can specify individual clients, install to all detected clients, or print the configuration block. ```APIDOC ## CLI Command: speechify mcp install ### Description Installs the MCP relay into local AI clients like Claude Code, Cursor, and Claude Desktop. This command configures the necessary environment for the AI client to communicate with the Speechify relay. ### Usage `speechify mcp install [options]` ### Options - `--client ` (string) - Optional - Client ID(s) to install into. Supported values: claude-code, cursor, claude-desktop, windsurf, vscode. - `--all` (boolean) - Optional - Install into every detected client. - `--print` (boolean) - Optional - Print the configuration block to stdout instead of writing it to the client configuration file. - `--embed-key` (boolean) - Optional - Embed the $SPEECHIFY_API_KEY directly into the client environment variables. ``` -------------------------------- ### runMcpInstall() Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Orchestrates the installation process across different modes and handles CLI errors. ```ts export async function runMcpInstall(opts: McpInstallOptions): Promise ``` -------------------------------- ### CLI usage examples for voices commands Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-voices.md Common usage patterns for listing voices with filters and retrieving specific voice details, including JSON output examples. ```bash speechify voices list # full table speechify voices list --locale en --gender female --search warm speechify voices list --json | jq '.[0].id' speechify voices get george # detail dump speechify voices get george --json # { id, displayName, gender, …, models: [{ name, languages: [{ locale, previewAudio? }] }] } ``` -------------------------------- ### CLI Authentication Commands Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-auth.md Examples of using the CLI commands to manage authentication state. ```bash speechify login --api-key sk_… # validates via GET /v1/voices, then stores speechify whoami --check # exit 78 when not authenticated or key invalid speechify logout # idempotent ``` -------------------------------- ### Initialize Client and Synthesize Speech Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/core-client.md Example showing how to resolve authentication and initialize the client to perform a speech synthesis request. ```ts import { createClient } from "./core/client.js"; import { resolveAuth } from "./auth/session.js"; import { synthesize } from "./core/speech.js"; const auth = await resolveAuth({ apiKey: "sk_…" }); const client = createClient({ bearer: auth.bearer, apiVersion: auth.apiVersion, baseUrl: auth.baseUrl, }); const result = await synthesize(client, { input: "Hello", voiceId: "george" }); console.log(result.audio, result.format, result.billableCharacters); ``` -------------------------------- ### Input resolution and binary reading example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/io.md Demonstrates how to use resolveTextInput for text sources and readStdinBytes for binary data. ```ts import { resolveTextInput, readStdinBytes } from "./io.js"; // mirror of `say`: positional > --input-file > piped stdin const text = await resolveTextInput("Hello", undefined); const fromPipe = await resolveTextInput(undefined, undefined); // non-TTY stdin // raw binary from stdin, for `api -d -` const body = await readStdinBytes(); ``` -------------------------------- ### runMcp usage example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-run.md Example of how to invoke the runMcp function with a specific URL and bearer token. ```ts import { runMcp, DEFAULT_MCP_URL } from "./mcp/run.js"; // The `mcp` command does exactly this: await runMcp({ url: DEFAULT_MCP_URL, bearer: "sk_…" }); // stdout: MCP JSON-RPC only; stderr: relay status/errors. ``` -------------------------------- ### Output Helpers Usage Example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/output.md Demonstrates using the output helpers to emit a result, log a warning, mask a key, and render a table. ```ts import { emit, logWarning, maskKey, renderTable } from "./output.js"; import { outputMode } from "./runtime.js"; const mode = await outputMode({ json: true }); emit(mode, { data: { status: "logged_in", key: maskKey("sk_abcdef123456") }, human: () => logWarning("saved to disk"), context: "Validated and stored a Speechify API key.", hints: ['Run `speechify say "hi"`.'], }); process.stdout.write(renderTable(["ID", "NAME"], [["george", "George"]])); ``` -------------------------------- ### Interactive Input Check Example Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/runtime.md Example of checking if a command can proceed with interactive input. ```ts import { isInteractive } from "./runtime.js"; if (!(await isInteractive({ input: opts.input }))) { throw new NeedsInputError("say", SAY_INPUTS, ["text"]); // rendered as a spec, exit 2 } ``` -------------------------------- ### MCP Configuration and Installation Interfaces Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/types.md Defines configuration options for running MCP and the interfaces required for the mcp-install command. ```ts // mcp/run.ts export interface McpOptions { url?: string; // default DEFAULT_MCP_URL ("https://mcp.speechify.ai/mcp") bearer?: string; } // commands/mcp-install.ts export interface McpClient { id: string; label: string; configPath: string; serversKey: "mcpServers" | "servers"; // internal alias ServersKey needsType?: boolean; marker: string; } export interface CliInvocation { command: string; args: string[]; } export type WriteStatus = "installed" | "skipped-unparsable"; export interface McpInstallOptions { client?: string[]; all?: boolean; print?: boolean; embedKey?: boolean; apiKey?: string; json?: boolean; } ``` -------------------------------- ### WriteStatus type Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Represents the outcome of the installation process. ```ts export type WriteStatus = "installed" | "skipped-unparsable"; ``` -------------------------------- ### Speechify say command usage examples Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-say.md Examples of using the speechify say command for standard speech synthesis, streaming, piping input, and JSON output. ```bash speechify say "Hello there" --voice henry --play speechify say --stream --input-file article.txt --out narration.mp3 echo "from a pipe" | speechify say - speechify say --stream "Telephony" --output-format ulaw_8000 --out call.ulaw speechify say "Text" --json --out speech.mp3 # { "path": …, "format": "mp3", … } ``` -------------------------------- ### McpInstallOptions interface Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Configuration options for the mcp install command, including flags for embedding API keys and selecting specific clients. ```ts export interface McpInstallOptions { client?: string[]; all?: boolean; print?: boolean; /** Bake $SPEECHIFY_API_KEY into each client entry's env. */ embedKey?: boolean; /** From the global --api-key. */ apiKey?: string; json?: boolean; } ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-api.md Common usage patterns for the speechify api command, including querying, sending fields, and custom headers. ```bash speechify api /v1/voices speechify api /v1/voices -q limit=10 -i speechify api /v1/audio/speech -f input="hello" -f voice_id=george speechify api /v1/x -X POST -d @body.json speechify api /v1/x -H "X-Debug: 1" ``` -------------------------------- ### Run the MCP relay server Source: https://github.com/speechify-ai/cli/blob/main/README.md Start the MCP relay to communicate with local AI clients. You can optionally specify a custom URL for staging or testing environments. ```bash speechify mcp # relay to the hosted server over stdio speechify mcp --url # relay to a different endpoint (staging/testing) ``` -------------------------------- ### Basic resolution with an explicit key Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/auth-session.md Example of calling resolveAuth with an explicit API key. ```ts import { resolveAuth } from "./auth/session.js"; const auth = await resolveAuth({ apiKey: "sk_…" }); // auth = { bearer: "sk_…", baseUrl: "https://api.speechify.ai", keySource: "flag" } ``` -------------------------------- ### McpClient interface Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Defines the structure for supported AI clients, including configuration paths and installation markers. ```ts export interface McpClient { id: string; label: string; configPath: string; serversKey: ServersKey; /** VS Code requires an explicit "type": "stdio" on each entry. */ needsType?: boolean; /** A path whose existence indicates the client is installed. */ marker: string; } ``` -------------------------------- ### runMcp function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-run.md Initializes and starts the MCP relay process, connecting the local stdio transport to the remote streamable HTTP transport. ```ts export async function runMcp(opts: McpOptions = {}): Promise ``` -------------------------------- ### Usage of speechify voices get Source: https://github.com/speechify-ai/cli/blob/main/docs/voices-get.md The command syntax for retrieving voice details. Omit the voice-id to be prompted for one. ```bash speechify voices get [voice-id] [options] ``` -------------------------------- ### Handle Needs-Input Error in Agent Mode Source: https://github.com/speechify-ai/cli/blob/main/README.md Example of the CLI returning a structured needs-input specification when required arguments are missing in a non-interactive environment. ```bash $ speechify say --json < /dev/null { "ok": false, "needsInput": true, "command": "say", "missing": ["text"], "inputs": [ … ] } # exit code 2 ``` -------------------------------- ### bridge function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-run.md Wires two transports into a bidirectional JSON-RPC relay. Callers must install callbacks before starting the transports. ```ts /** * Wire two transports into a bidirectional JSON-RPC relay: every message each side * emits is forwarded verbatim to the other, and a close (or fatal error) on either * end tears down both. Pure wiring — the caller starts the transports afterwards, * since the Transport contract requires callbacks to be installed before `start()`. */ export function bridge(local: Transport, remote: Transport): void ``` -------------------------------- ### CLIENT_IDS constant Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md An array of supported client identifiers for MCP installation. ```ts export const CLIENT_IDS = ["claude-code", "cursor", "claude-desktop", "windsurf", "vscode"] as const; ``` -------------------------------- ### cliInvocation() Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Determines how a client should launch the server, ensuring the correct binary is re-spawned. ```ts /** * How a client should launch our server: re-spawn the very binary running now, so * it works whether invoked via `node dist/bin.js`, a global `speechify` shim, or * npx. (Once published, this can simplify to `npx -y @speechify/cli mcp`.) */ export function cliInvocation(): CliInvocation ``` -------------------------------- ### speechify voices get Source: https://github.com/speechify-ai/cli/blob/main/docs/voices-get.md Retrieves details for a specific voice by its ID. ```APIDOC ## speechify voices get ### Description Show one voice: its models, locales, tags, and preview URLs. ### Usage `speechify voices get [voice-id] [options]` ### Arguments - **voice-id** (string) - Optional - id of the voice to show (see `speechify voices list`); omit to be prompted ``` -------------------------------- ### Configure Windsurf for MCP Source: https://github.com/speechify-ai/cli/blob/main/README.md Command and manual JSON configuration for integrating Speechify with Windsurf. ```bash speechify mcp install --client windsurf ``` ```json { "mcpServers": { "speechify": { "command": "speechify", "args": ["mcp"] } } } ``` -------------------------------- ### GET /v1/voices/{voice_id} Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/endpoints.md Retrieves details for a specific voice by its ID. ```APIDOC ## GET /v1/voices/{voice_id} ### Description Retrieves the details of a specific voice. The CLI response filters out null or empty media URLs. ### Method GET ### Endpoint /v1/voices/{voice_id} ### Parameters #### Path Parameters - **voice_id** (string) - Required - The unique identifier of the voice to retrieve. ``` -------------------------------- ### Configure Claude Desktop for MCP Source: https://github.com/speechify-ai/cli/blob/main/README.md Command and manual JSON configuration for integrating Speechify with Claude Desktop. ```bash speechify mcp install --client claude-desktop ``` ```json { "mcpServers": { "speechify": { "command": "speechify", "args": ["mcp"] } } } ``` -------------------------------- ### Run Verification Scripts Source: https://github.com/speechify-ai/cli/blob/main/verify/README.md Commands to build the CLI and execute verification scripts, including an option to skip live API tests. ```bash pnpm build # they run the built CLI, not the source ./verify/stream.sh # every check SKIP_LIVE=1 ./verify/stream.sh # skip the group that spends quota ``` -------------------------------- ### Handling the not-authenticated case Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/auth-session.md Example of catching the not_authenticated error when no credentials are found. ```ts import { resolveAuth } from "./auth/session.js"; import { CliError } from "./core/errors.js"; try { const auth = await resolveAuth(); } catch (err) { if (err instanceof CliError && err.code === "not_authenticated") { // Exit code 78 (EX_CONFIG): the caller must login or pass --api-key. } } ``` -------------------------------- ### speechify voices get Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-voices.md Retrieves detailed information for a specific voice by its ID. ```APIDOC ## CLI Command: voices get [voice-id] ### Description Retrieves detailed information for a specific voice, including model details, preview URLs, and avatar URLs. ### Parameters - **voice-id** (string) - Required - The unique identifier of the voice to retrieve. ### Response Returns a `VoiceDetail` object containing detailed voice metadata, including models with per-locale language support. ``` -------------------------------- ### Programmatic Request Building Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-api.md Example of using buildApiRequest programmatically to construct an authenticated request. ```ts import { resolveAuth } from "./auth/session.js"; import { buildApiRequest } from "./commands/api.js"; const auth = await resolveAuth(); const req = await buildApiRequest(auth, "/v1/voices", { query: ["limit=10"] }); // req = { url: "https://api.speechify.ai/v1/voices?limit=10", method: "GET", // headers: { authorization: "Bearer sk_…", accept: "application/json" } } ``` -------------------------------- ### createClient(config: ClientConfig) Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/core-client.md Initializes and returns a new SpeechifyClient instance configured with the provided authentication and environment settings. ```APIDOC ## createClient(config) ### Description Creates a new SpeechifyClient instance using the provided configuration object. This client is used to interact with the Speechify TTS and voice services. ### Parameters - **config** (ClientConfig) - Required - Configuration object containing authentication and environment settings. #### ClientConfig Fields - **bearer** (string) - Required - The API key (sk_...) used for Bearer authentication. - **apiVersion** (string) - Optional - Pins the Speechify-Version request header. - **baseUrl** (string) - Optional - The API origin URL; defaults to production if omitted. ### Returns - **SpeechifyClient** - A configured client instance exposing resource getters for audio, voices, and models. ### Example ```ts import { createClient } from "./core/client.js"; const client = createClient({ bearer: "sk_example_key", apiVersion: "2023-01-01" }); ``` ``` -------------------------------- ### Configure Cursor for MCP Source: https://github.com/speechify-ai/cli/blob/main/README.md Command and manual JSON configuration for integrating Speechify with Cursor. ```bash speechify mcp install --client cursor ``` ```json { "mcpServers": { "speechify": { "command": "speechify", "args": ["mcp"] } } } ``` -------------------------------- ### serverEntry() Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Builds the per-client server entry configuration. ```ts /** Build the per-client server entry (pure). */ export function serverEntry(opts: { needsType?: boolean; apiKey?: string; invocation: CliInvocation; }): Record ``` -------------------------------- ### buildProgram function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/bin-entry-point.md Creates and configures the main speechify commander program instance. ```ts function buildProgram(): Command ``` -------------------------------- ### SpeechifyClient Initialization Source: https://github.com/speechify-ai/cli/blob/main/AGENTS.md Initializes the Speechify API client with authentication credentials. ```APIDOC ## new SpeechifyClient({ auth: { token }, headers }) ### Description Initializes a new instance of the Speechify API client. Authentication is handled via a Bearer token (API key). ### Parameters - **auth** (object) - Required - Contains the API token under the `token` key. - **headers** (object) - Optional - Custom headers to include in requests. ``` -------------------------------- ### Handle SpeechifyError Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/core-client.md Example of catching and normalizing SDK errors using the CLI's error handling utilities. ```ts import { SpeechifyError } from "@speechify/api"; import { createClient } from "./core/client.js"; import { normalizeError } from "./core/errors.js"; try { await client.audio.speech({ input: "…", voice_id: "george" }); } catch (err) { // normalizeError folds SpeechifyError into the CLI's NormalizedError shape: // code, statusCode, exitCode, requestId come straight from the API envelope. const normalized = normalizeError(err); } ``` -------------------------------- ### configFilePath Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/configFile.md Returns the path to the legacy plaintext configuration file, used only for one-time migration. ```ts /** Legacy plaintext config (pre-keychain); read once for migration, then removed. */ export function configFilePath(): string ``` -------------------------------- ### speechify login command usage Source: https://github.com/speechify-ai/cli/blob/main/docs/login.md Basic syntax for executing the login command. Global options are also applicable. ```bash speechify login [options] ``` -------------------------------- ### speechify voices get Source: https://github.com/speechify-ai/cli/blob/main/llms-full.txt Retrieves detailed information for a specific voice, including models, locales, tags, and preview URLs. ```APIDOC ## speechify voices get ### Description Show one voice: its models, locales, tags, and preview URLs. ### Usage `speechify voices get [voice-id] [options]` ### Arguments - `[voice-id]` - Optional - ID of the voice to show; omit to be prompted. ``` -------------------------------- ### CLI usage patterns Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/bin-entry-point.md Displays the available command surface for the speechify CLI. ```text speechify login|logout|whoami speechify say [text] speechify voices list|get [voice-id] speechify api speechify mcp [install] ``` -------------------------------- ### Initialize SpeechifyClient Source: https://github.com/speechify-ai/cli/blob/main/AGENTS.md The client is initialized with an authentication token and optional headers. Note that the apiKey field from v3 is no longer supported. ```javascript new SpeechifyClient({ auth: { token: }, headers }) ``` -------------------------------- ### Authenticate with Speechify CLI Source: https://github.com/speechify-ai/cli/blob/main/README.md Commands to manage API key authentication. The login command validates and stores the key, while whoami verifies current authentication status. ```bash speechify login --api-key sk_… # validates the key against the API, then stores it speechify whoami # how you're authenticated (flag / env / stored) speechify whoami --check # also verify the key live; exits non-zero if invalid speechify logout # forget the stored key ``` -------------------------------- ### clients() Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Returns the list of supported MCP client descriptors. ```ts export function clients(): McpClient[] ``` -------------------------------- ### Usage of speechify voices list Source: https://github.com/speechify-ai/cli/blob/main/docs/voices-list.md The basic command syntax to list available voices. ```bash speechify voices list [options] ``` -------------------------------- ### GET /v1/voices Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/endpoints.md Retrieves a list of available voices. This endpoint is used by the CLI for listing voices, validating API keys, and checking user identity. ```APIDOC ## GET /v1/voices ### Description Retrieves a list of available voices. The CLI consumes this to populate voice lists and validate authentication. ### Method GET ### Endpoint /v1/voices ### Parameters None ### Response #### Success Response (200) - **id** (string) - Voice id used as --voice / voice_id - **display_name** (string) - Display name - **gender** ("male" | "female" | "not_specified") - Gender of the voice - **locale** (string) - e.g. "en-US" - **type** ("shared" | "personal") - Built-in vs cloned - **models** (GetVoicesModel[]) - Array of models containing name and languages - **tags** (string[] | null) - Optional tags associated with the voice ### Error Handling - 401/403: Exit 77 - 429: Exit 75 - 5xx: Exit 69 - Non-2xx bodies return: { "error": { "code", "message", "fields" }, "request_id" } ``` -------------------------------- ### writeClientConfig() Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Writes the client configuration atomically. If the entry contains a secret, the file is written with 0600 permissions. ```ts export async function writeClientConfig(client: McpClient, entry: Record): Promise ``` -------------------------------- ### Configure Claude Code for MCP Source: https://github.com/speechify-ai/cli/blob/main/README.md Commands and manual JSON configuration for integrating Speechify with Claude Code. ```bash speechify mcp install --client claude-code # or, using Claude Code's own CLI: claude mcp add speechify -- speechify mcp ``` ```json { "mcpServers": { "speechify": { "command": "speechify", "args": ["mcp"] } } } ``` -------------------------------- ### CliInvocation interface Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Specifies the command and arguments used to spawn the MCP server. ```ts /** How a client should spawn our CLI's mcp server. */ export interface CliInvocation { command: string; args: string[]; } ``` -------------------------------- ### playAudio(filePath: string) Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/audio-play.md Plays an audio file at the specified path using available system audio players. If all playback candidates fail, it throws a PlaybackUnavailableError. ```APIDOC ## playAudio(filePath: string) ### Description Attempts to play an audio file located at the provided path. The function iterates through a list of platform-specific audio players until one succeeds. ### Parameters - **filePath** (string) - Required - The absolute or relative path to the audio file to be played. ### Returns - **Promise** - Resolves when a player exits with code 0. ### Throws - **PlaybackUnavailableError** - Thrown if all candidate players are missing or fail to play the file. ``` -------------------------------- ### Register Auth Commands Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-auth.md Registers the login, logout, and whoami subcommands on the root CLI program. ```ts export function registerAuthCommands(program: Command): void ``` -------------------------------- ### credentialsFilePath Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/configFile.md Returns the path to the encrypted fallback file used when no OS keychain is available. ```ts /** Encrypted-file fallback when no OS keychain backend is available. */ export function credentialsFilePath(): string ``` -------------------------------- ### Consuming Stream Chunks with for await Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/core-stream.md Demonstrates how to consume chunks from a stream using the readStreamChunks generator, as implemented in the CLI's say command. ```ts import { readStreamChunks } from "./core/stream.js"; import { resolveTimeoutMs } from "./core/fetchWithTimeout.js"; const chunks = readStreamChunks(stream.body, { stallTimeoutMs: resolveTimeoutMs() }); for await (const chunk of chunks) { process.stdout.write(chunk); // bytes arrive as produced } ``` -------------------------------- ### POST /v1/audio/stream Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/endpoints.md Synthesizes text into chunked raw audio. Input is capped at 20,000 characters. ```APIDOC ## POST /v1/audio/stream ### Description Synthesizes text into chunked raw audio. The input is capped at 20,000 characters. ### Method POST ### Endpoint /v1/audio/stream ### Request Body - **input** (string) - Required - The text to synthesize. - **voice_id** (string) - Required - The identifier for the voice to use. - **model** (string) - Optional - The model version to use. - **language** (string) - Optional - The language code. - **options** (object) - Optional - Additional synthesis options. - **output_format** (string) - Optional - The desired audio format (e.g., pcm_16000, ulaw_8000). Takes precedence over Accept header. ### Response #### Success Response (200) - **raw audio bytes** (binary) - HTTP chunked raw audio stream. ### Error Handling - **empty_stream** (69) - No body received. - **stream_stalled** (69) - Inter-chunk gap exceeded timeout. - **stream_failed** (69) - Transport error during streaming. - **unsupported_stream_format** (65) - Format (e.g., wav) is not supported for streaming. ``` -------------------------------- ### writeConfigFile Function Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/configFile.md Persists the configuration, attempting to use the OS keychain first and falling back to an encrypted file on failure. ```ts /** Persist the config, preferring the OS keychain and falling back to an encrypted file. */ export async function writeConfigFile(config: StoredConfig): Promise ``` -------------------------------- ### Throwing and Normalizing CLI Errors Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/core-errors.md Demonstrates throwing a custom CliError, normalizing an SDK error, and throwing a NeedsInputError for missing command arguments. ```ts import { CliError, ExitCode, NeedsInputError, normalizeError } from "./core/errors.js"; throw new CliError("Input text is empty.", { exitCode: ExitCode.DATA_ERR, code: "empty_input" }); // Normalizing an SDK failure: const normalized = normalizeError(err); // normalized = { message, exitCode, code, statusCode, requestId, fields } console.error(`error (${normalized.code}): ${normalized.message}`); throw new NeedsInputError("say", SAY_INPUTS, ["text"]); ``` -------------------------------- ### Write audio stream to file or stdout Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/audio-sink.md Demonstrates using writeStreamToFile and writeStreamToStdout to handle audio streams, including path validation and TTY checks. ```ts import { writeStreamToFile, writeStreamToStdout, assertBinaryStdout, assertPathAvailable } from "./audio/sink.js"; import { readStreamChunks } from "./core/stream.js"; import { resolveTimeoutMs } from "./core/fetchWithTimeout.js"; const chunks = readStreamChunks(stream.body, { stallTimeoutMs: resolveTimeoutMs() }); await assertPathAvailable("out.mp3"); const bytes = await writeStreamToFile(chunks, "out.mp3"); console.log(`wrote ${bytes} bytes atomically`); // stdout path — refused on a TTY: assertBinaryStdout(); const n = await writeStreamToStdout(readStreamChunks(other.body, { stallTimeoutMs: resolveTimeoutMs() })); ``` -------------------------------- ### Programmatic MCP Client Configuration Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/mcp-install.md Iterates through available MCP clients and writes their configuration using the server entry point and CLI invocation. ```ts import { clients, cliInvocation, serverEntry, writeClientConfig } from "./commands/mcp-install.js"; const invocation = cliInvocation(); for (const client of clients()) { const status = await writeClientConfig(client, serverEntry({ needsType: client.needsType, invocation })); console.log(`${client.id}: ${status}`); } ``` -------------------------------- ### Using intArg with Commander Options Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/options.md Demonstrates integrating intArg into a commander Option to enforce numeric constraints on CLI flags. ```ts import { intArg } from "./options.js"; import { Option } from "commander"; new Option("--limit ", "max results").argParser(intArg("--limit", { min: 1, max: 200 })); // --limit abc → CliError: "--limit must be a whole number (got \"abc\")." — exit 65 // --limit 0 → CliError: "--limit must be at least 1 (got 0)." — exit 65 ``` -------------------------------- ### Configure VS Code for MCP Source: https://github.com/speechify-ai/cli/blob/main/README.md Command and manual JSON configuration for integrating Speechify with VS Code. Note that VS Code requires an explicit "type": "stdio" field. ```bash speechify mcp install --client vscode ``` ```json { "servers": { "speechify": { "type": "stdio", "command": "speechify", "args": ["mcp"] } } } ``` -------------------------------- ### Synthesize Speech with say Source: https://github.com/speechify-ai/cli/blob/main/README.md Use the say command to convert text to audio. Supports various voices, formats, and output options, including streaming to stdout and playing audio directly. ```bash speechify say "Text to speak" \ --voice henry \ # default: george --format wav \ # wav | mp3 | ogg | aac | pcm (default mp3) --language en-US \ --out narration.wav \ # default ./speech.; "-" streams to stdout --play # play after synthesis echo "from a pipe" | speechify say - # read text from stdin speechify voices list # browse voices speechify voices list --locale en --gender female --search warm # filter by locale prefix, gender, free text ``` -------------------------------- ### registerSayCommand function signature Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/commands-say.md The entry point for registering the say command within the CLI program. ```ts export function registerSayCommand(program: Command): void ``` -------------------------------- ### ClientConfig Interface Source: https://github.com/speechify-ai/cli/blob/main/_autodocs/api-reference/core-client.md The configuration object required to initialize the SpeechifyClient. ```ts export interface ClientConfig { bearer: string; apiVersion?: string; baseUrl?: string; } ``` -------------------------------- ### Project Directory Structure Source: https://github.com/speechify-ai/cli/blob/main/AGENTS.md The file system layout of the Speechify CLI project, highlighting the roles of core, auth, mcp, and command modules. ```text src/ bin.ts commander program; global opts attached to every subcommand (applyGlobalOptions); one error path (normalizeError) + exit codes auth/ session.ts resolveAuth() → AuthContext (the single auth source) core/ client.ts @speechify/api SDK client (TTS), fed the API-key bearer errors.ts CliError + normalizeError + apiErrorFromResponse; sysexits codes speech.ts / voices.ts service layer mcp/ server.ts buildServer() → MCP tools (search_docs + authed list_voices/get_voice/text_to_speech/stream_text_to_speech) run.ts stdio / streamable-HTTP transport wiring commands/ thin adapters over core/ (auth, say, voices, api, mcp) configFile.ts OS keychain (service speechify-cli) + AES-256-GCM credentials.enc fallback; StoredConfig API runtime.ts detectAgent() + outputMode(opts)/isInteractive(opts) — pure helpers (no global RunContext) output.ts io.ts options.ts ```