"use strict";
// =============================================================================
// Vibn Gitea MCP Server
//
// Exposes the Gitea tools from src/tools/gitea-api.ts over the Model Context
// Protocol via stdio. Same security guardrails, same code path as the
// in-process agent runner — accessible to any MCP-speaking client.
//
// Launch:
//   GITEA_API_URL=https://git.vibnai.com GITEA_API_TOKEN=... GITEA_USERNAME=mark \
//   node dist/mcp/gitea-server.js
// =============================================================================
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const api = __importStar(require("../tools/gitea-api"));
function loadConfig() {
    const apiUrl = process.env.GITEA_API_URL;
    const apiToken = process.env.GITEA_API_TOKEN;
    if (!apiUrl)
        throw new Error('GITEA_API_URL env var is required');
    if (!apiToken)
        throw new Error('GITEA_API_TOKEN env var is required');
    return { apiUrl, apiToken, username: process.env.GITEA_USERNAME };
}
const TOOL_DEFINITIONS = [
    {
        name: 'gitea_create_issue',
        description: 'Create a new issue in a Gitea repository.',
        inputSchema: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repository in "owner/name" format' },
                title: { type: 'string', description: 'Issue title' },
                body: { type: 'string', description: 'Issue body (markdown)' },
                labels: { type: 'array', items: { type: 'string' }, description: 'Optional label names' },
            },
            required: ['repo', 'title', 'body'],
        },
    },
    {
        name: 'gitea_list_issues',
        description: 'List open issues in a Gitea repository.',
        inputSchema: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repository in "owner/name" format' },
                state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' },
            },
            required: ['repo'],
        },
    },
    {
        name: 'gitea_close_issue',
        description: 'Close an issue in a Gitea repository.',
        inputSchema: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repository in "owner/name" format' },
                issue_number: { type: 'number', description: 'Issue number to close' },
            },
            required: ['repo', 'issue_number'],
        },
    },
    {
        name: 'list_repos',
        description: 'List all Git repositories in the Gitea organization. Returns repo names, descriptions, and last update time.',
        inputSchema: { type: 'object', properties: {} },
    },
    {
        name: 'list_all_issues',
        description: 'List open issues across all repos or a specific repo. Use this to understand what work is queued or in progress.',
        inputSchema: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Optional: "owner/name" to scope to one repo. Omit for all repos.' },
                state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' },
            },
        },
    },
    {
        name: 'read_repo_file',
        description: 'Read a file from any Gitea repository without cloning it. Useful for understanding project structure.',
        inputSchema: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repo in "owner/name" format' },
                path: { type: 'string', description: 'File path within the repo (e.g. "src/app/page.tsx")' },
            },
            required: ['repo', 'path'],
        },
    },
];
async function dispatch(cfg, name, args) {
    switch (name) {
        case 'gitea_create_issue':
            return api.createIssue(cfg, {
                repo: String(args.repo),
                title: String(args.title),
                body: String(args.body),
                labels: Array.isArray(args.labels) ? args.labels : undefined,
            });
        case 'gitea_list_issues':
            return api.listIssues(cfg, String(args.repo), String(args.state || 'open'));
        case 'gitea_close_issue':
            return api.closeIssue(cfg, String(args.repo), Number(args.issue_number));
        case 'list_repos':
            return api.listRepos(cfg);
        case 'list_all_issues':
            return api.listAllIssues(cfg, {
                repo: args.repo ? String(args.repo) : undefined,
                state: args.state ? String(args.state) : undefined,
            });
        case 'read_repo_file':
            return api.readRepoFile(cfg, String(args.repo), String(args.path));
        default:
            throw new Error(`Unknown tool: ${name}`);
    }
}
function buildServer(cfg) {
    const server = new index_js_1.Server({ name: 'vibn-gitea', version: '0.1.0' }, { capabilities: { tools: {} } });
    server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
        tools: TOOL_DEFINITIONS.map(t => ({ ...t })),
    }));
    server.setRequestHandler(types_js_1.CallToolRequestSchema, async (req) => {
        const { name, arguments: args = {} } = req.params;
        try {
            const result = await dispatch(cfg, name, args);
            const text = typeof result === 'string' ? result : JSON.stringify(result);
            return { content: [{ type: 'text', text }] };
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: message }) }],
                isError: true,
            };
        }
    });
    return server;
}
async function main() {
    const cfg = loadConfig();
    const server = buildServer(cfg);
    const transport = new stdio_js_1.StdioServerTransport();
    await server.connect(transport);
    console.error(`[vibn-gitea-mcp] ready — ${TOOL_DEFINITIONS.length} tools exposed (gitea=${cfg.apiUrl})`);
}
main().catch((err) => {
    console.error('[vibn-gitea-mcp] fatal:', err instanceof Error ? err.stack : err);
    process.exit(1);
});
