diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ef6bb1..cf4a0d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.3.0 + +- Allow one-call generation with an automatic UUID that reuses the same job for unchanged speech after a timeout or restart. Use a fresh explicit UUID to generate a new recording of the same speech. +- Support arbitrary speaker labels and ordered segments while retaining legacy `Speaker1:` / `Speaker2:` scripts. +- Add explicit server-side cancellation through `flowspeech_cancel_job`. +- Stage validated WAV files before saving, preserve existing destinations by default (including filesystems without hard links), and add opt-in `overwrite` for existing regular files. +- Back off pending-job polls from 1 to 2, 3, then 5 seconds while honoring a longer `Retry-After`. +- Document emotion cues, timed pauses, and setup for Claude Code, Cursor, and Claude Desktop. + ## 0.2.1 - 2026-10-27 - Filter reflected credentials and unknown diagnostic fields on read-only tools and terminal-job errors. diff --git a/README.md b/README.md index 6b167ff..6ec6b32 100644 --- a/README.md +++ b/README.md @@ -1,121 +1,144 @@ # FlowSpeech MCP Server -## 0.2.1 Security Update +Generate expressive narration and multi-speaker dialogue with [FlowSpeech](https://flowspeech.io/) directly from Claude Code, Cursor, or Claude Desktop. A single tool call saves a local WAV and returns the job ID and request ID. -Read-only tools and returned job errors reject the configured API key in diagnostic codes. Returned job errors contain only the validated code, not remote messages or extra fields. Recovery IDs and successful result links remain available. +- **Inline emotion & timed pauses**: Steer delivery with bracketed cues such as `[excited]`, `[calmly]`, `[whisper]`, and `[pause:1.0s]`. +- **Multi-speaker dialogue & podcasts**: Assign distinct voices to 2 or more named speakers (`Host`, `Guest`, `Narrator`) in one request, or use structured `segments`. +- **30+ natural voices & long-form scripts**: Multilingual narration and dialogue saved as 24 kHz mono 16-bit PCM WAV, up to 100,000 characters per request. +- **Commercial-ready API plans**: Paid [Basic ($19/month or $156/year, 200,000 credits), Pro, and Scale plans](https://flowspeech.io/pricing) include REST API/MCP access and commercial rights. -Use [FlowSpeech](https://flowspeech.io) speech generation from an MCP client. Version 0.2.1 uses the public API v1: create a job, wait for completion, download the WAV, and save it locally. +## Quick start -## Requirements +Use Node.js 20.3 or newer and a developer API key from [FlowSpeech API settings](https://flowspeech.io/settings/apikeys). Generation requires active paid API access on Basic, Pro, or Scale and consumes account credits. -- Node.js 20.3 or newer. -- A FlowSpeech developer API key from [API settings](https://flowspeech.io/settings/apikeys). -- Active paid Basic, Pro or Scale API access for generation. Trials do not include API access; generated speech consumes account credits. +### Claude Code -Keep keys in your MCP client's local environment or secret manager, not in prompts or public configuration files. +Set `FLOWSPEECH_API_KEY` privately in your shell, then register the stdio server (this stores the expanded value in your local `~/.claude.json`, so keep that file private): -## Configuration +```sh +claude mcp add --scope user --env "FLOWSPEECH_API_KEY=$FLOWSPEECH_API_KEY" \ + --transport stdio flowspeech -- npx -y mcp-flowspeech-server@0.3.0 +claude mcp list +``` -Set `FLOWSPEECH_API_KEY` in the environment used to launch your MCP client. A stdio configuration is: +### Cursor + +Add this entry to `~/.cursor/mcp.json` for local desktop use, or to `.cursor/mcp.json` for the current project. Set `FLOWSPEECH_API_KEY` in the environment Cursor inherits. + +```json +{ + "mcpServers": { + "flowspeech": { + "type": "stdio", + "command": "npx", + "args": ["-y", "mcp-flowspeech-server@0.3.0"], + "env": { + "FLOWSPEECH_API_KEY": "${env:FLOWSPEECH_API_KEY}" + } + } + } +} +``` + +### Claude Desktop + +Add this entry to `claude_desktop_config.json`, replace the placeholder with your key, then quit and reopen Claude Desktop. On macOS the file is under `~/Library/Application Support/Claude/`. On Windows it is under `%APPDATA%\Claude\`. Keep this file private. If the desktop app cannot find `npx`, use its absolute path. ```json { "mcpServers": { "flowspeech": { "command": "npx", - "args": ["-y", "mcp-flowspeech-server@0.2.1"] + "args": ["-y", "mcp-flowspeech-server@0.3.0"], + "env": { + "FLOWSPEECH_API_KEY": "YOUR_DEVELOPER_API_KEY" + } } } } ``` -The MCP client must pass the key to its child process. Clients which do not inherit environment variables need a private `env` entry or their own secret configuration. +## Generate audio -| Variable | Meaning | Default | -| --- | --- | --- | -| `FLOWSPEECH_API_KEY` | Required developer key | None | -| `FLOWSPEECH_OUTPUT_DIR` | Local output directory; `~/` is expanded | `~/.flowspeech-mcp/audio` | -| `FLOWSPEECH_TIMEOUT_MS` | Total operation deadline, at most 7200000 ms | `120000` | -| `FLOWSPEECH_BASE_URL` | Trusted API origin; never use an untrusted key recipient | `https://flowspeech.io` | +Call `flowspeech_tts` with text. Place an emotion cue such as `[excited]`, `[calmly]`, or `[whisper]` before the words it should guide. Put `[pause:1.0s]` between phrases for a one-second pause. -HTTP is allowed only for loopback test servers. Audio downloads never include the API key. Redirects are rejected, and audio downloads are limited to 100 MiB. +```json +{ + "text": "[excited] Welcome back! [pause:1.0s] [calmly] Today we’ll start with a short story.", + "voice": "Kore" +} +``` + +For a two-person podcast, call `flowspeech_tts_multi` with a labelled script and a map from speaker labels to voice names. Add more labels for more speakers. Only a label in the map starts a new turn. Other lines, including standalone pause cues, continue the preceding turn. + +```json +{ + "text": "Host: [excited] Welcome to the show! [pause:1.0s] How did you get started?\nGuest: [calmly] It began with a very small experiment.", + "speakers": { "Host": "Charon", "Guest": "Kore" } +} +``` + +You can supply ordered turns directly with `segments`, with one consistent `voiceName` per speaker: + +```json +{ + "segments": [ + { "speaker": "Host", "text": "[excited] Welcome!", "voiceName": "Charon" }, + { "speaker": "Guest", "text": "[calmly] Thanks for inviting me.", "voiceName": "Kore" }, + { "speaker": "Producer", "text": "[pause:1.0s] We’re recording.", "voiceName": "Puck" } + ] +} +``` + +Existing scripts with `Speaker1:` and `Speaker2:` still work without a `speakers` map. Their voice overrides are `voice_a` (default `Charon`) and `voice_b` (default `Kore`). + +## Example prompts + +Once configured in Claude Code, Cursor, or Claude Desktop, you can ask your assistant directly: + +- `"List available female FlowSpeech voices, then read this product changelog aloud with a calm narrator and a 1-second pause before the breaking change."` +- `"Turn these release notes into a 2-minute two-host podcast WAV using Charon as Host and Kore as Guest, and save it to ./audio/release-podcast.wav."` +- `"Generate a dramatic game-trailer voiceover with [whisper] and [excited] cues, then tell me how many FlowSpeech credits remain."` +- `"Regenerate ./audio/intro.wav with a warmer voice and overwrite the previous file."` ## Tools -| Tool | Arguments | Result | -| --- | --- | --- | -| `flowspeech_new_request_id` | None; no API key needed | Fresh UUID generated locally without network access | -| `flowspeech_tts` | Required `text` and `request_id`; optional `voice` (Kore), `output_path` | Local WAV path, job ID, request ID and usage | -| `flowspeech_tts_multi` | Required labelled `text` and `request_id`; optional `voice_a` (Charon), `voice_b` (Kore), `output_path` | Local WAV path and recovery IDs | -| `flowspeech_list_voices` | Optional `gender`: male, female or all | Current authenticated voice catalog | -| `flowspeech_quota` | None | Available, remaining and reserved credits | -| `flowspeech_get_job` | Exactly one UUID: `job_id` or `request_id` | Current job status and result; never creates work | +| Tool | Arguments and result | +| --- | --- | +| `flowspeech_tts` | Required `text`, optional `voice` (`Kore`). Returns the WAV path, job ID, request ID, and usage. | +| `flowspeech_tts_multi` | `segments`, `text` with `speakers`, or legacy `text` with optional `voice_a` and `voice_b`. Returns the WAV path, job ID, request ID, and usage. | +| `flowspeech_new_request_id` | No arguments. Returns a local UUID without a key or network access. | +| `flowspeech_list_voices` | Optional `gender` (`male`, `female`, or `all`). Returns the authenticated voice catalog. | +| `flowspeech_quota` | No arguments. Returns available, remaining, and reserved credits. | +| `flowspeech_get_job` | One of `job_id` or `request_id`. Returns the existing job and any audio result. | +| `flowspeech_cancel_job` | Required `job_id`. Stops a pending job. If you only know the request ID, look up the job first. Completed jobs cannot be cancelled or refunded. | -Call `flowspeech_new_request_id` first and retain its `request_id` before invoking -either generation tool. Never use a fresh UUID merely because a call was interrupted. -All tools reject unknown fields and incorrect argument types at runtime. -Model, source, speed and format options are unsupported. Output paths are validated -and preflighted before paid submission; the final write still uses atomic -no-overwrite protection in case another process creates the file meanwhile. +Both generation tools accept optional `request_id`, `output_path`, and `overwrite`. Output defaults to a job-specific file under `~/.flowspeech-mcp/audio`. To replace an existing regular file, set `overwrite: true`. The server validates and stages the complete WAV before saving. The default preserves existing files, including files created during generation. On filesystems without hard links, the server uses an exclusive copy. The output format is 24 kHz, mono, 16-bit PCM WAV. -Two-speaker input uses one label per turn. Continuation lines belong to the preceding speaker: +## Recovery -```text -Speaker1: Welcome.[pause:2s]Let's begin. -Speaker2: Thanks for inviting me. -Speaker1: What should we cover first? -``` +When `request_id` is omitted, repeating the same speech input with the same API key and base URL reuses the same job even after a client restart. Local output options can change without starting a new job. If the same WAV is already at the requested path, the tool can return that path. An unrelated existing file is preserved. The lower-level TypeScript `generate(input, requestId, signal?)` method still requires an explicit UUID. -Output is 24 kHz, mono, 16-bit PCM WAV. The client validates all result fields -(`url`, `mimeType`, `sampleRate`, `channels`, `bitsPerSample`, `access`), -usage counters, UUID correlation, RIFF length, chunk boundaries and padding, -PCM format, and nonempty sample-aligned data before saving. Existing output files -are never overwritten. Anyone holding a result URL can download it, so keep job -results and recordings private when appropriate. +1. After an interruption, repeat the same speech input with the original `request_id`, or leave it omitted if the first call omitted it. If you already have the request ID or job ID, you can use `flowspeech_get_job` to check the job directly. +2. While it is pending, follow the API’s polling guidance. The MCP generator uses 1, 2, 3, and then 5 seconds when the API does not ask for a longer wait. The FlowSpeech API currently sends `Retry-After: 5` for pending jobs. HTTP retries also honor `Retry-After`. +3. If the job succeeded, download its existing `result.url` without API credentials. Treat the result URL as private when appropriate, since anyone with the link can download it. +4. If lookup returns 404 or you need to retry the local save, reuse the same UUID with unchanged text and voices. Choose an unused output path or explicitly enable `overwrite` for a regular file you want to replace. +5. To start a new recording with the same speech input, including after a terminal failure or cancellation, call `flowspeech_new_request_id` and pass its fresh UUID explicitly. Retain that ID for any retries. -## Recovery and migration +Closing or timing out an MCP call stops the local wait. Use `flowspeech_cancel_job` to request server-side cancellation. For long scripts the MCP client may need a longer timeout than its default. -Version 0.1.0 called the retired synchronous endpoint. Upgrade the npm package and -restart your MCP client. All API tools require a developer key, including voice -listing; only `flowspeech_new_request_id` is entirely local. All five existing -tool names remain available. +## Configuration -**Breaking change in 0.2.0:** both generation tools now require `request_id`; -automatic UUID creation inside a blocking generation call has been removed. -The TypeScript client's `generate(input, requestId, signal?)` likewise requires a -caller-known UUID. UUIDs are normalized to lowercase. The client rejects -responses whose request or job identity does not match the requested operation. +| Variable | Default and behavior | +| --- | --- | +| `FLOWSPEECH_API_KEY` | Required for API tools. Use the client’s private environment or secret manager. | +| `FLOWSPEECH_OUTPUT_DIR` | `~/.flowspeech-mcp/audio`. A leading `~/` is expanded. | +| `FLOWSPEECH_TIMEOUT_MS` | `120000`. Total operation deadline, up to `7200000` ms. | +| `FLOWSPEECH_BASE_URL` | `https://flowspeech.io`. Set only to a trusted API origin. HTTP is available for loopback test servers. | -The server submits `{ "input": ... }` with a UUID idempotency key, polls no faster -than five seconds (including status retries), honors a longer `Retry-After`, -and downloads `result.url`. A received cooldown still applies if reading the -response body fails. It does not expect an API Base64 response. Transient API -retries preserve the exact request ID and body, with at most five attempts per -API request. Redirects and size-validation failures are not retried. +The server uses [FlowSpeech public API v1](https://flowspeech.io/docs/public-api). API and audio requests reject redirects. Audio downloads omit the API key, are limited to 100 MiB, and are validated before saving. -Recovery workflow: - -1. Call `flowspeech_new_request_id` and retain the returned UUID. -2. Pass that UUID as `request_id` to generation with the intended text and voices. -3. After a timeout or cancellation, call `flowspeech_get_job` with - `{"request_id":"YOUR_RETAINED_UUID"}`. If a job ID was already returned, - `{"job_id":"YOUR_JOB_UUID"}` is also supported. -4. While queued, running, merging or settling, wait at least five seconds between - status calls. On success, use the existing `result.url` for a credential-free - download. Do not request another recording to retry a download. -5. If lookup returns 404, retry the original generation with the same UUID and - unchanged text and voices. To retry local saving through MCP, replay that - same request with an unused output path; idempotency prevents new generation. - -Caller cancellation is passed to HTTP requests, response reads and polling waits. -It never sends a server-side cancellation request. MCP clients may time out -earlier than `FLOWSPEECH_TIMEOUT_MS` (the SDK default is 60 seconds); configure -their timeout as appropriate. Cancelled MCP requests may not receive a final -error response, which is why retaining the UUID **before submission** is required. -A deleted success result has no downloadable audio. A terminal failed/cancelled -job requires a new UUID only when intentionally requesting a new attempt. - -## Development and tests +## Development ```sh npm ci --ignore-scripts @@ -123,12 +146,16 @@ npm test npm run test:packed ``` -Tests cover mocked v1 contracts, real WAV fixtures and a loopback HTTP server -exercised through the built MCP stdio process. Packed tests rebuild the tarball, -inspect its members and credentials patterns, compare packaged bytes with local -files, and rerun the client and stdio suites against the extracted package. -They never call paid production generation. Node 20 and 22 CI run both suites. -See [CHANGELOG.md](CHANGELOG.md) and the [public API documentation](https://flowspeech.io/docs/public-api). +To run a local build, configure `node` as the MCP command and use the absolute path to this checkout’s `dist/index.js` as its only argument. The tests exercise the built MCP over stdio with a loopback REST fixture. Packed tests verify the tarball contents and rerun the same runtime checks against the extracted package. See [CHANGELOG.md](CHANGELOG.md). + +## Links + +- Website: [https://flowspeech.io](https://flowspeech.io/) +- Pricing & Commercial License: [https://flowspeech.io/pricing](https://flowspeech.io/pricing) +- Public API Documentation: [https://flowspeech.io/docs/public-api](https://flowspeech.io/docs/public-api) +- OpenAPI Specification: [https://flowspeech.io/openapi.json](https://flowspeech.io/openapi.json) +- npm Package: [https://www.npmjs.com/package/mcp-flowspeech-server](https://www.npmjs.com/package/mcp-flowspeech-server) +- Support: `support@flowspeech.io` ## License diff --git a/SKILL.md b/SKILL.md index b619558..e913340 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,100 +1,25 @@ --- name: flowspeech-tts -description: Use FlowSpeech to convert text, narration scripts, and two-speaker dialogue into human-like speech with emotion control, pause control, and 30+ voices through the FlowSpeech MCP server. +description: Use FlowSpeech MCP to create narration, voiceovers, or multi-speaker dialogue with emotion cues and timed pauses, or to explore available voices. --- # FlowSpeech TTS -Use this skill when a user wants to create audio from text with FlowSpeech, including narration, educational audio, product demos, creator scripts, short voiceovers, or two-speaker dialogue. - -FlowSpeech is a context-aware text-to-speech tool for human-like audio with emotion control, pause control, and 30+ voices. Learn more at https://flowspeech.io/. - -## When To Use - -- The user asks for text-to-speech, AI voice, narration, voiceover, spoken audio, or dialogue audio. -- The user wants expressive delivery with emotion stage directions. -- The user needs a local audio file generated from plain text or a two-speaker script. -- The user wants to explore available FlowSpeech voices before generating audio. +Use FlowSpeech when the user wants speech audio from text, including lessons, voiceovers, podcast scripts, and scenes with multiple voices. ## Setup -Install or run the FlowSpeech MCP server: +Use `npx -y mcp-flowspeech-server@0.3.0` as a stdio server. Configure `FLOWSPEECH_API_KEY` in the MCP client's private environment or secret manager. See [README.md](README.md) for Claude Code, Cursor, and Claude Desktop configurations. Node.js 20.3 or newer is required. Generation requires paid API access and consumes account credits. `flowspeech_new_request_id` runs locally without a key. -```bash -npx -y mcp-flowspeech-server@0.2.1 -``` +## Generate speech -For MCP clients, configure the server with stdio transport: +1. Choose the voice or voices requested by the user. Use `flowspeech_list_voices` for the current voice catalog or `flowspeech_quota` to check available credits if needed. +2. Call `flowspeech_tts` with `text` and an optional `voice` for narration. Use `flowspeech_tts_multi` for dialogue. Supply `segments` with ordered `{speaker, text, voiceName}` turns, or supply labelled `text` and a `speakers` map. Legacy `Speaker1:` and `Speaker2:` labels use `voice_a` and `voice_b`. +3. Place bracketed cues like `[excited]` or `[calmly]` before the speech they guide, and put `[pause:1.0s]` where a one-second pause belongs. For example, `Host: [excited] Welcome! [pause:1.0s] Let’s begin.` +4. Return the local WAV path and the job or request ID when useful. Use `output_path` for a requested location. Set `overwrite: true` only when the user wants to replace an existing file. -```json -{ - "mcpServers": { - "flowspeech": { - "command": "npx", - "args": ["-y", "mcp-flowspeech-server@0.2.1"], - "env": { - "FLOWSPEECH_OUTPUT_DIR": "~/flowspeech-audio" - } - } - } -} -``` +## Recover or cancel an existing job -Node.js 20.3 or newer and a FlowSpeech developer API key are required for API -operations. The local flowspeech_new_request_id tool needs no key or network. -Set FLOWSPEECH_API_KEY in the private environment passed to the MCP process. -Generation requires active paid API access and consumes account credits. -Do not ask the user to paste secrets, account credentials, or private tokens into -chat; use the MCP client's environment or secret manager. +Omit `request_id` for one-call generation. After a timeout or disconnect, repeat the same speech input with the same API key and base URL. Leave `request_id` omitted if the first call omitted it, or pass the same UUID if it was explicit. Use `flowspeech_get_job` when the request ID or job ID is already available. A completed result can be downloaded from its existing URL without API credentials. To deliberately generate a new recording of the same speech, first call `flowspeech_new_request_id` and retain its UUID for retries. -## Workflow - -1. Clarify the target format: single voice, two-speaker dialogue, or voice exploration. -2. If the user has not chosen a voice, use `flowspeech_list_voices` or pick a sensible default. -3. Call `flowspeech_new_request_id` and retain the returned `request_id` before submitting any text. -4. For single-speaker audio, call `flowspeech_tts` with that required `request_id`, text and selected voice. -5. For two-speaker audio, call `flowspeech_tts_multi` with that required `request_id` and `Speaker1:` / `Speaker2:` labels. -6. Return the generated audio file path and briefly describe the voice choices used. - -Version 0.2.0 requires a caller-known UUID on both generation tools; calls without -request_id are rejected before submission. Unknown fields, invalid argument -types and invalid output paths are rejected before paid work. Do not supply -unsupported model, source, speed or format options. - -The server uses API v1 job creation, polling and separate validated PCM WAV -download. It does not send credentials to the audio host. Use flowspeech_quota -for available credits. After timeout or cancellation, call flowspeech_get_job -with exactly one of request_id (the UUID retained before submission) or job_id. -Wait at least five seconds between status queries. If lookup returns 404, retry -the original generation with the same UUID and unchanged text/voices. If the job -succeeded, download its existing result URL without API credentials. To retry -saving through MCP, replay that unchanged request with an unused output path. -Never create a new UUID merely to retry an interrupted request or download. - -MCP cancellation can suppress the final error message, so do not rely on that -message to recover an automatically generated ID. Caller cancellation stops local -HTTP/poll/download work but never cancels the paid server job. Existing output -files are not overwritten. Deliberate new recordings require fresh UUIDs. - -## Emotion And Pause Control - -FlowSpeech supports inline emotion cues with stage directions: - -```text -***(say cheerfully: Welcome back!)*** -Today we are walking through the new release. -***(say thoughtfully: This part matters.)*** -``` - -Use emotion cues sparingly. Keep them tied to the content instead of decorating every sentence. - -## Example Requests - -- "Turn this lesson into a warm narration." -- "Create a two-host podcast intro from this script." -- "Read this product update in a calm professional voice." -- "List the available female voices before generating audio." - -## Output - -The MCP server saves generated audio locally and returns the file path. If the user needs a different location, pass a custom `output_path`. +Use `flowspeech_cancel_job` with a job ID if the user explicitly wants to stop a pending job. A timeout or MCP disconnect ends the local wait and the remote job can continue. The received server `Retry-After` controls the minimum wait between automatic polls when present. diff --git a/package-lock.json b/package-lock.json index 97a8065..9f53082 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "mcp-flowspeech-server", - "version": "0.2.1", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mcp-flowspeech-server", - "version": "0.2.1", + "version": "0.3.0", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.12.0" diff --git a/package.json b/package.json index e0ef78e..e1ac621 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mcp-flowspeech-server", - "version": "0.2.1", - "description": "MCP server for the FlowSpeech public API with asynchronous speech jobs, voice discovery and quota checks", + "version": "0.3.0", + "description": "MCP server for FlowSpeech text-to-speech — inline emotion cues, timed pauses, and multi-speaker dialogue for Claude Code, Cursor, and MCP clients", "keywords": [ "mcp", "mcp-server", @@ -10,7 +10,12 @@ "flowspeech", "ai", "voice", - "speech-synthesis" + "speech-synthesis", + "multi-speaker", + "emotion", + "podcast", + "claude-code", + "cursor" ], "homepage": "https://flowspeech.io", "repository": { diff --git a/scripts/test-packed.mjs b/scripts/test-packed.mjs index a0c1726..7fcda3b 100644 --- a/scripts/test-packed.mjs +++ b/scripts/test-packed.mjs @@ -13,7 +13,8 @@ const destination = path.resolve(process.env.FLOWSPEECH_PACK_DESTINATION ?? root await mkdir(destination, { recursive: true }); const packed = JSON.parse(execFileSync(process.execPath, [npmCli, 'pack', '--ignore-scripts', '--json', '--pack-destination', destination], { cwd: root, env, encoding: 'utf8' })); assert.equal(packed.length, 1); -assert.equal(packed[0].version, '0.2.1'); +const sourceManifest = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')); +assert.equal(packed[0].version, sourceManifest.version); const archive = path.join(destination, packed[0].filename); const expected = [ 'LICENSE', 'dist/client.js', 'dist/index.js', 'package.json', 'CHANGELOG.md', @@ -37,7 +38,7 @@ try { const target = path.join(directory, 'package'); const manifest = JSON.parse(await readFile(path.join(target, 'package.json'), 'utf8')); assert.equal(manifest.bin['mcp-flowspeech-server'], 'dist/index.js'); - assert.equal(manifest.version, '0.2.1'); + assert.equal(manifest.version, sourceManifest.version); assert.ok((await readFile(path.join(target, manifest.bin['mcp-flowspeech-server']), 'utf8')).startsWith('#!/usr/bin/env node')); // Dependencies resolve from the existing workspace install; implementation imports // and the child stdio process both use only the extracted package's dist files. diff --git a/src/client.ts b/src/client.ts index cf48988..ec71201 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,3 +1,4 @@ +import { createHmac } from 'node:crypto'; import { setTimeout as delay } from 'node:timers/promises'; export type SpeechInput = @@ -35,6 +36,7 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a- const PENDING = new Set(['queued', 'running', 'merging', 'settling']); const TERMINAL = new Set(['success', 'failed', 'cancelled']); const TRANSIENT = new Set([429, 500, 502, 503, 504]); +const POLL_DELAYS = [1000, 2000, 3000, 5000]; class InvalidResponse extends Error {} function object(value: unknown): Record { @@ -96,7 +98,7 @@ async function boundedBody(response: Response, maximum: number, signal: AbortSig } return Buffer.concat(chunks, length); } -function speechInput(value: unknown): SpeechInput { +export function validateSpeechInput(value: unknown): SpeechInput { const input = object(value); let result: SpeechInput; if (input.mode === 'single') { @@ -122,16 +124,33 @@ function speechInput(value: unknown): SpeechInput { if (Buffer.byteLength(JSON.stringify({ input: result })) > 1024 * 1024) throw new Error('Input exceeds the JSON body limit'); return result; } -export function dialogueInput(text: string, voiceA: string, voiceB: string): SpeechInput { +export function dialogueInput(text: string, voiceA: string, voiceB: string, speakers?: unknown): SpeechInput { nonempty(text, 'dialogue'); - const segments: { speaker: string; text: string; voiceName: string }[] = []; - for (const line of text.split(/\r?\n/)) { - const match = /^(Speaker[12]):\s*(.*)$/.exec(line.trim()); - if (match) segments.push({ speaker: match[1], text: match[2], voiceName: match[1] === 'Speaker1' ? voiceA : voiceB }); - else if (line.trim() && segments.length) segments[segments.length - 1].text += '\n' + line; - else if (line.trim()) throw new Error('Dialogue must start with Speaker1: or Speaker2:'); + const voices = new Map([['Speaker1', voiceA], ['Speaker2', voiceB]]); + if (speakers !== undefined) { + const entries = Object.entries(object(speakers)); + if (entries.length === 0 || entries.length > 1000) throw new Error('Expected 1 to 1000 speaker assignments'); + voices.clear(); + for (const [label, voice] of entries) { + if (!label.trim() || label.length > 100 || label !== label.trim() || /[:\r\n]/.test(label)) { + throw new Error('Speaker labels must be 1 to 100 characters without colons, line breaks or surrounding whitespace'); + } + voices.set(label, nonempty(voice, 'voice name', 100)); + } } - return speechInput({ mode: 'multi', segments }); + const segments: { speaker: string; text: string; voiceName: string }[] = []; + const labelPattern = speakers === undefined ? /^(Speaker[12]):\s*(.*)$/ : /^([^:]{1,100}):\s*(.*)$/; + for (const line of text.split(/\r?\n/)) { + const match = labelPattern.exec(line.trim()); + const voiceName = match ? voices.get(match[1]) : undefined; + if (match && voiceName !== undefined) { + segments.push({ speaker: match[1], text: match[2], voiceName }); + } else if (line.trim() && segments.length) segments[segments.length - 1].text += '\n' + line; + else if (line.trim()) throw new Error(speakers === undefined + ? 'Dialogue must start with Speaker1: or Speaker2:' + : 'Dialogue must start with a label from speakers followed by a colon'); + } + return validateSpeechInput({ mode: 'multi', segments }); } export function validateWav(audio: Uint8Array): void { const bytes = Buffer.from(audio.buffer, audio.byteOffset, audio.byteLength); @@ -199,17 +218,17 @@ export class FlowSpeechClient { const timeout = AbortSignal.timeout(Math.max(1, Math.ceil(Math.min(requestLimit, this.remaining(context))))); return context.signal ? AbortSignal.any([timeout, context.signal]) : timeout; } - private async api(path: string, context: Context, body?: unknown): Promise<{ data: Record; headers: Headers }> { - const encoded = body === undefined ? undefined : JSON.stringify(body); + private async api(path: string, context: Context, post?: { input?: SpeechInput }): Promise<{ data: Record; headers: Headers }> { + const encoded = post?.input === undefined ? undefined : JSON.stringify({ input: post.input }); for (let attempt = 0; attempt < 5; attempt++) { this.remaining(context); let response: Response | undefined; let raw: Uint8Array; - const fallback = Math.max(body === undefined ? 5000 : 1000, 1000 * 2 ** attempt); + const fallback = Math.max(post === undefined ? 5000 : 1000, 1000 * 2 ** attempt); try { const signal = this.signal(context, 30_000); response = await this.fetcher(this.baseUrl + path, { - method: body === undefined ? 'GET' : 'POST', redirect: 'manual', credentials: 'omit', signal, + method: post === undefined ? 'GET' : 'POST', redirect: 'manual', credentials: 'omit', signal, headers: { Authorization: `Bearer ${this.options.apiKey}`, ...(encoded === undefined ? {} : { 'Content-Type': 'application/json', 'Idempotency-Key': context.requestId! }), @@ -310,16 +329,40 @@ export class FlowSpeechClient { const requestId = validateId(id); return this.job((await this.api(`/api/v1/tts/jobs?requestId=${requestId}`, this.context(signal))).data, { requestId }); } + requestIdFor(input: SpeechInput): string { + const payload = JSON.stringify(['flowspeech-mcp-v1', this.baseUrl, validateSpeechInput(input)]); + const digest = createHmac('sha256', this.options.apiKey).update(payload).digest(); + // UUIDv8 leaves room for an application-defined digest with the standard variant. + digest[6] = (digest[6] & 0x0f) | 0x80; + digest[8] = (digest[8] & 0x3f) | 0x80; + const hex = digest.subarray(0, 16).toString('hex'); + return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-'); + } + async cancelJob(id: string, signal?: AbortSignal): Promise { + const jobId = validateId(id); + const result = await this.api(`/api/v1/tts/jobs/${jobId}/cancel`, this.context(signal), {}); + const job = this.job(result.data, { jobId }); + if (job.status !== 'cancelled' && job.status !== 'failed') throw new InvalidResponse('Cancellation did not return a stopped job'); + return job; + } async generate(input: SpeechInput, requestId: string, signal?: AbortSignal): Promise<{ job: Job; audio: Uint8Array; requestId: string }> { - requestId = validateId(requestId); + return this.recording(validateId(requestId), signal, { input }); + } + async resumeGeneration(requestId: string, signal?: AbortSignal): Promise<{ job: Job; audio: Uint8Array; requestId: string }> { + return this.recording(validateId(requestId), signal); + } + private async recording(requestId: string, signal?: AbortSignal, submission?: { input: SpeechInput }): Promise<{ job: Job; audio: Uint8Array; requestId: string }> { const context = this.context(signal, requestId); try { - const validated = speechInput(input); - let result = await this.api('/api/v1/tts/jobs', context, { input: validated }); + let result = submission + ? await this.api('/api/v1/tts/jobs', context, { input: validateSpeechInput(submission.input) }) + : await this.api(`/api/v1/tts/jobs?requestId=${requestId}`, context); let job = this.job(result.data, { requestId }); context.jobId = job.id; + let poll = 0; while (PENDING.has(job.status)) { - await this.pause(retryDelay(result.headers, 5000), context); + await this.pause(retryDelay(result.headers, POLL_DELAYS[Math.min(poll, POLL_DELAYS.length - 1)]), context); + poll++; result = await this.api(`/api/v1/tts/jobs/${context.jobId}`, context); job = this.job(result.data, { jobId: context.jobId, requestId }); } diff --git a/src/index.ts b/src/index.ts index 66a694d..3fdcb5f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,13 +3,13 @@ import { randomUUID } from 'node:crypto'; import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js'; -import { access, lstat, mkdir, stat, writeFile } from 'node:fs/promises'; +import { access, copyFile, link, lstat, mkdir, mkdtemp, open, rename, rm, stat, writeFile } from 'node:fs/promises'; import { constants } from 'node:fs'; import path from 'node:path'; import os from 'node:os'; -import { FlowSpeechClient, dialogueInput, validateId } from './client.js'; +import { FlowSpeechClient, dialogueInput, validateId, validateSpeechInput, type SpeechInput } from './client.js'; -const VERSION = '0.2.1'; +const VERSION = '0.3.0'; function expandHome(value: string): string { return value === '~' ? os.homedir() : value.startsWith('~/') ? path.join(os.homedir(), value.slice(2)) : path.resolve(value); } @@ -43,14 +43,75 @@ async function checkDirectory(directory: string): Promise { } } } -async function checkFile(file: string): Promise { - let exists = true; - try { await lstat(file); } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new Error('Cannot inspect output_path'); - exists = false; - } - if (exists) throw new Error('Cannot save audio without overwriting an existing file'); +async function checkFile(file: string, allowExisting: boolean): Promise { + const info = await lstat(file).catch((error: NodeJS.ErrnoException) => { + if (error.code !== 'ENOENT') throw new Error('Cannot inspect output_path'); + }); + if (info && !allowExisting) throw new Error('Cannot save audio without overwriting an existing file'); + if (info && !info.isFile()) throw new Error('output_path must refer to a regular file'); await checkDirectory(path.dirname(file)); + return info !== undefined; +} +async function saveAudio(file: string, audio: Uint8Array, overwrite: boolean, signal: AbortSignal): Promise { + signal.throwIfAborted(); + const parent = path.dirname(file); + await mkdir(parent, { recursive: true }); + const directory = await mkdtemp(path.join(parent, '.flowspeech-')); + const temporary = path.join(directory, 'audio.wav'); + try { + await writeFile(temporary, audio, { flag: 'wx', mode: 0o600, signal }); + if (overwrite) await checkFile(file, true); + signal.throwIfAborted(); + if (overwrite) await rename(temporary, file); + else { + try { + await link(temporary, file); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw error; + // Some writable filesystems cannot link files. The copy still fails if the destination exists. + signal.throwIfAborted(); + await copyFile(temporary, file, constants.COPYFILE_EXCL); + } + } + } finally { + await rm(directory, { recursive: true, force: true }).catch(() => {}); + } +} +async function matchesAudio(file: string, audio: Uint8Array, signal: AbortSignal): Promise { + try { + if (!(await lstat(file)).isFile()) return false; + const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const info = await handle.stat(); + if (!info.isFile() || info.size !== audio.byteLength) return false; + const expected = Buffer.from(audio.buffer, audio.byteOffset, audio.byteLength); + const bytes = Buffer.allocUnsafe(Math.min(expected.length, 64 * 1024)); + for (let offset = 0; offset < expected.length;) { + signal.throwIfAborted(); + const { bytesRead } = await handle.read(bytes, 0, Math.min(bytes.length, expected.length - offset), offset); + if (!bytesRead || !bytes.subarray(0, bytesRead).equals(expected.subarray(offset, offset + bytesRead))) return false; + offset += bytesRead; + } + signal.throwIfAborted(); + return (await handle.stat()).size === expected.length; + } finally { + await handle.close(); + } + } catch { + return false; + } +} +function multiInput(args: Record): SpeechInput { + if (args.segments !== undefined) { + if (['text', 'speakers', 'voice_a', 'voice_b'].some(key => args[key] !== undefined)) { + throw new Error('Supply segments by itself or labelled text with voice assignments'); + } + return validateSpeechInput({ mode: 'multi', segments: args.segments }); + } + if (args.speakers !== undefined && (args.voice_a !== undefined || args.voice_b !== undefined)) { + throw new Error('Use speakers or voice_a and voice_b for a labelled script'); + } + return dialogueInput(stringArg(args, 'text'), stringArg(args, 'voice_a', 'Charon'), stringArg(args, 'voice_b', 'Kore'), args.speakers); } function client(): FlowSpeechClient { return new FlowSpeechClient({ @@ -59,24 +120,44 @@ function client(): FlowSpeechClient { }); } const outputProperties = { - output_path: { type: 'string', description: 'Optional output WAV file path. An existing file is not overwritten.' }, - request_id: { type: 'string', format: 'uuid', description: 'Required caller-known UUID. Get one with flowspeech_new_request_id; reuse only for unchanged text and voices.' }, + output_path: { type: 'string', description: 'Optional local output WAV path.' }, + overwrite: { type: 'boolean', default: false, description: 'Set true to replace an existing regular file after audio is ready.' }, + request_id: { type: 'string', format: 'uuid', description: 'Optional UUID. Omit to generate in one call and reuse the same job when retrying unchanged speech with the same API key. For a deliberately new recording of the same speech, pass a fresh UUID from flowspeech_new_request_id.' }, }; +const speechText = { type: 'string', description: 'Use bracketed emotion cues before speech and pause tags between phrases, e.g. [excited] Welcome! [pause:1.0s] Let’s begin.' }; +const jobIdProperty = { type: 'string', format: 'uuid' }; const tools: Tool[] = [ - { name: 'flowspeech_tts', description: 'Generate a WAV recording with FlowSpeech. Requires a caller-known request UUID, an API key and paid API access; consumes account credits.', inputSchema: { - type: 'object', additionalProperties: false, properties: { text: { type: 'string' }, voice: { type: 'string', default: 'Kore' }, ...outputProperties }, required: ['text', 'request_id'], + { name: 'flowspeech_tts', description: 'Generate a single-voice WAV from text in one call. Use [excited] or [calmly] for emotion and [pause:1.0s] for a one-second pause. Requires a FlowSpeech API key and consumes paid API credits.', inputSchema: { + type: 'object', additionalProperties: false, properties: { text: speechText, voice: { type: 'string', default: 'Kore' }, ...outputProperties }, required: ['text'], } }, - { name: 'flowspeech_tts_multi', description: 'Generate a two-speaker WAV recording with a caller-known request UUID. Each turn starts with Speaker1: or Speaker2:. Consumes account credits.', inputSchema: { - type: 'object', additionalProperties: false, properties: { text: { type: 'string' }, voice_a: { type: 'string', default: 'Charon' }, voice_b: { type: 'string', default: 'Kore' }, ...outputProperties }, required: ['text', 'request_id'], + { name: 'flowspeech_tts_multi', description: 'Generate a multi-speaker WAV for a podcast or dialogue. Pass ordered segments, labelled text with a speakers map, or Speaker1:/Speaker2: text. Add cues like [excited] and [pause:1.0s] inside each turn. Requires a FlowSpeech API key and consumes paid API credits.', inputSchema: { + type: 'object', additionalProperties: false, properties: { + text: { ...speechText, description: `Start each turn with a label, e.g. Host: [excited] Welcome! [pause:1.0s] Let's begin. Supply speakers for custom labels, or use Speaker1:/Speaker2:.` }, + speakers: { type: 'object', minProperties: 1, maxProperties: 1000, additionalProperties: { type: 'string', minLength: 1, maxLength: 100 }, description: 'Map script labels to FlowSpeech voice names, e.g. {"Host":"Charon","Guest":"Kore"}.' }, + segments: { type: 'array', minItems: 1, maxItems: 1000, description: 'Ordered speaker turns. Use one consistent voice per speaker.', items: { + type: 'object', additionalProperties: false, required: ['speaker', 'text', 'voiceName'], + properties: { speaker: { type: 'string', minLength: 1, maxLength: 100 }, text: speechText, voiceName: { type: 'string', minLength: 1, maxLength: 100 } }, + } }, + voice_a: { type: 'string', description: 'Voice for the legacy Speaker1 label. Defaults to Charon.' }, + voice_b: { type: 'string', description: 'Voice for the legacy Speaker2 label. Defaults to Kore.' }, + ...outputProperties, + }, oneOf: [ + { required: ['segments'], not: { anyOf: ['text', 'speakers', 'voice_a', 'voice_b'].map(key => ({ required: [key] })) } }, + { required: ['text', 'speakers'], not: { anyOf: ['segments', 'voice_a', 'voice_b'].map(key => ({ required: [key] })) } }, + { required: ['text'], not: { anyOf: ['segments', 'speakers'].map(key => ({ required: [key] })) } }, + ], } }, { name: 'flowspeech_list_voices', description: 'Retrieve the current voice catalog from FlowSpeech.', inputSchema: { type: 'object', additionalProperties: false, properties: { gender: { type: 'string', enum: ['male', 'female', 'all'], default: 'all' } }, } }, { name: 'flowspeech_quota', description: 'Read available, remaining and reserved API credits.', inputSchema: { type: 'object', additionalProperties: false, properties: {} } }, { name: 'flowspeech_get_job', description: 'Read an existing job by job UUID or caller-known request UUID without creating a recording. Supply exactly one ID.', inputSchema: { - type: 'object', additionalProperties: false, properties: { job_id: { type: 'string', format: 'uuid' }, request_id: { type: 'string', format: 'uuid' } }, + type: 'object', additionalProperties: false, properties: { job_id: jobIdProperty, request_id: { type: 'string', format: 'uuid' } }, oneOf: [{ required: ['job_id'] }, { required: ['request_id'] }], } }, + { name: 'flowspeech_cancel_job', description: 'Explicitly cancel an existing FlowSpeech job by job UUID. A completed job cannot be cancelled or refunded.', inputSchema: { + type: 'object', additionalProperties: false, properties: { job_id: jobIdProperty }, required: ['job_id'], + } }, { name: 'flowspeech_new_request_id', description: 'Generate a fresh request UUID locally, without network access or an API key. Keep it before starting one recording.', inputSchema: { type: 'object', additionalProperties: false, properties: {}, } }, @@ -85,6 +166,7 @@ const server = new Server({ name: 'flowspeech', version: VERSION }, { capabiliti server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools })); server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { const { name, arguments: args = {} } = request.params; + let preflightRequestId: string | undefined; try { let text: string; if (name === 'flowspeech_new_request_id') { @@ -105,36 +187,52 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { const id = validateId(stringArg(args, byJob ? 'job_id' : 'request_id')); const api = client(); text = JSON.stringify(await (byJob ? api.getJob(id, extra.signal) : api.findJob(id, extra.signal)), null, 2); + } else if (name === 'flowspeech_cancel_job') { + allowedFields(args, ['job_id']); + const jobId = validateId(stringArg(args, 'job_id')); + text = JSON.stringify(await client().cancelJob(jobId, extra.signal), null, 2); } else if (name === 'flowspeech_tts' || name === 'flowspeech_tts_multi') { + const automatic = args.request_id === undefined; + let requestId = automatic ? undefined : validateId(args.request_id); + preflightRequestId = requestId; allowedFields(args, name === 'flowspeech_tts' - ? ['text', 'voice', 'output_path', 'request_id'] - : ['text', 'voice_a', 'voice_b', 'output_path', 'request_id']); - const requestId = validateId(stringArg(args, 'request_id')); - const script = stringArg(args, 'text'); + ? ['text', 'voice', 'output_path', 'request_id', 'overwrite'] + : ['text', 'voice_a', 'voice_b', 'segments', 'speakers', 'output_path', 'request_id', 'overwrite']); const input = name === 'flowspeech_tts' - ? { mode: 'single' as const, text: script, voiceName: stringArg(args, 'voice', 'Kore') } - : dialogueInput(script, stringArg(args, 'voice_a', 'Charon'), stringArg(args, 'voice_b', 'Kore')); + ? { mode: 'single' as const, text: stringArg(args, 'text'), voiceName: stringArg(args, 'voice', 'Kore') } + : multiInput(args); + if (args.overwrite !== undefined && typeof args.overwrite !== 'boolean') throw new Error('overwrite must be a boolean'); + const overwrite = args.overwrite === true; const customFile = args.output_path === undefined ? undefined : outputPath(stringArg(args, 'output_path')); const directoryValue = process.env.FLOWSPEECH_OUTPUT_DIR || '~/.flowspeech-mcp/audio'; if (/[\x00-\x1f\x7f]/.test(directoryValue)) throw new Error('Invalid output directory'); const outputDirectory = expandHome(directoryValue); - if (customFile) await checkFile(customFile); - else await checkDirectory(outputDirectory); - const result = await client().generate(input, requestId, extra.signal); + const api = client(); + requestId ??= api.requestIdFor(input); + preflightRequestId = requestId; + const existing = customFile ? await checkFile(customFile, overwrite || automatic) : false; + if (!customFile) await checkDirectory(outputDirectory); + preflightRequestId = undefined; // The client includes recovery IDs on generation errors. + const result = existing && !overwrite + ? await api.resumeGeneration(requestId, extra.signal) + : await api.generate(input, requestId, extra.signal); const file = customFile ?? path.join(outputDirectory, `flowspeech-${result.job.id}.wav`); try { - extra.signal.throwIfAborted(); - await mkdir(path.dirname(file), { recursive: true }); - extra.signal.throwIfAborted(); - await writeFile(file, result.audio, { flag: 'wx', mode: 0o600, signal: extra.signal }); - } catch { - throw new Error(`Cannot save audio without overwriting an existing file, or operation stopped. Retrieve jobId=${result.job.id}; requestId=${result.requestId}. Do not create another recording.`); + await saveAudio(file, result.audio, overwrite, extra.signal); + } catch (error) { + const identical = automatic && !overwrite && (error as NodeJS.ErrnoException).code === 'EEXIST' + && await matchesAudio(file, result.audio, extra.signal); + if (!identical) { + const reason = overwrite ? 'Cannot replace output file, or operation stopped' : 'Cannot save audio without overwriting an existing file, or operation stopped'; + throw new Error(`${reason}. Retrieve jobId=${result.job.id}; requestId=${result.requestId}. Reuse the existing recording.`); + } } text = `Audio saved to: ${file}\nFormat: audio/wav\nJob ID: ${result.job.id}\nRequest ID: ${result.requestId}\nUsage: ${JSON.stringify(result.job.usage)}`; } else throw new Error('Unknown tool'); return { content: [{ type: 'text', text }] }; } catch (error) { - return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : 'FlowSpeech operation failed' }] }; + const message = error instanceof Error ? error.message : 'FlowSpeech operation failed'; + return { isError: true, content: [{ type: 'text', text: preflightRequestId ? `${message}; requestId=${preflightRequestId}` : message }] }; } }); await server.connect(new StdioServerTransport()); diff --git a/test/client.test.mjs b/test/client.test.mjs index 4392bde..4c7e908 100644 --- a/test/client.test.mjs +++ b/test/client.test.mjs @@ -19,6 +19,17 @@ test('single creation, all pending states and credential-free audio', async () = assert.equal(h.calls.at(-1).init.headers, undefined); assert.ok(h.calls.every(call => call.init.redirect === 'manual' && call.init.credentials === 'omit')); }); +test('polling backs off from one second and honors the current five-second server hint', async () => { + const states = ['queued', 'running', 'merging', 'settling', 'settling']; + for (const [headers, expected] of [ + [{}, [1000, 2000, 3000, 5000, 5000]], + [{ 'Retry-After': '5' }, [5000, 5000, 5000, 5000, 5000]], + ]) { + const h = harness([...states.map(state => json(job(state), 200, headers)), json(job()), new Response(wav)]); + await h.client.generate(input, requestId); + assert.deepEqual(h.sleeps, expected); + } +}); test('network retries preserve the exact body and UUID', async () => { const h = harness([new Error('network'), json(job()), new Response(wav)]); await h.client.generate(input, requestId); @@ -26,6 +37,18 @@ test('network retries preserve the exact body and UUID', async () => { assert.equal(h.calls[0].init.headers['Idempotency-Key'], h.calls[1].init.headers['Idempotency-Key']); assert.deepEqual(h.sleeps, [1000]); }); +test('automatic request IDs are stable and scoped to speech, API key and origin', () => { + const base = new FlowSpeechClient({ apiKey: 'test-key' }); + const derived = base.requestIdFor(input); + assert.equal(derived, new FlowSpeechClient({ apiKey: 'test-key', baseUrl: 'https://flowspeech.io/' }).requestIdFor(input)); + assert.equal(validateId(derived), derived); + for (const changed of [ + base.requestIdFor({ ...input, text: 'Hello again' }), + base.requestIdFor({ ...input, voiceName: 'Charon' }), + new FlowSpeechClient({ apiKey: 'another-key' }).requestIdFor(input), + new FlowSpeechClient({ apiKey: 'test-key', baseUrl: 'https://api.example.test' }).requestIdFor(input), + ]) assert.notEqual(derived, changed); +}); test('429 and retryable 503 honor Retry-After', async () => { const h = harness([json({ error: { retryable: true } }, 429, { 'Retry-After': '9' }), json({ error: { retryable: true } }, 503, { 'Retry-After': '12' }), json(job()), new Response(wav)]); @@ -53,7 +76,7 @@ for (const failed of [() => new Error('network'), () => brokenResponse(), () => test('every status retry waits at least five seconds: ' + failed.toString(), async () => { const h = harness([json(job('queued'), 202), failed(), json(job()), new Response(wav)]); await h.client.generate(input, requestId); - assert.deepEqual(h.sleeps, [5000, 5000]); + assert.deepEqual(h.sleeps, [1000, 5000]); assert.equal(h.calls[2].at - h.calls[1].at, 5000); }); } @@ -63,6 +86,16 @@ test('long required cooldown exceeds deadline without another request', async () assert.equal(h.calls.length, 1); assert.deepEqual(h.sleeps, []); }); +test('cancel uses a bodyless POST and validates the returned job', async () => { + const h = harness([json(job('cancelled')), json(job('cancelled', { id: requestId })), json(job('running'))]); + assert.equal((await h.client.cancelJob(id.toUpperCase())).status, 'cancelled'); + assert.equal(h.calls[0].url, `https://flowspeech.io/api/v1/tts/jobs/${id}/cancel`); + assert.equal(h.calls[0].init.method, 'POST'); + assert.equal(h.calls[0].init.body, undefined); + assert.deepEqual(h.calls[0].init.headers, { Authorization: 'Bearer test-key' }); + await assert.rejects(h.client.cancelJob(id), /changed the job ID/); + await assert.rejects(h.client.cancelJob(id), /Cancellation did not return a stopped job/); +}); test('multi input preserves turn order and continuation text', async () => { const multi = dialogueInput('Speaker1: Hello\nMore text\nSpeaker2: Hi\nSpeaker1: Bye', 'Charon', 'Kore'); assert.deepEqual(multi.segments.map(segment => segment.voiceName), ['Charon', 'Kore', 'Charon']); @@ -232,7 +265,7 @@ test('invalid configuration fails locally', () => { assert.equal(validateId(requestId.toUpperCase()), requestId); }); test('deadline ends before a required poll with both recovery IDs', async () => { - const h = harness([json(job('queued'), 202)], { timeoutMs: 4000 }); + const h = harness([json(job('queued'), 202, { 'Retry-After': '5' })], { timeoutMs: 4000 }); await assert.rejects(h.client.generate(input, requestId), new RegExp('timeout.*requestId=' + requestId + '.*jobId=' + id)); assert.equal(h.calls.length, 1); }); diff --git a/test/stdio.test.mjs b/test/stdio.test.mjs index 05af4d1..8a17e79 100644 --- a/test/stdio.test.mjs +++ b/test/stdio.test.mjs @@ -2,7 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { createServer } from 'node:http'; import { once, EventEmitter } from 'node:events'; -import { mkdtemp, readFile, rm, mkdir, writeFile, readdir, stat } from 'node:fs/promises'; +import { mkdtemp, readFile, rm, mkdir, writeFile, readdir, stat, symlink } from 'node:fs/promises'; import { setTimeout as delay } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; @@ -11,7 +11,7 @@ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js' import { id, requestId, wav, job, packageRoot } from './fixtures.mjs'; const workspace = fileURLToPath(new URL('..', import.meta.url)); -async function setup(t, { queued = false, noKey = false, audio = wav, onCreate, reflectedError = false, apiKey = 'fake-test-key' } = {}) { +async function setup(t, { queued = false, noKey = false, audio = wav, onCreate, reflectedError = false, apiKey = 'fake-test-key', noHardLinks = false } = {}) { const scratch = path.join(workspace, '.test-tmp'); await mkdir(scratch, { recursive: true }); const directory = await mkdtemp(path.join(scratch, 'stdio-')); @@ -38,13 +38,15 @@ async function setup(t, { queued = false, noKey = false, audio = wav, onCreate, if (req.url === '/api/v1/tts/jobs' && req.method === 'POST') { const key = req.headers['idempotency-key']; assert.match(key, /^[0-9a-f-]{36}$/); - const response = job(queued ? 'queued' : 'success', { - requestId: key, - ...(queued ? {} : { result: { ...job().result, url: baseUrl + '/audio.wav' } }), - }); - jobs.set(key, response); - await onCreate?.(JSON.parse(body), directory); - res.writeHead(202).end(JSON.stringify(response)); + if (!jobs.has(key)) { + jobs.set(key, job(queued ? 'queued' : 'success', { + requestId: key, + ...(queued ? {} : { result: { ...job().result, url: baseUrl + '/audio.wav' } }), + })); + await onCreate?.(JSON.parse(body), directory); + } + const response = jobs.get(key); + res.writeHead(202, { 'Retry-After': '5' }).end(JSON.stringify(response)); events.emit('accepted'); return; } @@ -57,6 +59,15 @@ async function setup(t, { queued = false, noKey = false, audio = wav, onCreate, const response = [...jobs.values()][0] || job(); res.end(JSON.stringify(response)); return; } + if (req.url === `/api/v1/tts/jobs/${id}/cancel` && req.method === 'POST') { + const current = [...jobs.values()][0]; + if (current?.status === 'success') { + res.writeHead(409).end(JSON.stringify({ error: { code: 'job_already_completed' } })); return; + } + const stopped = job('cancelled', { requestId: current.requestId }); + jobs.set(current.requestId, stopped); + res.end(JSON.stringify(stopped)); return; + } res.writeHead(404).end(JSON.stringify({ error: { code: 'unexpected_route', retryable: false } })); } catch (error) { res.writeHead(500).end(JSON.stringify({ error: { code: 'fixture_error', retryable: false } })); @@ -68,19 +79,35 @@ async function setup(t, { queued = false, noKey = false, audio = wav, onCreate, server.listen(0, '127.0.0.1'); await once(server, 'listening'); baseUrl = 'http://127.0.0.1:' + server.address().port; - const client = new Client({ name: 'test', version: '1.0.0' }); + const launchArgs = []; + if (noHardLinks) { + const preload = path.join(scratch, path.basename(directory) + '-no-links.mjs'); + await writeFile(preload, `import fs from 'node:fs/promises'; +import { syncBuiltinESMExports } from 'node:module'; +fs.link = async () => { throw Object.assign(new Error('Hard links unavailable'), { code: 'ENOTSUP' }); }; +syncBuiltinESMExports(); +`); + t.after(() => rm(preload, { force: true })); + launchArgs.push('--import', preload); + } + const clients = []; t.after(async () => { - await client.close(); + await Promise.all(clients.map(client => client.close())); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await rm(directory, { recursive: true, force: true }); assert.deepEqual(fixtureErrors, []); }); - await client.connect(new StdioClientTransport({ - command: process.execPath, args: [path.join(packageRoot, 'dist/index.js')], - env: { FLOWSPEECH_API_KEY: noKey ? '' : apiKey, FLOWSPEECH_BASE_URL: baseUrl, FLOWSPEECH_OUTPUT_DIR: directory }, - })); - return { client, directory, requests, jobs, events, baseUrl }; + async function connect() { + const client = new Client({ name: 'test', version: '1.0.0' }); + clients.push(client); + await client.connect(new StdioClientTransport({ + command: process.execPath, args: [...launchArgs, path.join(packageRoot, 'dist/index.js')], + env: { FLOWSPEECH_API_KEY: noKey ? '' : apiKey, FLOWSPEECH_BASE_URL: baseUrl, FLOWSPEECH_OUTPUT_DIR: directory }, + })); + return client; + } + return { client: await connect(), connect, directory, requests, jobs, events, baseUrl }; } const call = (client, name, args = {}, options) => client.callTool({ name, arguments: args }, undefined, options); const content = response => response.content[0].text; @@ -89,7 +116,7 @@ test('read-only tool error output excludes reflected credentials', async t => { const { client } = await setup(t, { reflectedError: true, apiKey: 'fake_test_key' }); for (const [name, args] of [ ['flowspeech_quota', {}], ['flowspeech_list_voices', {}], - ['flowspeech_get_job', { jobId: id }], + ['flowspeech_get_job', { job_id: id }], ['flowspeech_cancel_job', { job_id: id }], ]) { const response = await call(client, name, args); assert.equal(response.isError, true); @@ -97,15 +124,22 @@ test('read-only tool error output excludes reflected credentials', async t => { } }); -test('six strict tool schemas retain the existing names and require generation UUIDs', async t => { +test('seven tool schemas retain the existing names and advertise one-call generation and speech cues', async t => { const { client } = await setup(t); + const manifest = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')); + assert.equal(client.getServerVersion().version, manifest.version); const tools = (await client.listTools()).tools; assert.deepEqual(tools.map(tool => tool.name), [ - 'flowspeech_tts', 'flowspeech_tts_multi', 'flowspeech_list_voices', 'flowspeech_quota', 'flowspeech_get_job', 'flowspeech_new_request_id', + 'flowspeech_tts', 'flowspeech_tts_multi', 'flowspeech_list_voices', 'flowspeech_quota', 'flowspeech_get_job', 'flowspeech_cancel_job', 'flowspeech_new_request_id', ]); for (const tool of tools) assert.equal(tool.inputSchema.additionalProperties, false); + assert.deepEqual(tools[0].inputSchema.required, ['text']); + assert.deepEqual(tools[1].inputSchema.oneOf.map(branch => branch.required), [['segments'], ['text', 'speakers'], ['text']]); for (const name of ['flowspeech_tts', 'flowspeech_tts_multi']) { - assert.deepEqual(tools.find(tool => tool.name === name).inputSchema.required, ['text', 'request_id']); + const tool = tools.find(tool => tool.name === name); + assert.match(tool.description, /\[excited\].*\[pause:1\.0s\]/); + assert.match(tool.inputSchema.properties.text.description, /\[excited\].*\[pause:1\.0s\]/); + assert.equal(tool.inputSchema.properties.request_id.format, 'uuid'); } }); test('fresh caller UUIDs are local and require no API key', async t => { @@ -137,6 +171,52 @@ test('single stdio generation saves a valid private WAV and preserves recovery i assert.equal(JSON.parse(content(byJob)).requestId, generated); assert.equal(requests.filter(request => request.method === 'POST').length, 1); }); +test('one-call generation creates a UUID and forwards emotion and pause syntax', async t => { + const { client, requests } = await setup(t); + const text = '[excited] Welcome! [pause:1.0s] Let’s begin.'; + const response = await call(client, 'flowspeech_tts', { text }); + assert.ok(!response.isError, content(response)); + const [submitted] = requests; + assert.match(submitted.key, /^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + assert.ok(content(response).includes(`Request ID: ${submitted.key}`)); + assert.equal(JSON.parse(submitted.body).input.text, text); +}); +test('one-call retry after timeout and a new stdio process reuses the accepted request', { timeout: 5000 }, async t => { + const { client, connect, requests, jobs, directory, baseUrl } = await setup(t, { queued: true }); + const args = { text: 'Hello' }; + await assert.rejects(call(client, 'flowspeech_tts', args, { timeout: 500 }), /Request timed out/); + assert.equal(requests.length, 1); + const [{ key }] = requests; + assert.equal(jobs.get(key).status, 'queued'); + await client.close(); + jobs.set(key, job('success', { requestId: key, result: { ...job().result, url: baseUrl + '/audio.wav' } })); + const restarted = await connect(); + const recovered = await call(restarted, 'flowspeech_tts', args); + assert.ok(!recovered.isError, content(recovered)); + assert.match(content(recovered), new RegExp('Request ID: ' + key)); + assert.deepEqual(await readFile(path.join(directory, `flowspeech-${id}.wav`)), wav); + assert.deepEqual(requests.filter(r => r.method === 'POST').map(r => r.key), [key, key]); + assert.equal(jobs.size, 1); +}); +test('replaying to an existing path only reads the job and checks WAV content', async t => { + const { client, directory, requests } = await setup(t); + const output_path = path.join(directory, 'example.wav'); + const args = { text: 'Hello', output_path }; + const created = await call(client, 'flowspeech_tts', args); + const replayed = await call(client, 'flowspeech_tts', args); + assert.ok(!created.isError && !replayed.isError, content(replayed)); + assert.equal(content(replayed), content(created)); + assert.equal(requests.filter(r => r.method === 'POST').length, 1); + assert.ok(requests.some(r => r.path.includes('?requestId='))); + await writeFile(output_path, Buffer.alloc(wav.length)); + assert.equal((await call(client, 'flowspeech_tts', args)).isError, true); + assert.deepEqual(await readFile(output_path), Buffer.alloc(wav.length)); + assert.equal((await call(client, 'flowspeech_tts', { ...args, text: 'Unrelated' })).isError, true); + assert.equal(requests.filter(r => r.method === 'POST').length, 1); + const fresh = await call(client, 'flowspeech_tts', { text: args.text, request_id: requestId, output_path: path.join(directory, 'fresh.wav') }); + assert.ok(!fresh.isError, content(fresh)); + assert.equal(requests.filter(r => r.method === 'POST').at(-1).key, requestId); +}); test('multi stdio generation maps labelled speaker turns', async t => { const { client, requests } = await setup(t); const response = await call(client, 'flowspeech_tts_multi', { text: 'Speaker1: Hello\nSpeaker2: Hi', request_id: requestId }); @@ -145,24 +225,48 @@ test('multi stdio generation maps labelled speaker turns', async t => { { speaker: 'Speaker1', text: 'Hello', voiceName: 'Charon' }, { speaker: 'Speaker2', text: 'Hi', voiceName: 'Kore' }, ] } }); }); +test('multi stdio supports three named speakers and structured turns without a request ID', async t => { + const { client, directory, requests } = await setup(t); + const segments = [ + { speaker: 'Host', text: '[excited] Welcome! [pause:1.0s] Let’s begin.', voiceName: 'Charon' }, + { speaker: 'Guest', text: '[calmly] Thanks.\n[pause:1.0s] I’m glad to be here.\nAt 8:00 we go live.', voiceName: 'Kore' }, + { speaker: 'Producer', text: 'We are recording.', voiceName: 'Puck' }, + ]; + const text = segments.map(turn => `${turn.speaker}: ${turn.text}`).join('\n'); + const speakers = Object.fromEntries(segments.map(turn => [turn.speaker, turn.voiceName])); + for (const [index, args] of [{ text, speakers }, { segments }].entries()) { + const response = await call(client, 'flowspeech_tts_multi', { ...args, output_path: path.join(directory, `${index}.wav`) }); + assert.ok(!response.isError, content(response)); + } + const submitted = requests.filter(request => request.method === 'POST'); + assert.equal(submitted.length, 2); + for (const request of submitted) assert.deepEqual(JSON.parse(request.body), { input: { mode: 'multi', segments } }); + assert.equal(submitted[0].key, submitted[1].key); +}); test('all invalid generation argument types and unsupported fields fail before network', async t => { const { client, directory, requests } = await setup(t); const invalid = [ - { text: 'Hello' }, { text: 'Hello', request_id: null }, { text: 'Hello', request_id: 42 }, + {}, { text: 'Hello', request_id: null }, { text: 'Hello', request_id: 42 }, { text: 42, request_id: requestId }, { text: ' ', request_id: requestId }, { text: 'Hello', request_id: requestId, voice: null }, { text: 'Hello', request_id: requestId, voice: 42 }, ...[42, null, [], {}, '', ' ', 'bad\0file.wav', directory + path.sep].map(output_path => ({ text: 'Hello', request_id: requestId, output_path })), ...['model', 'source', 'speed', 'format', 'originalText', 'speakers', 'voice_a'].map(key => ({ text: 'Hello', request_id: requestId, [key]: 'unsupported' })), + ...[null, 1, 'true'].map(overwrite => ({ text: 'Hello', overwrite })), ]; for (const args of invalid) { const response = await call(client, 'flowspeech_tts', args); assert.equal(response.isError, true, JSON.stringify(args)); } for (const args of [ - { text: 'Speaker1: Hi' }, { text: 'Speaker1: Hi', request_id: requestId, voice_a: null }, + {}, { text: 'Speaker1: Hi', request_id: requestId, voice_a: null }, { text: 'Speaker1: Hi', request_id: requestId, voice_b: [] }, { text: 'Speaker1: Hi', request_id: requestId, output_path: 42 }, { text: 'Speaker1: Hi', request_id: requestId, speed: 2 }, + { text: 'Unknown: Hello\nHost: Hi', speakers: { Host: 'Kore' } }, { text: 'Host: Hi', speakers: [] }, + { text: 'Host: Hi', speakers: { Host: 'Kore' }, voice_a: 'Charon' }, + { segments: null }, { segments: [] }, { text: 'Speaker1: Hi', segments: [] }, + { segments: [{ speaker: 'Host', text: 'Hi' }] }, + { segments: [{ speaker: 'Host', text: 'Hi', voiceName: 'Kore' }, { speaker: 'Host', text: 'Hello', voiceName: 'Charon' }] }, ]) assert.equal((await call(client, 'flowspeech_tts_multi', args)).isError, true); assert.deepEqual(requests, []); assert.deepEqual(await readdir(directory), []); @@ -189,14 +293,71 @@ test('atomic no-overwrite failure after submission retains both IDs', async t => assert.equal(await readFile(path.join(directory, 'race.wav'), 'utf8'), 'preserve'); assert.equal(requests.filter(request => request.method === 'POST').length, 1); }); +test('exclusive copy saves without hard links and preserves a file created during generation', async t => { + const { client, directory } = await setup(t, { + noHardLinks: true, + onCreate: async ({ input }, dir) => { + if (input.text === 'Race') await writeFile(path.join(dir, 'race.wav'), 'preserve'); + }, + }); + const output_path = path.join(directory, 'example.wav'); + const response = await call(client, 'flowspeech_tts', { text: 'Hello', output_path }); + assert.ok(!response.isError, content(response)); + assert.deepEqual(await readFile(output_path), wav); + assert.equal((await stat(output_path)).mode & 0o777, 0o600); + const raced = path.join(directory, 'race.wav'); + const failure = await call(client, 'flowspeech_tts', { text: 'Race', output_path: raced }); + assert.equal(failure.isError, true); + assert.equal(await readFile(raced, 'utf8'), 'preserve'); + assert.deepEqual((await readdir(directory)).sort(), ['example.wav', 'race.wav']); +}); +test('explicit overwrite replaces only a regular file with a complete private WAV', async t => { + const { client, directory, requests } = await setup(t); + const existing = path.join(directory, 'existing.wav'); + const symbolic = path.join(directory, 'alias.wav'); + await writeFile(existing, 'preserve', { mode: 0o644 }); + await symlink(existing, symbolic); + const args = { text: 'Hello', overwrite: true }; + for (const output_path of [symbolic, directory]) { + assert.equal((await call(client, 'flowspeech_tts', { ...args, output_path })).isError, true); + } + assert.deepEqual(requests, []); + assert.equal(await readFile(existing, 'utf8'), 'preserve'); + const response = await call(client, 'flowspeech_tts', { ...args, output_path: existing }); + assert.ok(!response.isError, content(response)); + assert.deepEqual(await readFile(existing), wav); + assert.equal((await stat(existing)).mode & 0o777, 0o600); + assert.deepEqual((await readdir(directory)).sort(), ['alias.wav', 'existing.wav']); +}); test('header-only WAV is not saved by stdio', async t => { const { client, directory, requests } = await setup(t, { audio: Buffer.from('RIFF\x04\0\0\0WAVE') }); - const response = await call(client, 'flowspeech_tts', { text: 'Hello', request_id: requestId }); + const existing = path.join(directory, 'existing.wav'); + await writeFile(existing, 'preserve'); + const response = await call(client, 'flowspeech_tts', { text: 'Hello', overwrite: true, output_path: existing }); assert.equal(response.isError, true); assert.match(content(response), /PCM WAV/); - assert.deepEqual(await readdir(directory), []); + assert.ok(content(response).includes(`requestId=${requests[0].key}`)); + assert.ok(content(response).includes(`jobId=${id}`)); + assert.equal(await readFile(existing, 'utf8'), 'preserve'); + assert.deepEqual(await readdir(directory), ['existing.wav']); assert.equal(requests.filter(request => request.method === 'POST').length, 1); }); +test('cancellation tool stops a queued job and preserves a completed job', async t => { + const { client, jobs, requests } = await setup(t); + for (const args of [{}, { job_id: id, request_id: requestId }, { job_id: 'invalid' }]) { + assert.equal((await call(client, 'flowspeech_cancel_job', args)).isError, true); + } + assert.deepEqual(requests, []); + jobs.set(requestId, job('queued')); + const cancelled = await call(client, 'flowspeech_cancel_job', { job_id: id.toUpperCase() }); + assert.equal(JSON.parse(content(cancelled)).status, 'cancelled'); + assert.equal(jobs.get(requestId).status, 'cancelled'); + jobs.set(requestId, job()); + const completed = await call(client, 'flowspeech_cancel_job', { job_id: id }); + assert.match(content(completed), /HTTP 409: job_already_completed/); + assert.equal(jobs.get(requestId).status, 'success'); + assert.ok(requests.every(request => request.path.endsWith('/cancel') && request.method === 'POST' && !request.body && !request.key)); +}); test('read-only tools and UUID tool reject unknown arguments before network', async t => { const { client, requests } = await setup(t); for (const [name, args] of [