MCP 设置页改成内置服务引导:预设卡片 + 字段表单

- header 掩码只遮密钥类(名字 Authorization/*token*/*key*,或值 Bearer…/sk-…),
  base-url / model 明文回显——引导表单得看得见当前值才能改
- restoreMcpHeaders 改为按键名还原(原按出现顺序,只遮部分 header 后会张冠李戴);
  补上单个 header 叶子写入的还原:原来把 ***** 直接写进 config.yml
- MCP 页分「内置服务」(4 张预设卡:未配置→添加、已配置→编辑)与「其它服务」
- 弹窗预设模式:name/url 只读、mode 收敛为「预设值 / disable」、字段按 presets.fields
  生成(左标签 + 右输入),隐藏 header 区;配置里历史多余的 header 保存时仍原样带上
- 超时 / 工具暴露改成左标签右控件的单行排版,ms 作输入框内后缀
- 移动端 MCP 弹窗放宽到 calc(100% - 24px),内边距收紧
This commit is contained in:
2026-10-25 15:22:48 +08:00
parent 1ea29c0448
commit d0e6a981a6
7 changed files with 327 additions and 98 deletions
+1
View File
@@ -165,6 +165,7 @@ curl -s http://127.0.0.1:8090/api/health
| 新增环境变量 | compose ↔ README「环境变量」 |
| 发版号 | `app/package.json` 的 `version` ↔ `app/server/routes/system.js` 的 `VERSION` 字面量(两者不自动同步) |
| 技能格式 | `skills/README.md` ↔ `app/server/tools/skills.js` 的解析 |
| 同栈 MCP 的 url / header 名 | `app/server/presets.json` ↔ `mcp/<服务>/src`(设置页引导表单的字段来自前者,不会自动跟随后者) |
| 对外 API | `app/server/routes/*` ↔ 前端 `app/server/public/js/*` ↔ README |
## 代码约定
+3 -1
View File
@@ -99,7 +99,9 @@ http://<服务器 IP>:<AGENT_PORT>
### 4. 同栈 MCP 服务
初始 `config.yml` 不包含任何 MCP 服务;四个服务都在设置页「MCP」添加(`web_search` 免费、无需 key)。手工写 YAML 的形状如下(`url` 与 header 名是固定的,容器不存密钥):
初始 `config.yml` 不包含任何 MCP 服务。设置页「MCP」会把四个同栈服务作为**内置服务卡片**列出来,
点卡片 → 填表 → 保存即可(url 与 header 名由 `app/server/presets.json` 提供,不用记)。
`web_search` 免费、无需 key;另外三个要填上游 key。手工写 YAML 的形状如下(容器不存密钥):
```yaml
mcp_servers:
+13 -15
View File
@@ -50,24 +50,24 @@
{
"key": "image_task",
"label": "图片生成",
"desc": "文生图 / 图生图,走任意 OpenAI 兼容的 /images/generations 与 /images/edits",
"desc": "文生图 / 图生图",
"url": "http://mcp_image_task:3000/mcp",
"mode": "skill",
"fields": [
{
"header": "Authorization",
"label": "API Key",
"label": "鉴权",
"secret": true,
"prefix": "Bearer ",
"required": true,
"placeholder": "上游的 API Key"
"placeholder": "API Key"
},
{
"header": "X-Image-Task-Base-Url",
"label": "上游地址",
"label": "地址",
"required": true,
"placeholder": "https://<host>/v1",
"hint": "填到 /v1 即可,文生图自动补 /images/generations,图生图自动补 /images/edits"
"hint": "OpenAI 兼容 generations / edits"
},
{
"header": "X-Image-Task-Model",
@@ -86,7 +86,7 @@
"fields": [
{
"header": "Authorization",
"label": "API Key",
"label": "鉴权",
"secret": true,
"prefix": "Bearer ",
"required": true,
@@ -95,38 +95,36 @@
{
"header": "X-Video-Task-Model",
"label": "模型",
"default": "cogvideox-flash",
"hint": "留空 = cogvideox-flash"
"default": "cogvideox-flash"
}
]
},
{
"key": "asr",
"label": "语音识别",
"desc": "输入框「按住说话」与模型的 transcribe_audio 共用",
"desc": "按住说话 / transcribe_audio",
"url": "http://mcp_asr:3000/mcp",
"mode": "skill",
"fields": [
{
"header": "Authorization",
"label": "API Key",
"label": "鉴权",
"secret": true,
"prefix": "Bearer ",
"placeholder": "自建免鉴权服务可留空"
"placeholder": "支持自建免鉴权服务"
},
{
"header": "X-ASR-Base-Url",
"label": "上游地址",
"label": "地址",
"required": true,
"placeholder": "https://<host>/v1",
"hint": "任意 OpenAI 兼容的 /audio/transcriptions"
"hint": "OpenAI 兼容的 /audio/transcriptions"
},
{
"header": "X-ASR-Model",
"label": "模型",
"required": true,
"default": "whisper-1",
"placeholder": "whisper-1"
"placeholder": "上游的模型 id"
}
]
}
+27 -7
View File
@@ -1186,6 +1186,9 @@ label.icon-btn { cursor: pointer; }
.model-card-state.busy { background: #fdecea; color: #b3382c; }
.model-card-state.pending { background: #fff4dc; color: #a06a00; }
.model-card-state.off { background: var(--surface); color: var(--gray); }
/* MCP 页分段标题:内置服务 / 其它服务 */
.mcp-sec-title { margin: 16px 4px 0; font-size: 12.5px; font-weight: 600; color: var(--gray); }
.mcp-list > .mcp-sec-title:first-child { margin-top: 10px; }
/* 禁用态卡片:背景转灰、名称/token 区淡化,开关保持正常亮度可点 */
.model-card.off { background: #f5f6f8; }
.model-card.off .model-card-name, .model-card.off .cfg-kv { opacity: 0.5; }
@@ -1204,6 +1207,8 @@ label.icon-btn { cursor: pointer; }
/* 三段分区:平台字段 / Keys / 模型,用虚线分隔 + 留白,避免挤在一起 */
.modal .mpe-sec { margin-top: 16px; padding-top: 12px; border-top: 1px dashed var(--border); }
.modal .mpe-sec-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 0 0 10px; font-size: 13px; font-weight: 600; color: var(--ink); }
/* 标题右侧的说明(如内置服务的 desc):跟 flex 靠右,去掉 .cfg-note 的上边距;min-width 让它在窄屏可折行 */
.modal .mpe-sec-head .cfg-note { margin: 0; text-align: right; min-width: 0; font-weight: 400; }
.modal .mpe-foot { margin-top: 18px; }
.modal .mpe-sec-head .ghost-btn.sm { flex: none; padding: 4px 12px; font-size: 12.5px; border-radius: 8px; }
.modal .mpe-row { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; }
@@ -1213,13 +1218,24 @@ label.icon-btn { cursor: pointer; }
.modal .mpe-mcard { border: 1px solid var(--border); border-radius: 10px; padding: 9px 10px; margin-bottom: 8px; background: #fafbfd; }
.modal .mpe-mcard .mpe-row { margin-bottom: 0; }
.modal .mpe-cks { display: flex; align-items: center; gap: 16px; margin-top: 8px; }
/* 超时(ms)与「启用」同排。数字框单独成类,不吃 .mpe-ck input 那套 15px 无边框样式(那是给 checkbox 的);
选择器带 .modal 前缀是为了压过 .modal input{width:100%},否则会被撑满整行。 */
.modal .mpe-num { display: flex; align-items: center; gap: 5px; flex: none; font-size: 12.5px; color: var(--gray); }
.modal .mpe-num input { width: 92px; padding: 5px 8px; margin: 0; font-size: 13px; border: 1px solid #dde1ea; border-radius: 8px; background: #fff; color: var(--ink); }
.modal .mpe-num input:focus { border-color: var(--active); }
/* MCP 的 mode 三态下拉:独立成行(弹窗内容宽仅 ~320px,与超时框同排会撑破),内层 select 用 .modal select 的全宽样式 */
.modal .mpe-field { display: block; margin-top: 14px; font-size: 12.5px; color: var(--gray); }
/* 单行设置项:左标签 / 右控件(与上面 header 那排同一种「一左一右」的节奏)
选择器带 .modal 前缀是为了压过 .modal input{width:100%},否则输入框会撑满整行。 */
.modal .mpe-line { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; font-size: 12.5px; color: var(--gray); }
.modal .mpe-line:last-child { margin-bottom: 0; }
.modal .mpe-line > span { flex: none; white-space: nowrap; }
.modal .mpe-line input { flex: 1; min-width: 0; margin: 0; }
.modal .mpe-line select { width: auto; min-width: 180px; margin: 0; }
/* 预设字段:一行(可选带说明)作为一个整体留间距 */
.modal .mpe-item { margin-bottom: 10px; }
.modal .mpe-item:last-child { margin-bottom: 0; }
.modal .mpe-item .mpe-line { margin-bottom: 0; }
.modal .mpe-item .cfg-note { margin-top: 4px; }
/* ms 作为输入框内的后缀:定位在框内右侧,pointer-events:none 保证点击穿给输入框 */
.modal .mpe-unit { position: relative; flex: none; width: 118px; }
.modal .mpe-unit input { width: 100%; margin: 0; padding: 8px 30px 8px 10px; }
.modal .mpe-unit i { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); font-style: normal; font-size: 11.5px; color: var(--gray-light); pointer-events: none; }
/* 预设模式下 name/url 是契约值(只读),压暗以区别于可编辑输入框 */
.modal input[readonly] { background: #f1f3f7; color: var(--gray); }
.modal .mpe-ck { display: flex; align-items: center; gap: 5px; font-size: 12.5px; color: var(--gray); }
.modal .mpe-ck input { width: 15px; height: 15px; padding: 0; margin: 0; border: none; background: none; accent-color: var(--active); cursor: pointer; }
.modal .mpe-del { flex: none; border: none; background: none; margin: 0; padding: 2px 7px; cursor: pointer; color: var(--gray-light); font-size: 18px; line-height: 1.2; }
@@ -1261,6 +1277,10 @@ label.icon-btn { cursor: pointer; }
background: var(--page); border-radius: 14px; padding: 20px; width: 84%; max-width: 360px;
position: relative; max-height: 88%; overflow-y: auto;
}
/* 移动端:MCP 配置弹窗左右留白收紧——表单是「左标签 + 右输入」双列,84% 宽度下输入框太窄 */
@media (max-width: 639px) {
#mcp-edit-modal .modal { width: calc(100% - 24px); padding: 18px 14px; }
}
.modal h3 { margin-bottom: 12px; font-size: 16px; }
.modal input {
width: 100%; border: 1px solid #dde1ea; border-radius: 10px;
+19 -13
View File
@@ -343,27 +343,33 @@
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
<h3 id="mce-title">编辑 MCP 服务</h3>
<input type="text" id="mce-name" placeholder="服务名(留空取 url 主机名首段)">
<input type="text" id="mce-url" placeholder="MCP 服务 JSON-RPC 端点(完整 URL)">
<div class="mpe-sec">
<input type="text" id="mce-name" placeholder="服务名">
<input type="text" id="mce-url" placeholder="MCP 服务 JSON-RPC URL">
<!-- 内置服务预设字段(url/name 只读,表单由预设生成) -->
<div class="mpe-sec hidden" id="mce-preset-sec">
<div class="mpe-sec-head"><span>配置参数</span><span class="cfg-note" id="mce-preset-desc"></span></div>
<div id="mce-preset-fields"></div>
</div>
<div class="mpe-sec" id="mce-headers-sec">
<div class="mpe-sec-head"><span>请求头(headers)</span><button class="ghost-btn sm" onclick="mcpUI.addHeader()">添加 header</button></div>
<div id="mce-headers"></div>
</div>
<div class="mpe-cks" style="margin-top:14px">
<label class="mpe-num">单次调用超时<input type="number" id="mce-timeout" min="1000" max="600000" step="1000" placeholder="默认 60000">ms</label>
<div class="mpe-sec">
<label class="mpe-line"><span>单次调用超时</span>
<span class="mpe-unit"><input type="number" id="mce-timeout" min="1000" max="600000" step="1000" placeholder="60000"><i>ms</i></span>
</label>
<label class="mpe-line"><span>工具暴露</span>
<select id="mce-mode">
<option value="advertise">advertise(下发给模型)</option>
<option value="skill">skill(以技能形式暴露)</option>
<option value="disable">disable(不加载)</option>
</select>
</label>
</div>
<label class="mpe-field">工具暴露
<select id="mce-mode">
<option value="advertise">advertise(下发给模型)</option>
<option value="skill">skill(以技能形式暴露)</option>
<option value="disable">disable(不加载)</option>
</select>
</label>
<div class="btn-row mpe-foot">
<button class="ghost-btn danger hidden" id="mce-del-btn" onclick="mcpUI.del()">删除服务</button>
<button class="primary-btn" onclick="mcpUI.save()">保存</button>
</div>
<div class="cfg-note">仅写入配置,点击「重启服务」后生效。</div>
</div>
</div>
+214 -47
View File
@@ -29,6 +29,7 @@
expandedGroups: {}, balanceByGroup: {}, balanceRequested: {}, balanceTypes: [], // 平台编辑弹窗工作态见 pfEdit(模块级变量)
// MCP 服务页:cfgMcp 缓存当前列表;改动待重启生效时置位,顶部常驻重启横幅
cfgMcp: [], mcpPendingRestart: false,
presets: null, // 平台/MCP 预设(GET /api/config/presets),设置页各页共用
};
let setTok = 0; // 异步渲染防竞态令牌
@@ -1425,8 +1426,38 @@
// mode 三态:advertise(默认,工具下发给模型) / skill(不下发,以技能形式暴露) / disable(不加载):
// 默认值不写进文件——选 advertise 时删键,回落到 config.js 的缺省。
// 运行配置(cg.effective.mcp_servers)即文件刚解析后的视图,按 pi 直接定位;重启后才会重新发现工具。
let mcpEdit = null; // 工作态:{ idx, headers:[{key, value, masked}] };idx=-1 为新增
// 预设取一次就缓存:取不到不报错,退化成纯自定义列表,不阻塞设置页
let presetsReq = null;
function loadPresets() {
if (SET.presets) return Promise.resolve(SET.presets);
if (!presetsReq) {
presetsReq = req('GET', '/api/config/presets').then(p => {
SET.presets = { platforms: (p && p.platforms) || [], mcp: (p && p.mcp) || [] };
return SET.presets;
}).catch(() => {
presetsReq = null; // 失败不缓存,下次进页再试
return { platforms: [], mcp: [] };
});
}
return presetsReq;
}
function presetMcpList() { return (SET.presets && SET.presets.mcp) || []; }
let mcpEdit = null; // 工作态:{ idx, preset, values:{header:值}, headers:[{key, value, masked}] };idx=-1 为新增
const MCP_HEADER_MASK = '*****'; // 与后端 routes/config.js 的掩码保持一致
const MCP_MODE_LABELS = {
advertise: 'advertise(下发给模型)',
skill: 'skill(以技能形式暴露)',
disable: 'disable(不加载)',
};
// url 归一化:内置服务按 url 认亲(name 允许用户改),尾斜杠不算差异
function normUrl(u) { return String(u || '').trim().replace(/\/+$/, ''); }
function presetIdx(p) {
const url = normUrl(p.url);
let i = SET.cfgMcp.findIndex(s => normUrl(s.url) === url);
if (i < 0) i = SET.cfgMcp.findIndex(s => String(s.name || '') === p.key);
return i;
}
async function setPageMcp(ctx) {
setTitle('MCP 服务');
setActions('<button class="icon-btn" title="添加 MCP 服务" onclick="mcpUI.add()">' +
@@ -1438,26 +1469,56 @@
const box = $('mcp-list');
if (!box || (ctx && !ctx())) return;
try {
const cg = await req('GET', '/api/config');
if (ctx && !ctx()) return;
if (!$('mcp-list')) return;
const [cg] = await Promise.all([req('GET', '/api/config'), loadPresets()]);
if ((ctx && !ctx()) || !$('mcp-list')) return;
SET.cfgMcp = (cg.effective && cg.effective.mcp_servers) || [];
if (!SET.cfgMcp.length) {
box.innerHTML = (SET.mcpPendingRestart
? '<div class="restart-bar"><span>配置已写入,重启后生效</span><button class="primary-btn" onclick="sUI.restartNow()">重启服务</button></div>'
: '') + '<div class="empty-tip">尚未配置 MCP 服务,点右上角 + 添加。</div>';
return;
}
const banner = SET.mcpPendingRestart
const presets = presetMcpList();
// 内置服务已占用的条目不再列入「其它」,避免同一服务出两张卡
const taken = new Set(presets.map(presetIdx).filter(i => i >= 0));
const others = SET.cfgMcp.map((s, i) => ({ s, i })).filter(o => !taken.has(o.i));
let html = SET.mcpPendingRestart
? '<div class="restart-bar"><span>配置已写入,重启后生效</span><button class="primary-btn" onclick="sUI.restartNow()">重启服务</button></div>'
: '';
box.innerHTML = banner + SET.cfgMcp.map(mcpCardHtml).join('') +
'<div class="empty-tip">点卡片编辑 MCP 服务。advertise 的工具启动时发现并追加到内置工具之后;skill 不下发,改为以技能形式暴露(skill 工具里 get 拿到原始 input_schema)。</div>';
if (presets.length) {
html += '<div class="mcp-sec-title">内置服务</div>' + presets.map(presetCardHtml).join('');
}
if (others.length) {
html += '<div class="mcp-sec-title">其它服务</div>' + others.map(o => mcpCardHtml(o.s, o.i)).join('');
}
if (!presets.length && !others.length) {
html += '<div class="empty-tip">尚未配置 MCP 服务,点右上角 + 添加。</div>';
}
$('mcp-list').innerHTML = html;
} catch (e) {
const b = $('mcp-list');
if (b && (!ctx || ctx())) b.innerHTML = '<div class="empty-tip">加载失败:' + esc(e.message) + '</div>';
}
}
// 内置服务卡:未配置→添加;已配置→显示当前值与状态,点击编辑。密钥类只显示「已配置」,不外显真值。
function presetCardHtml(p) {
const idx = presetIdx(p);
const s = idx >= 0 ? (SET.cfgMcp[idx] || {}) : null;
const mode = s ? (s.mode || 'advertise') : '';
const state = !s
? '<span class="model-card-state off">未配置</span>'
: mode === 'disable'
? '<span class="model-card-state off">已停用</span>'
: '<span class="model-card-state idle">已配置</span>';
const h = (s && s.headers) || {};
const kv = (p.fields || []).map(f => {
const v = h[f.header];
const txt = f.secret ? (v ? '已配置' : '--') : (v ? String(v) : '--');
return '<div class="cfg-kv"><label>' + esc(f.label || f.header) + '</label><b>' + esc(txt) + '</b></div>';
}).join('');
return '<div class="model-card' + (mode === 'disable' ? ' off' : '') + '"' +
' onclick="mcpUI.' + (s ? 'editPreset' : 'addPreset') + '(\'' + att(p.key) + '\')">' +
'<div class="model-card-head">' +
'<span class="model-card-name">' + esc(p.label || p.key) + '</span>' +
state +
'</div>' +
'<div class="cfg-kv"><label>地址</label><b>' + esc(p.url) + '</b></div>' + kv +
'</div>';
}
// MCP 卡:头部 = 名称 + url + mode 状态;体内 = headers 键值列表。整卡点击进入编辑。
function mcpCardHtml(s, pi) {
const mode = s.mode || 'advertise';
@@ -1467,8 +1528,12 @@
? '<span class="model-card-state idle">以技能暴露</span>'
: '<span class="model-card-state idle">启用</span>';
const entries = Object.entries(s.headers || {});
// header 值等同密码对待:后端 effective 已脱敏为固定短掩码,这里透传展示;若收到未脱敏原文也一律替换,不外显
const maskVal = (v) => { const str = String(v == null ? '' : v); if (!str) return '--'; return str.includes('*') ? esc(str) : MCP_HEADER_MASK; };
// 后端只对密钥类 header 脱敏(base-url/model 这类明文);掩码值统一显示「已配置」,不露长度
const maskVal = (v) => {
const str = String(v == null ? '' : v);
if (!str) return '--';
return str === MCP_HEADER_MASK ? '已配置' : esc(str);
};
const headersHtml = entries.length
? entries.map(([k, v]) => '<div class="cfg-kv"><label>' + esc(k) + '</label><b>' + maskVal(v) + '</b></div>').join('')
: '<div class="cfg-kv"><label>(无)</label><b>--</b></div>';
@@ -1480,25 +1545,58 @@
'</div>' + headersHtml +
'</div>';
}
// 弹窗打开:add 模式 (idx=-1) → 空工作态;edit 模式 → 从当前配置复制。
function openMcpEditor(idx) {
// 弹窗打开:add 模式 (idx=null) → 空工作态;edit 模式 → 从当前配置复制。
// presetKey 有值 = 内置服务模式:url/name/mode 是契约(只读),表单由预设的 fields 生成。
function openMcpEditor(idx, presetKey) {
const preset = presetKey ? (presetMcpList().find(p => p.key === presetKey) || null) : null;
const add = idx == null;
const s = add ? {} : (SET.cfgMcp[idx] || {});
const curH = s.headers || {};
const fieldHeaders = new Set(((preset && preset.fields) || []).map(f => f.header));
mcpEdit = {
idx: add ? -1 : Number(idx),
preset: preset,
values: {},
// 预设字段走 values;这里只留「配置里有、预设未声明」的 header(手加的)——
// headers 是整体替换的,不带着它们保存一次就丢了。
headers: Object.keys(curH).filter(k => !fieldHeaders.has(k)).map(k => {
const v = String(curH[k]);
// 明文值直接回填(可原地改);掩码值置空,placeholder 提示「留空保持不变」
return { key: k, value: v === MCP_HEADER_MASK ? '' : v, masked: v };
}),
};
if (preset) {
(preset.fields || []).forEach(f => {
// 明文项回填当前值(看得见才好改);密钥项只提示「已配置」,留空即保持原值
mcpEdit.values[f.header] = add
? (f.secret ? '' : String(f.default || ''))
: (f.secret ? '' : String(curH[f.header] || ''));
});
} else if (add) {
// headers 数组:每个 {key, value, masked} 为一条编辑行。已有行 value 置空、masked 存当前脱敏值仅做提示
// (同平台 Key 的留空=保持原值);新行 masked=null,必须手输真值。空 key 行保存时丢弃。
headers: add
? [{ key: '', value: '', masked: null }]
: Object.entries(s.headers || {}).map(([k, v]) => ({ key: k, value: '', masked: String(v) })),
};
$('mce-title').textContent = add ? '添加 MCP 服务' : '编辑 MCP 服务';
$('mce-name').value = add ? '' : (s.name || '');
$('mce-url').value = add ? '' : (s.url || '');
mcpEdit.headers = [{ key: '', value: '', masked: null }];
}
$('mce-title').textContent = (add ? '添加 ' : '编辑 ') + (preset ? preset.label : 'MCP 服务');
$('mce-name').value = preset ? preset.key : (add ? '' : (s.name || ''));
$('mce-url').value = preset ? preset.url : (add ? '' : (s.url || ''));
$('mce-name').readOnly = !!preset;
$('mce-url').readOnly = !!preset;
// 运行配置里的 timeout_ms 已被 config.js 填上缺省值,所以这里显示的就是当前生效值(没配则为 60000)。
$('mce-timeout').value = add || s.timeout_ms == null ? '' : String(s.timeout_ms);
$('mce-mode').value = add ? 'advertise' : (s.mode || 'advertise');
// 预设的 mode 是契约(asr / image_task 必须 skill 才不会把一堆转写/生成工具塞进每轮工具表),
// 只允许在「预设值 / disable」之间切;手改成别的值时按契约值显示,不凭空改写文件。
const curMode = add ? (preset ? (preset.mode || 'advertise') : 'advertise') : (s.mode || 'advertise');
const modes = preset ? [preset.mode || 'advertise', 'disable'] : ['advertise', 'skill', 'disable'];
$('mce-mode').innerHTML = modes.map(m => '<option value="' + att(m) + '">' + esc(MCP_MODE_LABELS[m] || m) + '</option>').join('');
$('mce-mode').value = modes.indexOf(curMode) >= 0 ? curMode : modes[0];
$('mce-preset-sec').classList.toggle('hidden', !preset);
$('mce-preset-desc').textContent = preset ? (preset.desc || '') : '';
// 预设已经覆盖该服务的全部 header,不再给「其它 header」入口;
// 配置里若还留着历史多余 header,仍原样带着(保存是整体替换,不带着就丢),只是不展示。
$('mce-headers-sec').classList.toggle('hidden', !!preset);
$('mce-del-btn').classList.toggle('hidden', add);
renderPresetFields();
renderMcpHeaders();
$('mcp-edit-modal').classList.remove('hidden');
}
@@ -1508,7 +1606,7 @@
// 已有行:输入框置空,placeholder 提示当前脱敏值;留空=保持原值,输入新值=替换
const ph = r.masked != null ? '当前: ' + r.masked + '(留空保持不变)' : '值';
return '<div class="mpe-row">' +
'<input class="mpe-grow" type="text" placeholder="Header 名(如 Authorization)" value="' + esc(r.key) + '" oninput="mcpUI.setHeader(' + i + ',\'key\',this.value)">' +
'<input class="mpe-grow" type="text" placeholder="Header 字段" value="' + esc(r.key) + '" oninput="mcpUI.setHeader(' + i + ',\'key\',this.value)">' +
'<input class="mpe-grow" type="text" placeholder="' + esc(ph) + '" value="' + esc(r.value) + '" oninput="mcpUI.setHeader(' + i + ',\'value\',this.value)">' +
'<button class="mpe-del" title="删除此 header" onclick="mcpUI.delHeader(' + i + ')">×</button>' +
'</div>';
@@ -1530,13 +1628,82 @@
renderMcpHeaders();
}
function setMcpHeader(i, f, v) { if (mcpEdit && mcpEdit.headers[i]) mcpEdit.headers[i][f] = v; }
// 预设字段表单:label + 输入框 + 提示。密钥项只提示「已配置」,不回填真值(前端拿到的本来就是掩码)。
function renderPresetFields() {
if (!mcpEdit) return;
const box = $('mce-preset-fields');
if (!box) return;
const p = mcpEdit.preset;
if (!p) { box.innerHTML = ''; return; }
const curH = ((mcpEdit.idx >= 0 && SET.cfgMcp[mcpEdit.idx]) || {}).headers || {};
box.innerHTML = (p.fields || []).map(f => {
const isSet = !!curH[f.header];
const ph = f.secret && isSet ? '已配置,留空保持不变' : (f.placeholder || '');
const val = mcpEdit.values[f.header] || '';
// 左标签 / 右输入,与下方「单次调用超时 / 工具暴露」同一种单行排版。
// 必填不加 * 标记(会破坏对齐)——空着保存时按 label 点名报错。
return '<div class="mpe-item"><label class="mpe-line"><span>' + esc(f.label || f.header) + '</span>' +
'<input type="' + (f.secret ? 'password' : 'text') + '"' +
' value="' + att(val) + '"' +
' placeholder="' + att(ph) + '"' +
' autocomplete="off" spellcheck="false"' +
' oninput="mcpUI.setField(\'' + att(f.header) + '\',this.value)">' +
'</label>' + (f.hint ? '<div class="cfg-note">' + esc(f.hint) + '</div>' : '') + '</div>';
}).join('');
}
function setPresetField(header, v) {
if (mcpEdit && mcpEdit.values) mcpEdit.values[header] = v;
}
// 预设里的 prefix(如 Bearer )只在用户没带过时才补,避开「Bearer Bearer sk-x」
function withPrefix(f, v) {
const p = String(f.prefix || '');
if (!p) return v;
const re = new RegExp('^' + p.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s', 'i');
return re.test(v) ? v : p + v;
}
// 与配置里的 headers 比较:key 顺序不同不算改动(避免无意义重写丢掉节点里的注释)
function sameHeaders(a, b) {
const ka = Object.keys(a).sort(), kb = Object.keys(b).sort();
if (ka.length !== kb.length) return false;
return ka.every((k, i) => k === kb[i] && a[k] === b[kb[i]]);
}
// 自定义服务的 headers:空 key 行丢弃,已有行留空 = 发回掩码占位由后端按键名还原
function plainHeaders() {
const out = {};
for (const r of mcpEdit.headers) {
const k = String(r.key || '').trim();
if (!k) continue;
const v = String(r.value || '').trim();
out[k] = v || (r.masked != null ? r.masked : '');
}
return out;
}
// 预设模式的 headers:字段按声明顺序取 values,空的可选项不写(不给上游塞空 header),
// 必填项空着直接报错并点名 label;手加的 header 原样跟上(整体替换语义下不带就丢)。
function presetHeaders() {
const p = mcpEdit.preset;
const curH = ((mcpEdit.idx >= 0 && SET.cfgMcp[mcpEdit.idx]) || {}).headers || {};
const out = {};
for (const f of p.fields || []) {
const raw = String(mcpEdit.values[f.header] || '').trim();
if (raw) { out[f.header] = withPrefix(f, raw); continue; }
if (f.secret && curH[f.header]) { out[f.header] = MCP_HEADER_MASK; continue; }
if (f.required) throw new Error('请填写「' + (f.label || f.header) + '」');
}
for (const r of mcpEdit.headers) {
const k = String(r.key || '').trim();
if (!k || out[k] !== undefined) continue;
const v = String(r.value || '').trim();
out[k] = v || (r.masked != null ? r.masked : '');
}
return out;
}
// 收集弹窗内的修改为批量 PATCH:服务端一次读文/写回/校验,原子生效。
// headers 整体替换(简单可靠;键值对场景下增量 diff 收益小):空 key 行不写入。
function buildMcpEdits() {
if (!mcpEdit) return [];
const edits = [];
const name = $('mce-name').value.trim();
const url = $('mce-url').value.trim();
const preset = mcpEdit.preset;
const mode = $('mce-mode').value;
// 超时:留空 = 不写入该项(沿用缺省 60s)。区间在 UI 先把一道,
// 比写进 YAML 再被 config.js 静默夹掉好排查(两边上限保持 600000 一致)。
@@ -1547,6 +1714,10 @@
if (!Number.isFinite(tmo) || tmo < 1000 || tmo > 600000) throw new Error('超时要填 1000 ~ 600000 毫秒(留空 = 默认 60s)');
tmo = Math.round(tmo);
}
// 内置服务的 name/url 是契约(表单只读),只有自定义服务才从输入框取
const name = preset ? preset.key : $('mce-name').value.trim();
const url = preset ? preset.url : $('mce-url').value.trim();
const headers = preset ? presetHeaders() : plainHeaders();
const add = mcpEdit.idx < 0;
if (add) {
if (!url) throw new Error('请填写 url');
@@ -1554,19 +1725,15 @@
if (name) obj.name = name;
if (mode !== 'advertise') obj.mode = mode;
if (tmo != null) obj.timeout_ms = tmo;
const headers = {};
for (const r of mcpEdit.headers) {
const k = String(r.key || '').trim();
const v = String(r.value || '').trim();
if (k) headers[k] = v;
}
if (Object.keys(headers).length) obj.headers = headers;
edits.push({ op: 'append', path: ['mcp_servers'], value: obj });
} else {
const cur = SET.cfgMcp[mcpEdit.idx] || {};
if (!url) throw new Error('请填写 url');
if (name !== (cur.name || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'name'], value: name });
if (url !== (cur.url || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'url'], value: url });
if (!preset) {
if (!url) throw new Error('请填写 url');
if (name !== (cur.name || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'name'], value: name });
if (url !== (cur.url || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'url'], value: url });
}
// mode:默认值不写进文件(选 advertise 就删键)
if ((cur.mode || 'advertise') !== mode) edits.push(mode === 'advertise'
? { path: ['mcp_servers', mcpEdit.idx, 'mode'], op: 'delete' }
@@ -1576,17 +1743,10 @@
if (tmo !== curTmo) edits.push(tmo == null
? { path: ['mcp_servers', mcpEdit.idx, 'timeout_ms'], op: 'delete' }
: { path: ['mcp_servers', mcpEdit.idx, 'timeout_ms'], value: tmo });
// headers 仅在内容变更时整体 setIn;避免无意义重写(顺序可能不同)
const newH = {};
for (const r of mcpEdit.headers) {
const k = String(r.key || '').trim();
// 已有行留空 = 保持原值:把脱敏占位原样发回,由后端按键名还原真值(前端不持有真值)
const v = String(r.value || '').trim() || (r.masked != null ? r.masked : '');
if (k) newH[k] = v;
// headers 仅在内容变更时整体 setIn;避免无意义重写(顺序或 key 顺序不同不算变更)
if (!sameHeaders(headers, cur.headers || {})) {
edits.push({ path: ['mcp_servers', mcpEdit.idx, 'headers'], value: headers });
}
const curH = cur.headers || {};
const same = JSON.stringify(newH) === JSON.stringify(curH);
if (!same) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'headers'], value: newH });
}
return edits;
}
@@ -1618,6 +1778,13 @@
}
window.mcpUI = {
add: function () { openMcpEditor(null); },
addPreset: function (key) { openMcpEditor(null, key); },
editPreset: function (key) {
const p = presetMcpList().find(x => x.key === key);
const i = p ? presetIdx(p) : -1;
if (i >= 0) openMcpEditor(i, key);
},
setField: setPresetField,
edit: openMcpEditor,
close: closeMcpEditor,
save: saveMcpEditor,
+50 -15
View File
@@ -156,13 +156,29 @@ function restorePasswords(submitted, orig) {
}).join('\n');
}
// MCP header 值脱敏(等同密码):统一固定短掩码 *****(不泄露长度),原文编辑器与 effective 视图共用。
// MCP header 值脱敏:只遮「像密钥的」,base-url / model 这类明文回显——
// 设置页的引导表单要看得见当前值才能改。两条启发式任一命中即遮:
// 名字(Authorization / X-*-Token / X-Api-Key …)、值(Bearer … / sk-…)。
// 值那条是兜底:用户自定义的怪名字(X-Upstream-Auth: sk-xxx)也不会明文外显。
// headers 行 = `headers:` 块内比它更深缩进的键值行(如 ` Authorization: Bearer sk-xxx`,引号可选)。
// 局限:块标量(|/>)续行内容无法逐行识别,与 api_key/password 的行级掩码同一量级的取舍。
const MCP_HEADER_MASK = '*****';
const HEADERS_BLOCK_LINE = /^(\s*)headers:\s*(?:#.*)?$/;
const MCP_HEADER_LINE = /^(\s*(?:-\s+)?[\w.-]+:\s*)(["']?)(.*)\2\s*$/;
function maskHeaderValue(v) { return v ? MCP_HEADER_MASK : ''; }
const SECRET_NAME_RE = /^(authorization|cookie)$|(?:^|[-_])(token|key|secret|password)(?:[-_]|$)/i;
const SECRET_VALUE_RE = /^Bearer\s|^sk-[A-Za-z0-9_-]{16,}/i;
function isSecretHeader(name, value) {
return SECRET_NAME_RE.test(String(name || '').trim()) ||
SECRET_VALUE_RE.test(String(value == null ? '' : value).trim());
}
function maskHeaderValue(name, v) {
if (!v) return '';
return isSecretHeader(name, v) ? MCP_HEADER_MASK : v;
}
// 从匹配行里取 header 名(去掉列表短横与结尾冒号),用于按键名遮罩/还原
function headerNameOf(m) {
return String(m[1] || '').replace(/^\s*-\s*/, '').replace(/:\s*$/, '').trim();
}
// 遍历 headers 块内的键值行,fn(line, match) 返回替换后的行;块边界按缩进判定。
function mapMcpHeaderLines(text, fn) {
if (!text) return text;
@@ -182,22 +198,32 @@ function mapMcpHeaderLines(text, fn) {
}
function maskMcpHeaders(text) {
return mapMcpHeaderLines(text, function (line, m) {
return m[1] + m[2] + maskHeaderValue(m[3]) + m[2];
return m[1] + m[2] + maskHeaderValue(headerNameOf(m), m[3]) + m[2];
});
}
// 还原:提交原文中值恰为 ***** 的 header 行 = 用户未改动,按出现顺序从原文件取回原值;其他值原样保留。
// 还原:提交原文里值恰为 ***** 的行 = 用户未改动,按键名从原文件取回真值。
// 按键名而非出现顺序:只遮部分 header 后,按顺序还原会张冠李戴。
// 键名在原文里找不到(改名/新增行却留着占位)直接报错,绝不把占位写进配置。
function restoreMcpHeaders(submitted, orig) {
if (!submitted) return submitted;
const origVals = [];
mapMcpHeaderLines(orig || '', function (line, m) { origVals.push(m[3]); return line; });
let i = 0;
const origVals = {};
mapMcpHeaderLines(orig || '', function (line, m) { origVals[headerNameOf(m)] = m[3]; return line; });
return mapMcpHeaderLines(submitted, function (line, m) {
if (m[3] !== MCP_HEADER_MASK) return line; // 用户改过,保留手输新值
const ov = i < origVals.length ? origVals[i] : '';
i++;
return m[1] + m[2] + ov + m[2];
const name = headerNameOf(m);
if (!(name in origVals)) throw new Error('Header「' + name + '」的值为脱敏占位且找不到原值,请填写真实值');
return m[1] + m[2] + origVals[name] + m[2];
});
}
// 整文件编辑的还原链:掩码占位按原文件回填真值;还原不了属于用户输入问题,回 400
function unmaskText(text, origText) {
try {
return restoreApiKeys(restorePasswords(restoreMcpHeaders(text, origText), origText), origText);
} catch (e) {
e.status_code = 400;
throw e;
}
}
// PATCH 细粒度编辑的 headers 还原:值=掩码占位时按键名找回原值(前端只持有脱敏视图,改不动真值)。
// 找不到可还原的原值(新增服务/用户改了 header 名)则报错,绝不把占位符写进配置。
function restoreHeaderMasks(headers, origHeaders) {
@@ -212,13 +238,22 @@ function restoreMaskedHeaderEdit(e, curCfg) {
if (e.delete) return;
const p = e.path;
if (p[0] !== 'mcp_servers') return;
const origOf = (i) => (((curCfg || {}).mcp_servers || [])[Number(i)] || {}).headers || {};
if (e.append) { // 新增服务没有“原值”可言,出现占位即拒绝
if (e.value && e.value.headers) restoreHeaderMasks(e.value.headers, null);
return;
}
if (p.length === 3 && p[2] === 'headers' && e.value && typeof e.value === 'object') {
const orig = (((curCfg || {}).mcp_servers || [])[Number(p[1])] || {}).headers || {};
restoreHeaderMasks(e.value, orig);
restoreHeaderMasks(e.value, origOf(p[1]));
return;
}
// 单个 header 的叶子写入(如 ['mcp_servers',0,'headers','Authorization'])同样要按键名还原;
// 漏了这一支会把 ***** 当真值写进 config.yml(前端引导表单不走这条路,但 API 可直达)。
if (p.length === 4 && p[2] === 'headers' && e.value === MCP_HEADER_MASK) {
const one = {};
one[p[3]] = MCP_HEADER_MASK;
restoreHeaderMasks(one, origOf(p[1]));
e.value = one[p[3]];
}
}
@@ -230,7 +265,7 @@ function maskEffective(cfg) {
}));
c.mcp_servers = (cfg.mcp_servers || []).map(s => {
const headers = {};
for (const [k, v] of Object.entries(s.headers || {})) headers[k] = maskHeaderValue(v);
for (const [k, v] of Object.entries(s.headers || {})) headers[k] = maskHeaderValue(k, v);
return Object.assign({}, s, { headers });
});
c.models = (cfg.models || []).map(m => Object.assign({}, m, { api_key: maskKey(m.api_key) }));
@@ -268,7 +303,7 @@ router.post('/validate', wrap((req, res) => {
const text = req.body && req.body.text;
if (typeof text !== 'string') return badRequest(res, new Error('body.text 必须是字符串'));
const origText = readConfigText(cfgOf()) || '';
const restored = restoreApiKeys(restorePasswords(restoreMcpHeaders(text, origText), origText), origText);
const restored = unmaskText(text, origText);
try {
const next = loadConfigFromText(restored, '');
res.json({ ok: true, changed: diffTop(cfgOf(), next) });
@@ -284,7 +319,7 @@ router.put('/', wrap((req, res) => {
const text = req.body && req.body.text;
if (typeof text !== 'string') return badRequest(res, new Error('body.text 必须是字符串'));
const origText = readConfigText(cfg) || '';
const restored = restoreApiKeys(restorePasswords(restoreMcpHeaders(text, origText), origText), origText);
const restored = unmaskText(text, origText);
let next;
try { next = loadConfigFromText(restored, cfg.config_path); } catch (e) { return badRequest(res, e); }
writeConfigText(cfg, restored);