/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var mcp_server_exports = {};
__export(mcp_server_exports, {
  McpServer: () => McpServer
});
module.exports = __toCommonJS(mcp_server_exports);
let mcpSdkPromise = null;
function getMcpSdkModules() {
  if (!mcpSdkPromise) {
    mcpSdkPromise = Promise.all([
      import("@modelcontextprotocol/sdk/server/mcp.js"),
      import("@modelcontextprotocol/sdk/server/streamableHttp.js"),
      import("@modelcontextprotocol/sdk/types.js")
    ]).then(([mcpServerModule, transportModule, typesModule]) => {
      return {
        McpServer: mcpServerModule.McpServer,
        StreamableHTTPServerTransport: transportModule.StreamableHTTPServerTransport,
        CallToolRequestSchema: typesModule.CallToolRequestSchema,
        ListToolsRequestSchema: typesModule.ListToolsRequestSchema
      };
    });
  }
  return mcpSdkPromise;
}
function stringifyContent(content) {
  if (typeof content === "string") {
    return content;
  }
  try {
    return JSON.stringify(content);
  } catch (error) {
    return String(content);
  }
}
function normalizeHeaderValue(value) {
  if (Array.isArray(value)) {
    return value[0];
  }
  return value;
}
function resolveTokenFromExtra(extra) {
  var _a, _b;
  if ((_a = extra == null ? void 0 : extra.authInfo) == null ? void 0 : _a.token) {
    return extra.authInfo.token;
  }
  const headers = (_b = extra == null ? void 0 : extra.requestInfo) == null ? void 0 : _b.headers;
  if (!headers) {
    return void 0;
  }
  const authHeader = normalizeHeaderValue(headers.authorization || headers.Authorization);
  if (!authHeader) {
    return void 0;
  }
  const match = authHeader.match(/^Bearer\s+(.+)$/i);
  return (match == null ? void 0 : match[1]) || authHeader;
}
class McpServer {
  constructor(options) {
    this.options = options;
  }
  async handlePost(ctx) {
    var _a;
    const body = ctx.request.body || {};
    const sdkModules = await getMcpSdkModules();
    const server = this.createServer(sdkModules, ctx, (_a = ctx.getBearerToken) == null ? void 0 : _a.call(ctx));
    const transport = new sdkModules.StreamableHTTPServerTransport({
      sessionIdGenerator: void 0
    });
    transport.onerror = (error) => {
      this.options.logger.error(error);
    };
    await server.connect(transport);
    try {
      await transport.handleRequest(ctx.req, ctx.res, body);
    } finally {
      await server.close();
    }
    ctx.respond = false;
  }
  createServer(sdkModules, ctx, requestToken) {
    const server = new sdkModules.McpServer(
      {
        name: this.options.name,
        version: this.options.version
      },
      {
        capabilities: {
          tools: {}
        }
      }
    );
    server.server.setRequestHandler(sdkModules.ListToolsRequestSchema, async () => {
      const tools = this.options.getTools ? await this.options.getTools(ctx) : this.options.toolsManager.listTools();
      return {
        tools: tools.map((tool) => {
          return {
            name: tool.name,
            description: tool.description,
            inputSchema: tool.inputSchema || {
              type: "object",
              properties: {}
            }
          };
        })
      };
    });
    server.server.setRequestHandler(sdkModules.CallToolRequestSchema, async (request, extra) => {
      var _a;
      const toolName = request.params.name;
      const args = request.params.arguments || {};
      const tool = this.options.getTools ? (await this.options.getTools(ctx)).find((item) => item.name === toolName) : this.options.toolsManager.getTool(toolName);
      if (!tool) {
        throw new Error(`Tool not found: ${toolName}`);
      }
      const token = requestToken || resolveTokenFromExtra(extra);
      try {
        const result = await tool.call(args, {
          token,
          headers: (_a = extra == null ? void 0 : extra.requestInfo) == null ? void 0 : _a.headers
        });
        return {
          content: [
            {
              type: "text",
              text: stringifyContent(result)
            }
          ],
          isError: false
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: error instanceof Error ? error.message : stringifyContent(error)
            }
          ],
          isError: true
        };
      }
    });
    return server;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  McpServer
});
