Skip to main content
Glama
mberg

Kokoro Text to Speech MCP Server

by mberg

text_to_speech

Convert text to speech using Kokoro TTS technology, generating MP3 audio files with customizable voice, speed, and language settings.

Instructions

    Convert text to speech using the Kokoro TTS service.
    
    Args:
        text: The text to convert to speech
        voice: Voice ID to use (default: af_heart)
        speed: Speech speed (default: 1.0)
        lang: Language code (default: en-us)
        filename: Optional filename for the MP3 (default: auto-generated UUID)
        upload_to_s3: Whether to upload to S3 if enabled (default: True)
        
    Returns:
        A dictionary with information about the generated audio file
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYes
voiceNoen_sarah
speedNo
langNoen-us
filenameNo
upload_to_s3No

Implementation Reference

  • The MCP tool handler for 'text_to_speech', registered via @mcp.tool() decorator. It prepares request data from arguments and delegates to the server's process_tts_request method for execution.
    @mcp.tool()
    async def text_to_speech(text: str, voice: str = os.environ.get('TTS_VOICE', 'af_heart'), 
                            speed: float = float(os.environ.get('TTS_SPEED', 1.0)), 
                            lang: str = os.environ.get('TTS_LANGUAGE', 'en-us'),
                            filename: str = None,
                            upload_to_s3: bool = os.environ.get('S3_ENABLED', 'true').lower() == 'true') -> dict:
        """
        Convert text to speech using the Kokoro TTS service.
        
        Args:
            text: The text to convert to speech
            voice: Voice ID to use (default: af_heart)
            speed: Speech speed (default: 1.0)
            lang: Language code (default: en-us)
            filename: Optional filename for the MP3 (default: auto-generated UUID)
            upload_to_s3: Whether to upload to S3 if enabled (default: True)
            
        Returns:
            A dictionary with information about the generated audio file
        """
        request_data = {
            "text": text,
            "voice": voice,
            "speed": speed,
            "lang": lang,
            "filename": filename,
            "upload_to_s3": upload_to_s3
        }
        
        return await mcp_tts_server.process_tts_request(request_data)
  • mcp-tts.py:495-495 (registration)
    Registration of the 'text_to_speech' tool using the FastMCP @tool() decorator.
    @mcp.tool()
  • Helper method in MCPTTSServer class that implements the core TTS logic: parameter extraction, audio generation with Kokoro TTS, local file saving, optional S3 upload, and response formatting.
    async def process_tts_request(self, request_data):
        """Process a TTS request and return a JSON response."""
        try:
            if not TTS_AVAILABLE:
                return {
                    "success": False,
                    "error": "TTS service is not available. Missing required modules."
                }
                
            text = request_data.get('text', '')
            voice = request_data.get('voice', os.environ.get('TTS_VOICE', 'af_heart'))
            speed = float(request_data.get('speed', 1.0))
            lang = request_data.get('lang', 'en-us')
            filename = request_data.get('filename', None)
            upload_to_s3_flag = request_data.get('upload_to_s3', True)
            
            if not text:
                return {"success": False, "error": "No text provided"}
            
            if not filename:
                filename = str(uuid.uuid4())
            
            if not filename.endswith('.mp3'):
                filename += '.mp3'
                
            filename = secure_filename(filename)
            os.makedirs(MP3_FOLDER, exist_ok=True)
            mp3_path = os.path.join(MP3_FOLDER, filename)
            mp3_filename = os.path.basename(mp3_path)
            
            print(f"Generating audio for: {text[:50]}{'...' if len(text) > 50 else ''}")
            print(f"Using voice: {voice}, speed: {speed}, language: {lang}")
            print(f"Output file: {mp3_path}")
            
            loop = asyncio.get_running_loop()
            
            try:
                # Attempt primary parameter format
                result = await loop.run_in_executor(
                    None, 
                    lambda: tts_service.generate_audio(
                        text=text, 
                        output_file=mp3_path, 
                        voice=voice,
                        speed=speed,
                        lang=lang
                    )
                )
                
                if isinstance(result, dict) and not result.get('success', True):
                    print(f"TTS service returned an error: {result}")  # Log the result for debugging
                    return {
                        "success": False,
                        "error": result.get('error', 'Unknown TTS generation error'),
                        "tts_result": result,  # Include full TTS service response
                        "request_params": {
                            "text": text,
                            "voice": voice,
                            "speed": speed,
                            "lang": lang,
                            "filename": filename
                        },
                        "timestamp": datetime.datetime.now().isoformat()
                    }
                    
            except TypeError as e:
                print(f"TypeError in TTS service call: {e}")
                print("Trying alternative parameter format...")
                result = await loop.run_in_executor(
                    None, 
                    lambda: tts_service.generate_audio(
                        text, 
                        mp3_path, 
                        voice=voice,
                        speed=speed
                    )
                )
            
            if not os.path.exists(mp3_path):
                return {
                    "success": False,
                    "error": "Failed to generate audio file"
                }
                
            file_size = os.path.getsize(mp3_path)
            print(f"Audio generated successfully. File size: {file_size} bytes")
            
            response_data = {
                "success": True,
                "message": "Audio generated successfully",
                "filename": mp3_filename,
                "file_size": file_size,
                "path": mp3_path,
                "s3_uploaded": False
            }
            
            if upload_to_s3_flag:
                print(f"Uploading {mp3_filename} to S3...")
                s3_url = self.upload_to_s3(mp3_path, mp3_filename)
                if s3_url:
                    response_data["s3_uploaded"] = True
                    response_data["s3_url"] = s3_url
                    
                    # Delete local file if configured to do so
                    if os.environ.get('DELETE_LOCAL_AFTER_S3_UPLOAD', '').lower() in ('true', '1', 'yes'):
                        try:
                            print(f"Removing local file {mp3_path} after successful S3 upload")
                            os.remove(mp3_path)
                            response_data["local_file_kept"] = False
                        except Exception as e:
                            print(f"Error removing local file after S3 upload: {e}")
                            response_data["local_file_kept"] = True
                    else:
                        response_data["local_file_kept"] = True
                else:
                    response_data["s3_uploaded"] = False
                    response_data["s3_error"] = "S3 upload failed"
            
            return response_data
            
        except Exception as e:
            print(f"Error processing TTS request: {str(e)}")
            import traceback
            traceback.print_exc()
            return {
                "success": False,
                "error": str(e)
            }
  • Input schema defined by function parameters with type hints and defaults, plus detailed docstring describing args and return type.
    async def text_to_speech(text: str, voice: str = os.environ.get('TTS_VOICE', 'af_heart'), 
                            speed: float = float(os.environ.get('TTS_SPEED', 1.0)), 
                            lang: str = os.environ.get('TTS_LANGUAGE', 'en-us'),
                            filename: str = None,
                            upload_to_s3: bool = os.environ.get('S3_ENABLED', 'true').lower() == 'true') -> dict:
        """
        Convert text to speech using the Kokoro TTS service.
        
        Args:
            text: The text to convert to speech
            voice: Voice ID to use (default: af_heart)
            speed: Speech speed (default: 1.0)
            lang: Language code (default: en-us)
            filename: Optional filename for the MP3 (default: auto-generated UUID)
            upload_to_s3: Whether to upload to S3 if enabled (default: True)
            
        Returns:
            A dictionary with information about the generated audio file
        """
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions that the output is an MP3 file and that upload to S3 is optional, which adds some context. However, it doesn't cover important aspects like rate limits, authentication requirements, error conditions, or what the returned dictionary contains. For a tool with 6 parameters and no annotation coverage, this is insufficient.

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 well-structured and appropriately sized. It starts with the core purpose, then lists parameters with clear explanations, and ends with return information. Every sentence earns its place, though the formatting with 'Args:' and 'Returns:' sections is slightly verbose but still efficient.

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

Completeness3/5

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

Given the tool's complexity (6 parameters, no annotations, no output schema), the description is moderately complete. It excels at parameter documentation but lacks behavioral context and usage guidelines. The absence of an output schema means the description should ideally explain the return dictionary structure, which it doesn't. It's adequate but has clear gaps.

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

Parameters5/5

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

The description provides excellent parameter semantics beyond the input schema. With 0% schema description coverage, the description fully compensates by explaining each parameter's purpose, default values, and optionality. It clarifies that 'filename' is auto-generated if not provided and that 'upload_to_s3' depends on whether S3 is enabled. This adds significant value over the bare schema.

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 using the Kokoro TTS service.' It specifies the verb ('convert') and resource ('text to speech'), and mentions the specific service. However, without sibling tools, it cannot demonstrate differentiation from alternatives, so it doesn't reach the highest 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 any prerequisites, constraints, or typical use cases. The only contextual information is the service name (Kokoro TTS), but this doesn't help an agent decide when this tool is appropriate.

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

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/mberg/kokoro-tts-mcp'

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