package com.correx.infrastructure.tools.mcp

import com.correx.core.approvals.Tier
import com.correx.core.tools.contract.Tool

/**
 * A running MCP server mounted into Correx: its advertised tools (ready to hand to the tool
 * registry as `extraTools`) plus the handle that shuts the child process down. The caller registers
 * [close] with the server's shutdown hook, exactly as the managed-model path unloads llama-server.
 */
class MountedMcpServer internal constructor(
    val serverId: String,
    private val client: McpClient,
    val tools: List<Tool>,
) : AutoCloseable {
    override fun close() = client.close()
}

/** Spawn an MCP server over stdio, initialize it, and surface its `tools/list` as Correx tools. */
object McpMounter {
    suspend fun mount(
        serverId: String,
        command: List<String>,
        env: Map<String, String> = emptyMap(),
        tier: Tier = Tier.T2,
    ): MountedMcpServer {
        val client = McpClient.spawn(serverId, command, env)
        val tools = client.listTools().map { descriptor ->
            McpTool(
                serverId = serverId,
                remoteName = descriptor.name,
                description = descriptor.description,
                parametersSchema = descriptor.inputSchema,
                tier = tier,
                client = client,
            )
        }
        return MountedMcpServer(serverId, client, tools)
    }
}
