@unified-llm/core
Version:
Unified LLM interface (in-memory).
67 lines • 2.83 kB
JavaScript
// src/utils/mcp/setup-mcp-tools.ts
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { createMcpTransport } from "../mcp-utils.js";
async function closeClientsQuietly(clients) {
await Promise.allSettled(clients.map(async (client) => {
try {
if (typeof client.close === "function") {
await client.close();
}
}
catch (_a) {
// ignore
}
}));
}
/**
* MCP クライアントを接続し、MCPの tools を収集する(プロバイダー非依存)。
* Connect MCP clients and collect MCP tools (provider-agnostic).
*
* - allowedTools によるフィルタ
* - Filter by allowedTools
* - tool名の衝突検出(複数サーバー間)
* - Detect tool name collisions across servers
* - 失敗時のクリーンアップ
* - Cleanup on failure
*/
export async function setupMcpClientsAndTools(options) {
var _a, _b, _c;
const mcpServers = (_a = options.mcpServers) !== null && _a !== void 0 ? _a : [];
const clientName = (_b = options.clientName) !== null && _b !== void 0 ? _b : "local-mcp-client";
const clientVersion = (_c = options.clientVersion) !== null && _c !== void 0 ? _c : "1.0.0";
const mcpClients = [];
const mcpTools = [];
const toolNameToClient = new Map();
const toolNameToServer = new Map();
try {
for (const server of mcpServers) {
const transport = createMcpTransport(server);
const mcpClient = new Client({ name: clientName, version: clientVersion }, { capabilities: {} });
await mcpClient.connect(transport, {});
mcpClients.push(mcpClient);
const toolsList = (await mcpClient.listTools());
const allTools = Array.isArray(toolsList === null || toolsList === void 0 ? void 0 : toolsList.tools) ? toolsList.tools : [];
const allowedTools = allTools.filter((tool) => {
// allowedTools 未指定なら全許可
// Allow all when allowedTools is not specified
if (!server.allowedTools)
return true;
return server.allowedTools.includes(tool.name);
});
for (const tool of allowedTools) {
if (toolNameToClient.has(tool.name)) {
throw new Error(`Tool name collision across MCP servers: ${tool.name}`);
}
toolNameToClient.set(tool.name, mcpClient);
toolNameToServer.set(tool.name, server);
mcpTools.push(tool);
}
}
return { mcpClients, mcpTools, toolNameToClient, toolNameToServer };
}
catch (error) {
await closeClientsQuietly(mcpClients);
throw error;
}
}
//# sourceMappingURL=setup-mcp-tools.js.map