Files
agenticSystem/mcp-server/tools/tables/schema.js
2026-04-12 10:16:52 +00:00

66 lines
3.1 KiB
JavaScript

import { z } from "zod";
import { withAuth, getSessionCredentials, getApiClient } from "../../auth/index.js";
import { handleToolError, validateRequired, handleApiResponse } from "../helpers/errorHandler.js";
import { AcaiHttpClient } from "../helpers/acaiHttpClient.js";
import { withAuthParams } from "../helpers/authSchema.js";
import { parseIniSchema } from "./iniParser.js";
export function registerGetTableSchemaTool(server) {
server.tool(
"get_table_schema",
"Get the full schema of a database table, including all fields and their types/metadata. Table names WITHOUT 'cms_' prefix. Primary key is 'num', never 'id'. Use minimal=true for compact output (saves tokens).",
withAuthParams({
tableName: z.string().describe("Table name without cms_ prefix"),
minimal: z.boolean().optional().describe("If true, returns only field names + types + labels"),
}),
{ readOnlyHint: true, destructiveHint: false },
withAuth(async ({ tableName, minimal }, extra) => {
try {
const validationError = validateRequired({ tableName }, ['tableName'], 'get_table_schema');
if (validationError) return validationError;
const credentials = await getSessionCredentials(extra.sessionId);
const payload = {
action_ws: "getTableSchemas",
tableName,
token: credentials.token,
tokenHash: credentials.tokenHash,
};
const response = await AcaiHttpClient.postViewerFunctions(
await getApiClient(extra.sessionId),
payload
);
const apiError = handleApiResponse(response.data, 'get_table_schema');
if (apiError) return apiError;
const schemas = response.data.schemas || {};
const filename = tableName + '.ini.php';
const iniContent = schemas[filename];
if (!iniContent) {
return {
content: [{ type: "text", text: `Table '${tableName}' not found` }],
isError: true,
};
}
const parsed = parseIniSchema(iniContent);
if (minimal) {
const minimalSchema = { menuName: parsed.menuName, menuType: parsed.menuType, enlace: parsed.enlace };
const minFields = {};
for (const [key, value] of Object.entries(parsed.fields || {})) {
minFields[key] = { type: value.type };
if (value.label) minFields[key].label = value.label;
}
minimalSchema.fields = minFields;
return { content: [{ type: "text", text: JSON.stringify(minimalSchema, null, 2) }] };
}
return { content: [{ type: "text", text: JSON.stringify(parsed, null, 2) }] };
} catch (error) {
return handleToolError(error, 'get_table_schema', { tableName });
}
})
);
}