From adb1656bff5e7bfcd47e2eb5e86c7a678caaba80 Mon Sep 17 00:00:00 2001 From: Tobias duelli Date: Tue, 24 Nov 2026 17:28:05 +0100 Subject: [PATCH 1/2] test(toolbox): update_office_hours and update_sla save through the settings registry Fails today: both tools write PUT /projects, update_sla reads GET /projects/current and sends the whole slaOptions object. Co-Authored-By: Claude Opus 5.5 --- src/tools/toolbox.tool.test.ts | 192 +++++++++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 src/tools/toolbox.tool.test.ts diff --git a/src/tools/toolbox.tool.test.ts b/src/tools/toolbox.tool.test.ts new file mode 100644 index 0000000..f8820d2 --- /dev/null +++ b/src/tools/toolbox.tool.test.ts @@ -0,0 +1,192 @@ +// update_office_hours and update_sla save through the project's settings registry (PUT /settings), one stored +// field per change, like update_settings: never PUT /projects, never the whole slaOptions object. The tools' +// inputs and results stay what AI clients know. Drives the real SDK server over an in-memory transport. +import assert from "node:assert/strict"; +import { beforeEach, describe, test } from "node:test"; +import axios from "axios"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { registerToolboxTools } from "./toolbox.tool.js"; +import { runWithCreds } from "../utils/credentials.js"; + +type Sent = { method: string; url: string; params: Record; body: unknown }; +type Change = { key: string; value: unknown }; + +const API = "https://gleap-api.invalid/v3"; +const WEEK = [ + { day: "Weekdays", openingTime: "09:00", closingTime: "17:00" }, + { day: "Saturday", openingTime: "10:00", closingTime: "12:30" }, +]; + +let sent: Sent[]; +let stored: Record; +let refusal: string | null; +let confirmation: string | null; + +const isChange = (value: unknown): value is Change => !!value && typeof value === "object" && "key" in value && typeof value.key === "string"; +const changesIn = (body: unknown): Change[] => + body && typeof body === "object" && "changes" in body && Array.isArray(body.changes) ? body.changes.filter(isChange) : []; + +// The settings API as GET/PUT /settings answer: values by stored key; changed, refused and needsConfirmation lists. +const settingsAnswer = (method: string, params: Record, body: unknown) => { + if (method === "get") { + const keys = `${params.keys ?? ""}`.split(",").filter(Boolean); + return { settings: [{ page: "sla", name: "SLAs", values: Object.fromEntries(keys.map((key) => [key, stored[key] ?? null])) }] }; + } + const changes = changesIn(body); + if (refusal) return { changed: [], refused: changes.map((change) => ({ change: change.key, reason: refusal })) }; + if (confirmation) return { changed: [], refused: [], needsConfirmation: changes.map((change) => ({ change: change.key, why: confirmation })) }; + const changed = changes.map((change) => ({ page: "sla", key: change.key, before: stored[change.key] ?? null, after: change.value, line: change.key })); + for (const change of changes) stored[change.key] = change.value; + return { changed, refused: [] }; +}; + +beforeEach(() => { + sent = []; + stored = { "slaOptions.enabled": true, "slaOptions.defaultSla": 3600 }; + refusal = null; + confirmation = null; + axios.defaults.adapter = async (config) => { + const method = `${config.method ?? "get"}`; + const url = `${config.url ?? ""}`; + const params: Record = { ...config.params }; + const body: unknown = typeof config.data === "string" ? JSON.parse(config.data) : config.data; + sent.push({ method, url, params, body }); + if (url !== `${API}/settings`) throw new Error(`unexpected request ${method} ${url}`); + return { data: settingsAnswer(method, params, body), status: 200, statusText: "OK", headers: {}, config }; + }; +}); + +const call = async (name: string, args: Record) => { + const server = new McpServer({ name: "gleap-mcp-test", version: "0.0.0" }); + registerToolboxTools(server); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "test-client", version: "0.0.0" }); + await server.connect(serverTransport); + await client.connect(clientTransport); + const result = await runWithCreds({ apiKey: "test-only", projectId: "p1" }, () => client.callTool({ name, arguments: args })); + const text = Array.isArray(result.content) ? result.content.map((part) => `${part?.text ?? ""}`).join("\n") : ""; + return { isError: result.isError === true, structured: result.structuredContent, text }; +}; + +const writes = () => sent.filter((request) => request.method !== "get"); + +describe("update_office_hours saves through the settings registry", () => { + test("the week, the timezone and always online -> one settings change each, nothing else written", async () => { + const result = await call("update_office_hours", { openingTimes: WEEK, timezone: "Europe/Vienna", alwaysOnline: false }); + assert.equal(result.isError, false, result.text); + assert.deepEqual(writes(), [ + { + method: "put", + url: `${API}/settings`, + params: {}, + body: { + changes: [ + { key: "flowConfig.openingTimes", value: WEEK }, + { key: "flowConfig.timezone", value: "Europe/Vienna" }, + { key: "flowConfig.alwaysOnline", value: false }, + ], + }, + }, + ]); + assert.deepEqual(result.structured, { changed: ["openingTimes", "timezone", "alwaysOnline"], message: "Office hours saved." }); + }); + + test("only the timezone -> only flowConfig.timezone is sent", async () => { + const result = await call("update_office_hours", { timezone: "America/New_York" }); + assert.equal(result.isError, false, result.text); + assert.deepEqual(changesIn(writes()[0]?.body), [{ key: "flowConfig.timezone", value: "America/New_York" }]); + assert.equal(writes().length, 1); + assert.deepEqual(result.structured, { changed: ["timezone"], message: "Office hours saved." }); + }); + + test("an empty week closes every day: the empty list is saved", async () => { + const result = await call("update_office_hours", { openingTimes: [] }); + assert.equal(result.isError, false, result.text); + assert.deepEqual(changesIn(writes()[0]?.body), [{ key: "flowConfig.openingTimes", value: [] }]); + assert.deepEqual(result.structured, { changed: ["openingTimes"], message: "Office hours saved." }); + }); + + test("a change the settings refuse -> an error with the reason, never 'saved'", async () => { + refusal = "only project admins change this page"; + const result = await call("update_office_hours", { alwaysOnline: true }); + assert.equal(result.isError, true); + assert.match(result.text, /only project admins change this page/); + assert.doesNotMatch(result.text, /Office hours saved/); + }); + + test("a change that waits for the person's yes ran nothing -> an error, never 'saved'", async () => { + confirmation = "Customers see the team as online at night."; + const result = await call("update_office_hours", { alwaysOnline: true }); + assert.equal(result.isError, true); + assert.doesNotMatch(result.text, /Office hours saved/); + }); + + test("closing before opening -> refused before any request", async () => { + const result = await call("update_office_hours", { openingTimes: [{ day: "Monday", openingTime: "17:00", closingTime: "09:00" }] }); + assert.equal(result.isError, true); + assert.equal(sent.length, 0); + }); +}); + +describe("update_sla saves single slaOptions fields through the settings registry", () => { + test("switching off sends only slaOptions.enabled and reports the stored deadline", async () => { + const result = await call("update_sla", { enabled: false }); + assert.equal(result.isError, false, result.text); + assert.equal(writes().length, 1); + assert.equal(writes()[0]?.url, `${API}/settings`); + assert.deepEqual(writes()[0]?.body, { changes: [{ key: "slaOptions.enabled", value: false }] }); + assert.deepEqual(result.structured, { sla: { enabled: false, minutes: 60 }, message: "SLA off." }); + }); + + test("a deadline alone switches the SLA on and saves it in seconds", async () => { + const result = await call("update_sla", { minutes: 240 }); + assert.equal(result.isError, false, result.text); + assert.deepEqual(writes(), [ + { + method: "put", + url: `${API}/settings`, + params: {}, + body: { + changes: [ + { key: "slaOptions.enabled", value: true }, + { key: "slaOptions.defaultSla", value: 14400 }, + ], + }, + }, + ]); + assert.deepEqual(result.structured, { sla: { enabled: true, minutes: 240 }, message: "SLA saved." }); + }); + + test("switched off with a new deadline -> both fields, reported off", async () => { + const result = await call("update_sla", { enabled: false, minutes: 120 }); + assert.equal(result.isError, false, result.text); + assert.deepEqual(changesIn(writes()[0]?.body), [ + { key: "slaOptions.enabled", value: false }, + { key: "slaOptions.defaultSla", value: 7200 }, + ]); + assert.deepEqual(result.structured, { sla: { enabled: false, minutes: 120 }, message: "SLA off." }); + }); + + test("no deadline stored -> minutes null", async () => { + stored = {}; + const result = await call("update_sla", { enabled: true }); + assert.equal(result.isError, false, result.text); + assert.deepEqual(result.structured, { sla: { enabled: true, minutes: null }, message: "SLA saved." }); + }); + + test("a change the settings refuse (plan, role) -> an error with the reason, never 'saved'", async () => { + refusal = "Ticket SLAs need the Pro plan."; + const result = await call("update_sla", { minutes: 60 }); + assert.equal(result.isError, true); + assert.match(result.text, /Ticket SLAs need the Pro plan\./); + assert.doesNotMatch(result.text, /SLA saved/); + }); + + test("nothing to change -> refused before any request", async () => { + const result = await call("update_sla", {}); + assert.equal(result.isError, true); + assert.equal(sent.length, 0); + }); +}); From fa413804a86210e295f4d37fb5885e70c62222bb Mon Sep 17 00:00:00 2001 From: Tobias duelli Date: Tue, 24 Nov 2026 17:30:04 +0100 Subject: [PATCH 2/2] feat(toolbox): update_office_hours and update_sla save through the settings registry Both tools now write PUT /settings, the path update_settings takes, instead of PUT /projects: update_office_hours sends flowConfig.openingTimes, timezone and alwaysOnline as single changes; update_sla sends slaOptions.enabled and slaOptions.defaultSla instead of the whole slaOptions object it read a moment earlier, so it no longer reverts slaOptions changes made between that read and its write. The stored deadline for the result is read through GET /settings. Inputs and results are unchanged; what the registry refuses or holds for a yes is an error. Co-Authored-By: Claude Opus 5.5 --- src/tools/toolbox.tool.test.ts | 23 +++++++++++- src/tools/toolbox.tool.ts | 65 ++++++++++++++++++++++------------ 2 files changed, 65 insertions(+), 23 deletions(-) diff --git a/src/tools/toolbox.tool.test.ts b/src/tools/toolbox.tool.test.ts index f8820d2..efd4f0b 100644 --- a/src/tools/toolbox.tool.test.ts +++ b/src/tools/toolbox.tool.test.ts @@ -3,7 +3,7 @@ // inputs and results stay what AI clients know. Drives the real SDK server over an in-memory transport. import assert from "node:assert/strict"; import { beforeEach, describe, test } from "node:test"; -import axios from "axios"; +import axios, { AxiosError } from "axios"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; @@ -23,6 +23,7 @@ let sent: Sent[]; let stored: Record; let refusal: string | null; let confirmation: string | null; +let failing: { method: string; status: number } | null; const isChange = (value: unknown): value is Change => !!value && typeof value === "object" && "key" in value && typeof value.key === "string"; const changesIn = (body: unknown): Change[] => @@ -47,6 +48,7 @@ beforeEach(() => { stored = { "slaOptions.enabled": true, "slaOptions.defaultSla": 3600 }; refusal = null; confirmation = null; + failing = null; axios.defaults.adapter = async (config) => { const method = `${config.method ?? "get"}`; const url = `${config.url ?? ""}`; @@ -54,6 +56,10 @@ beforeEach(() => { const body: unknown = typeof config.data === "string" ? JSON.parse(config.data) : config.data; sent.push({ method, url, params, body }); if (url !== `${API}/settings`) throw new Error(`unexpected request ${method} ${url}`); + if (failing?.method === method) { + const response = { data: { message: "Permission denied" }, status: failing.status, statusText: "Error", headers: {}, config }; + throw new AxiosError("Request failed", "ERR_BAD_REQUEST", config, null, response); + } return { data: settingsAnswer(method, params, body), status: 200, statusText: "OK", headers: {}, config }; }; }); @@ -184,6 +190,21 @@ describe("update_sla saves single slaOptions fields through the settings registr assert.doesNotMatch(result.text, /SLA saved/); }); + test("the stored deadline cannot be read -> an error, nothing written", async () => { + failing = { method: "get", status: 403 }; + const result = await call("update_sla", { enabled: false }); + assert.equal(result.isError, true); + assert.equal(writes().length, 0); + }); + + test("the settings save fails -> the API's error, never 'saved'", async () => { + failing = { method: "put", status: 403 }; + const result = await call("update_sla", { minutes: 30 }); + assert.equal(result.isError, true); + assert.match(result.text, /403/); + assert.doesNotMatch(result.text, /SLA saved/); + }); + test("nothing to change -> refused before any request", async () => { const result = await call("update_sla", {}); assert.equal(result.isError, true); diff --git a/src/tools/toolbox.tool.ts b/src/tools/toolbox.tool.ts index 108c083..2ad292d 100644 --- a/src/tools/toolbox.tool.ts +++ b/src/tools/toolbox.tool.ts @@ -41,6 +41,35 @@ const errorOf = (result: Result) => ("error" in result ? result.error : null); const dataOf = (result: Result): any => ("data" in result ? result.data : null); const failed = (response: GleapApiResponse) => response.isError === true || (response.structuredContent as any)?.error === true; +const OFFICE_HOURS_FIELDS = ["openingTimes", "timezone", "alwaysOnline"] as const; +const SLA_DEADLINE = "slaOptions.defaultSla"; + +const isRecord = (value: unknown): value is Record => !!value && typeof value === "object" && !Array.isArray(value); +const recordsOf = (value: unknown): Record[] => (Array.isArray(value) ? value.filter(isRecord) : []); + +/** A stored value as GET /settings shows it: `{ settings: [{ values: { [key]: value } }] }`. */ +const settingValueOf = (data: unknown, key: string): unknown => + recordsOf(isRecord(data) ? data.settings : undefined) + .map((page) => (isRecord(page.values) ? page.values[key] : undefined)) + .find((value) => value !== undefined); + +/** + * Saves stored fields through the project's settings registry (PUT /settings), the path update_settings takes: + * each field checked, gated and saved as its dashboard page saves it. What did not save comes back as an error. + */ +const saveSettings = async (changes: ReadonlyArray<{ key: string; value: unknown }>): Promise => { + const response = await gleapPut("/settings", { changes }); + if (failed(response)) return response; + const answer: unknown = response.structuredContent; + const notSaved = [ + ...recordsOf(isRecord(answer) ? answer.refused : undefined).map((entry) => `${entry.change}: ${entry.reason}`), + ...recordsOf(isRecord(answer) ? answer.needsConfirmation : undefined).map((entry) => `${entry.change} waits for the person's explicit yes (${entry.why})`), + ]; + if (!notSaved.length) return null; + const message = `Not saved. ${notSaved.join("; ")}`; + return { isError: true, content: [{ type: "text", text: message }], structuredContent: { error: true, message } }; +}; + const localizedMerge = (current: unknown, next: Record | undefined) => next ? { ...(current && typeof current === "object" && !Array.isArray(current) ? (current as Record) : {}), ...next } : undefined; @@ -354,15 +383,10 @@ export const registerToolboxTools = (server: McpServer) => { } const bad = (args.openingTimes ?? []).filter((row) => row.closingTime <= row.openingTime); if (bad.length) return validationErrorResponse(`Closing time must be after opening time (${bad.map((row) => row.day).join(", ")}).`); - const flowConfig: Record = { - ...(args.openingTimes ? { openingTimes: args.openingTimes } : {}), - ...(args.timezone ? { timezone: args.timezone } : {}), - ...(args.alwaysOnline !== undefined ? { alwaysOnline: args.alwaysOnline } : {}), - }; - // PUT /projects sets flowConfig one level deep: the fields above are replaced, the rest stays. - const response = await gleapPut("/projects", { flowConfig }); - if (failed(response)) return response; - return wrapResponse({ changed: Object.keys(flowConfig), message: "Office hours saved." }); + const given = OFFICE_HOURS_FIELDS.filter((name) => args[name] !== undefined); + const notSaved = await saveSettings(given.map((name) => ({ key: `flowConfig.${name}`, value: args[name] }))); + if (notSaved) return notSaved; + return wrapResponse({ changed: given, message: "Office hours saved." }); }, ); @@ -377,21 +401,18 @@ export const registerToolboxTools = (server: McpServer) => { }, async (args): Promise => { if (args.enabled === undefined && args.minutes === undefined) return validationErrorResponse("Say what changes: enabled or minutes."); - const current = await gleapGetData("/projects/current"); - const error = errorOf(current); + // A new deadline alone switches the SLA on. + const enabled = args.enabled ?? true; + const deadline = args.minutes === undefined ? await gleapGetData("/settings", { params: { keys: SLA_DEADLINE } }) : { data: null }; + const error = errorOf(deadline); if (error) return error; - // slaOptions is stored as one object: send it whole, with only these two fields changed. - const stored: Record = { ...((dataOf(current) as any)?.slaOptions ?? {}) }; - const slaOptions = { - ...stored, - ...(args.enabled !== undefined ? { enabled: args.enabled } : args.minutes !== undefined ? { enabled: true } : {}), - ...(args.minutes !== undefined ? { defaultSla: args.minutes * 60 } : {}), - }; - const response = await gleapPut("/projects", { slaOptions }); - if (failed(response)) return response; + const seconds = args.minutes === undefined ? settingValueOf(dataOf(deadline), SLA_DEADLINE) : args.minutes * 60; + const changes = [{ key: "slaOptions.enabled", value: enabled }, ...(args.minutes === undefined ? [] : [{ key: SLA_DEADLINE, value: seconds }])]; + const notSaved = await saveSettings(changes); + if (notSaved) return notSaved; return wrapResponse({ - sla: { enabled: slaOptions.enabled === true, minutes: typeof slaOptions.defaultSla === "number" ? Math.round((slaOptions.defaultSla as number) / 60) : null }, - message: slaOptions.enabled === true ? "SLA saved." : "SLA off.", + sla: { enabled, minutes: typeof seconds === "number" ? Math.round(seconds / 60) : null }, + message: enabled ? "SLA saved." : "SLA off.", }); }, );