ai-speaker MCP server 初始提交

- MCP Streamable HTTP (:8765 HTTP / :8766 HTTPS 自签)
- 工具:speak / play_url / play_file / download / stop / set_volume / list_voices / list_music / player_status / status
- 音量:上限 100,默认 30,夜间 22:00-08:30 静默压到 60
- CORS + Origin 白名单(局域网网段 + Android WebView 虚拟域)
- audio.py:PipeWire 蓝牙输出、JBL 绝对音量校验、播放状态/进度/设备信息
- tts.py:edge-tts 合成 + 缓存
- bt-play.sh:命令行播放工具
This commit is contained in:
jmj committed 2026-11-30 02:20:37 +08:00
commit 4ac2e959e0
10 files changed
+1050

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
# Python 虚拟环境(约 100MB+,各自重建)
venv/
__pycache__/
*.pyc
# TTS 缓存(运行时生成)
cache/
# 证书私钥——绝不提交
certs/key.pem
certs/*.pem
*.pem
# 测试音频/下载文件
storages/music/*
!storages/music/.gitkeep
# 运行时/临时
*.log
*.out
.DS_Store
+129
View File
@@ -0,0 +1,129 @@
# ai-speaker MCP 服务器使用说明
> 本文档供 AI 客户端 / 开发者阅读。把本文喂给 AI,它就知道如何调用这台设备上的语音播报服务。
## 1. 服务概况
- **名称**:ai-speaker
- **位置**:一台 RK3566 盒子(飞牛 fnOS, Debian 12),接 JBL PS3500 蓝牙音箱
- **用途**:AI 任务完成 / 需要人工确认 / 出错时,**通过音箱语音播报通知用户**;也可在线播放音乐、下载到 NAS
- **传输**:MCP Streamable HTTP
- **地址(HTTP)**:`http://192.168.1.111:8765/mcp`(普通客户端用这个;热点下 `http://10.42.0.1:8765/mcp`)
- **地址(HTTPS)**:`https://192.168.1.111:8766/mcp`(**https 加载的网页必须用这个**,否则浏览器拦截混合内容;自签证书,首次需手动信任)
- **鉴权**:无(局域网内使用)
- **浏览器直连**:已开启 CORS。`Origin`/`Host` 白名单为 `192.168.1.0/24` 和 `10.42.0.0/24` 整个网段(http/https 均可);其他来源返回 403(DNS rebinding 防护)。换网段需改 `server.py` 里的 `LAN_SUBNETS`
### 客户端配置(通用 JSON,字段名按客户端调整)
```json
{
"mcpServers": {
"ai-speaker": {
"url": "http://192.168.1.111:8765/mcp",
"transport": "streamable-http"
}
}
}
```
## 2. 工具列表
### `speak(text, volume?, voice?, rate?)`
TTS 语音播报。**这是最常用的工具。**
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| text | string | 是 | 要说的内容,建议 ≤200 字,上限 1500 字 |
| volume | int | 否 | 音量 0–100,默认 30 |
| voice | string | 否 | 音色名,见 `list_voices`,默认 `zh-CN-XiaoxiaoNeural` |
| rate | string | 否 | 语速,如 `+10%`、`-20%`,默认 `+0%` |
返回:`{"ok", "volume", "seconds", "tts": {"path", "cached", "seconds"}}`
**特点**:
- 合成走微软 edge-tts(需联网),首次约 3–4 秒,**相同文本 + 音色命中缓存后 0 秒**
- 蓝牙 A2DP 有约 2 秒缓冲,调用返回时声音可能还在播,属正常
- 播报会**自动重连**蓝牙音箱
### `play_url(url, volume?)`
在线播放音频直链(http/https)。ffmpeg 边下边播,支持 mp3 / m4a / flac / m3u8 / 流媒体等。
适合"AI 找到一首歌 → 直接让音箱放"。
### `list_music()`
列出 NAS 音乐库(`storages/music`)里已有的音频文件,返回每首的 `name`、`path`、`size_mb`、`duration_sec`。
**用户说"有什么歌 / 放首歌"时,先调这个,再用 `play_file` 播放。**
### `download(url, save_dir?)`
下载音频到 NAS 音乐库(默认 `storages/music`),返回 `{"ok", "path", "bytes"}`。之后可用 `play_file` 播放。
**设计原则**:AI 只传 URL / 路径引用,**不要通过 MCP 传音频二进制**。
### `play_file(path, volume?)`
播放 NAS 上已有的音频文件,路径必须以 `/vol1/` 开头。
### `stop()`
停止当前播放(TTS 或音乐)。正在播放时再次调用 `speak` 也会先停止前一个。
### `player_status()`
查询当前播放状态。返回:
| 字段 | 说明 |
|---|---|
| `playing` | 是否正在播放 |
| `title` | 正在播放的内容(文件名或 URL 末段) |
| `source` | 完整路径/URL |
| `duration` | 总时长(秒),读不到时为 null |
| `elapsed_sec` | 已播放秒数(空闲时为 null) |
| `progress_pct` | 进度百分比 0–100 |
| `remaining_sec` | 剩余秒数 |
`elapsed_sec` 从解码启动算,比实际听到的快约 2 秒(蓝牙缓冲)。
`status()` 的返回里也嵌了同样的 `player` 字段。
### `set_volume(volume)`
设置音量(0–100)。音箱支持绝对音量会回传,设置后自动校验。返回 `{"requested", "clamped", "actual"}`。
### `list_voices()`
列出可用中文音色。
### `status()`
返回蓝牙连接、输出节点、当前音量、缓存统计。排查问题时先调这个。
## 3. 使用建议(给 AI 的行为指引)
1. **任务完成、需要用户确认、发生错误**时,调 `speak()` 播报。默认音量 30,不要主动调到更高。
2. 播报内容**简短口语化**,一句话说清:"报表已生成,请确认"、"下载出错,网络超时"。
3. **不要把播报当唯一的输出**,该返回给客户端的文字照样返回。
4. 用户说"有什么歌 / 放首歌":先调 `list_music()` 看音乐库,有就 `play_file`;用户要新歌就用你自己的能力找到音频直链 → `play_url`。要保存就先 `download` 再 `play_file`。
5. 用户说"别放了":`stop()`。
6. 调用失败先看返回的 `error` 字段;`stage` 为 `tts` 是合成失败(网络),`audio` 是音箱问题(蓝牙未连)。
## 4. 示例对话
**用户**:帮我整理一下昨天拍的照片,好了告诉我。
**AI**:(整理完成)→ 调用 `speak(text="照片整理完成,共 235 张,已按日期归档。")` → 同时在对话里回复结果。
**用户**:来首周杰伦的晴天。
**AI**:先 `list_music()` 看 NAS 里有没有 → 没有则搜索音频直链 → `play_url(url="https://.../qing_tian.mp3")` → 回复"正在播放"。用户说"存下来" → `download(url)` → 回复保存路径。
**用户**:太吵了。
**AI**:调用 `set_volume(volume=8)`。
## 5. 已知限制
- TTS 需联网(微软服务器),离线时 `speak` 失败,可退化为只在对话里输出
- 蓝牙音箱约 2 秒延迟,**不适合需要实时同步的场景**
- 音量范围 0–100%,默认 30
- 一次只能播一个音频(后一个会打断前一个)
- 服务运行在 NAS 上,NAS 重启后需约 30 秒才恢复
## 6. 运维(设备管理员用)
```bash
systemctl status ai-speaker # 状态
journalctl -u ai-speaker -f # 日志
systemctl restart ai-speaker # 重启
cd /vol1/1000/Programs/ai-speaker && ./venv/bin/python test_client.py status # 本地测试
```
代码:`/vol1/1000/Programs/ai-speaker/`(`server.py` / `audio.py` / `tts.py`)
+77
View File
@@ -0,0 +1,77 @@
# ai-speaker — 盒子语音播报 MCP 服务
把荐片 TV 盒子(RK3566 / fnOS)的蓝牙音箱(JBL PS3500)暴露成 MCP 工具,供任意支持 MCP 的 AI 客户端调用:TTS 播报、在线播放、下载音乐、播放 NAS 文件。
## 连接
| 项 | 值 |
|---|---|
| 传输 | Streamable HTTP |
| 地址 | `http://192.168.1.111:8765/mcp`(有线地址;热点下用 `http://10.42.0.1:8765/mcp`) |
| 鉴权 | 无(纯局域网) |
在 AI 客户端的 MCP 配置里添加(以通用 JSON 为例):
```json
{
"mcpServers": {
"ai-speaker": {
"url": "http://192.168.1.111:8765/mcp",
"transport": "streamable-http"
}
}
}
```
## 工具
| 工具 | 说明 |
|---|---|
| `speak(text, volume?, voice?, rate?)` | TTS 播报(微软 edge-tts,默认晓晓),≤1500 字 |
| `play_url(url, volume?)` | 在线播放(ffmpeg 拉流,边下边播) |
| `play_file(path, volume?)` | 播放 `/vol1/` 下的音频文件 |
| `download(url, save_dir?)` | 下载到 `/vol1/1000/Music`,返回路径 |
| `stop()` | 停止当前播放 |
| `set_volume(volume)` | 设音量(0-40 硬上限) |
| `list_voices()` | 列出中文音色 |
| `status()` | 音箱连接 / 音量 / 缓存 |
**音量安全**:所有播放工具音量上限 **40%**(`audio.VOLUME_HARD_CAP`),默认 15%,设置后校验(防 JBL 绝对音量回传覆盖)。
## 文件
```
ai-speaker/
├── server.py MCP 服务(MCPServer,mcp 2.x)
├── audio.py 播放层:找节点、音量保护、播放、下载
├── tts.py edge-tts 合成 + 缓存(cache/)
├── test_client.py 本地测试:./venv/bin/python test_client.py <tool> '<json>'
├── venv/ Python 虚拟环境(mcp、edge-tts)
└── cache/ TTS 缓存
```
## 运维
```bash
systemctl status ai-speaker # 状态
journalctl -u ai-speaker -f # 日志
systemctl restart ai-speaker # 重启(改代码后)
```
环境变量(在 `/etc/systemd/system/ai-speaker.service` 里):`AI_SPEAKER_PORT`、`AI_SPEAKER_SINK`(音箱名关键字)、`AI_SPEAKER_MUSIC_DIR`。
**换 USB 音箱**:插上后 `wpctl status` 看 Sinks 里新设备的名字,把 `AI_SPEAKER_SINK` 改成对应关键字(如 `USB`),重启服务即可。
## 依赖
- `bluetooth.service` + `pipewire.service` + `wireplumber.service`(见修复记录第十节)
- 系统命令:`ffmpeg`、`pw-cat`、`wpctl`、`bluetoothctl`
- 联网(edge-tts 访问微软服务器)
## 回滚
```bash
systemctl disable --now ai-speaker.service
rm /etc/systemd/system/ai-speaker.service; systemctl daemon-reload
rm -rf /vol1/1000/Programs/ai-speaker
```
+293
View File
@@ -0,0 +1,293 @@
"""
音频播放层:负责找到输出设备、控制音量(带安全上限)、播放文件或 URL。
和 bt-play.sh 逻辑一致,但以 Python 实现,供 MCP server 调用。
"""
from __future__ import annotations
import hashlib
import logging
import os
import re
import shutil
import subprocess
import tempfile
import threading
import time
from pathlib import Path
from typing import Optional
log = logging.getLogger("ai-speaker.audio")
# ---------- 环境常量(与 pipewire-system.sh 一致) ----------
PIPEWIRE_RUNTIME_DIR = "/run/user/0"
DBUS_ADDR_FILE = Path("/run/pipewire-dbus-address")
# 音量安全:绝不允许超过此值(0-100),防止半夜被吓到
VOLUME_HARD_CAP = 100
DEFAULT_VOLUME = 30
# 夜间模式(22:00-08:30):上限静默压到此值,不向 MCP 调用方暴露
NIGHT_CAP = 60
def _env() -> dict[str, str]:
env = dict(os.environ)
env["PATH"] = env.get("PATH", "") + ":/usr/local/bin:/usr/sbin:/sbin:/bin"
env["PIPEWIRE_RUNTIME_DIR"] = PIPEWIRE_RUNTIME_DIR
addr = DBUS_ADDR_FILE.read_text().strip() if DBUS_ADDR_FILE.exists() else ""
if addr:
env["DBUS_SESSION_BUS_ADDRESS"] = addr
return env
def _run(cmd: list[str], timeout: float = 8, stdin=None, stdout=None, stderr=None):
return subprocess.run(cmd, env=_env(), timeout=timeout, stdin=stdin, stdout=stdout, stderr=stderr)
# ---------- 音量 ----------
def _effective_cap() -> int:
"""返回当前时刻的音量上限。夜间 22:00-08:30 强制压到 NIGHT_CAP,不向调用方暴露。"""
h = time.localtime().tm_hour + time.localtime().tm_min / 60.0
night = (h >= 22.0) or (h < 8.5)
return NIGHT_CAP if night else VOLUME_HARD_CAP
def clamp_volume(v: Optional[int]) -> int:
"""把请求音量限制在 [0, 当前时刻的上限]。None 用默认值。"""
cap = _effective_cap()
if v is None:
return min(DEFAULT_VOLUME, cap)
try:
v = int(v)
except (TypeError, ValueError):
return min(DEFAULT_VOLUME, cap)
return max(0, min(cap, v))
_sink_cache: dict[str, tuple[str, float]] = {} # keyword -> (node_id, ts)
def find_sink(keyword: str = "JBL", retries: int = 8) -> Optional[str]:
"""在 wpctl status 的 Sinks 段里按关键字找节点 ID。找不到返回 None。
优化:缓存 60 秒;命中时用 get-volume 校验节点仍存活。"""
now = time.time()
cached = _sink_cache.get(keyword)
if cached and now - cached[1] < 60 and _read_volume(cached[0]) is not None:
return cached[0]
for i in range(retries):
r = _run(["wpctl", "status"], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
text = re.sub(r"\x1b\[[0-9;]*m", "", r.stdout.decode(errors="ignore") if r.stdout else "")
in_sink = False
for line in text.splitlines():
if "Sinks:" in line:
in_sink = True
continue
if in_sink and re.match(r"^[ │]*[├└]─", line):
in_sink = False
if in_sink and keyword.lower() in line.lower():
m = re.search(r"(\d+)\.", line)
if m:
_sink_cache[keyword] = (m.group(1), now)
return m.group(1)
time.sleep(0.3) # 原来是 1 秒,缩短重试间隔
return None
def _read_volume(node: str) -> Optional[float]:
r = _run(["wpctl", "get-volume", node], timeout=5, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
m = re.search(r"([0-9.]+)", r.stdout.decode() if r.stdout else "")
return float(m.group(1)) if m else None
def device_info(node: str) -> dict:
"""从 pw-dump 读输出节点的设备信息:名称、蓝牙地址、编解码器、配置。"""
info = {"node": node, "name": None, "description": None, "address": None,
"codec": None, "profile": None, "transport": None, "volume": None}
try:
r = _run(["pw-dump", node], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
text = r.stdout.decode(errors="ignore") if r.stdout else ""
for key, field in [("node.name", "name"), ("node.description", "description"),
("api.bluez5.address", "address"), ("api.bluez5.codec", "codec"),
("api.bluez5.profile", "profile"), ("api.bluez5.transport", "transport")]:
m = re.search(rf'"{re.escape(key)}":\s*"([^"\n]+)"', text)
if m:
info[field] = m.group(1).strip()
info["volume"] = _read_volume(node)
except Exception:
pass
return info
def set_volume(node: str, vol_pct: int, verify_rounds: int = 3) -> float:
"""设置音量并验证。JBL 等绝对音量音箱会回传覆盖,需复读。返回最终音量(0-1)。
优化:已是目标值则直接返回,避免每次播放都白等 3 秒。"""
target = vol_pct / 100.0
cur = _read_volume(node)
if cur is not None and abs(cur - target) < 0.02:
return cur
time.sleep(0.4) # 若上一次设置刚发生,等 JBL 的 AVRCP 回传先稳定,避免被覆盖
for i in range(verify_rounds):
_run(["wpctl", "set-mute", node, "0"], timeout=5)
_run(["wpctl", "set-volume", node, f"{target:.4f}"], timeout=5)
time.sleep(0.5 if i == 0 else 0.9)
cur = _read_volume(node)
if cur is not None and abs(cur - target) < 0.02:
break
return cur if cur is not None else target
# ---------- 蓝牙连接 ----------
def ensure_bluetooth(mac: str = "43:5A:DC:68:1B:F8") -> bool:
r = _run(["bluetoothctl", "info", mac], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
if r.stdout and b"Connected: yes" in r.stdout:
return True
log.info("蓝牙未连接,尝试连接 %s", mac)
_run(["bluetoothctl", "connect", mac], timeout=30, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(3)
r = _run(["bluetoothctl", "info", mac], timeout=6, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
return bool(r.stdout and b"Connected: yes" in r.stdout)
# ---------- 播放 ----------
_play_lock = threading.Lock()
_current: Optional[subprocess.Popen] = None
_current_lock = threading.Lock()
# 播放状态跟踪(供 player_status 查询)
_now: dict = {"playing": False, "source": None, "started_at": None, "title": None, "duration": None}
def _probe_duration(src: str) -> Optional[float]:
"""用 ffprobe 读音频总时长(秒),读不到返回 None。"""
try:
r = _run(["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "csv=p=0", src], timeout=8,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
return float(r.stdout.decode().strip().splitlines()[0]) if r.stdout else None
except Exception:
return None
def player_state() -> dict:
"""返回当前播放状态,含进度。"""
with _current_lock:
p = _current
playing = bool(p and p.poll() is None)
st = dict(_now)
st["playing"] = playing
if playing and st.get("started_at"):
elapsed = max(0.0, time.time() - st["started_at"])
st["elapsed_sec"] = round(elapsed, 1)
if st.get("duration"):
st["progress_pct"] = round(min(100.0, elapsed / st["duration"] * 100), 1)
st["remaining_sec"] = round(max(0.0, st["duration"] - elapsed), 1)
else:
st["progress_pct"] = None
st["remaining_sec"] = None
else:
st["elapsed_sec"] = None
st["progress_pct"] = None
st["remaining_sec"] = None
st["playing"] = False
return st
def stop() -> bool:
"""停止当前播放。"""
with _current_lock:
p = _current
if p and p.poll() is None:
try:
p.terminate()
p.wait(timeout=3)
except Exception:
p.kill()
return True
return False
def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, timeout: float = 600.0) -> dict:
"""
播放文件或 URL(ffmpeg 能解的任何东西,含 http/https 流)。
返回 {"ok", "node", "volume", "seconds"}。
"""
global _current
vol = clamp_volume(vol_pct)
if not _play_lock.acquire(blocking=False):
stop()
time.sleep(0.5)
if not _play_lock.acquire(timeout=5):
return {"ok": False, "error": "另一个播放正在进行"}
try:
final_vol = set_volume(node, vol)
# 安全检查:最终音量不能超过请求值太多
if final_vol > vol / 100.0 + 0.05:
return {"ok": False, "error": f"音量校验失败: 请求 {vol}%, 实际 {final_vol:.2f}"}
t0 = time.time()
dec = subprocess.Popen(
["ffmpeg", "-v", "error", "-i", src, "-f", "wav", "-ac", "2", "-ar", "44100", "-"],
env=_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
pw = subprocess.Popen(
["pw-cat", "--playback", "-", "--target", node],
env=_env(), stdin=dec.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dec.stdout.close()
title = None
if src.startswith("http"):
title = src.split("?")[0].rstrip("/").split("/")[-1] or src
else:
title = os.path.basename(src) or src
_now.update({"source": src, "started_at": time.time(), "title": title,
"duration": _probe_duration(src)})
with _current_lock:
_current = pw # global:让 stop() 能找到并终止它
try:
rc = pw.wait(timeout=timeout)
except subprocess.TimeoutExpired:
pw.kill()
rc = -9
finally:
if dec.poll() is None:
dec.kill()
dec.stderr.close()
with _current_lock:
_current = None
_now["playing"] = False
err = ""
if rc != 0:
try:
err = dec.stderr.read().decode(errors="ignore").strip().splitlines()[-1:] or [""]
err = err[0][:200]
except Exception:
err = ""
return {
"ok": rc == 0,
"node": node,
"volume": final_vol,
"seconds": round(time.time() - t0, 2),
**({"error": err} if err else {}),
}
finally:
_play_lock.release()
# ---------- 下载 ----------
def download(url: str, save_dir: str = "/vol1/1000/Music", timeout: float = 600.0) -> dict:
"""用 ffmpeg 下载 URL 到 NAS 目录。返回 {"ok","path","bytes"}。"""
Path(save_dir).mkdir(parents=True, exist_ok=True)
# 从 URL 猜扩展名,猜不到就 .mp3
ext = Path(url.split("?")[0]).suffix.lower()
if ext not in {".mp3", ".m4a", ".flac", ".wav", ".ogg", ".opus", ".aac", ".m4b", ".wma", ".ape"}:
ext = ".mp3"
name = Path(url.split("?")[0]).stem[:60] or "audio"
name = re.sub(r"[\\/:*?\"<>|]", "_", name)
dst = Path(save_dir) / f"{name}{ext}"
if dst.exists():
dst = dst.with_name(f"{name}-{int(time.time())}{ext}")
r = _run(["ffmpeg", "-v", "error", "-y", "-i", url, "-c", "copy", str(dst)], timeout=timeout,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if r.returncode != 0:
dst.unlink(missing_ok=True)
err = (r.stderr or b"").decode(errors="ignore").strip().splitlines()[-1:] or ["unknown"]
return {"ok": False, "error": err[0][:200]}
return {"ok": True, "path": str(dst), "bytes": dst.stat().st_size}
Executable
+118
View File
@@ -0,0 +1,118 @@
#!/bin/sh
# bt-play.sh —— 把音频文件通过蓝牙音箱播放(A2DP,经 PipeWire)
#
# 用法:
# bt-play.sh [选项] <音频文件或URL>
#
# 选项:
# -v <0-100> 音量百分比(默认 10),会保存为下次默认值
# -s <名称> 指定音箱关键字(默认 JBL),用于查找蓝牙输出节点
# -t <秒> 只播放前 N 秒(默认播放完整)
# -q 静默,不打印状态
#
# 示例:
# bt-play.sh song.mp3 # 以默认音量播放整首
# bt-play.sh -v 20 song.m4a # 音量 20% 播放整首
# bt-play.sh -t 15 song.m4a # 试听前 15 秒
# bt-play.sh "https://example.com/a.mp3" # 直接播 URL(ffmpeg 解码)
#
# 环境:依赖系统级 pipewire.service 提供的运行时目录与会话总线
set -u
VOL_FILE=/root/.config/bt-play/volume
SINK_FILE=/root/.config/bt-play/sink
BT_MAC=43:5A:DC:68:1B:F8
mkdir -p "$(dirname "$VOL_FILE")"
[ -f "$VOL_FILE" ] && DEF_VOL=$(cat "$VOL_FILE") || DEF_VOL=10
[ -f "$SINK_FILE" ] && DEF_SINK=$(cat "$SINK_FILE") || DEF_SINK=JBL
VOL=""; SINK=""; DUR=""; QUIET=0
while getopts "v:s:t:q" o; do
case "$o" in
v) VOL="$OPTARG" ;;
s) SINK="$OPTARG" ;;
t) DUR="$OPTARG" ;;
q) QUIET=1 ;;
*) echo "用法: $0 [-v 音量] [-s 音箱] [-t 秒] <文件>"; exit 2 ;;
esac
done
shift $((OPTIND-1))
[ $# -ge 1 ] || { echo "用法: $0 [-v 音量] [-s 音箱] [-t 秒] <文件>"; exit 2; }
SRC="$1"
[ -f "$SRC" ] || echo "$SRC" | grep -qE '^https?://' || { echo "文件不存在: $SRC"; exit 1; }
say() { [ "$QUIET" = 1 ] || echo "$@"; }
# ---------- 1. 音量 ----------
VOL="${VOL:-$DEF_VOL}"
echo "$VOL" | grep -qE '^[0-9]+$' && [ "$VOL" -ge 0 ] && [ "$VOL" -le 100 ] || { echo "音量需为 0-100 的整数"; exit 2; }
echo "$VOL" > "$VOL_FILE"
# ---------- 2. 连接音箱 ----------
CONNECTED=$(bluetoothctl info "$BT_MAC" 2>/dev/null | grep -c "Connected: yes")
if [ "$CONNECTED" = 0 ]; then
say "连接音箱 $BT_MAC ..."
timeout 30 bluetoothctl connect "$BT_MAC" >/dev/null 2>&1
sleep 3
fi
# ---------- 3. 找到 PipeWire 蓝牙输出节点 ----------
SINK="${SINK:-$DEF_SINK}"
echo "$SINK" > "$SINK_FILE"
export PIPEWIRE_RUNTIME_DIR=/run/user/0
export DBUS_SESSION_BUS_ADDRESS="$(cat /run/pipewire-dbus-address 2>/dev/null)"
NODE_ID=""
for i in 1 2 3 4 5 6 7 8; do
# wpctl status 中,Sinks 段下的行形如: " │ * 36. JBL PS3500 [vol: 0.10]"
# 先截取 Sinks: 段(到下一个 ├─ 或 └─ 为止),再在段内按音箱名匹配 ID
NODE_ID=$(timeout 5 wpctl status 2>/dev/null \
| sed -E 's/\x1b\[[0-9;]*m//g' \
| awk -v kw="$SINK" '
/Sinks:/ {insink=1; next}
/^[ │]*[├└]─/ {insink=0}
insink && tolower($0) ~ tolower(kw) {
match($0, /[0-9]+\./); print substr($0, RSTART, RLENGTH-1); exit
}'
)
[ -n "$NODE_ID" ] && break
sleep 1
done
[ -n "$NODE_ID" ] || { echo "找不到蓝牙输出节点(音箱名含 '$SINK')。当前状态:"; timeout 5 wpctl status 2>&1 | sed -E 's/\x1b\[[0-9;]*m//g' | grep -iE "bluez|Sinks" ; exit 1; }
VOL_F=$(awk "BEGIN{printf \"%.4f\", $VOL/100}")
# JBL 等支持 AVRCP 绝对音量的音箱会把自身音量回传覆盖软件设置,
# 因此设完后等待并复读,若被覆盖则再设一次(最多 3 轮)
i=0
while [ $i -lt 3 ]; do
timeout 5 wpctl set-volume "$NODE_ID" "$VOL_F"
sleep 1
CUR=$(timeout 5 wpctl get-volume "$NODE_ID" 2>/dev/null | grep -oE '[0-9.]+' | head -1)
# 用 awk 比较是否在目标 ±0.02 内
OK=$(awk -v a="$CUR" -v b="$VOL_F" 'BEGIN{print (a-b<0.02 && b-a<0.02)?1:0}')
[ "$OK" = 1 ] && break
i=$((i+1))
done
say "音箱节点: $NODE_ID 音量: ${VOL}% (当前 ${CUR:-?})"
# ---------- 4. 播放 ----------
FF_ARGS="-v error -i"
[ -n "$DUR" ] && FF_ARGS="-v error -t $DUR -i"
if [ -n "$DUR" ]; then
say "播放前 ${DUR}s: $SRC"
else
say "播放: $SRC"
fi
# POSIX sh 没有 PIPESTATUS,用 ffmpeg 的 stderr 文件判断是否出错
timeout 5 wpctl set-mute "$NODE_ID" 0 2>/dev/null
: > /tmp/bt-play-fferr
ffmpeg $FF_ARGS "$SRC" -f wav -ac 2 -ar 44100 - 2>>/tmp/bt-play-fferr \
| pw-cat --playback - --target "$NODE_ID" 2>/dev/null
if [ -s /tmp/bt-play-fferr ]; then
echo "ffmpeg 出错:"; head -3 /tmp/bt-play-fferr; rm -f /tmp/bt-play-fferr; exit 1
fi
rm -f /tmp/bt-play-fferr
say "播放完成"
+4
View File
@@ -0,0 +1,4 @@
edge-tts==7.3.1
mcp==2.3.0
# 系统依赖(apt):pipewire pipewire-audio libspa-0.2-bluetooth wireplumber pipewire-bin ffmpeg
# 蓝牙:bluez;音频输出需 PipeWire 系统级服务(见 README)
+295
View File
@@ -0,0 +1,295 @@
#!/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) -> dict:
"""播放 NAS 上已有的音频文件。
Args:
path: 绝对路径,必须在 /vol1/ 下
volume: 音量百分比 0-100
"""
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)
@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 stop() -> dict:
"""停止当前正在播放的内容(TTS 或音乐)。"""
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")
View File
Whitespace-only changes.
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""本地测试 MCP server 的工具调用。用法: test_client.py <tool> [json_args]"""
import json
import sys
import anyio
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client # mcp 2.x
URL = "http://127.0.0.1:8765/mcp"
async def main():
tool = sys.argv[1] if len(sys.argv) > 1 else "status"
args = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}
async with streamable_http_client(URL) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
if tool == "list":
tools = await session.list_tools()
for t in tools.tools:
print(f"- {t.name}: {t.description.splitlines()[0]}")
return
res = await session.call_tool(tool, arguments=args)
for c in res.content:
if hasattr(c, "text"):
try:
print(json.dumps(json.loads(c.text), ensure_ascii=False, indent=2))
except Exception:
print(c.text)
if res.is_error:
print("[ERROR]")
anyio.run(main) # 用 anyio 事件循环,避免和 MCP 客户端的 TaskGroup 清理冲突
+78
View File
@@ -0,0 +1,78 @@
"""
TTS 层:edge-tts 合成 + 本地缓存(相同文本+音色不重复请求)。
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import time
from pathlib import Path
log = logging.getLogger("ai-speaker.tts")
DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"
CACHE_DIR = Path("/vol1/1000/Programs/ai-speaker/cache")
CACHE_DIR.mkdir(parents=True, exist_ok=True)
# 常用中文音色,供 list_voices 返回
VOICES = {
"zh-CN-XiaoxiaoNeural": "晓晓(女,标准,默认)",
"zh-CN-XiaoyiNeural": "晓伊(女,柔和)",
"zh-CN-YunxiNeural": "云希(男,年轻)",
"zh-CN-YunjianNeural": "云健(男,浑厚,适合播报)",
"zh-CN-YunyangNeural": "云扬(男,新闻播音)",
"zh-CN-YunxiaNeural": "云夏(男,童声/活泼)",
"zh-CN-liaoning-XiaobeiNeural": "晓北(女,东北口音)",
"zh-CN-shaanxi-XiaoniNeural": "晓妮(女,陕西口音)",
}
def _cache_path(text: str, voice: str, rate: str, volume: str) -> Path:
key = hashlib.sha256(f"{voice}|{rate}|{volume}|{text}".encode()).hexdigest()[:24]
return CACHE_DIR / f"{key}.mp3"
async def _synth(text: str, voice: str, rate: str, volume: str, out: Path) -> None:
import edge_tts
kw = {"rate": rate, "volume": volume}
if rate == "+0%":
kw.pop("rate")
if volume == "+0%":
kw.pop("volume")
communicate = edge_tts.Communicate(text, voice, **kw)
await communicate.save(str(out))
def synthesize(text: str, voice: str = DEFAULT_VOICE, rate: str = "+0%", volume: str = "+0%") -> dict:
"""
合成语音到缓存文件。返回 {"ok","path","cached","seconds"}。
失败返回 {"ok": False, "error"}。
"""
text = (text or "").strip()
if not text:
return {"ok": False, "error": "文本为空"}
if len(text) > 1500:
return {"ok": False, "error": f"文本过长({len(text)} 字),上限 1500 字"}
if voice not in VOICES:
return {"ok": False, "error": f"不支持的音色 {voice},可选: {', '.join(VOICES)}"}
out = _cache_path(text, voice, rate, volume)
if out.exists() and out.stat().st_size > 0:
return {"ok": True, "path": str(out), "cached": True, "seconds": 0.0}
t0 = time.time()
tmp = out.with_suffix(".tmp.mp3")
try:
asyncio.run(asyncio.wait_for(_synth(text, voice, rate, volume, tmp), timeout=30))
if not tmp.exists() or tmp.stat().st_size == 0:
raise RuntimeError("合成结果为空")
tmp.rename(out)
except Exception as e:
tmp.unlink(missing_ok=True)
log.exception("TTS 合成失败")
return {"ok": False, "error": f"{type(e).__name__}: {str(e)[:150]}"}
return {"ok": True, "path": str(out), "cached": False, "seconds": round(time.time() - t0, 2)}
def cache_stats() -> dict:
files = list(CACHE_DIR.glob("*.mp3"))
return {"count": len(files), "bytes": sum(f.stat().st_size for f in files), "dir": str(CACHE_DIR)}