Skip to main content
Glama

synthesize_speech

Convert text to audio using customizable voice, speed, emotion, and pacing for expressive and professional speech synthesis in multiple formats.

Instructions

Convert text to speech with advanced voice controls and natural expression

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
emotionNoVoice emotionneutral
filenameNoCustom filename for saved audio
outputFormatNoAudio output formatwav
pacingNoSpeech pacing stylenatural
saveFileNoSave audio to file
speedNoSpeech speed (0.25-3.0)
textYesText to convert to speech
voiceIdNoVoice to use for synthesisaf_heart
volumeNoAudio volume (0.1-2.0)

Implementation Reference

  • Main handler function for synthesize_speech tool. Validates inputs, enhances text for natural speech, calculates adjusted speed, and orchestrates native TTS synthesis.
    async synthesizeSpeech(params: {
      text: string;
      voiceId?: string;
      speed?: number;
      emotion?: keyof typeof VoiceEmotions;
      pacing?: keyof typeof PacingStyles;
      volume?: number;
      outputFormat?: string;
      saveFile?: boolean;
      filename?: string;
    }) {
      const {
        text,
        voiceId = this.config.defaultVoice,
        speed = this.config.defaultSpeed,
        emotion = this.config.defaultEmotion as keyof typeof VoiceEmotions,
        pacing = this.config.defaultPacing as keyof typeof PacingStyles,
        volume = 1.0,
        outputFormat = 'wav',
        saveFile = this.config.enableFileOutput,
        filename
      } = params;
    
      // Ensure TTS engine is initialized
      await this.ensureInitialized();
    
      // Input validation and sanitization
      if (!text || typeof text !== 'string') {
        throw new Error('Text must be a non-empty string');
      }
    
      if (text.length > this.config.maxTextLength) {
        throw new Error(`Text length (${text.length}) exceeds maximum allowed (${this.config.maxTextLength})`);
      }
    
      // Validate voice ID
      if (voiceId && !Object.keys(AvailableVoices).includes(voiceId)) {
        throw new Error(`Invalid voice ID: ${voiceId}`);
      }
    
      // Validate speed range
      if (speed < 0.25 || speed > 3.0) {
        throw new Error(`Speed ${speed} out of range (0.25-3.0)`);
      }
    
      // Validate volume range
      if (volume < 0.1 || volume > 2.0) {
        throw new Error(`Volume ${volume} out of range (0.1-2.0)`);
      }
    
      // Validate output format
      if (!AudioFormats.includes(outputFormat as any)) {
        throw new Error(`Unsupported output format: ${outputFormat}`);
      }
    
      // Sanitize text input
      const sanitizedText = text
        .replace(/[<>]/g, '') // Remove HTML-like tags
        .replace(/[\x00-\x1F\x7F]/g, '') // Remove control characters
        .trim();
    
      if (!sanitizedText) {
        throw new Error('Text is empty after sanitization');
      }
    
      // Enhance text for natural speech
      const enhancedText = this.enhanceTextForSpeech(sanitizedText, emotion, pacing);
      
      // Calculate final speed
      const finalSpeed = this.calculateFinalSpeed(speed, emotion, pacing);
    
      // Synthesize using native TypeScript TTS engine
      const result = await this.synthesizeWithNativeTTS(
        enhancedText,
        voiceId,
        finalSpeed,
        emotion,
        pacing,
        volume,
        outputFormat,
        saveFile,
        filename
      );
    
      if (result.success) {
        this.activeRequests.set(result.requestId, {
          status: 'completed',
          result
        });
    
        return {
          success: true,
          requestId: result.requestId,
          duration: result.duration,
          voiceUsed: voiceId,
          speedUsed: finalSpeed,
          emotion,
          pacing,
          outputFormat,
          filePath: saveFile ? result.audioPath : undefined,
          message: `Successfully synthesized ${text.length} characters with ${voiceId} voice`
        };
      } else {
        throw new Error(result.error || 'Synthesis failed');
      }
    }
  • Tool registration in MCP ListTools handler defining name, description, and input schema.
    {
      name: 'synthesize_speech',
      description: 'Convert text to speech with advanced voice controls and natural expression',
      inputSchema: {
        type: 'object',
        properties: {
          text: {
            type: 'string',
            description: 'Text to convert to speech',
            maxLength: config.maxTextLength,
          },
          voiceId: {
            type: 'string',
            description: 'Voice to use for synthesis',
            enum: Object.keys(AvailableVoices),
            default: config.defaultVoice,
          },
          speed: {
            type: 'number',
            description: 'Speech speed (0.25-3.0)',
            minimum: 0.25,
            maximum: 3.0,
            default: config.defaultSpeed,
          },
          emotion: {
            type: 'string',
            description: 'Voice emotion',
            enum: Object.keys(VoiceEmotions),
            default: config.defaultEmotion,
          },
          pacing: {
            type: 'string',
            description: 'Speech pacing style',
            enum: Object.keys(PacingStyles),
            default: config.defaultPacing,
          },
          volume: {
            type: 'number',
            description: 'Audio volume (0.1-2.0)',
            minimum: 0.1,
            maximum: 2.0,
            default: 1.0,
          },
          outputFormat: {
            type: 'string',
            description: 'Audio output format',
            enum: [...AudioFormats],
            default: 'wav',
          },
          saveFile: {
            type: 'boolean',
            description: 'Save audio to file',
            default: config.enableFileOutput,
          },
          filename: {
            type: 'string',
            description: 'Custom filename for saved audio',
          },
        },
        required: ['text'],
      },
    },
  • MCP CallToolRequestSchema handler case that receives tool call and invokes the synthesizeSpeech implementation.
    case 'synthesize_speech':
      const result = await ttsServer.synthesizeSpeech(args as any);
      return {
        content: [
          {
            type: 'text',
            text: `🎙️ **TTS Synthesis Complete**\n\n` +
                 `**Request ID:** ${result.requestId}\n` +
                 `**Voice:** ${result.voiceUsed} (${AvailableVoices[result.voiceUsed as keyof typeof AvailableVoices]?.name})\n` +
                 `**Duration:** ${result.duration?.toFixed(2)}s\n` +
                 `**Speed:** ${result.speedUsed?.toFixed(2)}x\n` +
                 `**Emotion:** ${result.emotion}\n` +
                 `**Pacing:** ${result.pacing}\n` +
                 `**Format:** ${result.outputFormat.toUpperCase()}\n` +
                 `${result.filePath ? `**File:** ${result.filePath}\n` : ''}` +
                 `\n${result.message}`,
          },
        ],
      };
  • JSON schema for synthesize_speech tool inputs including all parameters and validation rules.
    type: 'object',
    properties: {
      text: {
        type: 'string',
        description: 'Text to convert to speech',
        maxLength: config.maxTextLength,
      },
      voiceId: {
        type: 'string',
        description: 'Voice to use for synthesis',
        enum: Object.keys(AvailableVoices),
        default: config.defaultVoice,
      },
      speed: {
        type: 'number',
        description: 'Speech speed (0.25-3.0)',
        minimum: 0.25,
        maximum: 3.0,
        default: config.defaultSpeed,
      },
      emotion: {
        type: 'string',
        description: 'Voice emotion',
        enum: Object.keys(VoiceEmotions),
        default: config.defaultEmotion,
      },
      pacing: {
        type: 'string',
        description: 'Speech pacing style',
        enum: Object.keys(PacingStyles),
        default: config.defaultPacing,
      },
      volume: {
        type: 'number',
        description: 'Audio volume (0.1-2.0)',
        minimum: 0.1,
        maximum: 2.0,
        default: 1.0,
      },
      outputFormat: {
        type: 'string',
        description: 'Audio output format',
        enum: [...AudioFormats],
        default: 'wav',
      },
      saveFile: {
        type: 'boolean',
        description: 'Save audio to file',
        default: config.enableFileOutput,
      },
      filename: {
        type: 'string',
        description: 'Custom filename for saved audio',
      },
    },
    required: ['text'],
  • NativeTTSEngine.synthesizeText - Low-level TTS synthesis called by main handler to produce raw audio data.
    async synthesizeText(
      text: string,
      voiceConfig: VoiceConfig,
      outputFormat: string = 'wav'
    ): Promise<SynthesisResult> {
      const requestId = randomUUID();
    
      try {
        await this.initialize();
    
        // Validate inputs
        if (!text || text.length === 0) {
          throw new Error('Text cannot be empty');
        }
    
        if (text.length > 50000) {
          throw new Error(`Text too long: ${text.length} characters (max 50000)`);
        }
    
        // Simulate neural TTS synthesis
        const audioSegment = await this.generateAudioSegment(text, voiceConfig);
        
        return {
          success: true,
          audioSegment,
          requestId
        };
    
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error),
          requestId
        };
      }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Convert text to speech' implies a creation/write operation, it doesn't address key behavioral aspects: whether this is a synchronous or asynchronous process, potential rate limits, authentication requirements, file storage implications when saveFile is true, or what happens on failure. The mention of 'advanced voice controls' is vague and doesn't provide concrete behavioral information.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that gets straight to the point. 'Convert text to speech' is front-loaded with the core function, followed by additional context. There's no wasted verbiage or redundancy. However, it could be slightly more structured by separating core function from additional capabilities.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 9 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (audio data? file path? success status?), doesn't address error conditions, and provides minimal behavioral context. The combination of complex parameters and lack of structured metadata requires a more comprehensive description to guide proper tool usage.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds minimal value beyond the input schema, which has 100% coverage. 'with advanced voice controls and natural expression' vaguely references the emotion, pacing, and voiceId parameters but doesn't provide additional semantic context. The schema already comprehensively documents all 9 parameters with descriptions, defaults, enums, and constraints, so the baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Convert text to speech' specifies the verb and resource. It adds 'with advanced voice controls and natural expression' which provides additional context about capabilities. However, it doesn't explicitly differentiate from sibling tools like batch_synthesize or get_voices, which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention batch_synthesize for multiple texts, get_voices for voice selection, or list_output_files for file management. There's no context about prerequisites, limitations, or appropriate use cases beyond the basic function.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/samihalawa/advanced-tts-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server