#!/usr/bin/env node
"use strict";
// =============================================================================
// vibn-agent-mcp
// -----------------------------------------------------------------------------
// Stdio MCP server exposing the vibn-agent-runner sub-agent orchestration API.
// This lets any MCP-speaking client (Goose, Claude Desktop, Cursor, etc.)
// spawn Coder / PM / Marketing jobs against the vibn-agent-runner HTTP service
// and poll their status.
//
// Config (env):
//   AGENT_RUNNER_URL   (default: http://localhost:3333) — URL of the runner
// =============================================================================
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/agent-api"));
function loadConfig() {
    const runnerUrl = process.env.AGENT_RUNNER_URL?.trim() || 'http://localhost:3333';
    return { runnerUrl };
}
const TOOL_DEFINITIONS = [
    {
        name: 'spawn_agent',
        description: 'Dispatch a sub-agent job to run in the background on the vibn-agent-runner. Returns a job ID.',
        inputSchema: {
            type: 'object',
            properties: {
                agent: { type: 'string', description: '"Coder", "PM", or "Marketing"' },
                task: { type: 'string', description: 'Detailed task description for the agent' },
                repo: { type: 'string', description: 'Gitea repo in "owner/name" format' },
            },
            required: ['agent', 'task', 'repo'],
        },
    },
    {
        name: 'get_job_status',
        description: 'Check the status of a previously spawned agent job.',
        inputSchema: {
            type: 'object',
            properties: {
                job_id: { type: 'string', description: 'Job ID returned by spawn_agent' },
            },
            required: ['job_id'],
        },
    },
];
async function dispatch(cfg, name, args) {
    switch (name) {
        case 'spawn_agent':
            return api.spawnAgent(cfg, {
                agent: String(args.agent),
                task: String(args.task),
                repo: String(args.repo),
            });
        case 'get_job_status':
            return api.getJobStatus(cfg, String(args.job_id));
        default:
            throw new Error(`Unknown tool: ${name}`);
    }
}
function buildServer(cfg) {
    const server = new index_js_1.Server({ name: 'vibn-agent-mcp', version: '0.1.0' }, { capabilities: { tools: {} } });
    server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: TOOL_DEFINITIONS }));
    server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
        const name = request.params.name;
        const args = (request.params.arguments ?? {});
        try {
            const result = await dispatch(cfg, name, args);
            return { content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result, null, 2) }] };
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            return { isError: true, content: [{ type: 'text', text: `Error: ${message}` }] };
        }
    });
    return server;
}
async function main() {
    const cfg = loadConfig();
    const server = buildServer(cfg);
    const transport = new stdio_js_1.StdioServerTransport();
    await server.connect(transport);
    // eslint-disable-next-line no-console
    console.error(`[vibn-agent-mcp] ready — ${TOOL_DEFINITIONS.length} tools exposed (runner=${cfg.runnerUrl})`);
}
main().catch((err) => {
    // eslint-disable-next-line no-console
    console.error('[vibn-agent-mcp] fatal:', err);
    process.exit(1);
});
