"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports._setGetConfigObjForTest = _setGetConfigObjForTest;
exports._restoreGetConfigObj = _restoreGetConfigObj;
exports.registerMcpProfile = registerMcpProfile;
exports.handleApplication = handleApplication;
exports._resetApplicationStartedForTest = _resetApplicationStartedForTest;
/**
 * Native MCP (Model Context Protocol) server component for Harper.
 *
 * #614 replaces the foundation stub from #613 with a real Streamable HTTP
 * transport. Two entry points:
 *
 *   - `registerMcpProfile({profile:'operations', host, config, routeOptions})`
 *     called from `server/operationsServer.ts` (Fastify-side gate).
 *
 *   - `handleApplication(scope)` invoked by the component loader when the
 *     root config contains a top-level `mcp:` block. Registers the
 *     application-profile handler on the HTTP port iff `mcp.application` is
 *     present.
 *
 * Profile presence drives enablement, matching Harper's `replication`
 * convention (no `enabled` flag). See #465 for the umbrella design.
 */
const harper_logger_ts_1 = __importDefault(require("../../utility/logging/harper_logger.js"));
const configUtils_js_1 = require("../../config/configUtils.js");
const fastify_ts_1 = require("./adapters/fastify.js");
const harperHttp_ts_1 = require("./adapters/harperHttp.js");
const session_ts_1 = require("./session.js");
const listChanged_ts_1 = require("./listChanged.js");
const application_ts_1 = require("./tools/application.js");
const operations_ts_1 = require("./tools/operations.js");
// Indirection so tests can swap the config source.
let getConfigObj = configUtils_js_1.getConfigObj;
function _setGetConfigObjForTest(fn) {
    getConfigObj = fn;
}
function _restoreGetConfigObj() {
    getConfigObj = configUtils_js_1.getConfigObj;
}
const DEFAULT_MOUNT_PATH = '/mcp';
/**
 * Fastify-side registration. Used by `server/operationsServer.ts` for the
 * operations profile. Idempotent through the host's own route table.
 */
function registerMcpProfile({ profile, host, config, routeOptions }) {
    const profileConfig = config?.mcp?.[profile];
    if (!profileConfig) {
        harper_logger_ts_1.default.trace(`MCP ${profile} profile not configured, skipping registration`);
        return;
    }
    (0, session_ts_1.ensureSessionTable)();
    (0, listChanged_ts_1.initListChanged)();
    if (profile === 'operations') {
        (0, operations_ts_1.registerOperationsTools)();
    }
    const mountPath = profileConfig.mountPath ?? DEFAULT_MOUNT_PATH;
    const handler = (0, fastify_ts_1.createFastifyHandler)(profile);
    // Register POST, GET, and DELETE on the same mount path. The transport
    // core decides whether to handle (POST initialize / JSON-RPC dispatch),
    // return 405 with an accurate `Allow` header (GET always in v1, DELETE
    // when `mcp.session.allowClientDelete` is false), or process (DELETE
    // when enabled). Without explicit GET/DELETE routes Fastify would
    // short-circuit to its built-in 404 before the transport runs.
    for (const method of ['post', 'get', 'delete']) {
        if (routeOptions) {
            host[method](mountPath, routeOptions, handler);
        }
        else {
            host[method](mountPath, handler);
        }
    }
    harper_logger_ts_1.default.info(`MCP ${profile} profile registered at ${mountPath}`);
}
let applicationStarted = false;
/**
 * Trusted-Resource-Plugin entry point for the application profile. The
 * component loader invokes this with the runtime `Scope` when the root
 * config contains a top-level `mcp:` block. We register the handler iff the
 * `application` sub-block is also present.
 *
 * Idempotent — repeated invocations no-op via `applicationStarted`. This
 * matches REST's pattern at `server/REST.ts:283-303`.
 */
function handleApplication(scope) {
    if (applicationStarted)
        return;
    const config = getConfigObj();
    if (!config?.mcp?.application) {
        harper_logger_ts_1.default.trace('MCP application profile not configured, skipping registration');
        return;
    }
    applicationStarted = true;
    (0, session_ts_1.ensureSessionTable)();
    (0, listChanged_ts_1.initListChanged)();
    (0, application_ts_1.registerApplicationTools)();
    const mountPath = config.mcp.application.mountPath ?? DEFAULT_MOUNT_PATH;
    const handler = (0, harperHttp_ts_1.createHarperHttpHandler)('application');
    scope.server.http(handler, { urlPath: mountPath, after: 'authentication' });
    harper_logger_ts_1.default.info(`MCP application profile registered at ${mountPath}`);
}
/** Test seam: reset the module-level guard so tests can re-invoke handleApplication. */
function _resetApplicationStartedForTest() {
    applicationStarted = false;
}
//# sourceMappingURL=index.js.map