修复 MCP 工具调用 400:image-gen 等严格服务要求 initialize 后的请求带 Mcp-Session-Id。
init() 阶段先发 initialize 拿 session id 并缓存到 server.sessionId; rpc() 在 method !== 'initialize' 且 server.sessionId 存在时自动加上 Mcp-Session-Id 头; 老服务(无 initialize 或不返回 session id)保持原行为不受影响
This commit is contained in:
+31
-6
@@ -12,22 +12,30 @@ let toolDefs = []; // OpenAI function 格式(所有 MCP 工
|
|||||||
const toolIndex = new Map(); // 发送名 -> { server, tool }(服务配置 + 原始工具名)
|
const toolIndex = new Map(); // 发送名 -> { server, tool }(服务配置 + 原始工具名)
|
||||||
let builtinNames = new Set();
|
let builtinNames = new Set();
|
||||||
|
|
||||||
// 发一次 JSON-RPC 请求,返回 result(HTTP 非 2xx / error / 无法解析时抛异常)。
|
// 发一次 JSON-RPC 请求,返回 { result, headers }(HTTP 非 2xx / error / 无法解析时抛异常)。
|
||||||
|
// 某些 MCP 服务遵循 Streamable HTTP 规范会在 initialize 响应里返回 Mcp-Session-Id,
|
||||||
|
// 之后所有非 initialize 请求都必须带上该 header,否则返回 400。我们把会话 id 缓存在 server.sessionId 里。
|
||||||
async function rpc(server, method, params, timeoutMs) {
|
async function rpc(server, method, params, timeoutMs) {
|
||||||
const callId = Date.now();
|
const callId = Date.now();
|
||||||
const ctrl = new AbortController();
|
const ctrl = new AbortController();
|
||||||
const timer = setTimeout(() => ctrl.abort(), timeoutMs || 30000);
|
const timer = setTimeout(() => ctrl.abort(), timeoutMs || 30000);
|
||||||
try {
|
try {
|
||||||
|
const headers = Object.assign({
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
}, server.headers || {});
|
||||||
|
// initialize 请求自身不需要带 session id;其他请求如果该服务提供了 session id 则必须带
|
||||||
|
if (method !== 'initialize' && server.sessionId) headers['Mcp-Session-Id'] = server.sessionId;
|
||||||
const res = await fetch(server.url, {
|
const res = await fetch(server.url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
signal: ctrl.signal,
|
signal: ctrl.signal,
|
||||||
headers: Object.assign({
|
headers,
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Accept': 'application/json, text/event-stream',
|
|
||||||
}, server.headers || {}),
|
|
||||||
body: JSON.stringify({ jsonrpc: '2.0', id: callId, method, params: params || {} }),
|
body: JSON.stringify({ jsonrpc: '2.0', id: callId, method, params: params || {} }),
|
||||||
});
|
});
|
||||||
const raw = await res.text();
|
const raw = await res.text();
|
||||||
|
// 响应头里出现 Mcp-Session-Id 就缓存到 server(多处出现都被覆盖为最后一次,重复请求同一服务后保持一致)
|
||||||
|
const sid = res.headers.get('mcp-session-id');
|
||||||
|
if (sid) server.sessionId = sid;
|
||||||
if (!res.ok) throw new Error('HTTP ' + res.status + ': ' + raw.slice(0, 300));
|
if (!res.ok) throw new Error('HTTP ' + res.status + ': ' + raw.slice(0, 300));
|
||||||
// 响应可能是 SSE 帧(多行 data: {...}),取 id 匹配或最后一条 JSON
|
// 响应可能是 SSE 帧(多行 data: {...}),取 id 匹配或最后一条 JSON
|
||||||
let payload = null;
|
let payload = null;
|
||||||
@@ -52,6 +60,7 @@ async function rpc(server, method, params, timeoutMs) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 发现所有 MCP 服务的工具。单个服务失败只警告,不影响其他服务与内置工具。
|
// 发现所有 MCP 服务的工具。单个服务失败只警告,不影响其他服务与内置工具。
|
||||||
|
// 对要求会话的服务,先发 initialize 拿到 Mcp-Session-Id,再发 notifications/initialized + tools/list。
|
||||||
async function init(cfg) {
|
async function init(cfg) {
|
||||||
toolDefs = [];
|
toolDefs = [];
|
||||||
toolIndex.clear();
|
toolIndex.clear();
|
||||||
@@ -63,7 +72,23 @@ async function init(cfg) {
|
|||||||
|
|
||||||
const servers = (cfg && cfg.mcp_servers) || [];
|
const servers = (cfg && cfg.mcp_servers) || [];
|
||||||
for (const s of servers) {
|
for (const s of servers) {
|
||||||
|
// 清理上次会话 id(重启后服务端会拒绝旧 id;不清理会一直 400)
|
||||||
|
s.sessionId = null;
|
||||||
try {
|
try {
|
||||||
|
// 先 initialize:兼容要求会话的服务。strict 模式下服务端会返回 session id;
|
||||||
|
// 不要求的服务也会正常响应(只是响应头里没有 mcp-session-id)。
|
||||||
|
try {
|
||||||
|
await rpc(s, 'initialize', {
|
||||||
|
protocolVersion: '2024-11-05',
|
||||||
|
capabilities: {},
|
||||||
|
clientInfo: { name: 'agent', version: '1.0.0' },
|
||||||
|
}, 15000);
|
||||||
|
// 按 MCP 规范:initialize 成功后发 notifications/initialized 通知(不需要 id,不期待响应体)
|
||||||
|
try { await rpc(s, 'notifications/initialized', {}, 5000); } catch (_) { /* 通知失败不阻断 */ }
|
||||||
|
} catch (e) {
|
||||||
|
// 某些老服务(无 initialize)会报 Method not found;不阻断,走原 tools/list 路径
|
||||||
|
if (!/Method not found/i.test(String(e && e.message || e))) throw e;
|
||||||
|
}
|
||||||
const result = await rpc(s, 'tools/list', {}, 15000);
|
const result = await rpc(s, 'tools/list', {}, 15000);
|
||||||
const tools = (result && result.tools) || [];
|
const tools = (result && result.tools) || [];
|
||||||
for (const t of tools) {
|
for (const t of tools) {
|
||||||
@@ -80,7 +105,7 @@ async function init(cfg) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
log.info('[mcp] ' + s.name + ': 发现 ' + tools.length + ' 个工具');
|
log.info('[mcp] ' + s.name + ': 发现 ' + tools.length + ' 个工具' + (s.sessionId ? ' (session)' : ''));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.warn('[mcp] ' + s.name + ' 工具发现失败(本轮运行该服务不可用): ' + (err && err.message || err));
|
log.warn('[mcp] ' + s.name + ' 工具发现失败(本轮运行该服务不可用): ' + (err && err.message || err));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user