feat(mcp): tools de idiomas y traducciones

- Nueva categoria tools/languages: list_web_languages,
  get_record_translations y set_record_translations (registros, config,
  textos_generales y vars de modulo via builder_custom).
- Param lang opcional en list_table_records y get_record
  (options.translates de CocoDB).
- Docs actualizados (03/04/06/09/11b + ACAI_ENDPOINTS) con el modelo de
  cms_traducciones y los workflows de traduccion.
This commit is contained in:
Jordan Diaz
2026-07-16 20:09:47 +00:00
parent d475845c27
commit d46c204ed0
13 changed files with 382 additions and 3 deletions

View File

@@ -323,6 +323,75 @@ action=uploadModify
**Usado por**: `delete_record_upload`
**Headers**: `X-Acai-Token`, `X-Requested-With: XMLHttpRequest`
## Categoría: Idiomas y traducciones (multiidioma)
Las traducciones viven en la tabla central `cms_traducciones`, indexada por `(prefix, tableName sin cms_, fieldName, recordNum)`. `fieldValue` se guarda en Base64, pero la codificación/decodificación la hace el PHP: el cliente siempre trabaja con texto plano.
### 1. Listar idiomas activos
**Endpoint**: `/cms/lib/viewer_functions.php?action_ws=getLanguages`
**Método**: POST via `AcaiHttpClient.postViewerAction`
**Usado por**: `list_web_languages`
**Body**: `{}`
**Respuesta**:
```javascript
{
success: true,
languages: [
{ name: string, label: string, prefix: string, urlPrefix: string, isDefault: boolean }
],
defaultLanguage: string
}
```
Notas: `prefix === "www"` es el idioma base (URLs sin prefijo, `urlPrefix === ""`, `isDefault === true`). Otros prefixes (p.ej. `"en"`) sirven bajo `/<urlPrefix>/...`.
### 2. Leer traducciones de registros
**Endpoint**: `/cms/lib/viewer_functions.php?action_ws=getTranslations`
**Método**: POST via `AcaiHttpClient.postViewerAction`
**Usado por**: `get_record_translations`
**Body**:
```javascript
{
tableName: string, // sin prefijo cms_
recordNums: number[], // PKs a leer
fields?: string[], // opcional: solo estos campos
prefix?: string // opcional: solo este idioma
}
```
**Respuesta** (valores ya decodificados de Base64):
```javascript
{
success: true,
tableName: string,
translations: {
"<recordNum>": {
"<prefix>": { "<fieldName>": "<valor>" }
}
}
}
```
### 3. Escribir traducciones de un registro
**Endpoint**: `/cms/lib/viewer_functions.php?action_ws=setTranslations`
**Método**: POST via `AcaiHttpClient.postViewerAction`
**Usado por**: `set_record_translations`
**Body**:
```javascript
{
tableName: string, // sin prefijo cms_
recordNum: number, // PK a traducir
prefix: string, // idioma destino (nunca 'www')
fields: { "<fieldName>": "<valor>" } // '' borra la traducción
}
```
**Respuesta**: `{ success: true, updated: number, deleted: number }`
**Errores**: `{ error: { message: string, code: string } }` — p.ej. si se intenta traducir `enlace` (prohibido: lo mantiene CocoEnlace).
Notas:
- Solo campos traducibles: `textfield`, `textbox`, `wysiwyg`, `codigo`, `multitext` (el multitext se traduce como el JSON serializado completo en una fila).
- Un `fieldValue` vacío (`''`) borra la traducción y el runtime cae al idioma base.
- Vars de módulo: usar `tableName: 'builder_custom'` + el `recordNum`/`fieldName` que da `varsMeta` de `get_module_config_vars`.
- Lectura traducida en línea: las tools `list_table_records`/`get_record` pasan `options.translates = <prefix>` al `cmsApi` get (equivalente al header `X-ACAI-ACCEPT-LANGUAGE` en cms_api v3).
## Patrones Comunes
### getApiClient Calls

View File

@@ -11,6 +11,7 @@ import { registerHookTools } from './hooks/index.js';
import { registerLibrariesTools } from './libraries/index.js';
import { registerLayoutTools } from './layout/index.js';
import { registerDocsTools } from './docs/index.js';
import { registerLanguageTools } from './languages/index.js';
/**
* Register all tools on the MCP server
@@ -29,4 +30,5 @@ export function registerTools(server) {
registerLibrariesTools(server);
registerLayoutTools(server);
registerDocsTools(server);
registerLanguageTools(server);
}

View File

@@ -0,0 +1,74 @@
import { z } from "zod";
import { withAuth, getSessionCredentials } from "../../auth/index.js";
import { handleToolError, validateRequired, handleApiResponse } from "../helpers/errorHandler.js";
import { AcaiHttpClient } from "../helpers/acaiHttpClient.js";
import { withAuthParams } from "../helpers/authSchema.js";
export function registerGetRecordTranslationsTool(server) {
server.tool(
"get_record_translations",
`Read the stored translations for one or more records of a table, from the central cms_traducciones table.
Translations are keyed by (prefix = language code, tableName without 'cms_', fieldName, recordNum). Values are stored Base64 in the DB but this tool returns them already decoded (plain text). An absent field/prefix means there is no translation and the base-language value is used at runtime.
Params:
- tableName: table name WITHOUT the 'cms_' prefix (e.g. 'apartados', 'productos', 'builder_custom', 'textos_generales').
- recordNums: array of record 'num' primary keys to read.
- fields (optional): only return these field names. Omit to return every translated field found.
- prefix (optional): only return translations for this language prefix (e.g. 'en'). Omit to return all languages.
Returns translations shaped as { "<recordNum>": { "<prefix>": { "<fieldName>": "<value>" } } }.
To translate module vars, first call get_module_config_vars to obtain varsMeta ({ fieldName, recordNum } per var) and read from tableName='builder_custom'. For template literals, read tableName='textos_generales' field 'texto'.`,
withAuthParams({
tableName: z.string().describe("Table name without 'cms_' prefix (e.g. 'apartados', 'builder_custom', 'textos_generales')"),
recordNums: z.array(z.number()).describe("Array of record 'num' primary keys to read translations for"),
fields: z.array(z.string()).optional().describe("Only return these field names. Omit to return all translated fields."),
prefix: z.string().optional().describe("Only return translations for this language prefix (e.g. 'en'). Omit for all languages."),
}),
{ readOnlyHint: true, destructiveHint: false },
withAuth(async ({ tableName, recordNums, fields, prefix }, extra) => {
try {
const validationError = validateRequired(
{ tableName, recordNums },
["tableName", "recordNums"],
"get_record_translations"
);
if (validationError) return validationError;
const credentials = await getSessionCredentials(extra.sessionId);
const payload = { tableName, recordNums };
if (fields && fields.length > 0) payload.fields = fields;
if (prefix) payload.prefix = prefix;
const response = await AcaiHttpClient.postViewerAction(
credentials,
"getTranslations",
payload,
credentials.token,
credentials.tokenHash,
{},
15000
);
const apiError = handleApiResponse(response.data, "get_record_translations");
if (apiError) return apiError;
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
action: "get_record_translations",
tableName: response.data?.tableName || tableName,
translations: response.data?.translations || {},
}, null, 2)
}],
};
} catch (error) {
return handleToolError(error, "get_record_translations", { tableName, recordNums });
}
})
);
}

View File

@@ -0,0 +1,9 @@
import { registerListWebLanguagesTool } from './listWebLanguages.js';
import { registerGetRecordTranslationsTool } from './getRecordTranslations.js';
import { registerSetRecordTranslationsTool } from './setRecordTranslations.js';
export function registerLanguageTools(server) {
registerListWebLanguagesTool(server);
registerGetRecordTranslationsTool(server);
registerSetRecordTranslationsTool(server);
}

View File

@@ -0,0 +1,54 @@
import { withAuth, getSessionCredentials } from "../../auth/index.js";
import { handleToolError, handleApiResponse } from "../helpers/errorHandler.js";
import { AcaiHttpClient } from "../helpers/acaiHttpClient.js";
import { withAuthParams } from "../helpers/authSchema.js";
export function registerListWebLanguagesTool(server) {
server.tool(
"list_web_languages",
`List the active languages configured for the current website (from settings.dat.php [idiomas]).
Returns an array of languages, each with:
- name: internal code (e.g. 'espanol')
- label: human label
- prefix: the translation prefix stored in cms_traducciones. The prefix "www" is the BASE language (its URLs have NO path prefix). Any other prefix (e.g. "en") is a secondary language served under /<urlPrefix>/...
- urlPrefix: the URL path segment for that language ('' for the base language, e.g. 'en' otherwise)
- isDefault: true for the base language
Also returns defaultLanguage. Use the prefix values here when calling get_record_translations / set_record_translations.`,
withAuthParams({}),
{ readOnlyHint: true, destructiveHint: false },
withAuth(async (_args, extra) => {
try {
const credentials = await getSessionCredentials(extra.sessionId);
const response = await AcaiHttpClient.postViewerAction(
credentials,
"getLanguages",
{},
credentials.token,
credentials.tokenHash,
{},
15000
);
const apiError = handleApiResponse(response.data, "list_web_languages");
if (apiError) return apiError;
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
action: "list_web_languages",
languages: response.data?.languages || [],
defaultLanguage: response.data?.defaultLanguage,
}, null, 2)
}],
};
} catch (error) {
return handleToolError(error, "list_web_languages");
}
})
);
}

View File

@@ -0,0 +1,79 @@
import { z } from "zod";
import { withAuth, getSessionCredentials } from "../../auth/index.js";
import { handleToolError, validateRequired, handleApiResponse } from "../helpers/errorHandler.js";
import { AcaiHttpClient } from "../helpers/acaiHttpClient.js";
import { withAuthParams } from "../helpers/authSchema.js";
export function registerSetRecordTranslationsTool(server) {
server.tool(
"set_record_translations",
`Write translations for a single record + language into the central cms_traducciones table. Values are stored Base64 automatically (transparent — pass plain text). Only translatable field types can be translated: textfield, textbox, wysiwyg, codigo and multitext.
Four usage scenarios:
1. Normal records — translate the visible text fields of any content table. tableName without 'cms_', recordNum = the record 'num', fields = { fieldName: translatedText }.
2. configuracion / configuracion_tienda — the global settings tables are ordinary records; translate their text fields the same way (locate the row with list_table_records).
3. textos_generales — the template literals used by the Twig '| translate' filter are normal records: translate their 'texto' field. Find the right num by 'identificador' with list_table_records first (tableName='textos_generales', fields={ texto: '...' }).
4. Module vars — the textual values of a module live in the 'builder_custom' table. Call get_module_config_vars to get varsMeta ({ fieldName, recordNum } per var, and per item for multi vars), then set tableName='builder_custom', recordNum + fields={ <fieldName>: translatedText } from varsMeta.
Rules:
- An EMPTY STRING ('') as a value DELETES that translation (falls back to base language at runtime).
- The 'enlace' field is NEVER translated by hand — the CocoEnlace engine maintains it; the PHP rejects it.
- multitext fields are translated as the full serialized JSON string in a single row (translate the whole JSON value, not individual items).
- prefix is the language code from list_web_languages (e.g. 'en'); do NOT write to prefix 'www' (base language is edited via normal record fields, not translations).
Params:
- tableName (string) without 'cms_' prefix.
- recordNum (number) the record 'num' primary key.
- prefix (string) target language prefix (e.g. 'en').
- fields (object) { fieldName: translatedValue } map. '' deletes.`,
withAuthParams({
tableName: z.string().describe("Table name without 'cms_' prefix (e.g. 'apartados', 'builder_custom', 'textos_generales')"),
recordNum: z.number().describe("Record 'num' primary key to translate"),
prefix: z.string().describe("Target language prefix from list_web_languages (e.g. 'en'). Never 'www' (base language)."),
fields: z.record(z.string()).describe("Map { fieldName: translatedValue }. Empty string '' deletes the translation. 'enlace' is forbidden."),
}),
{ readOnlyHint: false, destructiveHint: false },
withAuth(async ({ tableName, recordNum, prefix, fields }, extra) => {
try {
const validationError = validateRequired(
{ tableName, recordNum, prefix, fields },
["tableName", "recordNum", "prefix", "fields"],
"set_record_translations"
);
if (validationError) return validationError;
const credentials = await getSessionCredentials(extra.sessionId);
const response = await AcaiHttpClient.postViewerAction(
credentials,
"setTranslations",
{ tableName, recordNum, prefix, fields },
credentials.token,
credentials.tokenHash,
{},
15000
);
const apiError = handleApiResponse(response.data, "set_record_translations");
if (apiError) return apiError;
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
action: "set_record_translations",
tableName,
recordNum,
prefix,
updated: response.data?.updated,
deleted: response.data?.deleted,
}, null, 2)
}],
};
} catch (error) {
return handleToolError(error, "set_record_translations", { tableName, recordNum, prefix });
}
})
);
}

View File

@@ -20,9 +20,10 @@ Examples:
recordNum: z.string().describe("Record 'num' (primary key)"),
loadUploads: z.boolean().optional().default(true).describe("Load upload field data (default: true)"),
loadRelations: z.boolean().optional().default(true).describe("Resolve foreign key relations (default: true)"),
lang: z.string().optional().describe("Language prefix (e.g. 'en'). Returns translated values for translatable fields"),
}),
{ readOnlyHint: true, destructiveHint: false },
withAuth(async ({ tableName, recordNum, loadUploads = true, loadRelations = true }, extra) => {
withAuth(async ({ tableName, recordNum, loadUploads = true, loadRelations = true, lang }, extra) => {
try {
const validationError = validateRequired(
{ tableName, recordNum },
@@ -53,6 +54,11 @@ Examples:
payload.options.ignoreSchema = true;
}
// Si se pide un idioma, el motor CocoDB aplica la traduccion en lectura.
if (lang) {
payload.options.translates = lang;
}
const response = await AcaiHttpClient.postCmsApi(
credentials,
"get",

View File

@@ -15,9 +15,10 @@ export function registerListTableRecordsTool(server) {
limit: z.number().optional().describe("Max records to return. Default: 50. Use 5-10 for previews, up to 200 max for large exports."),
fields: z.array(z.string()).optional().describe("Return only these columns (e.g., ['num', 'titulo', 'precio']). Omit to return all columns. Always include 'num' if you need record IDs."),
truncateText: z.number().optional().describe("Truncate string field values longer than this many chars. Appends '... [truncated, N chars]'. Combine with 'fields' for maximum token savings."),
lang: z.string().optional().describe("Language prefix (e.g. 'en'). Returns translated values for translatable fields"),
}),
{ readOnlyHint: true, destructiveHint: false },
withAuth(async ({ tableName, page, where, limit, fields, truncateText }, extra) => {
withAuth(async ({ tableName, page, where, limit, fields, truncateText, lang }, extra) => {
try {
// Validate required parameters
const validationError = validateRequired({ tableName }, ['tableName'], 'list_table_records');
@@ -33,6 +34,11 @@ export function registerListTableRecordsTool(server) {
options: {}
};
// Si se pide un idioma, el motor CocoDB aplica la traduccion en lectura.
if (lang) {
payload.options.translates = lang;
}
// Send to CMS API via viewer_functions
const response = await AcaiHttpClient.postCmsApi(
credentials,