import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
export async function connectMcpServers(specs, log = () => { }) {
    const out = [];
    for (const spec of specs) {
        if (spec.enabled === false)
            continue;
        try {
            const connected = await connectOne(spec, log);
            out.push(connected);
            log(`[mcp] ${spec.name}: ${connected.tools.length} tools`);
        }
        catch (err) {
            log(`[mcp] ${spec.name}: failed to connect — ${err.message}`);
        }
    }
    return out;
}
async function connectOne(spec, log) {
    const transport = new StdioClientTransport({
        command: spec.command,
        args: spec.args ?? [],
        env: { ...process.env, ...(spec.env ?? {}) },
    });
    const client = new Client({ name: "lisa", version: "0.1.0" }, { capabilities: {} });
    await client.connect(transport);
    const list = await client.listTools();
    const tools = list.tools.map((t) => mcpToolToLisaTool(spec.name, client, t, log));
    return {
        spec,
        client,
        tools,
        async close() {
            try {
                await client.close();
            }
            catch { }
        },
    };
}
function mcpToolToLisaTool(serverName, client, mcpTool, log) {
    const name = `mcp__${serverName}__${mcpTool.name}`;
    const description = mcpTool.description
        ? `[mcp:${serverName}] ${mcpTool.description}`
        : `[mcp:${serverName}] ${mcpTool.name}`;
    return {
        name,
        description,
        inputSchema: (mcpTool.inputSchema?.type === "object"
            ? mcpTool.inputSchema
            : { type: "object", properties: {} }),
        async execute(input) {
            const result = await client.callTool({
                name: mcpTool.name,
                arguments: (input ?? {}),
            });
            const content = result.content ?? [];
            const text = content
                .map((c) => (c.type === "text" ? c.text ?? "" : `[${c.type}]`))
                .join("\n");
            if (result.isError) {
                log(`[mcp] ${name} returned isError`);
            }
            return text || "(empty)";
        },
    };
}
//# sourceMappingURL=client.js.map