#!/usr/bin/env node
"use strict";
// =============================================================================
// vibn-platform-mcp
// -----------------------------------------------------------------------------
// Stdio MCP server exposing Vibn platform primitives:
//   - save_memory        → persists facts into a per-session in-memory store
//   - list_memory        → inspect what has been saved this session (MCP-only)
//   - list_skills        → enumerate .skills/ in a Gitea repo
//   - get_skill          → read a specific SKILL.md
//   - finalize_prd       → save a completed PRD keyed by SESSION_KEY
//   - get_prd            → read back the saved PRD (MCP-only convenience)
//   - web_search         → DuckDuckGo HTML search
//
// NOTE: The in-process agent-runner collects memory into ToolContext and
// consumes the PRD via the module-level prdStore. When the same logic is
// exposed over MCP, there is no shared process memory with the agent-runner,
// so this server maintains its own session-scoped stores. Set SESSION_KEY to
// give each MCP client a stable key into those stores.
//
// Config (env):
//   SESSION_KEY              (optional) — session scope for memory + PRD stores
//                                        (defaults to "default")
//   GITEA_API_URL            (optional) — required for list_skills / get_skill
//   GITEA_API_TOKEN          (optional) — required for list_skills / get_skill
// =============================================================================
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 memoryApi = __importStar(require("../tools/memory-api"));
const skillsApi = __importStar(require("../tools/skills-api"));
const prdApi = __importStar(require("../tools/prd-api"));
const searchApi = __importStar(require("../tools/search-api"));
function loadConfig() {
    const sessionKey = process.env.SESSION_KEY?.trim() || 'default';
    const giteaUrl = process.env.GITEA_API_URL;
    const giteaToken = process.env.GITEA_API_TOKEN;
    const gitea = giteaUrl && giteaToken ? { apiUrl: giteaUrl, apiToken: giteaToken } : undefined;
    return { sessionKey, gitea };
}
const TOOL_DEFINITIONS = [
    {
        name: 'save_memory',
        description: 'Persist an important fact about this project to long-term memory within this MCP session.',
        inputSchema: {
            type: 'object',
            properties: {
                key: { type: 'string', description: 'Short unique label (e.g. "primary_language", "auth_strategy")' },
                type: {
                    type: 'string',
                    enum: ['tech_stack', 'decision', 'feature', 'goal', 'constraint', 'note'],
                    description: 'Category of the memory item',
                },
                value: { type: 'string', description: 'The fact to remember (1-3 sentences)' },
            },
            required: ['key', 'type', 'value'],
        },
    },
    {
        name: 'list_memory',
        description: 'List all memory entries saved in the current session.',
        inputSchema: { type: 'object', properties: {} },
    },
    {
        name: 'list_skills',
        description: 'List available skills for a project repo. Skills are stored in .skills/<name>/SKILL.md. Requires Gitea credentials.',
        inputSchema: {
            type: 'object',
            properties: { repo: { type: 'string', description: 'Repo in "owner/name" format' } },
            required: ['repo'],
        },
    },
    {
        name: 'get_skill',
        description: 'Read the full content of a specific skill from a project repo. Requires Gitea credentials.',
        inputSchema: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repo in "owner/name" format' },
                skill_name: { type: 'string', description: 'Skill name (directory inside .skills/)' },
            },
            required: ['repo', 'skill_name'],
        },
    },
    {
        name: 'finalize_prd',
        description: 'Save a completed PRD document for this session.',
        inputSchema: {
            type: 'object',
            properties: { content: { type: 'string', description: 'The complete PRD in markdown' } },
            required: ['content'],
        },
    },
    {
        name: 'get_prd',
        description: 'Read back the PRD saved for this session, or null if none saved yet.',
        inputSchema: { type: 'object', properties: {} },
    },
    {
        name: 'web_search',
        description: 'Search the web via DuckDuckGo HTML endpoint. Returns titles + snippets for the top results.',
        inputSchema: {
            type: 'object',
            properties: { query: { type: 'string', description: 'The search query' } },
            required: ['query'],
        },
    },
];
async function dispatch(cfg, name, args) {
    switch (name) {
        case 'save_memory':
            return memoryApi.saveMemoryToStore(cfg.sessionKey, {
                key: String(args.key),
                type: String(args.type),
                value: String(args.value),
            });
        case 'list_memory':
            return { sessionKey: cfg.sessionKey, entries: memoryApi.listMemoryFromStore(cfg.sessionKey) };
        case 'list_skills':
            if (!cfg.gitea)
                return { error: 'list_skills requires GITEA_API_URL and GITEA_API_TOKEN.' };
            return skillsApi.listSkills(cfg.gitea, String(args.repo));
        case 'get_skill':
            if (!cfg.gitea)
                return { error: 'get_skill requires GITEA_API_URL and GITEA_API_TOKEN.' };
            return skillsApi.getSkill(cfg.gitea, String(args.repo), String(args.skill_name));
        case 'finalize_prd':
            return prdApi.finalizePrd(cfg.sessionKey, String(args.content));
        case 'get_prd':
            return { sessionKey: cfg.sessionKey, content: prdApi.getPrd(cfg.sessionKey) };
        case 'web_search':
            return searchApi.webSearch(String(args.query));
        default:
            throw new Error(`Unknown tool: ${name}`);
    }
}
function buildServer(cfg) {
    const server = new index_js_1.Server({ name: 'vibn-platform-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-platform-mcp] ready — ${TOOL_DEFINITIONS.length} tools exposed ` +
        `(session=${cfg.sessionKey}, gitea=${cfg.gitea ? 'enabled' : 'disabled'})`);
}
main().catch((err) => {
    // eslint-disable-next-line no-console
    console.error('[vibn-platform-mcp] fatal:', err);
    process.exit(1);
});
