新增语音输入(mcp_asr)与健康检查服务标识

语音输入:输入框为空时发送键变麦克风,进入语音模式后按住说话、松手转写并发送;套壳 App 走原生录音桥,浏览器走 MediaRecorder(需 HTTPS)。转写在 mcp_asr,经 /api/asr/transcribe 直达,不经过模型、不消耗 token。

/api/health 增加 service/api/auth_required 字段并设 no-store,供套壳 App 校验手填的服务器地址;免认证路径容忍尾斜杠,避免 /api/health/ 被中间件 401。

接线与文档:compose 新增 mcp_asr;init.sh 默认复用 BIGMODEL_KEY 作为 ASR_API_KEY;README/AGENTS/mcp 文档同步。版本 2.3.0 → 2.4.0。
This commit is contained in:
2026-10-24 16:13:30 +08:00
parent 5b70f7d614
commit 53fa5da82b
24 changed files with 1810 additions and 29 deletions
+12 -3
View File
@@ -1,12 +1,13 @@
# MCP 服务集合
三个 MCP(Model Context Protocol)服务,各占一个目录,由仓库根 `docker-compose.yml` 统一编排:
四个 MCP(Model Context Protocol)服务,各占一个目录,由仓库根 `docker-compose.yml` 统一编排:
| 目录 | 容器名 | 作用 | 容器内端口 | MCP 端点 |
|---|---|---|---|---|
| `web_search/` | `mcp_web_search` | 免费网页搜索(Parallel / Exa,无需 key) | `3000` | `POST /` |
| `image_task/` | `mcp_image_task` | 图片生成 / 编辑(智谱原生或任意 OpenAI 兼容 `/images/generations`,单工具 op=create/get) | `3000` | `POST /mcp` |
| `video_task/` | `mcp_video_task` | 智谱 CogVideo 视频生成(异步,单工具 op=create/get) | `3000` | `POST /mcp` |
| `asr/` | `mcp_asr` | 语音转文字(上游 OpenAI 兼容 `/audio/transcriptions`),**额外带一个给输入框用的 `POST /transcribe`** | `3000` | `POST /mcp` |
**这些服务一个宿主机端口都不占**——它们只挂在 `agent-mcp-net` 上,由 `agent-core` / `agent-executor`
按容器名访问。所以整台服务器对外只需要开 agent-core 那一个端口(`AGENT_PORT`,默认 8090)。
@@ -31,16 +32,23 @@ mcp_servers:
url: "http://mcp_image_task:3000/mcp"
- name: video_task
url: "http://mcp_video_task:3000/mcp"
# 可选:语音转写(低频,建议 skill 模式,不占每轮工具表)
- name: asr
url: "http://mcp_asr:3000/mcp"
mode: skill
```
服务没起来时,core 只在启动日志里告警,不影响 Web 主流程,但对应工具不会下发给模型。工具发现只在启动时做一次,失败后会自动按 2s / 20s / 1min 重试 3 次;三次都失败则需重启 core。三个服务都配了 `/health` 健康检查,`docker ps` 可直接看状态。
服务没起来时,core 只在启动日志里告警,不影响 Web 主流程,但对应工具不会下发给模型。工具发现只在启动时做一次,失败后会自动按 2s / 20s / 1min 重试 3 次;三次都失败则需重启 core。四个服务都配了 `/health` 健康检查,`docker ps` 可直接看状态。
> 从旧的「agent + mcp 双仓库」部署升级:先在旧 mcp 仓库目录 `docker compose down`(只需一次,否则同名容器与网络会冲突),再 `up` 本栈。
`image_task` / `video_task` 的 token **不由服务端保存**——每个请求从 `Authorization` header 读取
(agent 侧配在 `config.yml` 的 `mcp_servers[].headers`)。`video_task` 用智谱 token;
`image_task` 用对应上游(智谱或 OpenAI 兼容网关)的 token,上游地址与模型分别由
`X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定。所以这里不用配任何密钥。
`X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定。所以这两个服务不用配任何密钥。
`asr` 是例外:输入框那条路(`agent-core` → `POST /transcribe`)不经过 MCP 调用,拿不到 header,
所以它自己的上游密钥由容器 env `ASR_API_KEY` 提供(写在根 `.env`,已 gitignore,不挂给其他容器)。
### 调试端口
@@ -78,6 +86,7 @@ AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp
| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度);agent 走内网访问 |
| `mcp_image_task` | 无 | token 由调用方自带,暴露后可被拿去消耗你的上游图片额度 |
| `mcp_video_task` | 无 | 它需要的公开临时 URL 由 agent 侧集成的工具提供,自己不占端口 |
| `mcp_asr` | 无 | `/mcp` 与 `/transcribe` 都无鉴权,只能由 core 经内网调用;它持有上游 ASR 密钥 |
## 单独调试
+2
View File
@@ -0,0 +1,2 @@
node_modules
*.md
+18
View File
@@ -0,0 +1,18 @@
FROM node:22-slim
# ffmpeg 只装在这里(core 镜像保持干净):WebView 录出来是 webm/opus,iOS 是 mp4/aac,
# 云端只认 wav/mp3——统一在容器内转成 16k 单声道 wav,前端与引擎两头都不用关心格式。
RUN apt-get update \
&& apt-get install -y --no-install-recommends ffmpeg ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# 零依赖:不需要 npm install(也就没有 registry 慢/被墙的问题)
COPY package.json ./
COPY src ./src
ENV PORT=3000
EXPOSE 3000
CMD ["node", "src/server.js"]
+87
View File
@@ -0,0 +1,87 @@
# mcp/asr — 语音识别服务
一个容器,两个入口,共用同一套转写实现:
| 入口 | 谁在用 | 说明 |
|---|---|---|
| `POST /transcribe` | `agent-core` 的 `/api/asr/transcribe`(H5 输入框) | 普通 HTTP,音频二进制进、`{text}` 出。**不经过模型、不消耗 token、1~3s** |
| `POST /mcp` | 模型(MCP 工具 `transcribe_audio`) | 转写任务目录里已有的音频,参数是公网 URL(与 `video_task` 的 `image_url` 同构) |
| `GET /health` | compose healthcheck | `{ok, model, configured}` |
端口 `3000` **只在 `agent-mcp-net` 内网**,不映射宿主机——本服务自身没有鉴权,暴露即被白嫖。
对外唯一入口仍是 `agent-core`(`/api/asr` 走登录态鉴权)。
## 为什么不是「录音 → 上传附件 → 模型调工具」
那要额外一次完整模型往返(3~10s + token),识别结果落进聊天记录而不是输入框,用户还没法改错字。
输入法级别的功能必须绕开模型;`/mcp` 那个口只留给「转写一段已上传的录音」这种低频需求。
## 部署
```bash
# 1) 配上游密钥(写进仓库根 .env,已 gitignore)
# ASR_API_KEY=你的智谱 token
# 2) 起服务
docker compose up -d --build mcp_asr
docker compose restart agent-core # core 要在启动时读到 ASR_URL
curl -s http://127.0.0.1:8090/api/asr/status # {"enabled":true,...}
```
`agent-core` 的环境变量 `ASR_URL`(compose 里固定为 `http://mcp_asr:3000`)是开关:置空即
不启用,`/api/asr/*` 回 503,前端不显示麦克风按钮。
## 上游
任何 OpenAI 兼容的 `/audio/transcriptions` 都能用;默认智谱:
| 变量 | 默认 |
|---|---|
| `ASR_API_BASE` | `https://open.bigmodel.cn/api/paas/v4` |
| `ASR_API_KEY` | 空(空则 `/transcribe` 回 503) |
| `ASR_MODEL` | `glm-asr` |
常驻内存约 35~40MB,CPU 基本为 0。没有本地模型可选:2 vCPU / 2GB 的机器跑不动能用的
whisper(固定 30 秒窗口,`small` 单次要 15~30 秒),需要私有化就把这个容器放到另一台机器,
只改 core 的 `ASR_URL` 指向它。
## HTTP 接口
```bash
# 任意格式(webm / mp4 / mp3 / wav / ogg / aac / flac),服务端用 ffmpeg 归一化
curl -s -X POST http://mcp_asr:3000/transcribe \
-H 'Content-Type: audio/webm' \
--data-binary @voice.webm
# → {"text":"打开今天的日报","ms":842,"model":"glm-asr"}
```
- 上限 20MB;超过 `ASR_MAX_CHUNK_SEC`(默认 25s)的音频自动切片后逐段识别再拼接
(多数云端 ASR 单次只吃 ~30s)。
- 同时最多 `ASR_MAX_CONCURRENT`(默认 2)个转写,超了回 429。
## MCP 工具
```yaml
# config.yml
mcp_servers:
- name: asr
url: "http://mcp_asr:3000/mcp"
mode: skill # 低频能力,别每轮都发 schema
```
`transcribe_audio({ url })`:本地文件先用内置工具 `mint_public_link` 换成公网短链,
再把链接传进来(和 `video_task` 要 `image_url` 是同一套路)。
## 环境变量速查
| 变量 | 默认 | 说明 |
|---|---|---|
| `ASR_API_BASE` / `ASR_API_KEY` / `ASR_MODEL` | 见上 | 上游语音识别 |
| `ASR_MAX_BYTES` | 20971520 | 单次上传上限 |
| `ASR_MAX_CHUNK_SEC` | `25` | 超长音频切片长度,`0` = 不切 |
| `ASR_MAX_CONCURRENT` | `2` | 并发转写数 |
| `ASR_LOG_LEVEL` | `info` | debug / info / warn / error / none |
## 客户端怎么录音
浏览器侧只有 HTTPS 才允许开麦;**Android 套壳 App 用原生录音再把 base64 交给页面**,
http 页面也能用。桥的契约与 Kotlin 示例见 [docs/voice-input.md](../../docs/voice-input.md)。
+10
View File
@@ -0,0 +1,10 @@
{
"name": "mcp_asr",
"version": "1.0.0",
"description": "ASR service: POST /transcribe for the H5 composer, POST /mcp for the model (tool transcribe_audio). Zero dependencies.",
"type": "module",
"main": "src/server.js",
"scripts": {
"start": "node src/server.js"
}
}
+433
View File
@@ -0,0 +1,433 @@
#!/usr/bin/env node
// ASR(语音转文字)服务。一个进程两个入口,共用同一套转写实现:
//
// POST /transcribe 普通 HTTP —— 给 agent-core 的输入框用:录完音直接拿文字,
// 不经过模型、不花 token、延迟 1~3s。
// POST /mcp Streamable HTTP MCP —— 工具 transcribe_audio({url}),给模型转写
// 会话目录里的音频(本地文件先 mint_public_link 换公网短链,与 video_task 同构)。
//
// 为什么不直接用 MCP 工具做语音输入:MCP 是模型协议,走一次工具调用要多一轮模型往返
//(3~10s + token),识别结果还会落进聊天记录而不是输入框,用户没法改错字。输入法级别的
// 功能必须绕开模型。
//
// 为什么零依赖(不用 express / MCP SDK):core 的 MCP 客户端只发 initialize / tools/list /
// tools/call 三种请求,手写这几十行 JSON-RPC 就够;本机内存只有 2G,省掉 SDK 与 express
// 的常驻开销(本服务空载约 35MB)。
//
// 转写走上游的 OpenAI 兼容 /audio/transcriptions(默认智谱 glm-asr,换平台改 env 即可)。
// 音频一律先经 ffmpeg 归一化成 16kHz 单声道 wav:WebView 录出来是 webm/opus,iOS 是 mp4/aac,
// 上游只认 wav/mp3,归一化后两端都自由。
import http from 'node:http';
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
// ── 配置(全部走 env,不读 config.yml:本容器按仓库惯例只拿 env) ──────────────
const PORT = Number(process.env.PORT || 3000);
// 上游:任何 OpenAI 兼容的 /audio/transcriptions(智谱 glm-asr、OpenAI whisper-1 等)
const API_BASE = String(process.env.ASR_API_BASE || 'https://open.bigmodel.cn/api/paas/v4').trim().replace(/\/+$/, '');
const API_KEY = String(process.env.ASR_API_KEY || '').trim();
const API_MODEL = String(process.env.ASR_MODEL || 'glm-asr').trim();
// 单次上传上限。60s 的 AAC 约 240KB、16k wav 约 1.9MB,20MB 是给长音频留的余量。
const MAX_BYTES = Math.max(1024 * 1024, Number(process.env.ASR_MAX_BYTES || 20 * 1024 * 1024));
// 云端多数 ASR 单次只吃 ~30s:超长音频按这个秒数切片后逐段识别再拼接(0 = 不切)。
// 16k/16bit 单声道 wav 恒为 32000 B/s,所以用文件大小就能估时长,不用再起 ffprobe。
const CHUNK_SEC = Math.max(0, Number(process.env.ASR_MAX_CHUNK_SEC || 25));
// 同时转写数:2 vCPU 上并发再高只会互相拖慢。
const MAX_CONCURRENT = Math.max(1, Number(process.env.ASR_MAX_CONCURRENT || 2));
const FFMPEG = String(process.env.FFMPEG_BIN || 'ffmpeg').trim();
const LOG_LEVEL = String(process.env.ASR_LOG_LEVEL || 'info').toLowerCase();
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40, none: 99 };
function log(level, msg) {
if ((LEVELS[level] || 20) < (LEVELS[LOG_LEVEL] == null ? 20 : LEVELS[LOG_LEVEL])) return;
console.log('[asr ' + level + '] ' + msg);
}
// ── 子进程:统一超时 + 收 stdout/stderr ────────────────────────────────────
function run(cmd, args, timeoutMs) {
return new Promise((resolve, reject) => {
let child;
try {
child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
} catch (e) {
return reject(e);
}
let out = '';
let err = '';
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try { child.kill('SIGKILL'); } catch (_) { /* 已退出 */ }
reject(new Error(cmd + ' 超时(' + timeoutMs + 'ms)'));
}, timeoutMs);
timer.unref();
child.stdout.on('data', (d) => { out += d; });
child.stderr.on('data', (d) => { err += d; });
child.on('error', (e) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(e); // ENOENT:二进制没装(如没装 ffmpeg)
});
child.on('close', (code) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (code === 0) resolve({ stdout: out, stderr: err });
else reject(new Error(cmd + ' 退出码 ' + code + ':' + ((err || out).slice(-400) || '无输出')));
});
});
}
// ── 音频:归一化成 16k 单声道 wav(再把超长音频切片) ───────────────────────
async function toWav(buf, ext) {
const id = randomUUID();
const inPath = path.join(os.tmpdir(), 'asr-in-' + id + (ext ? '.' + ext : ''));
const wavPath = path.join(os.tmpdir(), 'asr-out-' + id + '.wav');
try {
await fs.writeFile(inPath, buf);
await run(FFMPEG, [
'-hide_banner', '-loglevel', 'error', '-y',
'-i', inPath,
'-vn', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', '-f', 'wav',
wavPath,
], 60000);
return wavPath;
} catch (e) {
await fs.rm(inPath, { force: true }).catch(() => {});
await fs.rm(wavPath, { force: true }).catch(() => {});
// ffmpeg 的 stderr 很有用(定位是封装不对还是文件截断),但只进日志——
// 回给前端的长英文堆栈对用户毫无意义,toast 里只会显示第一行。
log('warn', '音频解码失败:' + String(e && e.message || e));
const err = new Error('音频解码失败(格式不支持或文件损坏)');
err.status = 400;
throw err;
} finally {
await fs.rm(inPath, { force: true }).catch(() => {});
}
}
// 按秒切片:只在超过 CHUNK_SEC 时做。切片用 -c copy,纯 PCM 无损。
async function splitWav(wavPath, chunkSec) {
const dir = path.dirname(wavPath);
const base = path.basename(wavPath, '.wav');
const pattern = path.join(dir, base + '-part-%03d.wav');
await run(FFMPEG, [
'-hide_banner', '-loglevel', 'error', '-y',
'-i', wavPath,
'-f', 'segment', '-segment_time', String(chunkSec), '-c', 'copy',
pattern,
], 60000);
const files = (await fs.readdir(dir))
.filter((f) => f.startsWith(base + '-part-') && f.endsWith('.wav'))
.sort();
return files.map((f) => path.join(dir, f));
}
// ── 引擎 ──────────────────────────────────────────────────────────────────
function extractText(obj) {
if (!obj) return '';
if (typeof obj === 'string') return obj;
if (typeof obj.text === 'string') return obj.text;
if (obj.result && typeof obj.result.text === 'string') return obj.result.text;
return '';
}
async function runCloud(wavPath) {
if (!API_KEY) {
const e = new Error('语音识别未配置:容器环境变量 ASR_API_KEY 为空');
e.status = 503;
throw e;
}
const buf = await fs.readFile(wavPath);
const form = new FormData();
form.append('model', API_MODEL);
form.append('file', new Blob([buf], { type: 'audio/wav' }), 'audio.wav');
let res;
try {
res = await fetch(API_BASE + '/audio/transcriptions', {
method: 'POST',
headers: { Authorization: 'Bearer ' + API_KEY },
body: form,
signal: AbortSignal.timeout(60000),
});
} catch (e) {
const err = new Error('调用上游语音识别失败:' + String(e && e.message || e));
err.status = 502;
throw err;
}
const raw = await res.text();
if (!res.ok) {
// 智谱对“解码后没有可识别语音”的音频回 400/1210 no audio segment found。
// 这通常不是服务故障(录音是静音、或浏览器只录到空白),给一句人话,别把上游 JSON 丢给用户。
let upstreamMsg = raw.slice(0, 300);
let upstreamCode = '';
try {
const obj = JSON.parse(raw);
if (obj && obj.error) {
upstreamMsg = String(obj.error.message || upstreamMsg);
upstreamCode = String(obj.error.code || '');
}
} catch (_) { /* 非 JSON,保留原文 */ }
const noSpeech = /no audio segment/i.test(upstreamMsg) || upstreamCode === '1210';
const err = new Error(noSpeech
? '没有识别到语音内容(录到的是静音,或音频解码后为空)'
: '上游识别失败 HTTP ' + res.status + ':' + upstreamMsg);
err.status = noSpeech ? 400 : 502;
err.upstream = upstreamMsg;
throw err;
}
let obj = null;
try { obj = JSON.parse(raw); } catch (_) { return raw.trim(); }
const text = extractText(obj);
if (!text) {
const err = new Error('上游返回为空:' + raw.slice(0, 300));
err.status = 502;
throw err;
}
return text;
}
// 归一化后 wav 的实测音量(仅 debug 级别调用):用于区分“文件坏了”和“录到的是静音”。
// volumedetect 跟解码共用一次遍历,开销很小,但只在排查时跑。
async function wavLevel(wavPath) {
const r = await run(FFMPEG, [
'-hide_banner', '-nostats', '-i', wavPath, '-af', 'volumedetect', '-f', 'null', '-',
], 30000);
const mean = /mean_volume:\s*(-?[\d.]+) dB/.exec(r.stderr);
const max = /max_volume:\s*(-?[\d.]+) dB/.exec(r.stderr);
return (mean ? mean[1] : '?') + ' / ' + (max ? max[1] : '?') + ' dB';
}
// 转写一段音频缓冲:归一化 →(超长则切片)→ 逐段识别 → 拼接。
async function transcribeBuffer(buf, opts) {
const wavPath = await toWav(buf, opts && opts.ext);
const parts = [];
try {
const st = await fs.stat(wavPath);
const seconds = st.size / 32000; // 16k/单声道/16bit
// 每次请求都打一行:原始字节 → 归一化时长。排查“上游说没声音”时第一眼看这个。
log('info', '归一化:' + buf.length + 'B (' + ((opts && opts.ext) || '?') + ') → '
+ seconds.toFixed(1) + 's wav');
if (CHUNK_SEC > 0 && seconds > CHUNK_SEC * 1.2) {
parts.push(...await splitWav(wavPath, CHUNK_SEC));
log('info', '超长音频切成 ' + parts.length + ' 段');
}
if (!parts.length) {
try {
return (await runCloud(wavPath)).trim();
} catch (e) {
// 只在上游判定“没有语音”时量一遍音量(正常路径零开销):
// 静音是 -91dB,正常语音 -20dB 上下,一眼就能分清是设备没收到声还是文件坏了。
if (e && e.status === 400) {
log('warn', '音量(mean/max): ' + await wavLevel(wavPath).catch(() => '?'));
}
throw e;
}
}
const out = [];
for (const p of parts) {
// 每段独立识别;单段失败不连累其他段(长录音里偶发静音段常见)
try {
out.push((await runCloud(p)).trim());
} catch (e) {
log('warn', '切片识别失败(跳过):' + String(e && e.message || e).slice(0, 200));
}
}
return out.filter(Boolean).join('');
} finally {
await fs.rm(wavPath, { force: true }).catch(() => {});
for (const p of parts) await fs.rm(p, { force: true }).catch(() => {});
}
}
// ── HTTP 小工具 ───────────────────────────────────────────────────────────
function json(res, code, obj) {
if (res.headersSent) return;
const body = JSON.stringify(obj);
res.writeHead(code, {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': Buffer.byteLength(body),
'Cache-Control': 'no-store',
});
res.end(body);
}
function readBody(req, limit) {
return new Promise((resolve, reject) => {
const chunks = [];
let n = 0;
let failed = false;
req.on('data', (c) => {
if (failed) return;
n += c.length;
if (n > limit) {
failed = true;
const e = new Error('音频过大(上限 ' + Math.round(limit / 1048576) + 'MB)');
e.status = 413;
reject(e);
return;
}
chunks.push(c);
});
req.on('end', () => { if (!failed) resolve(Buffer.concat(chunks)); });
req.on('error', (e) => { if (!failed) reject(e); });
});
}
const EXT_BY_MIME = {
'audio/webm': 'webm', 'audio/ogg': 'ogg', 'audio/mp4': 'm4a', 'audio/x-m4a': 'm4a',
'audio/mpeg': 'mp3', 'audio/mp3': 'mp3', 'audio/wav': 'wav', 'audio/x-wav': 'wav',
'audio/aac': 'aac', 'audio/flac': 'flac', 'audio/amr': 'amr',
};
function extOf(contentType) {
const k = String(contentType || '').split(';')[0].trim().toLowerCase();
return EXT_BY_MIME[k] || '';
}
// ── 入口 1:POST /transcribe(普通 HTTP,给输入框) ────────────────────────
let active = 0;
async function handleTranscribe(req, res, url) {
if (active >= MAX_CONCURRENT) {
return json(res, 429, { error: '语音识别繁忙,请稍后再试' });
}
const buf = await readBody(req, MAX_BYTES);
if (!buf.length) return json(res, 400, { error: '未收到音频数据' });
active++;
const t0 = Date.now();
try {
const text = await transcribeBuffer(buf, { ext: extOf(req.headers['content-type']) });
log('info', 'transcribed ' + buf.length + 'B → ' + text.length + ' 字,' + (Date.now() - t0) + 'ms');
json(res, 200, { text, ms: Date.now() - t0, model: API_MODEL });
} finally {
active--;
}
}
// ── 入口 2:POST /mcp(Streamable HTTP,给模型) ──────────────────────────
const TOOL = {
name: 'transcribe_audio',
description:
'Transcribe an audio file to text. Provide a publicly reachable http(s) URL '
+ '(mp3 / wav / m4a / webm / ogg / aac / flac, <= 20MB). '
+ 'For a file inside the current task directory, first call the built-in mint_public_link tool '
+ 'to get a temporary public URL, then pass that URL here.',
inputSchema: {
type: 'object',
properties: {
url: { type: 'string', description: 'Publicly reachable http(s) URL of the audio file.' },
},
required: ['url'],
},
};
async function fetchAudio(urlStr) {
let u;
try { u = new URL(urlStr); } catch (_) { throw new Error('url 不是合法链接'); }
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error('只支持 http(s) 链接');
const res = await fetch(u, { redirect: 'follow', signal: AbortSignal.timeout(30000) });
if (!res.ok) throw new Error('下载音频失败 HTTP ' + res.status);
const buf = Buffer.from(await res.arrayBuffer());
if (!buf.length) throw new Error('下载到的音频为空');
if (buf.length > MAX_BYTES) throw new Error('音频过大(上限 ' + Math.round(MAX_BYTES / 1048576) + 'MB)');
return { buf, ext: extOf(res.headers.get('content-type')) };
}
async function handleMcp(req, res) {
const raw = await readBody(req, 1024 * 1024);
let msg;
try { msg = JSON.parse(raw.toString('utf8')); } catch (_) {
return json(res, 400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
}
const id = msg && msg.id !== undefined ? msg.id : null;
const method = msg && msg.method;
const params = (msg && msg.params) || {};
const ok = (result) => json(res, 200, { jsonrpc: '2.0', id, result });
const fail = (code, message) => json(res, 200, { jsonrpc: '2.0', id, error: { code, message } });
if (method === 'initialize') {
return ok({
protocolVersion: '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: 'asr', version: '1.0.0' },
});
}
// 无状态实现:不返回 Mcp-Session-Id,core 也就不会带;通知直接回空结果(core 不校验)。
if (method === 'notifications/initialized' || method === 'notifications/cancelled') return ok({});
if (method === 'ping') return ok({});
if (method === 'tools/list') return ok({ tools: [TOOL] });
if (method === 'tools/call') {
if (params.name !== TOOL.name) return fail(-32602, 'Unknown tool: ' + params.name);
const args = params.arguments || {};
const urlStr = String(args.url || '').trim();
if (!urlStr) return ok({ isError: true, content: [{ type: 'text', text: '缺少 url 参数' }] });
try {
const { buf, ext } = await fetchAudio(urlStr);
const text = await transcribeBuffer(buf, { ext });
return ok({ content: [{ type: 'text', text }] });
} catch (e) {
return ok({ isError: true, content: [{ type: 'text', text: '转写失败:' + String(e && e.message || e) }] });
}
}
return fail(-32601, 'Method not found: ' + method);
}
// ── 服务 ──────────────────────────────────────────────────────────────────
const server = http.createServer((req, res) => {
let url;
try { url = new URL(req.url, 'http://localhost'); } catch (_) {
return json(res, 400, { error: 'bad url' });
}
const done = (p) => {
Promise.resolve(p).catch((e) => {
const code = (e && e.status) || 500;
// 4xx 是可预期的输入问题(坏音频、没配 key),只记一行;5xx 才带堆栈
log(code >= 500 ? 'error' : 'warn', String(e && e.message || e) + (code >= 500 && e && e.stack ? '\n' + e.stack : ''));
if (!res.headersSent) json(res, code, { error: String(e && e.message || e) });
else try { res.end(); } catch (_) { /* 已断 */ }
});
};
if (req.method === 'GET' && url.pathname === '/health') {
return json(res, 200, {
ok: true,
model: API_MODEL,
configured: !!API_KEY,
});
}
if (req.method === 'POST' && url.pathname === '/transcribe') return done(handleTranscribe(req, res, url));
if (url.pathname === '/mcp') {
if (req.method !== 'POST') return json(res, 405, { error: 'only POST /mcp' });
return done(handleMcp(req, res));
}
return json(res, 404, { error: 'not found' });
});
let shuttingDown = false;
function shutdown(sig) {
if (shuttingDown) return;
shuttingDown = true;
log('info', '收到 ' + sig + ',退出');
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 3000).unref();
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
server.listen(PORT, '0.0.0.0', () => {
log('info', 'listening on ' + PORT + ',model=' + API_MODEL + ' @ ' + API_BASE);
if (!API_KEY) log('warn', 'ASR_API_KEY 为空:/transcribe 会返回 503');
});