"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.McpServerService = void 0;
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const common_1 = require("@nestjs/common");
const mcp_audit_service_1 = require("./mcp-audit.service");
const mcp_registry_service_1 = require("./mcp-registry.service");
let McpServerService = class McpServerService {
    constructor(registry, audit) {
        this.registry = registry;
        this.audit = audit;
    }
    async handleRequest(req, res, context) {
        const server = this.buildServer(context);
        const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
            sessionIdGenerator: undefined,
        });
        await server.connect(transport);
        await transport.handleRequest(req, res, req.body);
    }
    buildServer(context) {
        const server = new index_js_1.Server({ name: 'hedhog-mcp', version: '1.0.0' }, { capabilities: { tools: {} } });
        server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
            tools: this.registry.getAll().map((e) => {
                var _a;
                return ({
                    name: e.definition.name,
                    description: e.definition.description,
                    inputSchema: (_a = e.definition.inputSchema) !== null && _a !== void 0 ? _a : {
                        type: 'object',
                        properties: {},
                    },
                });
            }),
        }));
        server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
            var _a;
            const toolName = request.params.name;
            const args = ((_a = request.params.arguments) !== null && _a !== void 0 ? _a : {});
            const entry = this.registry.get(toolName);
            if (!entry) {
                return {
                    isError: true,
                    content: [{ type: 'text', text: `Tool '${toolName}' not found` }],
                };
            }
            const start = Date.now();
            try {
                const result = await entry.handler(args, Object.assign(Object.assign({}, context), { toolName }));
                await this.audit.record({
                    userId: context.userId,
                    toolName,
                    input: args,
                    success: true,
                    durationMs: Date.now() - start,
                });
                return { content: [{ type: 'text', text: JSON.stringify(result) }] };
            }
            catch (e) {
                await this.audit.record({
                    userId: context.userId,
                    toolName,
                    input: args,
                    success: false,
                    error: e.message,
                    durationMs: Date.now() - start,
                });
                return {
                    isError: true,
                    content: [{ type: 'text', text: e.message }],
                };
            }
        });
        return server;
    }
};
exports.McpServerService = McpServerService;
exports.McpServerService = McpServerService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [mcp_registry_service_1.McpRegistryService,
        mcp_audit_service_1.McpAuditService])
], McpServerService);
//# sourceMappingURL=mcp-server.service.js.map