import { getToolRegistry } from "./tool-registry.js";
import { hasRequiredFeatures } from "./auth.js";
function sanitizeEmptyStrings(input) {
  if (!input || typeof input !== "object" || Array.isArray(input)) return input;
  const result = {};
  for (const [key, value] of Object.entries(input)) {
    if (typeof value === "string" && value.trim() === "") continue;
    result[key] = value;
  }
  return result;
}
async function executeTool(toolName, input, context) {
  const registry = getToolRegistry();
  const tool = registry.getTool(toolName);
  if (!tool) {
    return {
      success: false,
      error: `Tool "${toolName}" not found`,
      errorCode: "NOT_FOUND"
    };
  }
  if (tool.requiredFeatures?.length) {
    const rbacService = context.container.resolve("rbacService");
    const hasAccess = hasRequiredFeatures(
      tool.requiredFeatures,
      context.userFeatures,
      context.isSuperAdmin,
      rbacService
    );
    if (!hasAccess) {
      return {
        success: false,
        error: `Insufficient permissions for tool "${toolName}". Required: ${tool.requiredFeatures.join(", ")}`,
        errorCode: "UNAUTHORIZED"
      };
    }
  }
  const sanitizedInput = sanitizeEmptyStrings(input);
  const parseResult = tool.inputSchema.safeParse(sanitizedInput);
  if (!parseResult.success) {
    const issues = parseResult.error.issues ?? [];
    const errorMessages = issues.map(
      (issue) => `${issue.path.join(".")}: ${issue.message}`
    ).join("; ");
    return {
      success: false,
      error: `Invalid input: ${errorMessages || "Validation failed"}`,
      errorCode: "VALIDATION_ERROR"
    };
  }
  const handlerContext = { ...context, tool };
  try {
    const result = await tool.handler(parseResult.data, handlerContext);
    return { success: true, result };
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`[MCP Tool] Error executing "${toolName}":`, error);
    return {
      success: false,
      error: message,
      errorCode: "EXECUTION_ERROR"
    };
  }
}
export {
  executeTool
};
//# sourceMappingURL=tool-executor.js.map
