import { z } from "zod"; import { withAuth, getSessionCredentials, getApiClient } from "../../auth/index.js"; import { handleToolError, validateRequired, handleApiResponse } from "../helpers/errorHandler.js"; import { withAuthParams } from "../helpers/authSchema.js"; import { AcaiHttpClient } from "../helpers/acaiHttpClient.js"; export function registerCheckModuleUsageTool(server) { server.tool( "check_module_usage", "Check which pages/URLs use a module. Call BEFORE delete_module to verify it's safe to remove.", withAuthParams({ id: z.string().describe("Module ID to check usage for"), }), { readOnlyHint: true, destructiveHint: false }, withAuth(async ({ id }, extra) => { try { // Validate required parameters const validationError = validateRequired({ id }, ['id'], 'check_module_usage'); if (validationError) return validationError; const credentials = await getSessionCredentials(extra.sessionId); // Build the request payload const payload = { action_ws: "checkModuleInWeb", module: id, token: credentials.token, tokenHash: credentials.tokenHash }; // Make the request to the client's website const response = await AcaiHttpClient.postViewerFunctions( await getApiClient(extra.sessionId), payload ); // Check for API errors in response const apiError = handleApiResponse(response.data, 'check_module_usage'); if (apiError) return apiError; // El PHP devuelve { result, success, message }. Si el modulo NO esta // en uso, message = "No encuentro el módulo en ninguna sección". // Si esta en uso, message contiene HTML con las tablas/paginas. const msg = (response.data?.message || ""); const inUse = !!msg && !msg.includes("No encuentro"); return { content: [{ type: "text", text: JSON.stringify({ success: true, moduleId: id, inUse, canDelete: !inUse, message: inUse ? "Module is in use — deletion denied. Inform the user which pages use it and stop. Do NOT attempt to remove it from pages." : "Module is not used anywhere — safe to delete", rawMessage: msg, }, null, 2) }], }; } catch (error) { return handleToolError(error, 'check_module_usage', { id }); } }) ); }