Skip to main content
Glama
tijs

MCP Sound Tool

by tijs

play_sound

Play audio feedback sounds to indicate task completion, errors, or notifications, providing non-visual status indicators for operations in MCP-compatible environments.

Instructions

    Play a notification sound on the user's device.
    
    WHEN TO USE THIS TOOL:
    - Use 'completion' sound when a task or command has SUCCESSFULLY completed
    - Use 'error' sound when a command has FAILED or an error has occurred
    - Use 'notification' sound for important alerts or information that needs attention
    - Use 'custom' sound only when you need a specific sound not covered by the standard types
    
    AI agents SHOULD proactively use these sounds to provide audio feedback based on
    the outcome of commands or operations, enhancing the user experience with
    non-visual status indicators.
    
    Example usage: After executing a terminal command, play a 'completion' sound if 
    successful or an 'error' sound if it failed.
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sound_typeNocompletion
custom_sound_pathNo

Implementation Reference

  • MCP tool handler for 'play_sound': selects appropriate sound file based on sound_type or custom path, plays it using SoundPlayer, returns success/error message.
    @self.mcp.tool(description="""
    Play a notification sound on the user's device.
    
    WHEN TO USE THIS TOOL:
    - Use 'completion' sound when a task or command has SUCCESSFULLY completed
    - Use 'error' sound when a command has FAILED or an error has occurred
    - Use 'notification' sound for important alerts or information that needs attention
    - Use 'custom' sound only when you need a specific sound not covered by the standard types
    
    AI agents SHOULD proactively use these sounds to provide audio feedback based on
    the outcome of commands or operations, enhancing the user experience with
    non-visual status indicators.
    
    Example usage: After executing a terminal command, play a 'completion' sound if 
    successful or an 'error' sound if it failed.
    """)
    def play_sound(sound_type: Literal["completion", "error", "notification", "custom"] = "completion",
               custom_sound_path: Optional[str] = None) -> str:
        if sound_type == "custom" and custom_sound_path:
            sound_path = custom_sound_path
        else:
            # Try MP3 file first, then WAV if MP3 doesn't exist
            mp3_filename = f"{sound_type}.mp3"
            wav_filename = f"{sound_type}.wav"
            mp3_path = os.path.join(self.sounds_dir, mp3_filename)
            wav_path = os.path.join(self.sounds_dir, wav_filename)
            
            # Check which file exists
            if os.path.exists(mp3_path):
                sound_path = mp3_path
            elif os.path.exists(wav_path):
                sound_path = wav_path
            else:
                # Print debug information
                print(f"Sounds directory: {self.sounds_dir}")
                print(f"Sound files available: {os.listdir(self.sounds_dir)}")
                return f"Error: Sound files not found: {mp3_path} or {wav_path}"
        
        # Play the sound
        try:
            self.player.play_sound(sound_path)
            return f"Successfully played {sound_type} sound"
        except Exception as e:
            return f"Error playing sound: {e}"
  • Platform-agnostic helper method to play sound files using native system commands (afplay on macOS, winsound on Windows, various players on Linux). Called by the play_sound handler.
    def play_sound(sound_file: str) -> None:
        """Play a sound file using the appropriate method for the current platform."""
        if not os.path.exists(sound_file):
            print(f"Error: Sound file not found: {sound_file}")
            return
        
        system = platform.system()
        
        try:
            if system == "Darwin":  # macOS
                subprocess.run(["afplay", sound_file], check=True)
            elif system == "Windows":
                import winsound
                winsound.PlaySound(sound_file, winsound.SND_FILENAME)
            elif system == "Linux":
                # Try different players until one works
                for player in ["paplay", "aplay", "mpg123", "mpg321"]:
                    try:
                        subprocess.run([player, sound_file], check=True)
                        break
                    except (subprocess.SubprocessError, FileNotFoundError):
                        continue
                else:
                    print("Error: Could not find a suitable audio player on Linux")
        except Exception as e:
            print(f"Error playing sound: {e}")
  • JSON schema defining the input parameters, description, and return type for the play_sound tool.
    play_sound_tool_definition = {
        "name": "play_sound",
        "description": """
        Play a notification sound on the user's device.
        
        Use this tool to provide audio feedback to the user:
        - Use 'completion' when a task or command has successfully completed
        - Use 'error' when an error or failure has occurred
        - Use 'notification' for important information or alerts
        - Use 'custom' when you need to play a specific sound file
        
        AI agents should proactively use these sounds to improve user experience by
        providing audio cues for important events.
        """,
        "parameters": {
            "type": "object",
            "properties": {
                "sound_type": {
                    "type": "string",
                    "enum": ["completion", "error", "notification", "custom"],
                    "description": "The type of sound to play. Default is 'completion'."
                },
                "custom_sound_path": {
                    "type": "string",
                    "description": "Path to a custom sound file (only used if sound_type is 'custom')."
                }
            },
            "required": []
        },
        "returns": {
            "type": "string",
            "description": "A message indicating the result of the operation"
        }
    }
  • Method that registers the play_sound tool (and others) using the @mcp.tool decorator during server initialization.
        # Print initialization message
        print(f"Sound Tool MCP server initialized - use sounds to provide audio feedback on command outcomes")
    
    def copy_sounds_to_user_dir(self):
        """Copy bundled sounds to user config directory."""
        user_sounds_dir = os.path.join(os.path.expanduser("~"), ".config", "mcp-sound-tool", "sounds")
        os.makedirs(user_sounds_dir, exist_ok=True)
        
        # Get list of sound files
        try:
            # Try with Python 3.9+ method
            sound_files = resources.files("sound_tool").joinpath("sounds").iterdir()
            for sound_file in sound_files:
                if sound_file.name.endswith((".mp3", ".wav")):
                    shutil.copy(sound_file, os.path.join(user_sounds_dir, sound_file.name))
        except (AttributeError, ImportError):
            # Fallback for older Python
            sounds_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sounds")
            if os.path.exists(sounds_dir):
                for sound_file in os.listdir(sounds_dir):
                    if sound_file.endswith((".mp3", ".wav")):
                        shutil.copy(
                            os.path.join(sounds_dir, sound_file), 
                            os.path.join(user_sounds_dir, sound_file)
                        )
        
        return user_sounds_dir
        
    def register_tools(self):

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/tijs/py-sound-mcp'

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