"""MCP server that sends iMessages via macOS Messages app using osascript.""" import subprocess from mcp.server.fastmcp import FastMCP mcp = FastMCP("imessage-send") SEND_TIMEOUT_SECONDS = 15 def _build_applescript(recipient: str, message: str) -> str: escaped_message = message.replace("\\", "\\\\").replace('"', '\\"') escaped_recipient = recipient.replace("\\", "\\\\").replace('"', '\\"') return ( f'tell application "Messages" to send "{escaped_message}" ' f'to buddy "{escaped_recipient}"' ) @mcp.tool() def send_imessage(recipient: str, message: str) -> str: """Send an iMessage or SMS via the macOS Messages app. Args: recipient: Phone number in E.164 format (e.g. +14155551234) or an Apple ID email address. message: Text content to send. Newlines are preserved. Returns: Confirmation string on success. Raises: RuntimeError: If osascript exits non-zero (Messages not open, recipient not found, etc.). """ script = _build_applescript(recipient, message) result = subprocess.run( ["osascript", "-e", script], capture_output=True, text=True, timeout=SEND_TIMEOUT_SECONDS, ) if result.returncode != 0: raise RuntimeError(result.stderr.strip() or "osascript returned non-zero exit code") return f"Message sent to {recipient}" if __name__ == "__main__": mcp.run()