"use strict";
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 });
exports.createClaudeCodeServer = createClaudeCodeServer;
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const logger_1 = require("../../lib/logger");
const claudeCode = __importStar(require("../activities/claude-code"));
// ── Schemas ──────────────────────────────────────────────────────────────────
const executeTaskSchema = zod_1.z.object({
    prompt: zod_1.z.string().describe('The task prompt for Claude Code. Be specific and actionable. ' +
        'Claude Code has access to terminal, file system, and code editing tools.'),
    working_directory: zod_1.z.string().optional().describe('Working directory for the task. Defaults to the server process cwd.'),
    allowed_tools: zod_1.z.array(zod_1.z.string()).optional().describe('Restrict which tools Claude Code can use (e.g., ["Read", "Grep", "Glob"]). ' +
        'Omit for unrestricted access.'),
    max_turns: zod_1.z.number().optional().describe('Maximum agentic turns (tool calls) before stopping. Default: model default.'),
    model: zod_1.z.string().optional().describe('Override the Claude model (e.g., "claude-sonnet-4-6"). Default: CLI default.'),
    system_prompt: zod_1.z.string().optional().describe('Additional system prompt to append to Claude Code\'s defaults.'),
    timeout_ms: zod_1.z.number().optional().describe('Execution timeout in milliseconds. Default: 120000 (2 min), max: 300000 (5 min).'),
    credential_label: zod_1.z.string().optional().describe('Label of the stored Anthropic credential to use (e.g., "subscription", "api-batch"). ' +
        'Default: "default". Use when the user has multiple Anthropic credentials.'),
});
const checkAvailabilitySchema = zod_1.z.object({});
// ── Factory ──────────────────────────────────────────────────────────────────
/**
 * Create a Claude Code MCP server.
 *
 * Provides 2 tools:
 *   execute_task       — Run a Claude Code prompt, return structured output
 *   check_availability — Verify CLI installation and API key presence
 *
 * Authentication by proxy:
 *   When invoked from a workflow, `_auth` is injected automatically by the
 *   framework. The activity uses `_auth.userId` for audit logging and
 *   `_auth.token` (delegation JWT) for resolving per-user API keys.
 *   Built-in tools that don't need auth simply ignore the `_auth` field.
 */
async function createClaudeCodeServer(options) {
    const name = options?.name || 'long-tail-claude-code';
    const instance = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    instance.registerTool('execute_task', {
        title: 'Execute Claude Code Task',
        description: 'Run a task using Claude Code CLI on the server. Claude Code is an agentic ' +
            'coding assistant with terminal access, file I/O, code search, and editing. ' +
            'Use for: code generation, refactoring, file analysis, running shell commands, ' +
            'searching codebases, and multi-step development tasks. ' +
            'The task runs in a subprocess with a scoped API key and optional tool restrictions. ' +
            'When called from a workflow, the requesting user\'s identity is propagated via delegation.',
        inputSchema: executeTaskSchema,
    }, async (args) => {
        try {
            const result = await claudeCode.executeTask(args);
            return {
                content: [{ type: 'text', text: JSON.stringify(result) }],
                isError: result.is_error,
            };
        }
        catch (err) {
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: err.message }) }],
                isError: true,
            };
        }
    });
    instance.registerTool('check_availability', {
        title: 'Check Claude Code Availability',
        description: 'Verify that the Claude Code CLI is installed and an Anthropic API key is available. ' +
            'Returns version info and key availability. Use before execute_task to verify readiness.',
        inputSchema: checkAvailabilitySchema,
    }, async (args) => {
        const result = await claudeCode.checkAvailability(args);
        return {
            content: [{ type: 'text', text: JSON.stringify(result) }],
        };
    });
    logger_1.loggerRegistry.info(`[lt-mcp:claude-code] ${name} ready (2 tools registered)`);
    return instance;
}
