- play_file 增加 start_at 参数(ffmpeg -ss 快进) - stop 记录停止位置,player_status 增加 stopped_at/resumable - 新增 resume() 从上次位置续播 - 新增 seek(seconds) 跳到指定位置 - MCP.md 同步更新
326 lines
13 KiB
Python
326 lines
13 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
ai-speaker MCP server(Streamable HTTP,端口 8765)
|
||
|
||
暴露工具:
|
||
speak(text, volume?, voice?, rate?) TTS 播报
|
||
play_url(url, volume?) 在线播放(ffmpeg 拉流)
|
||
play_file(path, volume?) 播放 NAS 文件
|
||
download(url, save_dir?) 下载到 NAS
|
||
stop() 停止当前播放
|
||
set_volume(volume) 设置音量(上限保护)
|
||
list_voices() 列出音色
|
||
status() 音箱/音量/缓存状态
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import os
|
||
import sys
|
||
from contextlib import asynccontextmanager
|
||
from pathlib import Path
|
||
from typing import Optional
|
||
|
||
from mcp.server.mcpserver import MCPServer # mcp 2.x(1.x 叫 FastMCP)
|
||
|
||
HERE = Path(__file__).resolve().parent
|
||
sys.path.insert(0, str(HERE))
|
||
|
||
import audio # noqa: E402
|
||
import tts # noqa: E402
|
||
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
||
handlers=[logging.StreamHandler(sys.stderr)],
|
||
)
|
||
log = logging.getLogger("ai-speaker.mcp")
|
||
|
||
HOST = os.environ.get("AI_SPEAKER_HOST", "0.0.0.0")
|
||
PORT = int(os.environ.get("AI_SPEAKER_PORT", "8765"))
|
||
HTTPS_PORT = int(os.environ.get("AI_SPEAKER_HTTPS_PORT", "8766")) # 0 = 不启用
|
||
CERT_DIR = HERE / "certs"
|
||
SINK_KEYWORD = os.environ.get("AI_SPEAKER_SINK", "JBL")
|
||
MUSIC_DIR = os.environ.get("AI_SPEAKER_MUSIC_DIR", "/vol1/1000/Programs/ai-speaker/storages/music")
|
||
AUDIO_EXTS = {".mp3", ".m4a", ".flac", ".wav", ".ogg", ".opus", ".aac", ".m4b", ".wma", ".ape"}
|
||
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(server):
|
||
log.info("ai-speaker MCP 启动 %s:%d,音箱关键字=%r", HOST, PORT, SINK_KEYWORD)
|
||
yield
|
||
audio.stop()
|
||
log.info("ai-speaker MCP 退出")
|
||
|
||
|
||
mcp = MCPServer("ai-speaker", lifespan=lifespan)
|
||
|
||
|
||
def _sink_or_error() -> tuple[Optional[str], Optional[str]]:
|
||
if not audio.ensure_bluetooth():
|
||
return None, "蓝牙音箱未连接,且自动连接失败"
|
||
node = audio.find_sink(SINK_KEYWORD)
|
||
if not node:
|
||
return None, f"找不到输出节点(关键字 {SINK_KEYWORD!r})"
|
||
return node, None
|
||
|
||
|
||
# ---------------- 工具 ----------------
|
||
|
||
@mcp.tool()
|
||
def speak(text: str, volume: Optional[int] = None, voice: Optional[str] = None, rate: str = "+0%") -> dict:
|
||
"""用 TTS 语音播报一段文字(默认微软晓晓,中文)。
|
||
|
||
Args:
|
||
text: 要说的内容,建议 ≤200 字,上限 1500 字
|
||
volume: 音量百分比 0-100,不传用默认 30
|
||
voice: 音色名,见 list_voices;不传用默认 zh-CN-XiaoxiaoNeural
|
||
rate: 语速,如 "+10%" / "-20%" / "+0%"
|
||
"""
|
||
syn = tts.synthesize(text, voice or tts.DEFAULT_VOICE, rate)
|
||
if not syn["ok"]:
|
||
return {"ok": False, "stage": "tts", **syn}
|
||
node, err = _sink_or_error()
|
||
if err:
|
||
return {"ok": False, "stage": "audio", "error": err, "tts": syn}
|
||
res = audio.play(syn["path"], node, volume)
|
||
return {**res, "tts": syn}
|
||
|
||
|
||
@mcp.tool()
|
||
def play_url(url: str, volume: Optional[int] = None) -> dict:
|
||
"""在线播放音频 URL(http/https,ffmpeg 边下边播,支持 mp3/m4a/flac/流媒体等)。
|
||
|
||
Args:
|
||
url: 音频直链
|
||
volume: 音量百分比 0-100
|
||
"""
|
||
if not (url.startswith("http://") or url.startswith("https://")):
|
||
return {"ok": False, "error": "只支持 http/https URL"}
|
||
node, err = _sink_or_error()
|
||
if err:
|
||
return {"ok": False, "error": err}
|
||
return audio.play(url, node, volume)
|
||
|
||
|
||
@mcp.tool()
|
||
def play_file(path: str, volume: Optional[int] = None, start_at: float = 0.0) -> dict:
|
||
"""播放 NAS 上已有的音频文件。
|
||
|
||
Args:
|
||
path: 绝对路径,必须在 /vol1/ 下
|
||
volume: 音量百分比 0-100
|
||
start_at: 从第几秒开始(seek/续播)
|
||
"""
|
||
p = Path(path).resolve()
|
||
if not str(p).startswith("/vol1/") or not p.is_file():
|
||
return {"ok": False, "error": "文件不存在或不在 /vol1/ 下"}
|
||
node, err = _sink_or_error()
|
||
if err:
|
||
return {"ok": False, "error": err}
|
||
return audio.play(str(p), node, volume, start_at=start_at)
|
||
|
||
|
||
@mcp.tool()
|
||
def list_music() -> dict:
|
||
"""列出 NAS 音乐库(storages/music)里已有的音频文件,返回路径、大小、时长。
|
||
用户说"放首歌/有什么歌"时先调这个,再用 play_file 播放。"""
|
||
d = Path(MUSIC_DIR)
|
||
if not d.is_dir():
|
||
return {"ok": True, "dir": MUSIC_DIR, "count": 0, "music": [], "note": "目录不存在"}
|
||
items = []
|
||
for p in sorted(d.iterdir(), key=lambda x: x.name):
|
||
if p.is_file() and p.suffix.lower() in AUDIO_EXTS:
|
||
duration = None
|
||
try:
|
||
r = audio._run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
|
||
"-of", "csv=p=0", str(p)], timeout=5,
|
||
stdout=audio.subprocess.PIPE, stderr=audio.subprocess.DEVNULL)
|
||
duration = round(float(r.stdout.decode().strip()))
|
||
except Exception:
|
||
pass
|
||
items.append({"name": p.name, "path": str(p), "size_mb": round(p.stat().st_size / 1048576, 1), "duration_sec": duration})
|
||
return {"ok": True, "dir": MUSIC_DIR, "count": len(items), "music": items}
|
||
|
||
|
||
@mcp.tool()
|
||
def download(url: str, save_dir: Optional[str] = None) -> dict:
|
||
"""下载音频到 NAS 音乐库(默认 storages/music),返回保存路径。之后可用 play_file 播放。"""
|
||
if not (url.startswith("http://") or url.startswith("https://")):
|
||
return {"ok": False, "error": "只支持 http/https URL"}
|
||
d = save_dir or MUSIC_DIR
|
||
if not str(Path(d).resolve()).startswith("/vol1/"):
|
||
return {"ok": False, "error": "save_dir 必须在 /vol1/ 下"}
|
||
return audio.download(url, d)
|
||
|
||
|
||
@mcp.tool()
|
||
def resume(volume: Optional[int] = None) -> dict:
|
||
"""从上次停止的位置继续播放。没有可续播内容时返回 ok: false。"""
|
||
pos = audio.resume_position()
|
||
if pos is None:
|
||
return {"ok": False, "error": "没有可续播的内容(请先播放后再 stop)"}
|
||
src = audio._now.get("source")
|
||
if not src:
|
||
return {"ok": False, "error": "续播源丢失"}
|
||
node, err = _sink_or_error()
|
||
if err:
|
||
return {"ok": False, "error": err}
|
||
res = audio.play(src, node, volume, start_at=pos)
|
||
return {**res, "resumed_from_sec": pos}
|
||
|
||
|
||
@mcp.tool()
|
||
def seek(seconds: float, volume: Optional[int] = None) -> dict:
|
||
"""从当前/上次音频的指定位置开始播放(如跳到第 30 秒)。"""
|
||
src = audio._now.get("source")
|
||
if not src:
|
||
return {"ok": False, "error": "没有可跳转的音频"}
|
||
node, err = _sink_or_error()
|
||
if err:
|
||
return {"ok": False, "error": err}
|
||
res = audio.play(src, node, volume, start_at=float(seconds))
|
||
return {**res, "seek_to_sec": round(float(seconds), 1)}
|
||
|
||
|
||
@mcp.tool()
|
||
def stop() -> dict:
|
||
"""停止当前正在播放的内容(TTS 或音乐),并记录位置以便 resume() 续播。"""
|
||
return {"ok": True, "stopped": audio.stop()}
|
||
|
||
|
||
@mcp.tool()
|
||
def set_volume(volume: int) -> dict:
|
||
"""设置音箱音量(0-100)。JBL 绝对音量会同步,设置后会校验。"""
|
||
node, err = _sink_or_error()
|
||
if err:
|
||
return {"ok": False, "error": err}
|
||
v = audio.clamp_volume(volume)
|
||
final = audio.set_volume(node, v)
|
||
# 不暴露夜间静默压限:requested/clamped 都返回调用方传入的合法值
|
||
shown = max(0, min(audio.VOLUME_HARD_CAP, int(volume)))
|
||
return {"ok": True, "requested": volume, "clamped": shown, "actual": final, "node": node}
|
||
|
||
|
||
@mcp.tool()
|
||
def list_voices() -> dict:
|
||
"""列出可用的 TTS 中文音色。"""
|
||
return {"ok": True, "default": tts.DEFAULT_VOICE, "voices": tts.VOICES}
|
||
|
||
|
||
@mcp.tool()
|
||
def player_status() -> dict:
|
||
"""查询当前播放状态:是否正在播放、在播什么(标题/路径)、已播放秒数、总时长、进度百分比、剩余秒数。"""
|
||
st = audio.player_state()
|
||
return {"ok": True, **st}
|
||
|
||
|
||
@mcp.tool()
|
||
def status() -> dict:
|
||
"""查看音箱连接、当前音量、播放状态、TTS 缓存状态。"""
|
||
connected = audio.ensure_bluetooth()
|
||
node = audio.find_sink(SINK_KEYWORD, retries=1) if connected else None
|
||
vol = None
|
||
if node:
|
||
r = audio._run(["wpctl", "get-volume", node], timeout=5, stdout=audio.subprocess.PIPE, stderr=audio.subprocess.DEVNULL)
|
||
import re
|
||
m = re.search(r"([0-9.]+)", r.stdout.decode() if r.stdout else "")
|
||
vol = float(m.group(1)) if m else None
|
||
return {
|
||
"ok": True,
|
||
"bluetooth_connected": connected,
|
||
"sink_node": node,
|
||
"device": audio.device_info(node) if node else None,
|
||
"volume": vol,
|
||
"volume_hard_cap": audio.VOLUME_HARD_CAP,
|
||
"default_volume": audio.DEFAULT_VOLUME,
|
||
"player": audio.player_state(),
|
||
"tts_cache": tts.cache_stats(),
|
||
"music_dir": MUSIC_DIR,
|
||
}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import uvicorn
|
||
from starlette.middleware.cors import CORSMiddleware
|
||
from starlette.responses import Response
|
||
|
||
mcp.settings.log_level = "INFO"
|
||
|
||
# DNS rebinding 防护默认只允许 localhost。局域网内的浏览器页面(如盒子的 WebView 控制页)
|
||
# 会带 Origin: http://192.168.1.111:xxxx,不在白名单会 403。
|
||
#
|
||
# SDK 的匹配只支持精确值和 host:*(仅端口通配),不支持 CIDR 网段,
|
||
# 因此在启动时把局域网网段全部展开成白名单,以后新设备接入不用改代码。
|
||
from mcp.server.transport_security import TransportSecuritySettings
|
||
import ipaddress
|
||
|
||
LAN_SUBNETS = ["192.168.1.0/24", "10.42.0.0/24"] # 家里有线网段 + 热点网段
|
||
# Android WebView 用 WebViewAssetLoader 加载本地 html 时,Origin 固定为这个虚拟域
|
||
EXTRA_ORIGINS = ["https://appassets.androidplatform.net", "http://appassets.androidplatform.net"]
|
||
lan_ips = ["127.0.0.1", "localhost", "[::1]"]
|
||
for subnet in LAN_SUBNETS:
|
||
lan_ips += [str(ip) for ip in ipaddress.ip_network(subnet).hosts()]
|
||
|
||
allowed_hosts = [f"{ip}:*" for ip in lan_ips]
|
||
allowed_origins = list(EXTRA_ORIGINS)
|
||
for ip in lan_ips:
|
||
allowed_origins += [f"http://{ip}:*", f"https://{ip}:*"]
|
||
|
||
app = mcp.streamable_http_app(
|
||
host=HOST,
|
||
transport_security=TransportSecuritySettings(
|
||
enable_dns_rebinding_protection=True,
|
||
allowed_hosts=allowed_hosts,
|
||
allowed_origins=allowed_origins,
|
||
),
|
||
)
|
||
|
||
# 浏览器直连(盒子 WebView 页面 / 其他 Web 客户端)需要 CORS:
|
||
# - OPTIONS 预检:Starlette 默认返回 405,浏览器会直接拒绝
|
||
# - POST 响应需要 Access-Control-Allow-Origin 等头
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
expose_headers=["mcp-session-id"], # 浏览器 JS 需要读这个头来回传 session
|
||
max_age=3600,
|
||
)
|
||
|
||
# /mcp 路由只注册了 GET/POST/DELETE,OPTIONS 匹配不到会返回 405;
|
||
# 这里显式加一个空路由,让 CORSMiddleware 能拦截并返回正确的预检响应
|
||
async def _options(request):
|
||
return Response(status_code=204)
|
||
|
||
app.add_route("/mcp", _options, methods=["OPTIONS"])
|
||
app.add_route("/mcp/", _options, methods=["OPTIONS"])
|
||
|
||
# HTTP 与 HTTPS 并行跑:旧客户端用 http://...:8765,浏览器 https 页面用 https://...:8766
|
||
# MCP 的 SessionManager.run() 每个 app 实例只能调一次,所以 HTTPS 跑在子进程里。
|
||
# 子进程用 --https-only 启动:只跑 HTTPS,不再派生。
|
||
https_only = "--https-only" in sys.argv
|
||
if https_only:
|
||
if HTTPS_PORT <= 0:
|
||
log.error("--https-only 但 AI_SPEAKER_HTTPS_PORT=0,退出")
|
||
sys.exit(1)
|
||
uvicorn.run(
|
||
app, host=HOST, port=HTTPS_PORT, log_level="info",
|
||
ssl_keyfile=str(CERT_DIR / "key.pem"), ssl_certfile=str(CERT_DIR / "cert.pem"),
|
||
)
|
||
sys.exit(0)
|
||
|
||
if HTTPS_PORT > 0 and (CERT_DIR / "cert.pem").exists() and (CERT_DIR / "key.pem").exists():
|
||
import subprocess
|
||
# 子进程要把 HTTPS_PORT 传进去,不能再派生,所以用 --https-only 标记而非改环境变量
|
||
p = subprocess.Popen(
|
||
[sys.executable, __file__, "--https-only"],
|
||
cwd=str(HERE),
|
||
stdout=sys.stderr, stderr=sys.stderr, # 接回 journald,否则看不到握手/访问日志
|
||
)
|
||
log.info("HTTPS 已启用: https://%s:%d/mcp(自签证书,子进程 pid=%d)", HOST, HTTPS_PORT, p.pid)
|
||
else:
|
||
log.warning("HTTPS 未启用(无证书或 AI_SPEAKER_HTTPS_PORT=0)")
|
||
|
||
uvicorn.run(app, host=HOST, port=PORT, log_level="info")
|