import { RegistryError } from './types.js';
const BASE = 'https://registry.modelcontextprotocol.io/v0';
function npmInvocation(pkg) {
    const hint = pkg.runtimeHint || pkg.runtime_hint || 'npx';
    return { command: hint, args: ['-y', pkg.identifier || ''] };
}
function pythonInvocation(pkg) {
    const hint = pkg.runtimeHint || pkg.runtime_hint || 'uvx';
    return { command: hint, args: [pkg.identifier || ''] };
}
export const mcpOfficialAdapter = {
    descriptor: {
        id: 'mcp-official',
        label: 'Official MCP Registry',
        kinds: ['mcp'],
        requiresAuth: false,
        enabled: true
    },
    async search(query, limit = 50) {
        const url = new URL(`${BASE}/servers`);
        url.searchParams.set('limit', String(Math.min(limit, 100)));
        if (query)
            url.searchParams.set('search', query);
        const res = await fetch(url, { headers: { accept: 'application/json' } });
        if (!res.ok)
            throw new RegistryError(`MCP registry list failed: ${res.status}`);
        const data = (await res.json());
        const records = (data.servers ?? []).map((item) => {
            if (item && typeof item === 'object' && 'server' in item && item.server) {
                return item.server;
            }
            return item;
        });
        return records
            .filter((record) => record.name)
            .map((record) => ({
            id: record.id || record.name,
            source: 'mcp-official',
            kind: 'mcp',
            name: record.name,
            title: record.title ?? null,
            description: record.description ?? null,
            version: record.version ?? null,
            repository: record.repository?.url ?? null,
            homepage: record.homepage ?? null,
            installManifest: record
        }));
    },
    async resolveInstall(entry) {
        const raw = entry.installManifest;
        const remote = raw.remotes?.[0];
        if (remote?.url) {
            return {
                name: shortServerName(entry.name),
                transport: 'http',
                url: remote.url,
                source: {
                    registry: 'mcp-official',
                    ref: entry.id,
                    version: entry.version,
                    url: entry.repository ?? entry.homepage ?? null
                }
            };
        }
        const pkg = raw.packages?.[0];
        if (!pkg) {
            throw new RegistryError('MCP entry has no installable package or remote', 422);
        }
        const registryType = (pkg.registryType || pkg.registry_type || pkg.registry || '').toLowerCase();
        const invocation = registryType === 'pypi' ? pythonInvocation(pkg) : npmInvocation(pkg);
        const runtimeArgs = pkg.runtimeArguments ?? pkg.runtime_arguments ?? [];
        const extraArgs = runtimeArgs
            .map((arg) => (typeof arg.value === 'string' ? arg.value : null))
            .filter((value) => Boolean(value));
        const envSpec = pkg.environmentVariables ?? pkg.environment_variables ?? [];
        const env = {};
        for (const variable of envSpec) {
            if (variable.name)
                env[variable.name] = '';
        }
        return {
            name: shortServerName(entry.name),
            transport: 'stdio',
            command: invocation.command,
            args: [...invocation.args, ...extraArgs],
            env,
            source: {
                registry: 'mcp-official',
                ref: entry.id,
                version: entry.version,
                url: entry.repository ?? entry.homepage ?? null
            }
        };
    }
};
function shortServerName(fullName) {
    const trimmed = fullName.replace(/^io\.github\.[^/]+\//, '');
    const parts = trimmed.split(/[/.]/);
    return parts[parts.length - 1] || trimmed;
}
//# sourceMappingURL=mcp-official.js.map