"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.createSchemaExchangeServer = createSchemaExchangeServer;
const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
const zod_1 = require("zod");
const logger_1 = require("../../lib/logger");
const schemaExchange = __importStar(require("../activities/schema-exchange"));
const exchangeSchema = zod_1.z.object({
    endpoint: zod_1.z.string().optional().describe('Service endpoint URL. Supports template variables resolved by the caller (e.g. /Patient/{id}).'),
    url: zod_1.z.string().optional().describe('Alias for endpoint (either endpoint or url is required).'),
    method: zod_1.z.string().describe('HTTP method: GET, POST, PUT, DELETE, PATCH.'),
    headers: zod_1.z.record(zod_1.z.string()).optional().describe('Request headers (e.g. Authorization, Accept, Content-Type).'),
    query: zod_1.z.record(zod_1.z.string()).optional().describe('Query parameters appended to the URL.'),
    body: zod_1.z.any().optional().describe('Request body. Validated against request_schema before sending (if provided).'),
    request_schema: zod_1.z.record(zod_1.z.any()).optional().describe('JSON Schema for the request body. When provided, the body is validated before the request is sent. Validation failure returns immediately — the request is never made.'),
    response_schema: zod_1.z.record(zod_1.z.any()).optional().describe('JSON Schema for the expected response body. When provided, the response is validated after receiving. The validated flag and validation_errors in the output indicate whether the response matched.'),
    timeout_ms: zod_1.z.number().optional().describe('Request timeout in milliseconds (default: 30000).'),
    credential_provider: zod_1.z.string().optional().describe('Credential provider name (e.g. "stripe", "epic", "google"). When set, resolves authentication from the connection store using the calling principal\'s identity. No manual token input needed.'),
    credential_label: zod_1.z.string().optional().describe('Credential label for multi-credential accounts (default: "default").'),
    auth_scheme: zod_1.z.string().optional().describe('Authentication scheme (default: "Bearer"). Used with credential_provider to build the auth header value.'),
    auth_header: zod_1.z.string().optional().describe('Header name for the credential (default: "Authorization"). Some APIs use X-API-Key instead.'),
});
const validateSchema = zod_1.z.object({
    data: zod_1.z.any().describe('The value to validate against the schema.'),
    schema: zod_1.z.record(zod_1.z.any()).describe('JSON Schema to validate against.'),
});
async function createSchemaExchangeServer(options) {
    const name = options?.name || 'long-tail-schema-exchange';
    const instance = new mcp_js_1.McpServer({ name, version: '1.0.0' });
    instance.registerTool('exchange', {
        title: 'Schema Exchange',
        description: 'Exchange data with an external service endpoint under schema enforcement. ' +
            'Validates the request body against request_schema before sending and the response ' +
            'body against response_schema after receiving. Transport is an implementation detail — ' +
            'the principle is endpoint + schema + validated data exchange. ' +
            'Use response_schema to detect API drift: schedule on cron and the validated flag ' +
            'tells you immediately when the API shape changes.',
        inputSchema: exchangeSchema,
    }, async (args) => {
        try {
            const result = await schemaExchange.exchange(args);
            return { content: [{ type: 'text', text: JSON.stringify(result) }] };
        }
        catch (err) {
            return { content: [{ type: 'text', text: JSON.stringify({ error: err.message }) }], isError: true };
        }
    });
    instance.registerTool('validate_schema', {
        title: 'Validate Schema',
        description: 'Validate any value against a JSON Schema without making a network call. ' +
            'Useful for pre-validating data before storage, checking API response shapes in tests, ' +
            'or verifying that transforms produce correct output.',
        inputSchema: validateSchema,
    }, async (args) => {
        const result = schemaExchange.validateSchema(args.data, args.schema);
        return { content: [{ type: 'text', text: JSON.stringify(result) }] };
    });
    logger_1.loggerRegistry.info(`[lt-mcp:schema-exchange] ${name} ready (2 tools registered)`);
    return instance;
}
