Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/schemas/settings.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,21 @@ export const GetSettingsArgs = z.object({
.max(50)
.optional()
.describe('Setting keys instead of a page, e.g. ["flowConfig.color", "flowConfig.timezone"].'),
locale: z
.string()
.max(35)
.optional()
.describe('Static translations: the language of the texts, e.g. "de" (the primary language when left out).'),
texts: z
.array(z.string().max(80))
.max(50)
.optional()
.describe('Static translations: text keys to read, e.g. ["newConversation", "sendMessage"].'),
search: z
.string()
.max(100)
.optional()
.describe("Static translations: words to find texts by, in Gleap's text, the own wording, the key or what it is for (e.g. \"new conversation\")."),
});

export const SettingChange = z.object({
Expand All @@ -23,7 +38,12 @@ export const SettingChange = z.object({
.max(120)
.optional()
.describe('A field: its key from get_settings, e.g. "flowConfig.color", "flowConfig.openingTimes", "slaOptions.defaultSla", "emailConversation.receivedConfirmation".'),
value: z.any().optional().describe("The field's new value in the type get_settings lists (null clears it). Lists and objects go whole: read, change, send back."),
value: z
.any()
.optional()
.describe(
"The field's new value in the type get_settings lists (null clears it). Lists and objects go whole: read, change, send back. Static translations take a list of text changes instead: [{ key: 'newConversation', locale: 'de', text: '…' }], text null resets one text.",
),
page: z.string().max(60).optional().describe('For an item of a page of items: the page key ("project-teams", "macros", "attributes", "helpcenter-sites", "webhooks").'),
op: z.enum(["create", "update", "delete"]).optional().describe("What to do with the item."),
id: z.string().max(40).optional().describe("The item id (update, delete), from get_settings."),
Expand Down
29 changes: 24 additions & 5 deletions src/tools/settings.tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,24 @@ import { gleapGet, gleapPut, validationErrorResponse } from "../utils/api.js";
* never returned. Risky changes run only with `confirmed: true` after the person said yes.
*/

const STATIC_TRANSLATIONS_PAGE = "static-translations";
const READ = { readOnlyHint: true, destructiveHint: false, openWorldHint: false } as const;
const WRITE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false } as const;

/** Settings › Static translations: Gleap's UI texts, read by language, key or words and changed one cell at a time. */
const STATIC_TRANSLATIONS_EXAMPLE = "{key:'flowConfig.staticTranslations', value:[{key:'newConversation', locale:'de', text:'Neue Anfrage'}]}";
const STATIC_TRANSLATIONS_HELP =
"Gleap's widget, email and survey texts as the project words them; get_settings with locale, texts or search reads them with Gleap's text and a status; " +
`change one text and language at a time, e.g. ${STATIC_TRANSLATIONS_EXAMPLE}, text null resets it to Gleap's, never the whole table; ` +
"placeholders in single braces as Gleap's text has them ({name}), locked texts only reset";

/** The pages and their main keys, for the descriptions (the API's list is the full truth). */
const PAGES_HELP =
"Pages (key: main fields): " +
"general (name, picture, moveToOpenOnReply, autoAssignTicketToRecentCommenter, reactionsEnabled, threadsEnabled, customArchiveDate …); " +
"operating-hours (flowConfig.showOnlineStatus, alwaysOnline, timezone, openingTimes [{day: All days|Weekdays|Weekends|Monday…, openingTime 'HH:MM', closingTime}], replyTime, holidays); " +
"sla (slaOptions.enabled, defaultSla in seconds, ticketTypes, restUrl); languages (localizations); static-translations (flowConfig.staticTranslations); " +
"sla (slaOptions.enabled, defaultSla in seconds, ticketTypes, restUrl); languages (localizations); " +
"static-translations (flowConfig.staticTranslations: " + STATIC_TRANSLATIONS_HELP + "); " +
"user-identity (secureSessionIdentify, acceptLegacyUserHash, customerIdentity, protectedContactFields, protectedCompanyFields, customerAuth, authenticatedConversationFiles …); allowed-domains (allowedWidgetDomains); " +
"widget-install (flowConfig.trackWidgetInteractions); widget-look (flowConfig.color, darkColor, backgroundColor, colorScheme, headerColor, bgType, feedbackButtonPosition, buttonColor, hideBranding, borderRadius, customCSS …); " +
"widget-content (flowConfig.welcomeText, hideNews, hideKnowledgeBase, startPage, homeWidgets …); widget-conversations (flowConfig.ticketHeaderMode, sendOnEnter, disableAttachments …); aichatbar (aiBar.*); " +
Expand Down Expand Up @@ -61,16 +70,26 @@ export const registerSettingsTools = (server: McpServer) => {
{
title: "Get Settings",
description:
"Current values of a settings page (`page`) or of named setting keys (`keys`). Pages of items (teams, macros, help center sites, webhooks) list their items with ids. Secrets show only whether they are set ({ set: true }). Read a value before you change it, so lists and objects go back whole with only the change made.",
"Current values of a settings page (`page`) or of named setting keys (`keys`). Pages of items (teams, macros, help center sites, webhooks) list their items with ids. Secrets show only whether they are set ({ set: true }). Read a value before you change it, so lists and objects go back whole with only the change made. " +
"Static translations (Gleap's widget, email and survey texts) show one language (`locale`, the primary one when left out): the project's own wording, or the texts named in `texts` or found by `search` (use it to find a text's key), each with Gleap's text and its status; at most 25 rows. `locale`, `texts` or `search` alone read that page.",
inputSchema: GetSettingsArgs.shape,
annotations: READ,
},
async (args): Promise<GleapApiResponse> => {
if (!args.page && !args.keys?.length) return validationErrorResponse("Give a page or keys (list_setting_pages names them).");
const textsQuery = {
...(args.locale ? { locale: args.locale } : {}),
...(args.texts?.length ? { texts: args.texts.join(",") } : {}),
...(args.search ? { search: args.search } : {}),
};
const hasTextsQuery = Object.keys(textsQuery).length > 0;
// The texts parameters only mean something on Static translations, so alone they read that page.
const page = args.page ?? (hasTextsQuery && !args.keys?.length ? STATIC_TRANSLATIONS_PAGE : undefined);
if (!page && !args.keys?.length) return validationErrorResponse("Give a page or keys (list_setting_pages names them).");
return gleapGet("/settings", {
params: {
...(args.page ? { page: args.page } : {}),
...(page ? { page } : {}),
...(args.keys?.length ? { keys: args.keys.join(",") } : {}),
...textsQuery,
},
});
},
Expand All @@ -81,7 +100,7 @@ export const registerSettingsTools = (server: McpServer) => {
{
title: "Update Settings",
description:
"Change project settings with the connected person's rights, through the dashboard's own saves. A field change is { key, value }; an item change is { page, op: create|update|delete, id, values }. Returns what changed (before → after) and what was refused and why. Risky changes do not run without `confirmed: true`: the first call lists them in needsConfirmation and changes nothing; ask the person, and only after their explicit yes call again with confirmed: true. Risky: " + RISKY_SETTINGS_HELP + " Also inbound email off, SSO, deleting a team, macro, site or webhook. Examples: {key:'flowConfig.color', value:'#2142E7'}; {key:'flowConfig.openingTimes', value:[{day:'Weekdays', openingTime:'09:00', closingTime:'17:00'}]}; {page:'project-teams', op:'create', values:{name:'Billing', members:['anna@acme.com']}}.",
"Change project settings with the connected person's rights, through the dashboard's own saves. A field change is { key, value }; an item change is { page, op: create|update|delete, id, values }. Returns what changed (before → after) and what was refused and why. Risky changes do not run without `confirmed: true`: the first call lists them in needsConfirmation and changes nothing; ask the person, and only after their explicit yes call again with confirmed: true. Risky: " + RISKY_SETTINGS_HELP + " Also inbound email off, SSO, deleting a team, macro, site or webhook. Examples: {key:'flowConfig.color', value:'#2142E7'}; " + STATIC_TRANSLATIONS_EXAMPLE + " (one text in one language; text null resets it to Gleap's); {key:'flowConfig.openingTimes', value:[{day:'Weekdays', openingTime:'09:00', closingTime:'17:00'}]}; {page:'project-teams', op:'create', values:{name:'Billing', members:['anna@acme.com']}}.",
inputSchema: UpdateSettingsArgs.shape,
annotations: WRITE,
},
Expand Down
75 changes: 75 additions & 0 deletions tests/settings.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import { test, beforeEach } from 'node:test';
import axios from 'axios';
import { z } from 'zod';

process.env.GLEAP_API_BASE = 'https://gleap-api.invalid/v3';
const { registerSettingsTools } = await import('../src/tools/settings.tool.js');
const { GetSettingsArgs } = await import('../src/schemas/settings.schema.js');
const { runWithCreds } = await import('../src/utils/credentials.js');
const { applySessionScopePolicy } = await import('../src/utils/sessionScope.js');

const tools = new Map();
const registry = { registerTool(name, config, handler) { tools.set(name, { config, handler }); } };
applySessionScopePolicy(registry);
registerSettingsTools(registry);

let requests;
beforeEach(() => {
requests = [];
axios.defaults.adapter = async config => {
requests.push({ method: config.method, url: config.url, params: config.params ?? {} });
return { data: { settings: [] }, status: 200, statusText: 'OK', headers: {}, config };
};
});
const call = (name, args) => runWithCreds({ apiKey: 'test-only', projectId: 'test-project' }, async () => {
const { config, handler } = tools.get(name);
return handler(z.object(config.inputSchema).parse(args));
});

test('get_settings reads static translations in one language, by text keys and by words', async () => {
const result = await call('get_settings', { page: 'static-translations', locale: 'de', texts: ['newConversation', 'sendMessage'], search: 'new conversation' });
assert.equal(result.isError, undefined);
assert.deepEqual(requests.map(r => [r.method, r.url]), [['get', 'https://gleap-api.invalid/v3/settings']]);
assert.deepEqual(requests[0].params, { page: 'static-translations', locale: 'de', texts: 'newConversation,sendMessage', search: 'new conversation' });
});

test('locale, texts or search alone read the Static translations page', async () => {
await call('get_settings', { search: 'we are back' });
await call('get_settings', { locale: 'fr' });
assert.deepEqual(requests.map(r => r.params), [{ page: 'static-translations', search: 'we are back' }, { page: 'static-translations', locale: 'fr' }]);
});

test('a page or keys alone are sent as before, without the texts parameters', async () => {
await call('get_settings', { page: 'operating-hours' });
await call('get_settings', { keys: ['flowConfig.color', 'flowConfig.timezone'] });
assert.deepEqual(requests.map(r => r.params), [{ page: 'operating-hours' }, { keys: 'flowConfig.color,flowConfig.timezone' }]);
});

test('nothing to read: refused without a request', async () => {
const result = await call('get_settings', {});
assert.equal(result.isError, true);
assert.equal(requests.length, 0);
});

test('the texts parameters are bounded', () => {
assert.equal(GetSettingsArgs.safeParse({ texts: Array.from({ length: 51 }, (_, index) => `key${index}`) }).success, false);
assert.equal(GetSettingsArgs.safeParse({ search: 'x'.repeat(101) }).success, false);
assert.equal(GetSettingsArgs.safeParse({ locale: 'x'.repeat(36) }).success, false);
assert.equal(GetSettingsArgs.safeParse({ texts: ['k'.repeat(81)] }).success, false);
assert.equal(GetSettingsArgs.safeParse({ page: 'static-translations', locale: 'zh-Hant', texts: ['newConversation'], search: 'new' }).success, true);
});

test('the descriptions show how to read and change one text in one language', () => {
const pages = tools.get('list_setting_pages').config.description;
const read = tools.get('get_settings').config.description;
const write = tools.get('update_settings').config.description;
for (const description of [pages, write]) {
assert.match(description, /\{key:'flowConfig\.staticTranslations', value:\[\{key:'newConversation', locale:'de', text:'[^']+'\}\]\}/);
assert.match(description, /text null/);
}
assert.match(read, /locale/);
assert.match(read, /texts/);
assert.match(read, /search/);
assert.doesNotMatch(pages, /static-translations \(flowConfig\.staticTranslations\);/);
});