Skip to main content
Glama

send_notification

Send desktop notifications with optional sound alerts to notify users when AI agent tasks are completed, integrating with LLM clients like Claude Desktop and Cursor.

Instructions

Send system notification with optional sound

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
titleYes
messageYes
play_soundNo
timeoutNo

Implementation Reference

  • Registers the "send_notification" tool, providing its name, description, and input schema via the MCP server's list_tools decorator.
    @self.server.list_tools()
    async def list_tools() -> list[Tool]:
        """List available tools"""
        logger.debug("Listing tools.....")
        return [
            Tool(
                name="send_notification",
                description="Send system notification with optional sound",
                inputSchema=NotificationRequest.model_json_schema(),
            )
        ]
  • Pydantic model defining the input schema for the send_notification tool: title (str), message (str), play_sound (bool, default True), timeout (int, default 60).
    class NotificationRequest(BaseModel):
        """Request schema for sending a system notification
        
        title: str - Notification title
    
        message: str - Notification message
    
        play_sound: bool - Whether to play a sound
    
        timeout: int - Notification timeout in seconds
        """
        title: str
        message: str
        play_sound: bool = True
        timeout: int = 60  # seconds
  • MCP server call_tool handler that dispatches to send_notification: validates input using schema, calls _send_notification, and returns success/error response.
    @self.server.call_tool()
    async def call_tool(name: str, arguments: dict) -> list[TextContent]:
        """Call a tool
    
        name: str - Tool name
    
        arguments: dict - Tool arguments
        """
        logger.info(f"Calling tool: {name} with arguments: {arguments}")
        if name != "send_notification":
            return [TextContent(type="text", text="Invalid tool name")]
        try:
            logger.debug("Validating request...")
            req = NotificationRequest(**arguments)
            logger.debug("Sending notification...")
            self._send_notification(req)
            logger.info("Notification sent successfully")
            return [TextContent(type="text", text="Notification sent successfully")]
        except ValidationError as e:
            logger.error(f"Validation error: {str(e)}")
            return [TextContent(type="text", text=f"Invalid request: {str(e)}")]
        except Exception as e:
            logger.error(f"Error: {str(e)}")
            return [TextContent(type="text", text=f"Error: {str(e)}")]
  • Core implementation of send_notification: sends notification via Apprise (primary), plyer (fallback), console/log (last resort), and plays sound if requested.
    def _send_notification(self, request: NotificationRequest):
        logger.debug("request: %s", request)
        notification_sent = False
    
        # 尝试使用 Apprise 发送
        if self.apprise and len(self.apprise) > 0:
            try:
                logger.debug("尝试使用 Apprise 发送通知...")
                result = self.apprise.notify(title=request.title, body=request.message)
                if result:
                    logger.info("Apprise 通知发送成功")
                    notification_sent = True
                else:
                    logger.warning("Apprise 通知发送失败")
            except Exception as e:
                logger.error(f"Apprise 通知异常: {str(e)}")
    
        # 如果 Apprise 失败,尝试 plyer
        if not notification_sent:
            try:
                logger.debug("尝试使用 plyer 发送通知...")
                notification.notify(
                    title=request.title,
                    message=request.message,
                    timeout=request.timeout,
                    app_name="mcp-notification",
                )
                logger.info("plyer 通知发送成功")
                notification_sent = True
            except Exception as e:
                logger.error(f"plyer 通知失败: {str(e)}")
    
        # 如果两种方法都失败或在容器环境中,使用日志输出
        if not notification_sent or os.path.exists("/.dockerenv"):
            logger.info(f"通知:{request.title} - {request.message}")
            print(f"Notification: {request.title} - {request.message}")
    
        # 播放声音
        if request.play_sound:
            logger.debug("播放通知声音...")
            self.sound_player.play()
  • Cross-platform SoundPlayer utility used by the handler to play notification sounds, with platform-specific implementations and embedded WAV data.
    class SoundPlayer:
        # 这是一个简短的WAV格式"叮"声音的base64编码
        _DEFAULT_SOUND = """
        UklGRnQFAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YVAFAACAjYyLhoWHioyQlZyp
        tcDJ0dbd5+rs7erm3tfRyMG5sKeekIeBfHNrW0g6KRoQBvLj1se1pJR/Z043GAT27OfgzLSLYkMl
        BuzPsotqUSIMx6V+VTYVAdy0ilcxEwLZsoRNKxAJ78ulcD4hFR7+4L+ATC0cKTcvGQT03MLAqYFU
        PUBOTzQQ58Sjg2VMWGpjSiYR++fo5NW7mXBVRDE0NyIL8efn29CuimRPOhwbJiUN8ebg1MazmX1r
        YVlORDcpGQkB/P/9+O7hyLamlYd5Z1hJNyYWCf7s28vAuLO0tLS1tLW4vcPK0NXZ2dnY1dPQz87P
        0dPW2Nzg4+Xp6+3u7/Dx8vLz8/T19fb19PPy8vLy8vP09fb3+Pn6+vv7+/v7+/v7+/v7+/v7+vr5
        +Pj39/f39/f3+Pn5+vr7+/z8/fz8/Pz8+/v7+/v7+/v7+/v7+/z8/Pz8/Pz8/Pz8/Pz8/Pz8/f39
        /f39/f7+/v///////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
        AAAAAA==
        """
        
        def __init__(self):
            self.system = platform.system()
            self.sound_data = base64.b64decode(self._DEFAULT_SOUND.strip())
            
        def play(self):
            """跨平台播放声音"""
            try:
                if self.system == 'Windows':
                    logger.debug("Playing sound on Windows...")
                    self._play_windows()
                elif self.system == 'Darwin':
                    logger.debug("Playing sound on MacOS...")
                    self._play_macos()
                elif self.system == 'Linux':
                    logger.debug("Playing sound on Linux...")
                    if os.path.exists('/.dockerenv'):
                        logger.debug("Playing sound on Linux in container...")
                        self._play_linux_simple()
                    else:
                        logger.debug("Playing sound on Linux...")
                        self._play_linux()
                else:
                    logger.debug("Playing sound on fallback...")
                    self._play_fallback()
            except Exception as e:
                logger.error(f"Sound playback failed: {str(e)}")
                print(f"Sound playback failed: {str(e)}")
    
        def _play_windows(self):
            import winsound
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
                f.write(self.sound_data)
                f.close()
                winsound.PlaySound(f.name, winsound.SND_FILENAME)
                os.unlink(f.name)
    
        def _play_macos(self):
            with tempfile.NamedTemporaryFile(suffix='.wav') as f:
                f.write(self.sound_data)
                f.flush()
                os.system(f'afplay "{f.name}"')
    
        def _play_linux(self):
            players = ['paplay', 'aplay', 'play']
            with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
                try:
                    f.write(self.sound_data)
                    f.flush()
                    for player in players:
                        if os.system(f'which {player} > /dev/null 2>&1') == 0:
                            logger.debug(f"Playing sound with {player}...")
                            os.system(f'{player} "{f.name}"')
                            break
                finally:
                    try:
                        os.unlink(f.name)
                    except:
                        pass
        def _play_linux_simple(self):
            with tempfile.NamedTemporaryFile(suffix='.wav') as f:
                f.write(self.sound_data)
                f.flush()
                os.system(f'aplay "{f.name}" 2>/dev/null')
        def _play_fallback(self):
            try:
                import pygame
                pygame.mixer.init()
                sound = pygame.mixer.Sound(io.BytesIO(self.sound_data))
                logger.debug("Playing sound with pygame...")
                sound.play()
                time.sleep(1)
            except ImportError:
                logger.error("No sound playback available")
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states the tool sends a notification but doesn't disclose behavioral traits like whether it's synchronous/asynchronous, what happens on failure, if it requires specific permissions, or how notifications are delivered. 'Optional sound' hints at a feature but lacks details on default behavior or sound types.

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

Conciseness5/5

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

The description is extremely concise with a single sentence that directly states the tool's function. It's front-loaded and wastes no words, making it easy to parse quickly. Every part of the sentence contributes to understanding the tool's purpose.

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?

Given no annotations, no output schema, and 0% schema description coverage for 4 parameters, the description is incomplete. It covers the basic action but lacks details on behavior, parameters, return values, or error handling. For a notification-sending tool with multiple parameters, more context is needed to guide effective use.

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?

Schema description coverage is 0%, but the description doesn't add meaning beyond what the schema provides. It mentions 'optional sound' which corresponds to the 'play_sound' parameter, but doesn't explain other parameters like 'title', 'message', or 'timeout'. With 4 parameters and no schema descriptions, the description fails to compensate adequately, resulting in a baseline score.

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 action ('send') and resource ('system notification') with an additional feature ('optional sound'). It's specific about what the tool does, though without sibling tools, differentiation isn't applicable. The purpose is unambiguous but could be more detailed about the notification type or system context.

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, such as appropriate contexts, prerequisites, or alternatives. It mentions 'optional sound' but doesn't explain when sound should be enabled or disabled. With no sibling tools, this is less critical, but still lacks usage context.

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/Cactusinhand/mcp_server_notify'

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