"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listMcpServerTools = listMcpServerTools;
exports.callMcpTool = callMcpTool;
const mcp_1 = require("../../services/mcp");
/**
 * List all tools exposed by a connected MCP server.
 *
 * Requires the MCP adapter to be registered and the server to be connected.
 *
 * @param input.id — the MCP server identifier
 * @returns `{ status: 200, data: { tools } }` array of tool descriptors
 */
async function listMcpServerTools(input) {
    try {
        const adapter = mcp_1.mcpRegistry.current;
        if (!adapter) {
            return { status: 400, error: 'MCP adapter not registered' };
        }
        const tools = await adapter.listTools(input.id);
        return { status: 200, data: { tools } };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
/**
 * Invoke a specific tool on a connected MCP server.
 *
 * Passes the tool arguments and an optional auth context (derived from
 * `execute_as` or the authenticated user) to the MCP adapter. Returns
 * 422 with `missing_credential` if the tool requires a credential the
 * user has not registered.
 *
 * @param input.id — the MCP server identifier
 * @param input.toolName — name of the tool to invoke
 * @param input.arguments — key-value arguments to pass to the tool
 * @param input.execute_as — optional user ID to impersonate for the tool call
 * @param auth — authenticated user context
 * @returns `{ status: 200, data: { result } }` the tool execution result
 */
async function callMcpTool(input, auth) {
    try {
        const adapter = mcp_1.mcpRegistry.current;
        if (!adapter) {
            return { status: 400, error: 'MCP adapter not registered' };
        }
        const effectiveUserId = input.execute_as || auth?.userId;
        const authContext = effectiveUserId ? { userId: effectiveUserId } : undefined;
        // Inject user_id into arguments so builtin tools can resolve
        // the calling user's credentials (OAuth tokens, etc.)
        const args = { ...(input.arguments || {}) };
        if (effectiveUserId && !args.user_id) {
            args.user_id = effectiveUserId;
        }
        const result = await adapter.callTool(input.id, input.toolName, args, authContext);
        return { status: 200, data: { result } };
    }
    catch (err) {
        if (err.name === 'MissingCredentialError') {
            return {
                status: 422,
                error: 'missing_credential',
                ...{ provider: err.provider, message: err.message },
            };
        }
        return { status: 500, error: err.message };
    }
}
