lkpgestao-mcp 0.23.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
8
8
  import { execFileSync } from "child_process";
9
9
  import { z } from "zod";
10
10
  var SERVER_NAME = "lkpgestao-mcp";
11
- var SERVER_VERSION = "0.23.0";
11
+ var SERVER_VERSION = "0.27.0";
12
12
  var ConfigSchema = z.object({
13
13
  LKP_API_BASE_URL: z.string().url("must be a valid URL").refine((u) => u.startsWith("https://"), {
14
14
  message: "must use https:// (TLS is mandatory)"
@@ -478,6 +478,148 @@ function extractApiError(body) {
478
478
 
479
479
  // src/tools/ping.ts
480
480
  import { z as z2 } from "zod";
481
+
482
+ // src/contract.ts
483
+ var EXPECTED_CONTRACT = "2.23";
484
+ var serverSettings = null;
485
+ function getServerSettings() {
486
+ return serverSettings;
487
+ }
488
+ function parseServerSettings(raw) {
489
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
490
+ const out = {};
491
+ for (const [k, v] of Object.entries(raw)) {
492
+ if (typeof v === "boolean") out[k] = v;
493
+ }
494
+ return out;
495
+ }
496
+ function minorOf(version) {
497
+ const [major = "", minor = ""] = version.split(".");
498
+ return { major, minor: Number(minor) };
499
+ }
500
+ function compareContract(serverContract, expected = EXPECTED_CONTRACT) {
501
+ if (serverContract === null) {
502
+ return {
503
+ status: "pre_contract",
504
+ server_contract: null,
505
+ message: `LKPGest\xE3o predates API contract ${expected} (no GET /api/v1/meta). Fields documented by this MCP build may be missing from responses.`
506
+ };
507
+ }
508
+ if (serverContract === expected) {
509
+ return {
510
+ status: "ok",
511
+ server_contract: serverContract,
512
+ message: `API contract ${serverContract} matches this build.`
513
+ };
514
+ }
515
+ const srv = minorOf(serverContract);
516
+ const exp = minorOf(expected);
517
+ if (srv.major !== exp.major) {
518
+ return {
519
+ status: "incompatible",
520
+ server_contract: serverContract,
521
+ message: `Incompatible API contract: server ${serverContract}, this build expects ${expected}. A major bump means a field was removed, renamed or retyped \u2014 tool responses may not match their docstrings.`
522
+ };
523
+ }
524
+ if (Number.isFinite(srv.minor) && Number.isFinite(exp.minor) && srv.minor < exp.minor) {
525
+ return {
526
+ status: "server_older",
527
+ server_contract: serverContract,
528
+ message: `API contract ${serverContract} is older than the ${expected} this build expects. Fields added after ${serverContract} may be absent from responses.`
529
+ };
530
+ }
531
+ return {
532
+ status: "server_newer",
533
+ server_contract: serverContract,
534
+ message: `API contract ${serverContract} is newer than the ${expected} this build expects (additive). New fields exist that this MCP does not document yet.`
535
+ };
536
+ }
537
+ var BLOCKING_STATUSES = /* @__PURE__ */ new Set([
538
+ "pre_contract",
539
+ "incompatible",
540
+ "server_older"
541
+ ]);
542
+ function isStartupBlocked(status, required) {
543
+ return required && BLOCKING_STATUSES.has(status);
544
+ }
545
+ async function enforceContractOnStartup(client, logger, required, expected = EXPECTED_CONTRACT) {
546
+ const result = await checkContractVersion(client, logger, expected);
547
+ if (isStartupBlocked(result.status, required)) {
548
+ logger.fatal(
549
+ {
550
+ expected_contract: expected,
551
+ server_contract: result.server_contract,
552
+ check: result.status,
553
+ require_contract: true
554
+ },
555
+ "refusing to start: LKP_REQUIRE_CONTRACT is on and the API contract does not satisfy this build"
556
+ );
557
+ throw new Error(
558
+ `LKP_REQUIRE_CONTRACT is on and the API contract check returned "${result.status}". ${result.message} Point LKP_API_BASE_URL at a deployment on contract ${expected}, or unset LKP_REQUIRE_CONTRACT to start anyway.`
559
+ );
560
+ }
561
+ return result;
562
+ }
563
+ async function checkContractVersion(client, logger, expected = EXPECTED_CONTRACT) {
564
+ let serverContract;
565
+ try {
566
+ const meta = await client.get("/api/v1/meta");
567
+ const settings = parseServerSettings(meta?.data?.settings);
568
+ if (settings !== null) {
569
+ serverSettings = settings;
570
+ logger.info(
571
+ { server_settings: settings },
572
+ "server_settings_loaded"
573
+ );
574
+ }
575
+ const raw = meta?.data?.contract_version;
576
+ if (typeof raw !== "string" || raw === "") {
577
+ const result2 = {
578
+ status: "unavailable",
579
+ server_contract: null,
580
+ message: `GET /api/v1/meta answered without a contract_version string.`
581
+ };
582
+ logger.warn(
583
+ { expected_contract: expected, check: result2.status },
584
+ result2.message
585
+ );
586
+ return result2;
587
+ }
588
+ serverContract = raw;
589
+ } catch (e) {
590
+ if (e instanceof LkpError && e.http_status === 404) {
591
+ serverContract = null;
592
+ } else {
593
+ const err = e instanceof LkpError ? e.toJSON() : { message: String(e) };
594
+ const result2 = {
595
+ status: "unavailable",
596
+ server_contract: null,
597
+ message: `Could not read the API contract version from GET /api/v1/meta.`
598
+ };
599
+ logger.warn(
600
+ { expected_contract: expected, check: result2.status, err },
601
+ result2.message
602
+ );
603
+ return result2;
604
+ }
605
+ }
606
+ const result = compareContract(serverContract, expected);
607
+ const fields = {
608
+ expected_contract: expected,
609
+ server_contract: result.server_contract,
610
+ check: result.status
611
+ };
612
+ if (result.status === "incompatible") {
613
+ logger.error(fields, result.message);
614
+ } else if (result.status === "ok") {
615
+ logger.info(fields, result.message);
616
+ } else {
617
+ logger.warn(fields, result.message);
618
+ }
619
+ return result;
620
+ }
621
+
622
+ // src/tools/ping.ts
481
623
  var PingUser = z2.object({
482
624
  id: z2.number().optional(),
483
625
  name: z2.string().optional(),
@@ -501,7 +643,7 @@ function registerPing(server, client, logger) {
501
643
  "lkp_ping",
502
644
  {
503
645
  title: "Ping LKPGest\xE3o",
504
- description: "Health check. Confirms the MCP server can reach LKPGest\xE3o and the configured API token is valid. Returns the bound user (name/email), the token's label, and the granted scopes. The granted scopes are at data.token.scopes (not data.scopes and not a top-level scopes) \u2014 read them to tell the user their token lacks e.g. write:helpdesk before attempting a call and taking a 403. Use this first when unsure about connectivity or permissions.",
646
+ description: "Health check. Confirms the MCP server can reach LKPGest\xE3o and the configured API token is valid. Returns the bound user (name/email), the token's label, and the granted scopes. The granted scopes are at data.token.scopes (not data.scopes and not a top-level scopes) \u2014 read them to tell the user their token lacks e.g. write:helpdesk before attempting a call and taking a 403. Use this first when unsure about connectivity or permissions. ALSO REPORTS server_settings (API contract 2.20): the global toggles that change the EFFECT of a write without changing its body, read once from GET /api/v1/meta when this MCP started. Today the only one is helpdesk_task_ticket_autosync_enabled, which gates the TASK-TO-TICKET direction of the auto-resolution \u2014 with false, completing a task does NOT move its ticket. THE REVERSE DIRECTION (a ticket PATCH moving its tasks) IS NEVER GATED and always runs, so this toggle answers only half the question. Three readings and they are NOT the same: true/false is the value the server reported at startup; a MISSING key means this server predates 2.20; and server_settings: null means the startup read has not landed yet or could not be made \u2014 null is 'I do not know', NEVER 'it is off'. It is a SNAPSHOT, not a contract: an administrator can flip the toggle while this process runs, so on anything consequential say when it was read rather than presenting it as current.",
505
647
  inputSchema: {}
506
648
  },
507
649
  async () => {
@@ -510,13 +652,17 @@ function registerPing(server, client, logger) {
510
652
  const raw = await client.get("/api/v1/ping");
511
653
  const parsed = PingResponse.safeParse(raw);
512
654
  const payload = parsed.success ? parsed.data : raw;
655
+ const withSettings = {
656
+ ...typeof payload === "object" && payload !== null ? payload : { data: payload },
657
+ server_settings: getServerSettings()
658
+ };
513
659
  logger.info(
514
660
  { tool: "lkp_ping", duration_ms: Date.now() - started, ok: true },
515
661
  "tool_ok"
516
662
  );
517
663
  return {
518
664
  content: [
519
- { type: "text", text: JSON.stringify(payload, null, 2) }
665
+ { type: "text", text: JSON.stringify(withSettings, null, 2) }
520
666
  ]
521
667
  };
522
668
  } catch (e) {
@@ -546,7 +692,10 @@ var COMMENT_DELETE_DOC = "Deleting a comment is NOT reversible through this API:
546
692
  function withServiceIdentity(body, replyAsServiceIdentity) {
547
693
  return replyAsServiceIdentity === true ? { ...body, reply_as_service_identity: true } : body;
548
694
  }
695
+ var ASK_CLIENT_OUTCOME_DOC = "TWO DIFFERENT 422 CODES DESCRIBE 'THE TICKET WILL NOT TAKE THIS QUESTION', AND SINCE API CONTRACT 2.22 EACH ONE MEANS EXACTLY ONE THING. 'ticket_closed' means THE TICKET IS OVER \u2014 Fechado (7) or Cancelado (8) \u2014 and the way out is to reopen the ticket, never to retry. 'invalid_origin' means the ticket is OPEN but there is no transition from its CURRENT status to 'Aguardando Resposta' (10), and the way out is to move the ticket first, typically to 'Em Atendimento' (3); the message names the offending status. READ THE RULE, NOT AN EXAMPLE: 'invalid_origin' is NOT 'the ticket is in Novo'. Novo is merely one status without that transition, and where the client's helpdesk config auto-assigns, a ticket never sits in Novo at all \u2014 so a caller that special-cases Novo handles a situation that may never occur and misses the ones that do. Until 2.21 a CLOSED ticket answered 'invalid_origin' on this route and 'ticket_closed' on lkp_task_reply_to_client: the same fact under two names. That is fixed \u2014 ALL THREE thread-writing routes now agree on 'ticket_closed' for a finished ticket \u2014 so if you carry a branch that treats 'invalid_origin' as 'the ticket is closed', it is now wrong and will mis-advise the user. THE 201 CARRIES blocked_task_status_id (API contract 2.22): WHICH status the task ended up in, so you do not have to re-read the task to find out. It is 6 (Bloqueado) whenever a task was in the path, and null when there was none \u2014 on the ticket-side tool that means you did not pass task_id. THE KEY IS NEVER OMITTED; null is a value, not an absence. \u{1F534} IT IS THE FINAL STATE, NOT A RECEIPT FOR AN UPDATE: it comes back filled in even when the task was ALREADY blocked and nothing was written, exactly like status_changed: false. \u{1F534} AND READ IT WITH === null, NEVER WITH ??: in JavaScript `data.blocked_task_status_id ?? 6` yields 6 for a null, which silently turns 'there was no task' into 'the task was blocked' \u2014 the inverse of what happened.";
696
+ var THREAD_BOUNDARY_DOC = "WHICH THREAD YOU WRITE TO DECIDES WHETHER THE CLIENT SEES IT, and picking the wrong tool is not a type error the server will catch \u2014 it is a note the client was never meant to read, or an answer the client never receives. Read this table before choosing: (1) lkp_task_comment_add writes to task_comments, an INTERNAL note \u2014 the client NEVER sees it, no email, no status change; it is the right tool for a note between consultants and the WRONG tool for anything addressed to the client. (2) lkp_task_reply_to_client writes to the TICKET's thread \u2014 the CLIENT READS IT in the portal AND AN EMAIL GOES TO THE CONTACT; it changes no status and blocks nothing. (3) lkp_task_ask_client also writes to the TICKET's thread and the client reads it, and ON TOP OF THAT it moves the ticket to 'Aguardando Resposta' (10), PAUSING THE SLA, and BLOCKS the originating task. (4) lkp_helpdesk_ticket_comment_add writes to the ticket thread with is_internal deciding visibility. (5) lkp_helpdesk_ticket_ask_client is the same three effects as (3), entered from the ticket instead of the task, and blocks a task only if you pass task_id. THE RULE OF THUMB: if the text is addressed to the client, never use the plain comment tool on a TASK \u2014 it is the one place where 'I replied' and 'the client can read it' come apart silently. Show the user the exact text and say which of these five doors you are about to use, before calling.";
549
697
  var FINANCIAL_TWO_DOORS_DOC = "AUTHORIZATION HAS TWO INDEPENDENT DOORS and the scope named above is only the first one. Beyond it, the TOKEN OWNER must be an administrator, a manager, or a user flagged as FINANCIAL RESPONSIBLE (is_financial_responsible) \u2014 a plain user holding the right scope is refused. Tell the two apart by error.code, never by the message: 'insufficient_scope' means the TOKEN lacks the scope (reissuing it with the scope fixes it), while 'forbidden' means the scope was fine and the OWNER'S ROLE barred the call (no token can fix that \u2014 it needs a different person, or that person given the role). Both arrive as HTTP 403, so the code is the only deterministic discriminator. The scope is checked FIRST, so a token failing both doors reports only 'insufficient_scope': after adding the scope the SAME call can come back 'forbidden'. That is not the API contradicting itself and not a reason to retry. This role door is WIDER than the one guarding lkp_alerts, which admits administrators and managers ONLY: the very same token can read this report and still be refused there.";
698
+ var WRITE_SCOPE_LITERAL_DOC = "\u{1F534} THE WRITE SCOPE IS TAKEN LITERALLY \u2014 THERE IS NO WORKING WILDCARD FOR WRITES. The backend's own scope table lists write:* and * beside the named scope on most write routes, but requireScope() strips * and any prefix:* out of the REQUIRED list before comparing, and on the TOKEN side it expands only read:*. What is left is an exact match against the named scope. So a token holding write:* or * is refused on writes with 403 insufficient_scope exactly like a token holding nothing \u2014 read:* is the only wildcard that works. That 403 is about the TOKEN, so changing the person will not help and the resource is not missing: the token must carry the named write scope spelled out. ";
550
699
  var CLIENT_TWO_DOORS_DOC = "AUTHORIZATION HAS TWO INDEPENDENT DOORS and the scope is only the first one. Beyond the scope, the TOKEN OWNER must be an administrator or a manager \u2014 a plain user holding the right scope is refused. Tell the two apart by error.code, never by the message: 'insufficient_scope' means the TOKEN lacks the scope (reissuing it with the scope fixes it), while 'forbidden' means the scope was fine and the OWNER'S ROLE barred the call (no token can fix that \u2014 it needs a different person, or that person promoted). Both arrive as HTTP 403, so the code is the only deterministic discriminator. The scope is checked FIRST, so a token failing both doors reports only 'insufficient_scope': after adding the scope the SAME call can come back 'forbidden'. That is not the API contradicting itself and not a reason to retry \u2014 it is the second door, and the fix is a person with the role, not another token.";
551
700
  async function runTool(logger, name, fn) {
552
701
  const started = Date.now();
@@ -787,7 +936,7 @@ function registerProjects(server, client, logger) {
787
936
  "lkp_projects_list",
788
937
  {
789
938
  title: "List projects",
790
- description: "List projects with filters. Returns status, client, manager, budget, progress (task completion %), source opportunity, next pending billing milestone. Use to explore the portfolio.",
939
+ description: "List projects with filters. Returns status, client, manager (projects.manager_id \u2014 WHEN NAMING THIS ROLE TO THE USER IN PORTUGUESE, CALL IT 'Gestor do Projeto': it was renamed from 'Gerente Respons\xE1vel' on 2026-08-28 and the old label is now the wrong name; the column and every payload key are unchanged, and this is the same person who holds the strict write ruler on that project's helpdesk tickets and task threads), budget, progress (task completion %), source opportunity, next pending billing milestone. Use to explore the portfolio.",
791
940
  inputSchema: {
792
941
  status_id: z6.coerce.number().int().positive().optional(),
793
942
  client_id: z6.coerce.number().int().positive().optional(),
@@ -983,7 +1132,8 @@ function registerProjects(server, client, logger) {
983
1132
  import { z as z7 } from "zod";
984
1133
  var SkillLevel = z7.enum(["J\xFAnior", "Pleno", "S\xEAnior", "Especialista"]);
985
1134
  var Priority = z7.enum(["low", "medium", "high", "urgent"]);
986
- var TASK_STATUS_REF = "Task status IDs (1-7): 1 Em Planejamento, 2 Liberado para Execu\xE7\xE3o, 3 Em Execu\xE7\xE3o, 4 Enviado para Testes, 5 Faturar, 6 Bloqueado, 7 Conclu\xEDda.";
1135
+ var TASK_STATUS_REF = "Task status IDs (1-7): 1 Em Planejamento, 2 Liberado para Execu\xE7\xE3o, 3 Em Execu\xE7\xE3o, 4 Enviado para Testes, 5 Faturar (RETIRED \u2014 readable, no longer assignable), 6 Bloqueado, 7 Conclu\xEDda.";
1136
+ var TASK_RETIRED_STATUS_DOC = "STATUS 5 (Faturar) IS RETIRED AND CAN NO LONGER BE ASSIGNED (API contract 2.18): the backend answers 422 with error.code 'status_retired' \u2014 a code of its own, NOT 'validation_failed' \u2014 and the message names the id. The rule is sovereign (Task::RETIRED_STATUSES, applied in Task::validateData), so it holds for every door, not only this one. Three things that are easy to get backwards: ONLY THE ASSIGNMENT is blocked, so a task ALREADY sitting in 5 (production has history there) stays editable in every other field, and on a PATCH re-sending status_id 5 when 5 is ALREADY the current status is accepted \u2014 the comparison is against the CURRENT value, and only lkp_task_create has no such exception. The row id = 5 STILL EXISTS in task_statuses because the history joins it to render the name, so never strip it out of a READING path (lkp_task_list accepts it as a filter, and a task can legitimately come back carrying it). And the retired list is OPEN, not 'the 5' \u2014 treat any 'status_retired' as authoritative for whatever id it names rather than special-casing this one.";
987
1137
  function registerTasks(server, client, logger) {
988
1138
  server.registerTool(
989
1139
  "lkp_task_list",
@@ -1028,7 +1178,7 @@ function registerTasks(server, client, logger) {
1028
1178
  "lkp_task_create",
1029
1179
  {
1030
1180
  title: "Create task (write)",
1031
- description: "Create a new task in a project. Required: title, start_date, due_date and estimated_hours (YYYY-MM-DD for the dates, start_date <= due_date) \u2014 the backend validator (Task::validateData) rejects the request with 422 when any of them is missing, even though older docs listed them as optional. estimated_hours: 0 is only accepted when the target status is Em Planejamento (1) or Conclu\xEDda (7); a create defaults to Em Planejamento (1) so 0 goes through here, but the same 0 is rejected once the task moves to any other status. Dates that are individually valid can still fail with 422 when they fall outside the project window or outside the subtasks' range \u2014 that check is the server's, do not try to replicate it. status_id defaults to 1 (Em Planejamento), priority defaults to 'medium'. If specialty_id is provided, skill_level is required (J\xFAnior/Pleno/S\xEAnior/Especialista). parent_task_id must belong to the same project and cannot be nested more than 1 level deep. project_b1_code_id must belong to the same client as the project. status_id >= 2 (Liberado para Execu\xE7\xE3o) TURNS assignee_id, specialty_id (which in turn requires skill_level) AND project_b1_code_id INTO REQUIRED FIELDS \u2014 creating a task already released for execution means supplying the whole task, so to create just the skeleton leave status_id at its default 1; a create with status_id: 2 carrying only the four fields listed as required above comes back 422 validation_failed naming three fields this schema presents as optional. CREATING A TASK IS AN ADMIN/MANAGER ACTION and write:tasks is only the first door: the TOKEN OWNER must be an administrator, or a MANAGER LINKED TO THIS PROJECT (a member in project_users, or its manager_id) \u2014 a plain user holding write:tasks is refused with 403 forbidden, and no token fixes that, only a different person or that person promoted. 404 not_found means the project does not exist OR IS ARCHIVED: tasks are created in ACTIVE projects only. 422 helpdesk_ticket_no_new_subtask means the parent_task_id belongs to a task whose helpdesk ticket is already resolved, closed or cancelled \u2014 the way forward is to REOPEN THE TICKET, never to retry the create or to reword it. Ask the user for the dates and the estimate if they were not given \u2014 do not invent them. Confirm the draft with the user before calling. " + TASK_STATUS_REF,
1181
+ description: TASK_RETIRED_STATUS_DOC + " Create a new task in a project. Required: title, start_date, due_date and estimated_hours (YYYY-MM-DD for the dates, start_date <= due_date) \u2014 the backend validator (Task::validateData) rejects the request with 422 when any of them is missing, even though older docs listed them as optional. estimated_hours: 0 is only accepted when the target status is Em Planejamento (1) or Conclu\xEDda (7); a create defaults to Em Planejamento (1) so 0 goes through here, but the same 0 is rejected once the task moves to any other status. Dates that are individually valid can still fail with 422 when they fall outside the project window or outside the subtasks' range \u2014 that check is the server's, do not try to replicate it. status_id defaults to 1 (Em Planejamento), priority defaults to 'medium'. If specialty_id is provided, skill_level is required (J\xFAnior/Pleno/S\xEAnior/Especialista). parent_task_id must belong to the same project and cannot be nested more than 1 level deep. project_b1_code_id must belong to the same client as the project. status_id >= 2 (Liberado para Execu\xE7\xE3o) TURNS assignee_id, specialty_id (which in turn requires skill_level) AND project_b1_code_id INTO REQUIRED FIELDS \u2014 creating a task already released for execution means supplying the whole task, so to create just the skeleton leave status_id at its default 1; a create with status_id: 2 carrying only the four fields listed as required above comes back 422 validation_failed naming three fields this schema presents as optional. CREATING A TASK IS AN ADMIN/MANAGER ACTION and write:tasks is only the first door: the TOKEN OWNER must be an administrator, or a MANAGER LINKED TO THIS PROJECT (a member in project_users, or its manager_id) \u2014 a plain user holding write:tasks is refused with 403 forbidden, and no token fixes that, only a different person or that person promoted. 404 not_found means the project does not exist OR IS ARCHIVED: tasks are created in ACTIVE projects only. 422 helpdesk_ticket_no_new_subtask means the parent_task_id belongs to a task whose helpdesk ticket is already DELIVERED OR TERMINAL \u2014 since API contract 2.18 the set is {4 Aguardando Homologa\xE7\xE3o, 6 Resolvido (legacy tickets still parked there), 7 Fechado, 8 Cancelado}, and 4 is both the newest member and the common one, because a delivery under the client's validation must not accrete new work. THE WAY FORWARD DEPENDS ON WHICH ONE IT IS, and 'reopen the ticket' is only right for the two terminals: a ticket in 4 is NOT closed, so the move is to take it BACK TO 'Em Atendimento'. Read the ticket (lkp_helpdesk_ticket_get) before advising either. Never retry the create or reword it, and branch on error.code \u2014 the 422's prose changed in 2.18 and will change again. Ask the user for the dates and the estimate if they were not given \u2014 do not invent them. Confirm the draft with the user before calling. " + TASK_STATUS_REF,
1032
1182
  inputSchema: {
1033
1183
  project_id: z7.coerce.number().int().positive(),
1034
1184
  title: z7.string().min(1),
@@ -1055,7 +1205,7 @@ function registerTasks(server, client, logger) {
1055
1205
  "lkp_task_update",
1056
1206
  {
1057
1207
  title: "Update task (write)",
1058
- description: "Update whitelisted fields on a task. project_id is immutable. Moving the task INTO status_id 7 (Conclu\xEDda) automatically records completed_at and completed_by on the server side, and moving it OUT of 7 clears them again. estimated_hours: 0 is only accepted when the target status is Em Planejamento (1) or Conclu\xEDda (7) \u2014 any other target status requires a value > 0. Setting is_active: false archives the task (equivalent to lkp_task_archive). MOVING A TICKET-LINKED TASK INTO 4, 5 OR 7 CAN CLOSE THE HELPDESK TICKET AND WRITE TO THE CLIENT. When the task resolves a helpdesk_ticket_id \u2014 its own, or one inherited from its parent \u2014 and it was the LAST pending task of that ticket, the server can move the ticket to Resolvido, publish a note VISIBLE TO THE CLIENT naming the consultants who worked on it, and fire the resolution email. The whole package sits behind a server-side setting (helpdesk_task_ticket_autosync_enabled, default OFF) that THIS API CANNOT READ, so treat it as POSSIBLE rather than certain and confirm with the user before advancing a ticket-linked task. The sync failure is swallowed on the server: the PATCH answers 200 either way and the payload carries no trace of what happened to the ticket \u2014 read the ticket with lkp_helpdesk_ticket_get when you need to know. NONE OF THIS ENDPOINT'S REFUSALS IS RETRYABLE, and there are 13 of them \u2014 read error.code, never the prose. Authorization splits across TWO DIFFERENT 403s that need opposite answers: 'forbidden' means the PERSON may not do it (a plain member may only change status_id, and only on a task assigned to them; deactivating needs an administrator or a manager), while 'invalid_status_transition' means the TRANSITION does not exist for that role from the current status \u2014 the way out of the first is another person or another tool, the way out of the second is another target status, or a manager. Body shape, all 422: 'immutable_field' (project_id was sent), 'unknown_field' (a key outside the whitelist), 'validation_failed' (empty body, bad enum, dates, or the sovereign Task::validateData, whose details name the offending fields). Ticket locks, all 422 and all with the SAME way out \u2014 act on the TICKET, not on the task: 'helpdesk_ticket_closed' (the linked ticket is closed or cancelled), 'helpdesk_ticket_resolved' (a backwards move while the ticket is resolved), 'helpdesk_ticket_no_regression' (a ticket-linked task does not regress). Process locks, 422: 'test_evidence_required' (evidence is required before Enviado para Testes or Conclu\xEDda) and 'timesheet_required' (3 -> 4 needs at least one time entry ON THE TASK, logged by anyone). Deactivation locks, 422: 'linked_to_helpdesk_ticket' and 'has_timesheets'. Do not read the two timesheet codes as the same wall: 'has_timesheets' means the task HAS entries so it cannot be deactivated, and 'timesheet_required' means it has NONE so it cannot advance. 404 not_found means the task does not exist or is out of the token owner's reach \u2014 the two are not distinguished on purpose. Confirm with the user before calling. " + TASK_STATUS_REF,
1208
+ description: TASK_RETIRED_STATUS_DOC + " Update whitelisted fields on a task. project_id is immutable. Moving the task INTO status_id 7 (Conclu\xEDda) automatically records completed_at and completed_by on the server side, and moving it OUT of 7 clears them again. estimated_hours: 0 is only accepted when the target status is Em Planejamento (1) or Conclu\xEDda (7) \u2014 any other target status requires a value > 0. Setting is_active: false archives the task (equivalent to lkp_task_archive). MOVING A TICKET-LINKED TASK CAN MOVE THE HELPDESK TICKET AND WRITE TO THE CLIENT. When the task carries a helpdesk_ticket_id \u2014 its own, or one inherited from its parent \u2014 the server consults an ADMIN-EDITABLE MATRIX (helpdesk_status_matrix, direction task_to_ticket) to decide where the ticket goes; this is configuration, not a fixed map, so DO NOT reproduce it here and do not promise a specific destination. What it is NOT any more: it is not a fixed '4, 5 or 7' trigger (5 is now a retired status this endpoint refuses outright), and the destination is NOT 'Resolvido', a status deactivated in 2.18 \u2014 in practice a completed delivery lands the ticket in 'Aguardando Homologa\xE7\xE3o' (4). What follows from the destination rather than from this call: landing the ticket in 4 or 10 EMAILS THE CLIENT, and a client-visible note naming the consultants can be published to the ticket thread. The whole package sits behind a server-side setting, helpdesk_task_ticket_autosync_enabled, AND SINCE API CONTRACT 2.20 YOU CAN READ IT \u2014 call lkp_ping and look at server_settings instead of guessing. Do not assume it is off because the backend's default is false: on the development deployment it is true. Read the asymmetry literally, because only half of it is gated: ONLY THIS DIRECTION (task \u2192 ticket) obeys the toggle. The opposite one \u2014 a ticket PATCH moving its tasks \u2014 is NEVER gated and always runs. So 'the toggle is off' means this call will not move the ticket; it never means the two are safely disconnected. Confirm with the user before advancing a ticket-linked task. The sync failure is swallowed on the server: the PATCH answers 200 either way and the payload carries no trace of what happened to the ticket \u2014 read the ticket with lkp_helpdesk_ticket_get when you need to know. NONE OF THIS ENDPOINT'S REFUSALS IS RETRYABLE \u2014 read error.code, never the prose. Authorization splits across TWO DIFFERENT 403s that need opposite answers: 'forbidden' means the PERSON may not do it (a plain member may only change status_id, and only on a task assigned to them; deactivating needs an administrator or a manager), while 'invalid_status_transition' means the TRANSITION does not exist for that role from the current status \u2014 the way out of the first is another person or another tool, the way out of the second is another target status, or a manager. Body shape, all 422: 'immutable_field' (project_id was sent), 'unknown_field' (a key outside the whitelist), 'validation_failed' (empty body, bad enum, dates, or the sovereign Task::validateData, whose details name the offending fields). Ticket locks, all 422 and all with the SAME way out \u2014 act on the TICKET, not on the task: 'helpdesk_ticket_closed' (the linked ticket is Fechado (7) or Cancelado (8) \u2014 reopen the ticket) and 'helpdesk_ticket_no_regression' (a ticket-linked task does not move backwards \u2014 reopen the ticket). THE CODE 'helpdesk_ticket_resolved' NO LONGER EXISTS: the resolved_no_regression lock left the task in 2.18 together with the 'Resolvido' status itself, so a branch still testing for it is DEAD CODE, and \u2014 worse \u2014 the live code it was meant to catch, 'helpdesk_ticket_no_regression', falls through to the default of any switch that still lists the old name first. Delete the branch rather than keeping it 'just in case'. Process locks, 422: 'test_evidence_required' (evidence is required before Enviado para Testes or Conclu\xEDda) and 'timesheet_required' (3 -> 4 needs at least one time entry ON THE TASK, logged by anyone). Deactivation locks, 422: 'linked_to_helpdesk_ticket' and 'has_timesheets'. Do not read the two timesheet codes as the same wall: 'has_timesheets' means the task HAS entries so it cannot be deactivated, and 'timesheet_required' means it has NONE so it cannot advance. 404 not_found means the task does not exist or is out of the token owner's reach \u2014 the two are not distinguished on purpose. Confirm with the user before calling. " + TASK_STATUS_REF,
1059
1209
  inputSchema: {
1060
1210
  task_id: z7.coerce.number().int().positive(),
1061
1211
  title: z7.string().optional(),
@@ -1136,7 +1286,7 @@ function registerTasks(server, client, logger) {
1136
1286
  "lkp_task_comment_add",
1137
1287
  {
1138
1288
  title: "Add task comment (write)",
1139
- description: "Adiciona um coment\xE1rio ao hist\xF3rico da tarefa (aba Coment\xE1rios), SEM alterar a descri\xE7\xE3o. The author is the token owner. body accepts HTML or plain text. Returns the created comment. " + REPLY_AS_SERVICE_IDENTITY_DOC + " On this endpoint the created comment comes back with author = the REAL author (the token owner), never the service identity, even when the flag was accepted \u2014 that is the contract, not a bug, so do not 'correct' the name. Since API contract 2.12 the created comment also carries responded_as, which is where the identity shows up: author and responded_as are the two halves of the internal 'X responded as Y' badge, and reading them as if one should overwrite the other loses the audit trail. The endpoint also still accepts the older responded_as_user_id (an explicit identity id, since contract 2.5), but this tool deliberately does NOT expose it: the boolean is the supported path, and sending both in one call is 422 validation_failed with details.reply_as_service_identity='mutually exclusive with responded_as_user_id'. PUBLISHING EMAILS THE TASK'S ASSIGNEE \u2014 not the client \u2014 WITH THE COMMENT TEXT EMBEDDED IN THE MESSAGE BODY, sent synchronously inside the request. There is no way to unsend it: deleting the comment afterwards removes it from the thread and never recalls the email. No email goes out when the author IS the assignee, and an email failure is logged without failing the call, so a 201 confirms the comment, never the delivery. An IDENTICAL comment from the SAME author on the same task WITHIN 60 SECONDS is absorbed as a duplicate: the 201 hands back THE COMMENT THAT ALREADY EXISTS, with no new row and no second email. That is what makes a retry after a timeout safe \u2014 but it also means deliberately posting the same text twice inside a minute does NOT produce two comments, so do not read the second 201 as a second publication; change the wording, or wait the window out, when two are really wanted. Confirm with the user before calling.",
1289
+ description: "Adiciona um coment\xE1rio ao hist\xF3rico da tarefa (aba Coment\xE1rios), SEM alterar a descri\xE7\xE3o. The author is the token owner. body accepts HTML or plain text. Returns the created comment. " + REPLY_AS_SERVICE_IDENTITY_DOC + " On this endpoint the created comment comes back with author = the REAL author (the token owner), never the service identity, even when the flag was accepted \u2014 that is the contract, not a bug, so do not 'correct' the name. Since API contract 2.12 the created comment also carries responded_as, which is where the identity shows up: author and responded_as are the two halves of the internal 'X responded as Y' badge, and reading them as if one should overwrite the other loses the audit trail. The endpoint also still accepts the older responded_as_user_id (an explicit identity id, since contract 2.5), but this tool deliberately does NOT expose it: the boolean is the supported path, and sending both in one call is 422 validation_failed with details.reply_as_service_identity='mutually exclusive with responded_as_user_id'. PUBLISHING EMAILS THE TASK'S ASSIGNEE \u2014 not the client \u2014 WITH THE COMMENT TEXT EMBEDDED IN THE MESSAGE BODY, sent synchronously inside the request. There is no way to unsend it: deleting the comment afterwards removes it from the thread and never recalls the email. No email goes out when the author IS the assignee, and an email failure is logged without failing the call, so a 201 confirms the comment, never the delivery. WRITING TO A TASK THREAD IS NARROWER THAN READING IT, AND NARROWER THAN IT WAS (API contract 2.19, errata of 2026-08-29). The ruler is the new sovereign point Task::userCanWriteTaskThread and it admits THREE doors only: an administrator, the projects.manager_id of the TASK'S PROJECT (the Gestor do Projeto), or the task's own assignee_id. Three doors that DO reach the task were left out on purpose: a HELPDESK AGENT (the thread is unified, and an agent's message belongs on the ticket, not here), a plain MEMBER of the project, and the opportunity's Gestor da Conta. THE REFUSAL IS 404 not_found, NOT 403 \u2014 this API collapses 'does not exist' into 'you cannot reach it' so that it never becomes an enumeration oracle, so DO NOT read a 404 here as 'wrong id' and do not go hunting for a working id: check who owns the token instead. Being able to LIST the comments (lkp_task_comments_list) proves nothing about being able to add one. " + THREAD_BOUNDARY_DOC + " THIS ENDPOINT IS INTERNAL-ONLY AND THAT IS ITS ENTIRE POINT: the comment lands in task_comments and the client never sees it, in any status. Since API contract 2.21 there ARE doors to the client from a task \u2014 lkp_task_reply_to_client and lkp_task_ask_client \u2014 so 'the API cannot talk to the client from here' is no longer true, and using THIS tool for text addressed to the client means the client simply never receives it, with a 201 that looks like success. An IDENTICAL comment from the SAME author on the same task WITHIN 60 SECONDS is absorbed as a duplicate: the 201 hands back THE COMMENT THAT ALREADY EXISTS, with no new row and no second email. That is what makes a retry after a timeout safe \u2014 but it also means deliberately posting the same text twice inside a minute does NOT produce two comments, so do not read the second 201 as a second publication; change the wording, or wait the window out, when two are really wanted. Confirm with the user before calling.",
1140
1290
  inputSchema: {
1141
1291
  task_id: z7.coerce.number().int().positive(),
1142
1292
  body: z7.string().min(1),
@@ -1152,6 +1302,46 @@ function registerTasks(server, client, logger) {
1152
1302
  )
1153
1303
  )
1154
1304
  );
1305
+ server.registerTool(
1306
+ "lkp_task_reply_to_client",
1307
+ {
1308
+ title: "Reply to the client from a task (write, client-visible)",
1309
+ description: "Publish a reply TO THE CLIENT from a task, into the thread of the helpdesk ticket the task belongs to. THE CLIENT READS THIS IN THE PORTAL AND AN EMAIL GOES OUT TO THE CONTACT \u2014 it is not a note and there is no way to unsend it. " + THREAD_BOUNDARY_DOC + " This tool changes NO status and blocks nothing: it is the safe one of the two client-facing doors on a task. Use lkp_task_ask_client instead only when you are asking the client a QUESTION and want the ticket to wait for them. body is required and must be non-empty AFTER the backend sanitizes it \u2014 HTML is sanitized server-side, so a body of only markup can arrive empty and come back 422 validation_failed with details.body even though you sent characters. Do not pre-escape it here. RETURNS { id, ticket_id, source_task_id, is_internal: false, responded_as }. id IS THE MESSAGE ID IN THE TICKET'S THREAD, not a task comment id \u2014 the two live in different tables and their sequences are unrelated, so never cross-reference them. source_task_id tells the reader which task the message came from. \u{1F534} A 201 DOES NOT PROVE THE MESSAGE IS NEW. The sovereign point holds a 60-second duplicate guard: the same text, by the same author, on the same ticket, inside that window returns THE MESSAGE THAT ALREADY EXISTS, with the SAME id and no second row and no second email. That makes a retry after a timeout safe, and it makes 'I just published' a lie in that window \u2014 compare the returned id with the previous call's when it matters. AUTHORIZATION IS THE SAME RULER AS THE INTERNAL COMMENT (Task::userCanWriteTaskThread): administrator, the project's strict manager_id (Gestor do Projeto), or the task's assignee_id. THE REFUSAL IS 404 not_found, NOT 403 \u2014 'the task does not exist' and 'you may not write in it' are collapsed on purpose so this endpoint never becomes an enumeration oracle. Do not read that 404 as a bad id and do not go looking for one that works: check whose token is in use. Other refusals, all with error.code: 422 no_source_ticket (the task is not linked to any ticket, so there is no client thread to write to \u2014 this is not retryable and not fixable from here), 422 ticket_closed (the linked ticket is Fechado (7) or Cancelado (8): reopen the TICKET, do not retry), 422 validation_failed (empty body, or both persona spellings at once), 422 publish_failed (the sovereign service refused to publish AFTER every other guard passed \u2014 it has no single cause and the message carries the domain reason, so surface that message rather than guessing; it is the safety net, not a retryable condition), 403 forbidden (you asked for the service identity without being an administrator or a helpdesk agent), 403 insufficient_scope (the token lacks write:tasks). READ THE TWO 403s AS OPPOSITE PROBLEMS: insufficient_scope means change the TOKEN, forbidden here means change the PERSON or drop the persona flag. Requires write:tasks. " + REPLY_AS_SERVICE_IDENTITY_DOC + " SHOW THE USER THE EXACT TEXT AND GET APPROVAL BEFORE CALLING \u2014 this reaches the client and sends mail.",
1310
+ inputSchema: {
1311
+ task_id: z7.coerce.number().int().positive(),
1312
+ body: z7.string().min(1),
1313
+ reply_as_service_identity: ReplyAsServiceIdentity
1314
+ }
1315
+ },
1316
+ async ({ task_id, reply_as_service_identity, ...rest }) => runTool(
1317
+ logger,
1318
+ "lkp_task_reply_to_client",
1319
+ () => client.post(
1320
+ `/api/v1/tasks/${task_id}/reply-to-client`,
1321
+ withServiceIdentity(rest, reply_as_service_identity)
1322
+ )
1323
+ )
1324
+ );
1325
+ server.registerTool(
1326
+ "lkp_task_ask_client",
1327
+ {
1328
+ title: "Ask the client a question from a task (write, THREE side effects)",
1329
+ description: "\u{1F534} ONE CALL, THREE EFFECTS, AND THE TOOL NAME ONLY SUGGESTS THE FIRST. (1) It publishes your question in the CLIENT'S thread on the helpdesk ticket and EMAILS THE CONTACT. (2) It moves the TICKET to 'Aguardando Resposta' (10), WHICH PAUSES THE SLA CLOCK. (3) It BLOCKS the originating task (status 6). Do not reach for this because it sounds like 'send a message' \u2014 if you only want to answer the client, use lkp_task_reply_to_client, which moves nothing and blocks nothing. Use THIS one when the work genuinely cannot proceed until the client answers, because that is exactly what it records. " + THREAD_BOUNDARY_DOC + " RETURNS { id, ticket_id, source_task_id, is_internal: false, status_changed, task_blocked, responded_as }. \u{1F534} status_changed: false IS SUCCESS, NOT FAILURE. It means the ticket was ALREADY in Aguardando Resposta, so the question went out exactly as asked and there was simply no transition to record. Only the first question on a waiting ticket reports true. Never surface a false there as an error and never retry because of it \u2014 retrying republishes. task_blocked is always true on this tool, because the originating task is known, and blocked_task_status_id tells you the status it landed in \u2014 you no longer need a second call to find out. AUTHORIZATION IS NOT THE RULER OF THE OTHER TWO TASK TOOLS. It lives entirely in HelpdeskTicketService::askClientFromTask and needs EITHER end: the right to write on the ticket, OR the right to write on a task in its tree. The visible consequence is that THE SAME USER can get 404 not_found from lkp_task_reply_to_client and 403 forbidden here, on the same task \u2014 different doors, different codes. Do not collapse them into one branch. " + ASK_CLIENT_OUTCOME_DOC + " Other refusals, all by error.code: 403 forbidden (neither end grants it), 422 no_source_ticket (task not linked to a ticket), 422 task_ticket_mismatch (the task is not in this ticket's tree), 422 task_not_blockable (the task cannot be blocked right now), 422 validation_failed (empty body after sanitizing, or both persona spellings), 422 publish_failed (the sovereign service refused the publication after every guard passed), 404 not_found (only for a caller who already had the reach to be told), 403 insufficient_scope (token lacks write:tasks). \u{1F534} 422 status_not_changed IS A PARTIAL FAILURE, AND IT IS THE ONE THAT TRAPS A RETRY: THE QUESTION WAS ALREADY PUBLISHED and only the status move failed. Do NOT retry it blindly \u2014 you would ask the client twice, and only the 60-second duplicate guard stands between you and a second email. Read the ticket, move it by hand if it must move, and tell the user what happened. Requires write:tasks. " + REPLY_AS_SERVICE_IDENTITY_DOC + " SHOW THE USER THE EXACT QUESTION, AND SAY THAT THE TICKET WILL WAIT ON THE CLIENT AND THE TASK WILL BE BLOCKED, BEFORE CALLING.",
1330
+ inputSchema: {
1331
+ task_id: z7.coerce.number().int().positive(),
1332
+ body: z7.string().min(1),
1333
+ reply_as_service_identity: ReplyAsServiceIdentity
1334
+ }
1335
+ },
1336
+ async ({ task_id, reply_as_service_identity, ...rest }) => runTool(
1337
+ logger,
1338
+ "lkp_task_ask_client",
1339
+ () => client.post(
1340
+ `/api/v1/tasks/${task_id}/ask-client`,
1341
+ withServiceIdentity(rest, reply_as_service_identity)
1342
+ )
1343
+ )
1344
+ );
1155
1345
  }
1156
1346
 
1157
1347
  // src/tools/opportunities.ts
@@ -1216,7 +1406,7 @@ function registerOpportunities(server, client, logger) {
1216
1406
  "lkp_opportunities_list",
1217
1407
  {
1218
1408
  title: "List sales opportunities",
1219
- description: "List sales opportunities (CRM pipeline) with filters. Returns stage, probability, expected_value, weighted_value, expected_close_date, account manager, last_activity_at. Use for pipeline review. Stage values: NEW | QUALIFYING | PROPOSAL | SENT | NEGOTIATION | WON | PARTIALLY_WON | LOST | CANCELLED. ROW-LEVEL VISIBILITY: if the token owner is not an administrator or a manager, the result contains ONLY the opportunities where they are the account manager, and an explicit account_manager_id is overridden by the backend with the token owner's own id. Nothing in the payload says so \u2014 meta.total counts that slice as if it were everything \u2014 so a short list is NOT evidence of a short pipeline, and this same call answers differently for different tokens. Establish whose token is in use before reporting a pipeline as the company's, and never conclude 'manager 5 has nothing' from a filtered call made with a plain user's token.",
1409
+ description: "List sales opportunities (CRM pipeline) with filters. Returns stage, probability, expected_value, weighted_value, expected_close_date, account manager (account_manager_id \u2014 WHEN NAMING THIS ROLE TO THE USER IN PORTUGUESE, CALL IT 'Gestor da Conta': it was renamed from 'Gerente de Contas' on 2026-08-28 and the old label is now the wrong name; the column and every payload key are unchanged), last_activity_at. Use for pipeline review. Stage values: NEW | QUALIFYING | PROPOSAL | SENT | NEGOTIATION | WON | PARTIALLY_WON | LOST | CANCELLED. ROW-LEVEL VISIBILITY: if the token owner is not an administrator or a manager, the result contains ONLY the opportunities where they are the account manager, and an explicit account_manager_id is overridden by the backend with the token owner's own id. Nothing in the payload says so \u2014 meta.total counts that slice as if it were everything \u2014 so a short list is NOT evidence of a short pipeline, and this same call answers differently for different tokens. Establish whose token is in use before reporting a pipeline as the company's, and never conclude 'manager 5 has nothing' from a filtered call made with a plain user's token.",
1220
1410
  inputSchema: {
1221
1411
  status: OpportunityStatus.optional(),
1222
1412
  account_manager_id: z8.coerce.number().int().positive().optional(),
@@ -1292,7 +1482,7 @@ function registerOpportunities(server, client, logger) {
1292
1482
  "lkp_opportunity_update",
1293
1483
  {
1294
1484
  title: "Update opportunity (write)",
1295
- description: "Update whitelisted fields on an opportunity. For status changes, business rules apply (e.g., LOST requires lost_reason). Setting is_active toggles archive/restore (true = restore, false = archive \u2014 equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored. RESPONSE SHAPE \u2014 returns a FLAT SUBSET of the opportunity (id, code, name, description, status, probability, expected_value, expected_close_date, actual_close_date, account_manager_id, lost_reason, is_active, updated_at), NOT the object lkp_opportunity_detail and lkp_opportunities_list return: there is no client, no status_label, no weighted_value, no source, no last_activity_at, no counts, and account_manager arrives as a bare id instead of {id, name}. Do not report a field as missing or emptied because it is absent here \u2014 re-read with lkp_opportunity_detail whenever the full shape matters. Requires the write:opportunities scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling.",
1485
+ description: "Update whitelisted fields on an opportunity. STATUS CHANGES ACTUALLY APPLY AGAIN, AND THEY HAVE CONSEQUENCES (fixed 2026-08-29, API contract 2.19). From 18/08 to 29/08 \u2014 in production too \u2014 a refactor left the variable that applied the change orphaned and status outside the simple-field list, so this endpoint answered 200 WITH THE OLD STATUS IN THE BODY and wrote nothing; the transition rules and the lost_reason requirement went silent with it. A caller that appeared to work against that bug now MOVES THE OPPORTUNITY FOR REAL. Never confirm a transition from the fact that the call returned 200 alone \u2014 read the status in the response body, which is now the truth. \u{1F534} status: 'WON' CREATES PROJECTS. The transition calls OpportunityConversionService::convertAcceptedQuotesWithoutProject, which converts EVERY ACCEPTED quote of the opportunity that does not already have one into a real project \u2014 this is what closes an acceptance the client made in the Portal. It is idempotent (a quote that already has a project is skipped) and best-effort per quote (one that fails to convert blocks neither the transition nor its siblings). THE RESPONSE CARRIES NO TRACE of which projects were created or which conversions failed: to find out, read the quotes (lkp_quote_detail, field converted_project_id). A project is not something this API can undo. Say the word 'project' to the user and get an explicit approval before sending WON. status is UPPERCASED before anything else, so 'won' and 'WON' are the same request \u2014 there is no lowercase safe-mode. A transition the model refuses is 422 status_transition_not_allowed. LOST REQUIRES lost_reason, in the body or already stored, and the rule runs EVEN WHEN THE STATUS IS NOT CHANGING: re-sending LOST on an opportunity that is already LOST and has no reason stored is refused with the same 422 ('lost_reason is required when status is LOST.'). The other way round, lost_reason / lost_reason_detail / lost_notes are only written TOGETHER WITH the transition \u2014 sent alone in a PATCH without status they are a SILENT NO-OP, not an error, and the 200 will look like they were saved. \u{1F534} lost_reason IS A CLOSED ENUM OF NINE VALUES, NOT FREE TEXT (API contract 2.20). Send exactly one of: PRICE_HIGH, COMPETITOR_WON, CLIENT_CANCELLED, DEADLINE_NOT_MET, SCOPE_NOT_MET, BUDGET_CUT, INTERNAL_SOLUTION, NO_RESPONSE, OTHER. Anything else \u2014 including a human sentence, and including the older screen labels PRICE, COMPETITOR, NO_BUDGET, NO_DECISION, RELATIONSHIP, REQUIREMENTS or TIMING, which never existed in the database \u2014 is 422 validation_failed with details.lost_reason listing the accepted values. THIS SCHEMA DELIBERATELY ACCEPTS ANY STRING so that the backend stays the authority on the list and its error message reaches you intact: pick the value that matches what the user said, and if none fits, use OTHER and put the human explanation in lost_reason_detail. Never invent a code and never translate the user's words into one that is not on this list. lost_reason_detail is free text and is capped at 200 CHARACTERS \u2014 counted as characters, not bytes, so 200 accented characters pass even though they weigh 400 bytes. NOTE THE CONTRAST, because this API is not uniform about it: the notes of a payment milestone are capped in BYTES. If you ever measure locally, it is s.length here and Buffer.byteLength(s, 'utf8') there. Over the cap: 422 validation_failed with details.lost_reason_detail, and NOTHING is written \u2014 not even the valid half of the body. \u{1F534} THREE DIFFERENT error.code VALUES SHARE THE 422 ON THIS ROUTE AND THEY MEAN DIFFERENT REPAIRS. Branch on the code, never on the message: 'validation_failed' WITH details.lost_reason means the motive is not in the enum (send a valid one); 'validation_failed' WITH details.lost_reason_detail means the detail is too long (shorten it); 'validation_failed' WITHOUT details, carrying 'Unknown fields: \u2026', means you sent a key this route does not accept; and 'status_transition_not_allowed' means either LOST arrived with no motive at all, or the transition itself is refused. The first three are about the BODY, the last is about the STATE. \u{1F534} LOST IS A TERMINAL STATUS AND THIS API CANNOT UNDO IT. Once an opportunity is LOST the only status it will accept is CANCELLED; every other target, including NEW, comes back 422 status_transition_not_allowed ('Esta oportunidade est\xE1 em status final e n\xE3o pode ter o status alterado.'). Marking an opportunity as lost is therefore IRREVERSIBLE through this tool \u2014 confirm with the user in those words before sending it, the same way you would before a delete. TWO DIFFERENT 403s ON THIS ROUTE AND THEY NEED OPPOSITE ANSWERS: error.code 'insufficient_scope' means the TOKEN lacks write:opportunities (another token fixes it), while error.code 'forbidden' means the token owner is neither an administrator nor a manager ('Only admins or managers can modify opportunities.') \u2014 another PERSON fixes it, another token does not. That person check runs BEFORE the visibility check, so an ordinary consultant holding the scope gets 403, never the 404 this family answers for records it will not confirm the existence of. AN UNKNOWN KEY HERE IS 422 validation_failed WITH 'Unknown fields: \u2026', NOT 422 unknown_field \u2014 this family predates the \xA77.5 convention and was never migrated to it. Do not unify the two in one branch. For other status changes, business rules apply. Setting is_active toggles archive/restore (true = restore, false = archive \u2014 equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored. RESPONSE SHAPE \u2014 returns a FLAT SUBSET of the opportunity (id, code, name, description, status, probability, expected_value, expected_close_date, actual_close_date, account_manager_id, lost_reason, is_active, updated_at), NOT the object lkp_opportunity_detail and lkp_opportunities_list return: there is no client, no status_label, no weighted_value, no source, no last_activity_at, no counts, and account_manager arrives as a bare id instead of {id, name}. Do not report a field as missing or emptied because it is absent here \u2014 re-read with lkp_opportunity_detail whenever the full shape matters. Requires the write:opportunities scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling.",
1296
1486
  inputSchema: {
1297
1487
  opportunity_id: z8.coerce.number().int().positive(),
1298
1488
  name: z8.string().optional(),
@@ -1528,6 +1718,7 @@ var QuoteItemInput = z9.object({
1528
1718
  cost_rate: z9.coerce.number().nonnegative().optional(),
1529
1719
  sort_order: z9.coerce.number().int().optional()
1530
1720
  });
1721
+ var MILESTONE_LIMITS_DOC = "SIZE LIMITS ON A PAYMENT MILESTONE, AND THE TWO ARE MEASURED IN DIFFERENT UNITS ON PURPOSE (API contract 2.19, errata of 2026-08-28): description is at most 200 CHARACTERS (counted with mb_strlen over a VARCHAR(200) \u2014 200 exactly is accepted, the limit is inclusive), and notes is at most 65535 BYTES (counted with strlen over a TEXT column). Over either one the backend answers 422 validation_failed with the offending key in error.details \u2014 'description' / 'notes' on the single-milestone routes, and the indexed path on the bulk ones ('payment_milestones.0.description' when creating a quote, 'milestones.0.description' on the replace). BEFORE THIS IT WAS AN OPAQUE 500 server_error (MySQL 1406), so any caller that treats a 500 as 'retry' used to loop here forever; that is fixed, and a 422 is final. THE BYTE COUNT IS THE TRAP: in JavaScript '\xE1'.length is 1 but the field costs 2 bytes, and an emoji costs 4, so a length-based estimate of notes is PERMISSIVE and will hand the backend a body it rejects. If you want to check locally before sending, measure notes with Buffer.byteLength(s, 'utf8'), never with .length. Neither limit is enforced by this MCP: the backend is the authority on both, and its 422 names the field.";
1531
1722
  var PaymentMilestoneInput = z9.object({
1532
1723
  description: z9.string().min(1),
1533
1724
  percentage: z9.coerce.number().positive().max(100),
@@ -1590,7 +1781,7 @@ function registerQuotes(server, client, logger) {
1590
1781
  "lkp_quote_detail",
1591
1782
  {
1592
1783
  title: "Quote detail",
1593
- description: "Full quote detail: parent fields (version, status, totals, discount, valid_until, timestamps) plus embedded items[] and payment_milestones[]. Use before any write on a quote (send, accept, update, item/milestone mutation) to verify current state and avoid stale edits. 404 HAS THREE CAUSES, not one: an id that does not exist, a quote the token owner may not see (the API never confirms existence), and \u2014 without include_inactive \u2014 an ARCHIVED quote. Before concluding an id is gone, retry with include_inactive=true: an archived quote then comes back carrying is_active=0, and the flag also includes archived items and milestones in the children.",
1784
+ description: "Full quote detail: parent fields (version, status, totals, discount, valid_until, timestamps) plus embedded items[] and payment_milestones[]. Use before any write on a quote (send, accept, update, item/milestone mutation) to verify current state and avoid stale edits. \u{1F534} converted_project_id AND converted_at ARE PROJECTED HERE SINCE API CONTRACT 2.23, and this is the ONLY way to find the project an acceptance created. Both keys are ALWAYS PRESENT AND NEVER OMITTED, and both are null while the quote has not been converted. READ THEM WITH === null, NEVER WITH ??: `quote.converted_project_id ?? 0` yields 0 for a null and turns 'not converted yet' into a project id that does not exist \u2014 the inverse of the truth. Their ABSENCE from the payload means the server predates 2.23, never 'not converted': the spec told callers to read these keys from 2.21 on while they were not projected at all, so an older server answers with neither the value nor the null. 404 HAS THREE CAUSES, not one: an id that does not exist, a quote the token owner may not see (the API never confirms existence), and \u2014 without include_inactive \u2014 an ARCHIVED quote. Before concluding an id is gone, retry with include_inactive=true: an archived quote then comes back carrying is_active=0, and the flag also includes archived items and milestones in the children.",
1594
1785
  inputSchema: {
1595
1786
  quote_id: z9.coerce.number().int().positive(),
1596
1787
  include_inactive: z9.coerce.boolean().optional()
@@ -1627,7 +1818,7 @@ function registerQuotes(server, client, logger) {
1627
1818
  "lkp_quote_create",
1628
1819
  {
1629
1820
  title: "Create quote (write)",
1630
- description: "Create a new DRAFT quote under an opportunity. billing_model is REQUIRED (milestone | installment | measurement | subscription): the backend refuses to save an unclassified quote (422 validation_failed). Each item requires specialty_id (resolve via lkp_specialties_list) and skill_level (J\xFAnior | Pleno | S\xEAnior | Especialista \u2014 required; rate card indexes both dimensions). hourly_rate is optional per item: when omitted, backend resolves via the client's active price_list for (specialty_id, skill_level); pass it explicitly to override the rate card. PER-MODEL FIELDS: subscription requires monthly_amount + contract_months and items[] must be omitted \u2014 and needs billing_cadence, recurring_start_date and subscription_due_day (1-28) to ever be ACCEPTED, so a subscription created without them reaches the client impossible to accept; measurement requires measurement_cadence ('weekly' \u2192 measurement_cutoff_weekday 1-7, 'monthly' \u2192 measurement_cutoff_day 1-28). SIDE EFFECTS: when the opportunity already has quotes, EVERY previous DRAFT of that opportunity is marked SUPERSEDED in the same transaction; and an opportunity in NEW or QUALIFYING is auto-advanced to PROPOSAL, announced in meta.opportunity_status_changed. meta also carries items_rate_from_caller / items_rate_from_price_list \u2014 the proof of which rate entered each line. Refusals to expect, all 422 (read error.code, never the prose): no_items (items[] empty outside subscription), milestones_invalid_total (payment_milestones present and not summing to 100, details.total_percentage), opportunity_stage_forbids_quote (terminal stage), and opportunity_has_pending_tasks \u2014 open CRM tasks on the opportunity block quote creation, NOTHING in the payload reveals that, and the fix is resolving the tasks, not reshaping the quote. Summarize the draft (opportunity, items, totals, milestones) and wait for explicit user approval before calling.",
1821
+ description: MILESTONE_LIMITS_DOC + " (Those limits apply to every entry of payment_milestones[] below.) Create a new DRAFT quote under an opportunity. billing_model is REQUIRED (milestone | installment | measurement | subscription): the backend refuses to save an unclassified quote (422 validation_failed). Each item requires specialty_id (resolve via lkp_specialties_list) and skill_level (J\xFAnior | Pleno | S\xEAnior | Especialista \u2014 required; rate card indexes both dimensions). hourly_rate is optional per item: when omitted, backend resolves via the client's active price_list for (specialty_id, skill_level); pass it explicitly to override the rate card. PER-MODEL FIELDS: subscription requires monthly_amount + contract_months and items[] must be omitted \u2014 and needs billing_cadence, recurring_start_date and subscription_due_day (1-28) to ever be ACCEPTED, so a subscription created without them reaches the client impossible to accept; measurement requires measurement_cadence ('weekly' \u2192 measurement_cutoff_weekday 1-7, 'monthly' \u2192 measurement_cutoff_day 1-28). SIDE EFFECTS: when the opportunity already has quotes, EVERY previous DRAFT of that opportunity is marked SUPERSEDED in the same transaction; and an opportunity in NEW or QUALIFYING is auto-advanced to PROPOSAL, announced in meta.opportunity_status_changed. meta also carries items_rate_from_caller / items_rate_from_price_list \u2014 the proof of which rate entered each line. Refusals to expect, all 422 (read error.code, never the prose): no_items (items[] empty outside subscription), milestones_invalid_total (payment_milestones present and not summing to 100, details.total_percentage), opportunity_stage_forbids_quote (terminal stage), and opportunity_has_pending_tasks \u2014 open CRM tasks on the opportunity block quote creation, NOTHING in the payload reveals that, and the fix is resolving the tasks, not reshaping the quote. Summarize the draft (opportunity, items, totals, milestones) and wait for explicit user approval before calling.",
1631
1822
  inputSchema: {
1632
1823
  opportunity_id: z9.coerce.number().int().positive(),
1633
1824
  ...QuoteHeaderFields,
@@ -1698,7 +1889,7 @@ function registerQuotes(server, client, logger) {
1698
1889
  "lkp_quote_accept",
1699
1890
  {
1700
1891
  title: "Accept quote (write)",
1701
- description: "Transition a SENT quote to ACCEPTED (only SENT \u2014 anything else answers 422 invalid_transition; send first if DRAFT). THIS CALL MATERIALIZES THE DEAL, in one transaction: the quote is CONVERTED INTO A PROJECT \u2014 items become project tasks, contacts and team are carried over, the payment milestones become project billing milestones, measurement/subscription config is created, and converted_project_id is stamped on the quote and the opportunity \u2014 and FINANCE IS EMAILED right after the response. The parent opportunity moves to PARTIALLY_WON, not WON: closing it as WON stays a manual user decision. The cascade hits ONLY sibling quotes in SENT status, which become REJECTED ('Outra vers\xE3o foi aceita'); sibling DRAFTs are left untouched. Commercially binding and the most expensive side effect in this API \u2014 ALWAYS ask for explicit, unambiguous approval referencing the quote code (e.g. 'sim, aceitar QT-2026-0007'). Never accept on inference or implicit cues.",
1892
+ description: "Transition a SENT quote to ACCEPTED (only SENT \u2014 anything else answers 422 invalid_transition; send first if DRAFT). THIS CALL MATERIALIZES THE DEAL, in one transaction: the quote is CONVERTED INTO A PROJECT \u2014 items become project tasks, contacts and team are carried over, the payment milestones become project billing milestones, measurement/subscription config is created, and converted_project_id is stamped on the quote and the opportunity \u2014 and FINANCE IS EMAILED right after the response. The parent opportunity moves to PARTIALLY_WON, not WON: closing it as WON stays a manual user decision. The cascade hits ONLY sibling quotes in SENT status, which become REJECTED ('Outra vers\xE3o foi aceita'); sibling DRAFTs are left untouched. \u{1F534} THIS ENDPOINT ONLY STARTED WORKING IN API CONTRACT 2.23 (fixed 2026-08-29). From 2.9 to 2.22 it refused EVERY SENT quote with 422 validation_failed / 'o modelo de faturamento precisa estar definido', because the sovereign pre-validation was fed a narrow projection in which billing_model was always empty \u2014 while GET /quotes/{id}, at the same instant, showed billing_model: 'milestone'. If you carry any memory that accepting through this API is impossible, or any workaround built around that, DROP IT: the refusal was never about the quote. THE 422 YOU GET NOW IS REAL, and it is a readiness check, not a field-format check. Before transitioning, the backend runs Quote::validateForAcceptance \u2014 the SAME sovereign point the SPA and the Client Portal use \u2014 which requires: billing_model present and valid; the fields of the chosen model (subscription \u2192 monthly_amount, contract_months, billing_cadence, recurring_start_date, subscription_due_day; measurement \u2192 cadence plus cut-off day/weekday; installment \u2192 installment_count from 1 to 60); AT LEAST ONE payment milestone for milestone and installment; and AT LEAST ONE active item for every model except subscription. It fails as 422 validation_failed with THE WHOLE LIST in details.errors \u2014 read that array and tell the user what is missing, rather than reporting 'the quote was refused'. It is not retryable: fix the quote (lkp_quote_update, lkp_quote_item_add, lkp_quote_milestone_add) and call again. Do not confuse it with 422 invalid_transition, which is about the STATUS, not the content. TO FIND THE PROJECT THIS CREATED, re-read with lkp_quote_detail: converted_project_id and converted_at are projected there since 2.23. Requires write:quotes. Commercially binding and the most expensive side effect in this API \u2014 ALWAYS ask for explicit, unambiguous approval referencing the quote code (e.g. 'sim, aceitar QT-2026-0007'). Never accept on inference or implicit cues.",
1702
1893
  inputSchema: {
1703
1894
  quote_id: z9.coerce.number().int().positive()
1704
1895
  }
@@ -1744,7 +1935,7 @@ function registerQuotes(server, client, logger) {
1744
1935
  "lkp_quote_duplicate",
1745
1936
  {
1746
1937
  title: "Duplicate quote to another opportunity (write)",
1747
- description: "Copy a quote (including items) to a DIFFERENT opportunity as a new DRAFT (version 1). Milestones are NOT copied. The 201 carries meta.source_quote_id as the trace back to the origin. REFUSALS ABOUT THE TARGET (read error.code, never the prose): 422 validation_failed when target_opportunity_id is missing or not a positive integer; 404 not_found \u2014 which covers the source quote AND a target opportunity the token owner has no visibility of, because the API never confirms the existence of what the caller may not see; 422 target_opportunity_invalid when the target does not exist, is archived, or sits in a terminal stage (details.target_status); and 422 target_opportunity_no_b1 when the target has no project_b1_code_id. Confirm the target opportunity with the user before calling.",
1938
+ description: "Copy a quote (including items) to a DIFFERENT opportunity as a new DRAFT. Milestones are NOT copied. The 201 carries meta.source_quote_id as the trace back to the origin. \u{1F534} THE COPY IS BORN version = 1, AND THAT IS DELIBERATE, NOT A BUG (clarified in API contract 2.23, finding D-R10-1). Duplicating points at ANOTHER opportunity, where the copy opens a NEW LINEAGE \u2014 so numbering restarts. Do not report the version as lost and do not try to 'correct' it. If what you actually want is a new version on the SAME opportunity, this is the wrong tool: use lkp_quote_new_version, which is the versioning route. REFUSALS ABOUT THE TARGET (read error.code, never the prose): 422 validation_failed when target_opportunity_id is missing or not a positive integer; 404 not_found \u2014 which covers the source quote AND a target opportunity the token owner has no visibility of, because the API never confirms the existence of what the caller may not see; 422 target_opportunity_invalid when the target does not exist, is archived, or sits in a terminal stage (details.target_status); 422 target_opportunity_no_b1 when the target has no project_b1_code_id; and 422 target_opportunity_same (API contract 2.23) when target_opportunity_id is the SOURCE QUOTE'S OWN opportunity, carrying details.target_opportunity_id. THAT GUARD RUNS FIRST, BEFORE THE STAGE CHECK \u2014 pointing at your own opportunity answers target_opportunity_same even when that opportunity is also in a terminal stage that would otherwise be target_opportunity_invalid, so the code you get names the closer problem, not every problem. Until 2.22 that last one was not guarded and collided on the uk_opportunity_version index, coming back as a 500 with a raw SQLSTATE 23000 in development and an opaque 500 in production \u2014 so a 500 from this route on an older server is very likely this, and the repair is to pick a different target or switch to lkp_quote_new_version, never to retry. Confirm the target opportunity with the user before calling.",
1748
1939
  inputSchema: {
1749
1940
  quote_id: z9.coerce.number().int().positive(),
1750
1941
  target_opportunity_id: z9.coerce.number().int().positive()
@@ -1828,7 +2019,7 @@ function registerQuotes(server, client, logger) {
1828
2019
  "lkp_quote_milestones_replace",
1829
2020
  {
1830
2021
  title: "Replace all payment milestones (write)",
1831
- description: "Replace the entire payment_milestones[] collection on a quote in DRAFT, SENT or EXPIRED status, atomically. due_days and due_date are mutually exclusive per milestone. percentages must sum to 100 (\xB10.01), or the call answers 422 milestones_invalid_total with details.total_percentage; amount is computed server-side \u2014 do not send it. milestones: [] is ALLOWED and clears the whole schedule \u2014 it is the only atomic way to zero it, and it is destructive, so require explicit user confirmation before sending an empty array. ORDER IS THE ARRAY ORDER: the backend renumbers sort_order 0..n-1 exactly as sent, which is why the milestones here carry no sort_order field \u2014 the endpoint discards that value in silence (the single-milestone add/update tools are where sort_order is honored). " + QUOTE_EDITABLE_GATE_DOC + " Summarize the new schedule and wait for user approval.",
2022
+ description: "Replace the entire payment_milestones[] collection on a quote in DRAFT, SENT or EXPIRED status, atomically. due_days and due_date are mutually exclusive per milestone. percentages must sum to 100 (\xB10.01), or the call answers 422 milestones_invalid_total with details.total_percentage; amount is computed server-side \u2014 do not send it. milestones: [] is ALLOWED and clears the whole schedule \u2014 it is the only atomic way to zero it, and it is destructive, so require explicit user confirmation before sending an empty array. ORDER IS THE ARRAY ORDER: the backend renumbers sort_order 0..n-1 exactly as sent, which is why the milestones here carry no sort_order field \u2014 the endpoint discards that value in silence (the single-milestone add/update tools are where sort_order is honored). " + QUOTE_EDITABLE_GATE_DOC + " " + MILESTONE_LIMITS_DOC + " Summarize the new schedule and wait for user approval.",
1832
2023
  inputSchema: {
1833
2024
  quote_id: z9.coerce.number().int().positive(),
1834
2025
  milestones: z9.array(PaymentMilestoneInput)
@@ -1847,7 +2038,7 @@ function registerQuotes(server, client, logger) {
1847
2038
  "lkp_quote_milestone_add",
1848
2039
  {
1849
2040
  title: "Add payment milestone (write)",
1850
- description: "Append a single payment milestone to a quote in DRAFT, SENT or EXPIRED status (additive; does not enforce sum=100 \u2014 use replace for atomic rewrite). due_days and due_date are mutually exclusive. " + QUOTE_EDITABLE_GATE_DOC + " Summarize (description, percentage, due) and wait for user approval.",
2041
+ description: "Append a single payment milestone to a quote in DRAFT, SENT or EXPIRED status (additive; does not enforce sum=100 \u2014 use replace for atomic rewrite). due_days and due_date are mutually exclusive. " + QUOTE_EDITABLE_GATE_DOC + " " + MILESTONE_LIMITS_DOC + " Summarize (description, percentage, due) and wait for user approval.",
1851
2042
  inputSchema: {
1852
2043
  quote_id: z9.coerce.number().int().positive(),
1853
2044
  description: z9.string().min(1),
@@ -1871,7 +2062,7 @@ function registerQuotes(server, client, logger) {
1871
2062
  "lkp_quote_milestone_update",
1872
2063
  {
1873
2064
  title: "Update payment milestone (write)",
1874
- description: "Update whitelisted fields on a payment milestone of a quote in DRAFT, SENT or EXPIRED status. due_days and due_date are mutually exclusive. Does NOT enforce sum=100 \u2014 caller is responsible. " + QUOTE_EDITABLE_GATE_DOC + " Summarize the diff and wait for user approval.",
2065
+ description: "Update whitelisted fields on a payment milestone of a quote in DRAFT, SENT or EXPIRED status. due_days and due_date are mutually exclusive. Does NOT enforce sum=100 \u2014 caller is responsible. " + QUOTE_EDITABLE_GATE_DOC + " " + MILESTONE_LIMITS_DOC + " Summarize the diff and wait for user approval.",
1875
2066
  inputSchema: {
1876
2067
  quote_id: z9.coerce.number().int().positive(),
1877
2068
  milestone_id: z9.coerce.number().int().positive(),
@@ -1931,12 +2122,13 @@ function requireAbsolute(p, field) {
1931
2122
  }
1932
2123
  return resolve(p);
1933
2124
  }
2125
+ var VISIBLE_TO_CLIENT_DOC = "is_visible_to_client (API contract 2.19) IS THE ONLY GATE BETWEEN AN ATTACHMENT AND THE CLIENT, and turning it on is a PUBLICATION, not a metadata edit. Until 2.19 a proposal attachment never reached the client in any status (RN-QT-A-009); now the commercial team marks, one attachment at a time, what the client can download from the quote inside the Client Portal \u2014 through a route of its own outside /api/v1, which is the ONLY door that serves a proposal attachment to a client and which refuses any attachment whose flag is false. Setting it to true PUBLISHES THE FILE IMMEDIATELY; setting it back to false REVOKES ACCESS IMMEDIATELY. The default is deny and it did not change: an attachment is born internal, and every attachment that existed before 2.19 is false. SHOW THE USER THE FILENAME AND ASK BEFORE TURNING THIS ON \u2014 a model that treats it as 'just a boolean' publishes an internal document to a client without either of them noticing.";
1934
2126
  function registerQuoteAttachments(server, client, logger) {
1935
2127
  server.registerTool(
1936
2128
  "lkp_quote_attachments_list",
1937
2129
  {
1938
2130
  title: "List quote attachments",
1939
- description: "List the attachments of a proposal (quote). Each item is { id, quote_id, filename, file_size (bytes), mime_type, description, uploaded_by (a user id), uploader_name, created_at, updated_at }. meta carries total, total_size (the sum of file_size, in bytes) and max_file_size \u2014 READ THE CEILING FROM HERE rather than assuming a number, because it is the backend's constant and this is where it is published. " + PERMISSIONS_DOC + " Attachments are INTERNAL: they are never sent to the client automatically, not even when the quote moves to SENT (RN-QT-A-009), so their presence says nothing about what the client has received. A new version of a quote does NOT inherit them (RN-QT-A-008) \u2014 each version owns its own set, so an empty list on version 3 does not mean the attachments of version 2 are gone. Requires read:quotes or read:*. " + ARCHIVED_QUOTE_DOC,
2131
+ description: "List the attachments of a proposal (quote). Each item is { id, quote_id, filename, file_size (bytes), mime_type, description, is_visible_to_client (boolean), uploaded_by (a user id), uploader_name, created_at, updated_at }. THE KEY is_visible_to_client IS ALWAYS PRESENT AND NEVER OMITTED \u2014 false on everything that predates API contract 2.19 \u2014 so its absence means the server is older than this contract, never 'this attachment is internal'. meta carries total, total_size (the sum of file_size, in bytes) and max_file_size \u2014 READ THE CEILING FROM HERE rather than assuming a number, because it is the backend's constant and this is where it is published. " + PERMISSIONS_DOC + " NOTHING IS EVER PUSHED TO THE CLIENT AUTOMATICALLY, not even when the quote moves to SENT (RN-QT-A-009), so the presence of an attachment still says nothing about what the client received. But since API contract 2.19 'internal' is no longer a property of the family \u2014 it is a property of each row: read is_visible_to_client per item, and never tell the user 'attachments are internal' without looking. " + VISIBLE_TO_CLIENT_DOC + " A new version of a quote does NOT inherit them (RN-QT-A-008) \u2014 each version owns its own set, so an empty list on version 3 does not mean the attachments of version 2 are gone. Requires read:quotes or read:*. " + ARCHIVED_QUOTE_DOC,
1940
2132
  inputSchema: {
1941
2133
  quote_id: z10.coerce.number().int().positive()
1942
2134
  }
@@ -1951,13 +2143,18 @@ function registerQuoteAttachments(server, client, logger) {
1951
2143
  "lkp_quote_attachment_upload",
1952
2144
  {
1953
2145
  title: "Upload quote attachment (write)",
1954
- description: "Attach a LOCAL FILE to a proposal. file_path is an absolute path on the machine running this MCP server, which the server reads and sends as multipart/form-data \u2014 this is the only endpoint of the API that is not JSON. You cannot pass file contents inline; if the file is not on this machine, it has to get here first. THE BACKEND ENFORCES A TYPE ALLOWLIST, whatever you may have read elsewhere, and IT is the authority \u2014 not this text. It checks the extension AND the real content type (sniffed from the bytes, not from the name), and refuses with 422 invalid_file_type. Renaming a file to a permitted extension does not get it through, because the sniff reads the content. Nothing is checked here before the call, so DO NOT refuse a file on your own: send it and read the answer. As last observed the permitted extensions were " + ALLOWED_EXTENSIONS_DOC + ` \u2014 treat that as a hint for choosing a format, never as a reason to skip an upload the user asked for, since the list can change on the server without this text moving (zip, listed above, was added in 2.16 and this text is the second version of it). WHEN invalid_file_type COMES BACK, REPORT IT AND STOP. Do NOT repackage the refused file into a zip to get it through. That would now SUCCEED \u2014 zip is on the list and the backend does not inspect an archive's contents \u2014 and succeeding is exactly the problem: the allowlist exists to keep executable content (.svg, .html, .php) from being served under the web root, so zipping a refused file defeats a security control rather than solving the user's problem. If the user asks for the zip explicitly, that is their call to make and theirs to state; it is never a workaround you choose on your own. filename is optional and defaults to the basename of file_path \u2014 but WHATEVER YOU PASS THERE DECIDES THE EXTENSION HALF OF THE ALLOWLIST, because the backend reads the extension from THE NAME SENT and never from the local file. So a rename must keep an extension from the list: filename: "Proposta assinada" (no extension) or "Proposta.rar" makes a perfectly valid PDF come back 422 invalid_file_type. Use it to replace a meaningless temp name, and carry the original extension over when you do. Size: the ceiling is the max_file_size published by lkp_quote_attachments_list. Over it, 413 file_too_large \u2014 which the backend also returns when the PHP upload limit is the lower of the two, so a 413 is not proof the file exceeded max_file_size specifically. 400 upload_failed means no file arrived at all. ` + STATUS_FREEZE_DOC + " " + PERMISSIONS_DOC + " description is optional and travels with the file in the same request. Returns the created attachment (201) in the same shape lkp_quote_attachments_list returns. Confirm the file and the target quote with the user before calling. " + ARCHIVED_QUOTE_DOC,
2146
+ description: "Attach a LOCAL FILE to a proposal. file_path is an absolute path on the machine running this MCP server, which the server reads and sends as multipart/form-data \u2014 this is the only endpoint of the API that is not JSON. You cannot pass file contents inline; if the file is not on this machine, it has to get here first. THE BACKEND ENFORCES A TYPE ALLOWLIST, whatever you may have read elsewhere, and IT is the authority \u2014 not this text. It checks the extension AND the real content type (sniffed from the bytes, not from the name), and refuses with 422 invalid_file_type. Renaming a file to a permitted extension does not get it through, because the sniff reads the content. Nothing is checked here before the call, so DO NOT refuse a file on your own: send it and read the answer. As last observed the permitted extensions were " + ALLOWED_EXTENSIONS_DOC + ` \u2014 treat that as a hint for choosing a format, never as a reason to skip an upload the user asked for, since the list can change on the server without this text moving (zip, listed above, was added in 2.16 and this text is the second version of it). WHEN invalid_file_type COMES BACK, REPORT IT AND STOP. Do NOT repackage the refused file into a zip to get it through. That would now SUCCEED \u2014 zip is on the list and the backend does not inspect an archive's contents \u2014 and succeeding is exactly the problem: the allowlist exists to keep executable content (.svg, .html, .php) from being served under the web root, so zipping a refused file defeats a security control rather than solving the user's problem. If the user asks for the zip explicitly, that is their call to make and theirs to state; it is never a workaround you choose on your own. filename is optional and defaults to the basename of file_path \u2014 but WHATEVER YOU PASS THERE DECIDES THE EXTENSION HALF OF THE ALLOWLIST, because the backend reads the extension from THE NAME SENT and never from the local file. So a rename must keep an extension from the list: filename: "Proposta assinada" (no extension) or "Proposta.rar" makes a perfectly valid PDF come back 422 invalid_file_type. Use it to replace a meaningless temp name, and carry the original extension over when you do. Size: the ceiling is the max_file_size published by lkp_quote_attachments_list. Over it, 413 file_too_large \u2014 which the backend also returns when the PHP upload limit is the lower of the two, so a 413 is not proof the file exceeded max_file_size specifically. 400 upload_failed means no file arrived at all. ` + STATUS_FREEZE_DOC + " " + PERMISSIONS_DOC + " description is optional and travels with the file in the same request. " + VISIBLE_TO_CLIENT_DOC + " ON THIS ENDPOINT THE FLAG IS FORM DATA, NOT JSON, so there is no boolean to send: the backend accepts the affirmative strings 1, true, on and yes, and EVERYTHING ELSE \u2014 including 0, false, no and omitting the field entirely \u2014 means internal. That is a real asymmetry with the PATCH, where a STRING is an error; here a string is the only thing there is. This tool takes a real boolean and converts it: pass is_visible_to_client: true only when the user has said the client should download this file. Omit it and the attachment is born internal, exactly as in 2.18. Returns the created attachment (201) in the same shape lkp_quote_attachments_list returns. Confirm the file and the target quote with the user before calling. " + ARCHIVED_QUOTE_DOC,
1955
2147
  inputSchema: {
1956
2148
  quote_id: z10.coerce.number().int().positive(),
1957
2149
  file_path: z10.string().min(1),
1958
2150
  // Optional and sent as a form field alongside the file. The backend
1959
2151
  // normalizes "" to null, so an empty string is not an error here.
1960
2152
  description: z10.string().optional(),
2153
+ // Strict boolean on purpose, and NOT z.coerce.boolean(): coercion turns
2154
+ // the string "false" into true, and here that would publish an internal
2155
+ // document to the client. Absent means internal — the backend's own
2156
+ // default-deny — so there is nothing to default here.
2157
+ is_visible_to_client: z10.boolean().optional(),
1961
2158
  // The name the attachment is stored under. Defaults to the basename of
1962
2159
  // file_path, which is what a user means by "upload this file" — it is
1963
2160
  // exposed because the local name is sometimes a temp name that would be
@@ -1965,7 +2162,7 @@ function registerQuoteAttachments(server, client, logger) {
1965
2162
  filename: z10.string().min(1).optional()
1966
2163
  }
1967
2164
  },
1968
- async ({ quote_id, file_path, description, filename }) => runTool(logger, "lkp_quote_attachment_upload", async () => {
2165
+ async ({ quote_id, file_path, description, filename, is_visible_to_client }) => runTool(logger, "lkp_quote_attachment_upload", async () => {
1969
2166
  const abs = requireAbsolute(file_path, "file_path");
1970
2167
  let bytes;
1971
2168
  try {
@@ -1981,6 +2178,7 @@ function registerQuoteAttachments(server, client, logger) {
1981
2178
  const form = new FormData();
1982
2179
  form.append("file", new Blob([bytes]), name);
1983
2180
  if (description !== void 0) form.append("description", description);
2181
+ if (is_visible_to_client === true) form.append("is_visible_to_client", "1");
1984
2182
  return client.postMultipart(
1985
2183
  `/api/v1/quotes/${quote_id}/attachments`,
1986
2184
  form
@@ -2049,25 +2247,45 @@ function registerQuoteAttachments(server, client, logger) {
2049
2247
  server.registerTool(
2050
2248
  "lkp_quote_attachment_update",
2051
2249
  {
2052
- title: "Update quote attachment description (write)",
2053
- description: "Change the description of an attachment. THE DESCRIPTION IS THE ONLY MUTABLE FIELD \u2014 the filename, the file itself and its type cannot be changed here; replacing a file means uploading a new attachment and deleting the old one. Pass description: null to clear it, and note that an empty or whitespace-only string is stored as null too. The field is REQUIRED in the call: omitting it is 400 invalid_body, not a no-op, and a non-string non-null value is also 400 invalid_body. THIS ROUTE NOW REJECTS UNKNOWN KEYS, like the client endpoints do (API contract 2.16): any key other than description is 422 unknown_field, naming the offenders. Until 2.15 they were ignored in silence and a misspelled 'descriptionn' came back as 400 invalid_body ('description is required') \u2014 the right message for the wrong error. This tool sends exactly { description } and nothing else, so it cannot trip that itself; the warning is for the shape of the call, NEVER build an update by echoing back an attachment object read from lkp_quote_attachments_list, because id, quote_id, filename, file_size, mime_type, uploaded_by, uploader_name, created_at and updated_at would all be rejected together. " + STATUS_FREEZE_DOC + " " + PERMISSIONS_DOC + " Both ids are required and validated as a pair: an attachment of another quote is 404 not_found. Returns the updated attachment. Requires write:quotes. " + ARCHIVED_QUOTE_DOC,
2250
+ title: "Update quote attachment metadata (write)",
2251
+ description: "Change what is mutable on an attachment: its description and, since API contract 2.19, its VISIBILITY TO THE CLIENT. The filename, the file itself and its type still cannot be changed here \u2014 replacing a file means uploading a new attachment and deleting the old one. " + VISIBLE_TO_CLIENT_DOC + ` BOTH KEYS ARE OPTIONAL AND AT LEAST ONE IS REQUIRED (this changed in 2.19: description used to be mandatory). An empty body is 400 invalid_body, and the message names BOTH keys now \u2014 it used to read 'description field is required.', so anything matching on that old text is broken. This tool refuses an empty call locally, with the same meaning, rather than spending a round trip to be told the obvious. description: pass null to clear it; an empty or whitespace-only string is stored as null too. is_visible_to_client MUST BE A REAL JSON BOOLEAN \u2014 the string "true" is 400 invalid_body ('is_visible_to_client must be a boolean.'), which is the opposite of the multipart upload, where form data has no booleans and affirmative strings are the only way to say it. This tool takes a strict boolean and never coerces, so a stray "false" cannot become true on the way out. VALIDATION IS TOTAL BEFORE ANYTHING IS WRITTEN: a body carrying a good description and a bad flag writes NEITHER. Do not read a 400 here as 'it saved half' and do not re-send only the remaining field to 'finish' it \u2014 re-send the whole intended change. THIS ROUTE REJECTS UNKNOWN KEYS, like the client endpoints do (API contract 2.16): any key other than description and is_visible_to_client is 422 unknown_field, naming the offenders. Until 2.15 they were ignored in silence and a misspelled 'descriptionn' came back as 400 invalid_body ('description is required') \u2014 the right message for the wrong error. This tool sends only the keys you actually passed, so it cannot trip that itself; the warning is for the shape of the call, NEVER build an update by echoing back an attachment object read from lkp_quote_attachments_list, because id, quote_id, filename, file_size, mime_type, uploaded_by, uploader_name, created_at and updated_at would all be rejected together \u2014 nine keys, and note that is_visible_to_client is NOT among them any more: it is now accepted, so echoing the object trips on the other nine and nothing tells you the tenth was fine. ` + STATUS_FREEZE_DOC + " " + PERMISSIONS_DOC + " Both ids are required and validated as a pair: an attachment of another quote is 404 not_found. Returns the updated attachment. Requires write:quotes. " + ARCHIVED_QUOTE_DOC,
2054
2252
  inputSchema: {
2055
2253
  quote_id: z10.coerce.number().int().positive(),
2056
2254
  attachment_id: z10.coerce.number().int().positive(),
2057
- // Nullable and NOT optional: null is the documented way to clear the
2058
- // description, and absence is a 400 on the backend — so making it
2059
- // optional here would only move a guaranteed error one round trip later.
2060
- description: z10.string().nullable()
2255
+ // Optional since API contract 2.19, and still nullable: null is the
2256
+ // documented way to CLEAR the description, which is a different act
2257
+ // from not touching it. Both meanings have to survive, so absence and
2258
+ // null cannot be collapsed — hence the guard in the handler instead of
2259
+ // a default.
2260
+ description: z10.string().nullable().optional(),
2261
+ // Strict boolean, never z.coerce.boolean(): coercion turns the string
2262
+ // "false" into true, and the backend itself rejects a string here with
2263
+ // 400. Coercing would take a body the server would have refused and
2264
+ // turn it into a silent publication.
2265
+ is_visible_to_client: z10.boolean().optional()
2266
+ }
2267
+ },
2268
+ async ({ quote_id, attachment_id, description, is_visible_to_client }) => runTool(logger, "lkp_quote_attachment_update", () => {
2269
+ if (description === void 0 && is_visible_to_client === void 0) {
2270
+ throw new LkpError({
2271
+ code: "validation_error",
2272
+ message: "At least one of description, is_visible_to_client is required.",
2273
+ api_code: "invalid_body",
2274
+ details: {
2275
+ description: "Pass a string, or null to clear it.",
2276
+ is_visible_to_client: "Pass a real boolean \u2014 true publishes the file to the client."
2277
+ }
2278
+ });
2061
2279
  }
2062
- },
2063
- async ({ quote_id, attachment_id, description }) => runTool(
2064
- logger,
2065
- "lkp_quote_attachment_update",
2066
- () => client.patch(
2280
+ const body = {};
2281
+ if (description !== void 0) body.description = description;
2282
+ if (is_visible_to_client !== void 0)
2283
+ body.is_visible_to_client = is_visible_to_client;
2284
+ return client.patch(
2067
2285
  `/api/v1/quotes/${quote_id}/attachments/${attachment_id}`,
2068
- { description }
2069
- )
2070
- )
2286
+ body
2287
+ );
2288
+ })
2071
2289
  );
2072
2290
  server.registerTool(
2073
2291
  "lkp_quote_attachment_delete",
@@ -2095,7 +2313,7 @@ function registerClients(server, client, logger) {
2095
2313
  "lkp_clients_list",
2096
2314
  {
2097
2315
  title: "List clients",
2098
- description: "List clients (hierarchical). Returns active project count, B1 codes count, account manager, price list. Use to find clients by name/doc or explore the portfolio. WITHOUT status THIS LISTS ACTIVE CLIENTS ONLY \u2014 the backend applies status = 1 whenever the filter is absent or empty, so never report a page of this as 'every client of the portfolio' unless you also asked for status: 'inactive'. status is the STRING 'active' | 'inactive' (the backend still tolerates '0' and '1' for backwards compatibility; they are not offered here because they mean the same two things), and any other value is 400 invalid_filter \u2014 not an empty list. parent_client_id narrows the list to the children of that client; the LITERAL STRING 'null' asks instead for the TOP-LEVEL clients, the ones with no parent of their own. Requires the read:clients scope (or read:*). " + CLIENT_TWO_DOORS_DOC,
2316
+ description: "List clients (hierarchical). Returns active project count, B1 codes count, account manager (account_manager_id \u2014 in Portuguese this role is 'Gestor da Conta', renamed from 'Gerente de Contas' on 2026-08-28; the payload keys did not change), price list. Use to find clients by name/doc or explore the portfolio. WITHOUT status THIS LISTS ACTIVE CLIENTS ONLY \u2014 the backend applies status = 1 whenever the filter is absent or empty, so never report a page of this as 'every client of the portfolio' unless you also asked for status: 'inactive'. status is the STRING 'active' | 'inactive' (the backend still tolerates '0' and '1' for backwards compatibility; they are not offered here because they mean the same two things), and any other value is 400 invalid_filter \u2014 not an empty list. parent_client_id narrows the list to the children of that client; the LITERAL STRING 'null' asks instead for the TOP-LEVEL clients, the ones with no parent of their own. Requires the read:clients scope (or read:*). " + CLIENT_TWO_DOORS_DOC,
2099
2317
  inputSchema: {
2100
2318
  status: z11.enum(["active", "inactive"]).optional(),
2101
2319
  // The literal "null" is the backend's own spelling for "top-level only"
@@ -2133,7 +2351,7 @@ function registerClients(server, client, logger) {
2133
2351
  "lkp_client_create",
2134
2352
  {
2135
2353
  title: "Create client (write)",
2136
- description: "Create a new client. Requires name (\u2264100). document is a CPF (11 digits) or CNPJ (14 digits), unique in the system \u2014 pass it with or without mask, the backend strips non-digits, so never normalize it here. parent_client_id (optional) must be an active TOP-LEVEL client (one with no parent of its own); for a child, negotiated_price_list_id is inherited from the parent when omitted \u2014 and on THIS endpoint sending it as an explicit null is treated identically to omitting it, so null also inherits and cannot be used to mean 'no list'. (lkp_client_update behaves differently: read its description.) account_manager_id (optional) must be a valid user. status is NOT accepted here and is not offered: a client is always born active \u2014 use lkp_client_update to deactivate. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Summarize the draft and wait for user approval before calling. Field errors come back as 422 validation_failed with error.details.fields, a map of field \u2192 message: report the offending field, do not retry blind. RESPONSE SHAPE \u2014 do not expect a full client detail: this returns the SAME flat shape as lkp_clients_list plus full_name/parent_name/client_type/price_list/updated_at, and it does NOT carry projects[], b1_codes[], stats or sap_environments[] (only lkp_client_detail builds those). active_projects_count and b1_codes_count are always 0 here \u2014 they are only populated by lkp_clients_list, so do not report them as real counts after a write. notes and address ARE READABLE from API contract 2.16 \u2014 they come back in this write's own response and in every read (lkp_clients_list and lkp_client_detail alike), so what you sent can be confirmed against what was stored. Against a server older than 2.16 they are simply absent, and absence there means 'this server does not return the field', never 'the field is empty'.",
2354
+ description: WRITE_SCOPE_LITERAL_DOC + "Create a new client. Requires name (\u2264100). document is a CPF (11 digits) or CNPJ (14 digits), unique in the system \u2014 pass it with or without mask, the backend strips non-digits, so never normalize it here. parent_client_id (optional) must be an active TOP-LEVEL client (one with no parent of its own); for a child, negotiated_price_list_id is inherited from the parent when omitted \u2014 and on THIS endpoint sending it as an explicit null is treated identically to omitting it, so null also inherits and cannot be used to mean 'no list'. (lkp_client_update behaves differently: read its description.) account_manager_id (optional) must be a valid user. status is NOT accepted here and is not offered: a client is always born active \u2014 use lkp_client_update to deactivate. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Summarize the draft and wait for user approval before calling. Field errors come back as 422 validation_failed with error.details.fields, a map of field \u2192 message: report the offending field, do not retry blind. RESPONSE SHAPE \u2014 do not expect a full client detail: this returns the SAME flat shape as lkp_clients_list plus full_name/parent_name/client_type/price_list/updated_at, and it does NOT carry projects[], b1_codes[], stats or sap_environments[] (only lkp_client_detail builds those). active_projects_count and b1_codes_count are always 0 here \u2014 they are only populated by lkp_clients_list, so do not report them as real counts after a write. notes and address ARE READABLE from API contract 2.16 \u2014 they come back in this write's own response and in every read (lkp_clients_list and lkp_client_detail alike), so what you sent can be confirmed against what was stored. Against a server older than 2.16 they are simply absent, and absence there means 'this server does not return the field', never 'the field is empty'.",
2137
2355
  inputSchema: {
2138
2356
  name: z11.string().min(1).max(100),
2139
2357
  document: z11.string().optional(),
@@ -2155,7 +2373,7 @@ function registerClients(server, client, logger) {
2155
2373
  "lkp_client_update",
2156
2374
  {
2157
2375
  title: "Update client (write)",
2158
- description: "Update allowlisted fields on a client. status here is the STRING 'active' | 'inactive' \u2014 NOT the 1/0 integer of the database column and NOT a boolean, whatever a read of the record may suggest; anything else is 422. status: 'inactive' deactivates (soft delete, same effect and same guard as lkp_client_deactivate) and status: 'active' reactivates. Deactivating a client that still has active projects, children or tasks fails with 422 cannot_deactivate \u2014 propagate error.details.reason verbatim to the user, it names the actual blocker and is the only way to know what to clear first. overwrite_child_overrides is a BEHAVIOUR FLAG, not a field of the client: it decides whether a negotiated_price_list_id change CASCADES over children that carry their own list. Without it, children that follow the parent still get the new list and children with a specific one keep theirs; with it, the specific ones are overwritten too. It does nothing unless the price list actually changes. negotiated_price_list_id distinguishes omitted from null on THIS endpoint (unlike lkp_client_create): omit it to leave the current value untouched, send null to clear it and RE-INHERIT the parent's list. THE SAME OMITTED-VERSUS-NULL RULE GOVERNS parent_client_id, account_manager_id, document, phone, address and notes: omit the field to leave the stored value alone, send an explicit null to ERASE it. parent_client_id: null promotes a child to TOP-LEVEL, a hierarchy change \u2014 confirm it with the user instead of sending it to 'tidy up' a payload. document accepts CPF/CNPJ with or without mask. THE ALLOWLIST IS STRICT \u2014 name, document, phone, address, notes, parent_client_id, negotiated_price_list_id, account_manager_id, status, overwrite_child_overrides \u2014 and any other key is 422 unknown_field naming the offending keys, so NEVER build this call by echoing back an object read from lkp_client_detail or lkp_clients_list: id, created_at, status as an object, account_manager, price_list and the two *_count fields would all be rejected. Send only the fields being changed. Calling with no field at all sends an empty body and is 422 validation_failed ('Request body is empty'). 404 if the client does not exist. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling. RESPONSE SHAPE \u2014 same caveat as lkp_client_create: the flat shape, WITHOUT projects[], b1_codes[], stats or sap_environments[]; active_projects_count and b1_codes_count are always 0 here. notes and address DO come back, here and on every read, since API contract 2.16.",
2376
+ description: WRITE_SCOPE_LITERAL_DOC + "Update allowlisted fields on a client. status here is the STRING 'active' | 'inactive' \u2014 NOT the 1/0 integer of the database column and NOT a boolean, whatever a read of the record may suggest; anything else is 422. status: 'inactive' deactivates (soft delete, same effect and same guard as lkp_client_deactivate) and status: 'active' reactivates. Deactivating a client that still has active projects, children or tasks fails with 422 cannot_deactivate \u2014 propagate error.details.reason verbatim to the user, it names the actual blocker and is the only way to know what to clear first. overwrite_child_overrides is a BEHAVIOUR FLAG, not a field of the client: it decides whether a negotiated_price_list_id change CASCADES over children that carry their own list. Without it, children that follow the parent still get the new list and children with a specific one keep theirs; with it, the specific ones are overwritten too. It does nothing unless the price list actually changes. negotiated_price_list_id distinguishes omitted from null on THIS endpoint (unlike lkp_client_create): omit it to leave the current value untouched, send null to clear it and RE-INHERIT the parent's list. THE SAME OMITTED-VERSUS-NULL RULE GOVERNS parent_client_id, account_manager_id, document, phone, address and notes: omit the field to leave the stored value alone, send an explicit null to ERASE it. parent_client_id: null promotes a child to TOP-LEVEL, a hierarchy change \u2014 confirm it with the user instead of sending it to 'tidy up' a payload. document accepts CPF/CNPJ with or without mask. THE ALLOWLIST IS STRICT \u2014 name, document, phone, address, notes, parent_client_id, negotiated_price_list_id, account_manager_id, status, overwrite_child_overrides \u2014 and any other key is 422 unknown_field naming the offending keys, so NEVER build this call by echoing back an object read from lkp_client_detail or lkp_clients_list: id, created_at, status as an object, account_manager, price_list and the two *_count fields would all be rejected. Send only the fields being changed. Calling with no field at all sends an empty body and is 422 validation_failed ('Request body is empty'). 404 if the client does not exist. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling. RESPONSE SHAPE \u2014 same caveat as lkp_client_create: the flat shape, WITHOUT projects[], b1_codes[], stats or sap_environments[]; active_projects_count and b1_codes_count are always 0 here. notes and address DO come back, here and on every read, since API contract 2.16.",
2159
2377
  inputSchema: {
2160
2378
  client_id: z11.coerce.number().int().positive(),
2161
2379
  name: z11.string().min(1).max(100).optional(),
@@ -2187,7 +2405,7 @@ function registerClients(server, client, logger) {
2187
2405
  "lkp_client_deactivate",
2188
2406
  {
2189
2407
  title: "Deactivate client (write)",
2190
- description: "DEACTIVATE a client \u2014 this is NOT a deletion, despite the DELETE verb. status goes to inactive, the row and all its data stay in the database, and lkp_client_update with status: 'active' brings it back. There is NO permanent (hard) delete for clients through this API. Say it that way to the user: nothing is destroyed here. The backend guards it \u2014 a client with active projects, children or tasks fails with 422 cannot_deactivate, and error.details.reason names the blocker; propagate that text, it is what tells the user what to clear first. Success is 204 No Content with an EMPTY body, so this tool synthesizes its own {ok, deactivated, client_id} confirmation rather than echoing an API payload \u2014 do not report fields of the client from this response, there are none. A 404 here means the client does not exist OR IS ALREADY INACTIVE: the backend refuses to report success for a no-op DELETE, so on a 404 check the current state with lkp_client_detail before telling the user the operation failed \u2014 if it is already inactive, the desired end state is the one you wanted and there is nothing to fix. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Always ask user approval before calling \u2014 destructive intent, even though it is reversible.",
2408
+ description: WRITE_SCOPE_LITERAL_DOC + "DEACTIVATE a client \u2014 this is NOT a deletion, despite the DELETE verb. status goes to inactive, the row and all its data stay in the database, and lkp_client_update with status: 'active' brings it back. There is NO permanent (hard) delete for clients through this API. Say it that way to the user: nothing is destroyed here. The backend guards it \u2014 a client with active projects, children or tasks fails with 422 cannot_deactivate, and error.details.reason names the blocker; propagate that text, it is what tells the user what to clear first. Success is 204 No Content with an EMPTY body, so this tool synthesizes its own {ok, deactivated, client_id} confirmation rather than echoing an API payload \u2014 do not report fields of the client from this response, there are none. A 404 here means the client does not exist OR IS ALREADY INACTIVE: the backend refuses to report success for a no-op DELETE, so on a 404 check the current state with lkp_client_detail before telling the user the operation failed \u2014 if it is already inactive, the desired end state is the one you wanted and there is nothing to fix. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Always ask user approval before calling \u2014 destructive intent, even though it is reversible.",
2191
2409
  inputSchema: {
2192
2410
  client_id: z11.coerce.number().int().positive()
2193
2411
  }
@@ -2219,7 +2437,7 @@ function registerClients(server, client, logger) {
2219
2437
  "lkp_client_b1_code_create",
2220
2438
  {
2221
2439
  title: "Create client B1 code (write)",
2222
- description: "Add a B1 code to a client. code is required and non-empty; description is optional. UNIQUENESS IS SYSTEM-WIDE, not per client: the backend checks the code against every B1 code of every client, so 'this client does not have it yet' does not mean it is available. Backend validation has three outcomes and they are NOT interchangeable \u2014 read error.code, never the prose: 422 validation_failed means the code field was missing or empty (the controller short-circuits before the format check, so there is no details.fields here); 422 b1_invalid_format means it was present and non-empty but broke the backend's length rule, which it measures in BYTES after trimming \u2014 so accented or non-ASCII characters cost more than one each, and the exact ceiling is the backend's to state, not this text's; 422 b1_duplicate means the code already exists SOMEWHERE in the system. Those last two lead to opposite next steps \u2014 b1_duplicate means the code is taken and b1_invalid_format means shorten it \u2014 so surface which one came back instead of retrying. ON b1_duplicate, READ error.details: since API contract 2.16 it carries owner_client_id and owner_client_name, the client that actually holds the code. NAME THAT OWNER to the user instead of telling them to search \u2014 the owner is usually a DIFFERENT client, so 'check this client's list' sends them looking for something that is not there. details is ABSENT when the backend could not resolve the owner (a race, or a server older than 2.16); treat it as optional and fall back to 'the code is already in use somewhere' rather than reporting a missing owner as client id 0 or null. Only emptiness is checked here before the call: the length rule is the backend's, because it counts bytes after a trim and second-guessing it locally would swallow the b1_invalid_format the caller needs to see. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Returns the created code { id, code, description, is_active } with is_active as a boolean. 404 if the client does not exist. Confirm with the user before calling.",
2440
+ description: WRITE_SCOPE_LITERAL_DOC + "Add a B1 code to a client. code is required and non-empty; description is optional. UNIQUENESS IS SYSTEM-WIDE, not per client: the backend checks the code against every B1 code of every client, so 'this client does not have it yet' does not mean it is available. Backend validation has three outcomes and they are NOT interchangeable \u2014 read error.code, never the prose: 422 validation_failed means the code field was missing or empty (the controller short-circuits before the format check, so there is no details.fields here); 422 b1_invalid_format means it was present and non-empty but broke the backend's length rule, which it measures in BYTES after trimming \u2014 so accented or non-ASCII characters cost more than one each, and the exact ceiling is the backend's to state, not this text's; 422 b1_duplicate means the code already exists SOMEWHERE in the system. Those last two lead to opposite next steps \u2014 b1_duplicate means the code is taken and b1_invalid_format means shorten it \u2014 so surface which one came back instead of retrying. ON b1_duplicate, READ error.details: since API contract 2.16 it carries owner_client_id and owner_client_name, the client that actually holds the code. NAME THAT OWNER to the user instead of telling them to search \u2014 the owner is usually a DIFFERENT client, so 'check this client's list' sends them looking for something that is not there. details is ABSENT when the backend could not resolve the owner (a race, or a server older than 2.16); treat it as optional and fall back to 'the code is already in use somewhere' rather than reporting a missing owner as client id 0 or null. Only emptiness is checked here before the call: the length rule is the backend's, because it counts bytes after a trim and second-guessing it locally would swallow the b1_invalid_format the caller needs to see. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Returns the created code { id, code, description, is_active } with is_active as a boolean. 404 if the client does not exist. Confirm with the user before calling.",
2223
2441
  inputSchema: {
2224
2442
  client_id: z11.coerce.number().int().positive(),
2225
2443
  // min(1) only. The 14-char ceiling used to live here too, and it had to
@@ -2244,7 +2462,7 @@ function registerClients(server, client, logger) {
2244
2462
  "lkp_client_b1_code_update",
2245
2463
  {
2246
2464
  title: "Update client B1 code (write)",
2247
- description: "Update a client B1 code. The allowlist is exactly description and is_active \u2014 anything else is 422 unknown_field, so do not echo back an item read from lkp_client_b1_codes_list (its id would be rejected). is_active is a BOOLEAN: false deactivates the code, true reactivates it. Calling with neither field sends an empty body and is 422 validation_failed ('Request body is empty'). Deactivating a code that still has active tasks fails with 422 cannot_deactivate, with the blocker in error.details.reason. BOTH client_id AND b1_code_id are required and the backend validates them AS A PAIR: a code that exists but belongs to ANOTHER client answers 404 not_found, identically to one that does not exist at all \u2014 so a cached b1_code_id is worthless without the client_id of its owner, and a 404 here never confirms whether the id exists elsewhere. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling.",
2465
+ description: WRITE_SCOPE_LITERAL_DOC + "Update a client B1 code. The allowlist is exactly description and is_active \u2014 anything else is 422 unknown_field, so do not echo back an item read from lkp_client_b1_codes_list (its id would be rejected). is_active is a BOOLEAN: false deactivates the code, true reactivates it. Calling with neither field sends an empty body and is 422 validation_failed ('Request body is empty'). Deactivating a code that still has active tasks fails with 422 cannot_deactivate, with the blocker in error.details.reason. BOTH client_id AND b1_code_id are required and the backend validates them AS A PAIR: a code that exists but belongs to ANOTHER client answers 404 not_found, identically to one that does not exist at all \u2014 so a cached b1_code_id is worthless without the client_id of its owner, and a 404 here never confirms whether the id exists elsewhere. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling.",
2248
2466
  inputSchema: {
2249
2467
  client_id: z11.coerce.number().int().positive(),
2250
2468
  b1_code_id: z11.coerce.number().int().positive(),
@@ -2265,7 +2483,7 @@ function registerClients(server, client, logger) {
2265
2483
  "lkp_client_b1_code_deactivate",
2266
2484
  {
2267
2485
  title: "Deactivate client B1 code (write)",
2268
- description: "DEACTIVATE a client B1 code \u2014 not a deletion, despite the DELETE verb: is_active goes to false, the row stays, and lkp_client_b1_code_update with is_active: true brings it back. The backend guards it: a code with active tasks fails with 422 cannot_deactivate, with the blocker in error.details.reason. Success is 204 No Content with an EMPTY body, so this tool synthesizes its own {ok, deactivated, client_id, b1_code_id} confirmation \u2014 there are no code fields in this response to report. BOTH ids are required and are validated as a pair: a code belonging to another client answers 404 not_found, the same as one that does not exist. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Always ask user approval before calling \u2014 destructive intent, even though it is reversible.",
2486
+ description: WRITE_SCOPE_LITERAL_DOC + "DEACTIVATE a client B1 code \u2014 not a deletion, despite the DELETE verb: is_active goes to false, the row stays, and lkp_client_b1_code_update with is_active: true brings it back. The backend guards it: a code with active tasks fails with 422 cannot_deactivate, with the blocker in error.details.reason. Success is 204 No Content with an EMPTY body, so this tool synthesizes its own {ok, deactivated, client_id, b1_code_id} confirmation \u2014 there are no code fields in this response to report. BOTH ids are required and are validated as a pair: a code belonging to another client answers 404 not_found, the same as one that does not exist. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Always ask user approval before calling \u2014 destructive intent, even though it is reversible.",
2269
2487
  inputSchema: {
2270
2488
  client_id: z11.coerce.number().int().positive(),
2271
2489
  b1_code_id: z11.coerce.number().int().positive()
@@ -2303,7 +2521,9 @@ var SapEnvironmentFilter = z12.union([
2303
2521
  z12.number().int().positive(),
2304
2522
  z12.string().regex(/^[1-9]\d*$/).transform((v) => Number(v))
2305
2523
  ]);
2306
- var SLA_DEADLINES_DOC = "sla ALSO CARRIES deadlines[] (API contract 2.17): the deadline ruler resolved server-side, and THE answer to 'what is the deadline?'. The 8 scalar sla.* keys LIE for an improvement ticket BY DESIGN, not by accident \u2014 improvements use no SLA policy, so resolution_due_at is NULL on purpose and the delivery forecast lives ONLY in deadlines[] ({phase: 'delivery'}, derived at read time from the ticket's task tree); when the question is a deadline, read the ruler, never the scalars. Each entry has exactly 8 keys: {phase, rule, due_at, met_at, breached, open, granularity, label}. phase has THREE values \u2014 'response', 'resolution', 'delivery' \u2014 never two: 'delivery' exists only on an improvement with a RECORDED ACCEPTANCE and never appears on an AMS ticket, so a consumer that assumes response|resolution will reject real payloads months later. rule says which ruler applies, and has three values: 'sla_policy' (AMS), 'improvement_business_days' (the improvement response phase, and an improvement resolved without acceptance), 'task_tree' (the improvement delivery phase). granularity CHANGES THE FORMAT of due_at: 'datetime' entries carry 'YYYY-MM-DD HH:MM:SS' and are due at that instant; 'date' entries (today only the delivery phase) carry a bare 'YYYY-MM-DD' \u2014 the ONE exception to this API's timestamp format \u2014 and are due at the END of that day (23:59:59), so parsing the bare date as a datetime silently concludes 'breached' about a day early. An entry with due_at: null is HISTORY, never a running clock \u2014 open is always false there. The documented edge case: an improvement RESOLVED WITHOUT ACCEPTANCE (rejected technically, or closed with no approved proposal) publishes {phase: 'resolution', rule: 'improvement_business_days', due_at: null, met_at: the instant of resolution} \u2014 the entry exists to carry the FULFILLMENT, not a deadline, because without an acceptance there is no delivery commitment. How many clocks run at once depends on the ticket kind: on an IMPROVEMENT at most ONE entry has open: true \u2014 whenever a second phase exists, the 'response' entry is FORCED to open: false even when no fulfillment was recorded (e.g. a ticket adopted by backfill); on an AMS ticket the response and resolution clocks run IN PARALLEL, and BOTH entries can arrive open: true until the first response is recorded \u2014 'which deadline is running?' can legitimately have two answers on a fresh AMS ticket, and that is the server's real behaviour, not a payload error. Everywhere, open is only ever true with due_at present, met_at absent and the ticket not closed/cancelled. AMS tickets (non-improvement) always carry EXACTLY 2 entries \u2014 'response' + 'resolution', both rule 'sla_policy', both granularity 'datetime', with due_at null when no policy applies \u2014 the array is never empty there. The ruler follows the improvements PROJECT, not the category: after a 'skipped_gate_off' recategorization the ticket has an improvement category but keeps the AMS ruler (2 'sla_policy' entries). label arrives ALREADY TRANSLATED from the server (a token consumer has no access to the app's i18n) \u2014 do not re-translate it, do not build an enum over it, and never use it as a discriminator: the discriminators are phase + rule.";
2524
+ var TICKET_ATTENDANT_DOC = "WRITING TO THIS TICKET IS NARROWER THAN READING IT, and narrower than it was before API contract 2.19 (errata of 2026-08-29). The ruler is HelpdeskTicket::userIsTicketAttendant and it admits FOUR doors only: an administrator, a helpdesk agent (is_helpdesk_agent = 1), the STRICT projects.manager_id of the ticket's project (the Gestor do Projeto \u2014 being a manager of something else grants nothing, and being a MEMBER of that project grants nothing), or the user in assigned_to. created_by IS NOT A DOOR \u2014 it was one for a few hours on 2026-08-27 and was deliberately removed, so the internal author of a ticket who is none of the four above can neither move it nor comment on it. THE TWO 403s ARE NOT THE SAME REFUSAL AND NEED OPPOSITE ANSWERS: error.code 'insufficient_scope' means the TOKEN lacks write:helpdesk \u2014 another token fixes it, another person does not; error.code 'forbidden' means the token has the scope but the PERSON is not an attendant \u2014 another person fixes it, another token does not. Branch on error.code, never on the message text.";
2525
+ var RESOLVED_AT_DOC = "READ sla.resolved_at LITERALLY, NOT AS 'THE TICKET IS DONE' (this changed in API contract 2.18, same name and same type as before). It is stamped when the ticket ENTERS 'Aguardando Homologa\xE7\xE3o' (status 4) \u2014 'the delivery was released for the client to validate' \u2014 which is EARLIER in the cycle than the old meaning, and it is NOT closure: a ticket with a non-null resolved_at can be wide open. It also REGRESSES TO NULL when the client rejects the homologation and the ticket goes back to 'Em Atendimento' (or leaves 4 for any non-closed destination), and a re-delivery re-stamps it with no COALESCE \u2014 so this field is NOT monotonic and any cache or aggregate that assumes it only ever moves forward is wrong. Only the close path uses COALESCE (an existing stamp is never overwritten), and Cancelado never stamps it at all. To answer 'is this ticket finished?', read status.is_closed; to answer 'when was it delivered for validation?', read this field. Anything else derived from the same sla_resolved_at column inherits this change with it.";
2526
+ var SLA_DEADLINES_DOC = "met_at OF THE 'resolution' AND 'delivery' PHASES READS sla_resolved_at, so it inherits that field's change of meaning wholesale (see it described above): a met_at there marks the release for the client to validate, not the end of the ticket, and it can go back to null. sla ALSO CARRIES deadlines[] (API contract 2.17): the deadline ruler resolved server-side, and THE answer to 'what is the deadline?'. The 8 scalar sla.* keys LIE for an improvement ticket BY DESIGN, not by accident \u2014 improvements use no SLA policy, so resolution_due_at is NULL on purpose and the delivery forecast lives ONLY in deadlines[] ({phase: 'delivery'}, derived at read time from the ticket's task tree); when the question is a deadline, read the ruler, never the scalars. Each entry has exactly 8 keys: {phase, rule, due_at, met_at, breached, open, granularity, label}. phase has THREE values \u2014 'response', 'resolution', 'delivery' \u2014 never two: 'delivery' exists only on an improvement with a RECORDED ACCEPTANCE and never appears on an AMS ticket, so a consumer that assumes response|resolution will reject real payloads months later. rule says which ruler applies, and has three values: 'sla_policy' (AMS), 'improvement_business_days' (the improvement response phase, and an improvement resolved without acceptance), 'task_tree' (the improvement delivery phase). granularity CHANGES THE FORMAT of due_at: 'datetime' entries carry 'YYYY-MM-DD HH:MM:SS' and are due at that instant; 'date' entries (today only the delivery phase) carry a bare 'YYYY-MM-DD' \u2014 the ONE exception to this API's timestamp format \u2014 and are due at the END of that day (23:59:59), so parsing the bare date as a datetime silently concludes 'breached' about a day early. An entry with due_at: null is HISTORY, never a running clock \u2014 open is always false there. The documented edge case: an improvement RESOLVED WITHOUT ACCEPTANCE (rejected technically, or closed with no approved proposal) publishes {phase: 'resolution', rule: 'improvement_business_days', due_at: null, met_at: the instant of resolution} \u2014 the entry exists to carry the FULFILLMENT, not a deadline, because without an acceptance there is no delivery commitment. How many clocks run at once depends on the ticket kind: on an IMPROVEMENT at most ONE entry has open: true \u2014 whenever a second phase exists, the 'response' entry is FORCED to open: false even when no fulfillment was recorded (e.g. a ticket adopted by backfill); on an AMS ticket the response and resolution clocks run IN PARALLEL, and BOTH entries can arrive open: true until the first response is recorded \u2014 'which deadline is running?' can legitimately have two answers on a fresh AMS ticket, and that is the server's real behaviour, not a payload error. Everywhere, open is only ever true with due_at present, met_at absent and the ticket not closed/cancelled. AMS tickets (non-improvement) always carry EXACTLY 2 entries \u2014 'response' + 'resolution', both rule 'sla_policy', both granularity 'datetime', with due_at null when no policy applies \u2014 the array is never empty there. The ruler follows the improvements PROJECT, not the category: after a 'skipped_gate_off' recategorization the ticket has an improvement category but keeps the AMS ruler (2 'sla_policy' entries). label arrives ALREADY TRANSLATED from the server (a token consumer has no access to the app's i18n) \u2014 do not re-translate it, do not build an enum over it, and never use it as a discriminator: the discriminators are phase + rule.";
2307
2527
  function assertSapEnvironmentFilter(value) {
2308
2528
  if (value === void 0 || value === "none") return;
2309
2529
  const n = typeof value === "string" && /^[1-9]\d*$/.test(value) ? Number(value) : value;
@@ -2323,7 +2543,7 @@ function registerHelpdesk(server, client, logger) {
2323
2543
  "lkp_helpdesk_tickets_list",
2324
2544
  {
2325
2545
  title: "List helpdesk tickets",
2326
- description: "List helpdesk tickets with filters. Use for triage and to find tickets exceeding SLA. Each item is {id, ticket_number ('HD-AAAA-NNN'), subject, priority, status, client, category, project, assigned_to, contact, sla, closed_at, reopened_count, created_by, created_at, updated_at, tags}. Four of those have a shape that is easy to guess wrong, so read them literally: status is an OBJECT {id, name, color, is_closed, pauses_sla} and NEVER a bare string like 'in_progress' \u2014 compare status.id, and use status.is_closed rather than inferring closure from the name. tags is an array of OBJECTS {id, name, color}, not of strings. project on a LIST item carries only {id}: project.name exists on the detail (lkp_helpdesk_ticket_get) and nowhere else, so never print a project name from the list. sla is {policy_id, response_due_at, resolution_due_at, first_response_at, resolved_at, response_breached, resolution_breached, paused_minutes, deadlines} \u2014 the scalar deadline keys are response_due_at/resolution_due_at (there are no *_deadline keys), and 'is it late?' is the boolean response_breached/resolution_breached, computed server-side; do not re-derive it by comparing a due date against the clock. Every date in this payload is 'YYYY-MM-DD HH:MM:SS' in America/Sao_Paulo with NO 'T' and NO offset \u2014 it is not ISO 8601 and never was, so do not feed it to a date parser that assumes UTC; the single exception is a deadlines[] entry with granularity 'date', described below. meta here is {total, page, per_page} and carries NO has_more and NO returned, unlike lkp_helpdesk_ticket_comments_list which does: to know whether more pages exist, compare page * per_page against total; reading a missing has_more as false stops pagination after the first page. sap_environment_id filters by SAP environment: a positive int for a single environment, or the exact lowercase string 'none' for tickets with no environment informed; omit it to get all. Any other value is rejected here before the call, and the backend also rejects it with 400 invalid_filter since API contract 2.9 \u2014 it used to cast the value to int (so 'all' became 0) and answer 200 with an empty list, which reads as 'no tickets' rather than 'bad filter'. The client-side check only turns that into a clearer error without a round trip. An unknown priority is validated the same way. That filter is a convenience only \u2014 the security boundary is still the server-side role/line scoping. Use lkp_helpdesk_ticket_get for the full body, comments count and attachments of one ticket. " + SLA_DEADLINES_DOC,
2546
+ description: "List helpdesk tickets with filters. Use for triage and to find tickets exceeding SLA. Each item is {id, ticket_number ('HD-AAAA-NNN'), subject, priority, status, client, category, project, assigned_to, contact, sla, closed_at, reopened_count, created_by, created_at, updated_at, tags}. Four of those have a shape that is easy to guess wrong, so read them literally: status is an OBJECT {id, name, color, is_closed, pauses_sla} and NEVER a bare string like 'in_progress' \u2014 compare status.id, and use status.is_closed rather than inferring closure from the name. tags is an array of OBJECTS {id, name, color}, not of strings. project on a LIST item carries only {id}: project.name exists on the detail (lkp_helpdesk_ticket_get) and nowhere else, so never print a project name from the list. sla is {policy_id, response_due_at, resolution_due_at, first_response_at, resolved_at, response_breached, resolution_breached, paused_minutes, deadlines} \u2014 the scalar deadline keys are response_due_at/resolution_due_at (there are no *_deadline keys), and 'is it late?' is the boolean response_breached/resolution_breached, computed server-side; do not re-derive it by comparing a due date against the clock. " + RESOLVED_AT_DOC + " Every date in this payload is 'YYYY-MM-DD HH:MM:SS' in America/Sao_Paulo with NO 'T' and NO offset \u2014 it is not ISO 8601 and never was, so do not feed it to a date parser that assumes UTC; the single exception is a deadlines[] entry with granularity 'date', described below. meta here is {total, page, per_page} and carries NO has_more and NO returned, unlike lkp_helpdesk_ticket_comments_list which does: to know whether more pages exist, compare page * per_page against total; reading a missing has_more as false stops pagination after the first page. sap_environment_id filters by SAP environment: a positive int for a single environment, or the exact lowercase string 'none' for tickets with no environment informed; omit it to get all. Any other value is rejected here before the call, and the backend also rejects it with 400 invalid_filter since API contract 2.9 \u2014 it used to cast the value to int (so 'all' became 0) and answer 200 with an empty list, which reads as 'no tickets' rather than 'bad filter'. The client-side check only turns that into a clearer error without a round trip. An unknown priority is validated the same way. That filter is a convenience only \u2014 the security boundary is still the server-side role/line scoping. status_id FILTERS BY THE NUMERIC STATUS ID (the parameter is status_id, not status). Since API contract 2.18 the ids 2 (Triagem) and 6 (Resolvido) are DEACTIVATED: they are still valid ids and the call answers 200 WITH A LIST \u2014 WHICH CAN HAVE ROWS. Deactivating a status removes the ways INTO it (it is the destination of no transition, and the picker filters is_active = 1), it does NOT empty it: tickets seeded or moved there before the cutover stay, and the DEV database currently holds 29 in status 6. So never read this filter as 'always empty' and never read a non-empty page as a bug; equally, an empty page means only that nobody happens to be there, never 'bad filter'. The ids 10 (Aguardando Resposta) and 11 (Pausado pelo Cliente) are new and accepted. The historical ids are NOT removed from the database \u2014 a ticket's history still joins them to render a name \u2014 so never strip them from a reading path. Use lkp_helpdesk_ticket_get for the full body, comments count and attachments of one ticket. " + SLA_DEADLINES_DOC,
2327
2547
  inputSchema: {
2328
2548
  status_id: z12.coerce.number().int().positive().optional(),
2329
2549
  priority: z12.string().optional(),
@@ -2347,7 +2567,7 @@ function registerHelpdesk(server, client, logger) {
2347
2567
  "lkp_helpdesk_summary",
2348
2568
  {
2349
2569
  title: "Helpdesk summary",
2350
- description: "Helpdesk dashboard: counts by status and priority, top 10 clients by open tickets, SLA breaches, resolved today.",
2570
+ description: "Helpdesk dashboard: counts by status and priority, top 10 clients by open tickets, SLA breaches, and the day's deliveries. by_status IS KEYED BY THE STATUS NAME, NOT BY ID, and it only carries the statuses that are currently ACTIVE \u2014 this MCP passes the object through exactly as the backend built it and has no opinion about the keys, so read whatever keys arrive instead of asking for one you expect. Two consequences that produce a wrong number rather than an error: a key you expect and do not find reads as absence, and summing a missing key gives 0 or NaN in a figure the user takes for the truth. As of API contract 2.18 the set moved \u2014 'Triagem' and 'Resolvido' are DEACTIVATED and no longer appear at all, 'Aguardando Cliente' and 'Aguardando Interno' were RENAMED to 'Aguardando Homologa\xE7\xE3o' and 'Aguardando LINKUP' (same ids 4 and 5, new names), and 'Aguardando Resposta' and 'Pausado pelo Cliente' were born \u2014 but treat that list as today's reading, not as a contract: the backend can rename or deactivate a status without any version moving. Enumerate the keys, never hardcode them. totals.resolved_today DOES NOT COUNT TICKETS THAT WERE FINISHED TODAY. It is derived from the same sla_resolved_at column described below, so since 2.18 it counts tickets that entered 'Aguardando Homologa\xE7\xE3o' today \u2014 deliveries released for the client to validate, some of which the client will reject. Never report it to the user as 'resolved today' or 'closed today'. " + RESOLVED_AT_DOC,
2351
2571
  inputSchema: {}
2352
2572
  },
2353
2573
  async () => runTool(
@@ -2360,7 +2580,7 @@ function registerHelpdesk(server, client, logger) {
2360
2580
  "lkp_helpdesk_ticket_get",
2361
2581
  {
2362
2582
  title: "Helpdesk ticket detail",
2363
- description: "Full detail of one helpdesk ticket: the same shape as an item of lkp_helpdesk_tickets_list plus description (the original body), comments_count, attachments[] ({id, file_name, file_size, mime_type, message_id, uploaded_by, created_at}), project.name, contact.email/phone, linked_task, sap_environment_id, sap_environment, csat, and requester {type: 'user'|'contact'|null, id, name}. Every documented key is ALWAYS present in the payload \u2014 only the value varies, and it is null when there is nothing to report. A missing key means the server is older than this contract, never 'this ticket has no value'. linked_task is {id, title, status_id}, or null when no task is linked: under API contract < 2.9 that key was omitted entirely instead of null, so never read its absence as a value. sap_environment_id is the raw int or null; sap_environment is the resolved {id, nome, sid} or null, and it resolves environments that have since been DEACTIVATED, so display sap_environment.nome (+ sid) rather than the bare id. csat is {rating (1-5), comment, created_at}, or null when the client has not rated the ticket; inside a non-null csat, rating is never null but comment can be. requester is {type: null, id: null, name: null} on legacy tickets whose created_by and contact_person_id are both empty. attachments[].uploaded_by is the uploader's DISPLAY NAME as a string, and can be null when that user/contact was removed \u2014 it is not an id and not an object, so never use it to look a user up. There is NO resolution field \u2014 the outcome lives in the comments (lkp_helpdesk_ticket_comments_list); that is the one documented key which is genuinely absent rather than null. Requires read:helpdesk (or read:*); 404 if the ticket does not exist, 403 if the token user has no access to it. " + SLA_DEADLINES_DOC,
2583
+ description: "Full detail of one helpdesk ticket: the same shape as an item of lkp_helpdesk_tickets_list plus description (the original body), comments_count, attachments[] ({id, file_name, file_size, mime_type, message_id, uploaded_by, created_at}), project.name, contact.email/phone, linked_task, sap_environment_id, sap_environment, csat, and requester {type: 'user'|'contact'|null, id, name}. Every documented key is ALWAYS present in the payload \u2014 only the value varies, and it is null when there is nothing to report. A missing key means the server is older than this contract, never 'this ticket has no value'. linked_task is {id, title, status_id}, or null when no task is linked: under API contract < 2.9 that key was omitted entirely instead of null, so never read its absence as a value. sap_environment_id is the raw int or null; sap_environment is the resolved {id, nome, sid} or null, and it resolves environments that have since been DEACTIVATED, so display sap_environment.nome (+ sid) rather than the bare id. csat is {rating (1-5), comment, created_at}, or null when the client has not rated the ticket; inside a non-null csat, rating is never null but comment can be. requester is {type: null, id: null, name: null} on legacy tickets whose created_by and contact_person_id are both empty. attachments[].uploaded_by is the uploader's DISPLAY NAME as a string, and can be null when that user/contact was removed \u2014 it is not an id and not an object, so never use it to look a user up. There is NO resolution field \u2014 the outcome lives in the comments (lkp_helpdesk_ticket_comments_list); that is the one documented key which is genuinely absent rather than null. " + RESOLVED_AT_DOC + " Requires read:helpdesk (or read:*); 404 if the ticket does not exist, 403 if the token user has no access to it. " + SLA_DEADLINES_DOC,
2364
2584
  inputSchema: {
2365
2585
  ticket_id: z12.coerce.number().int().positive()
2366
2586
  }
@@ -2395,7 +2615,7 @@ function registerHelpdesk(server, client, logger) {
2395
2615
  "lkp_helpdesk_ticket_comment_add",
2396
2616
  {
2397
2617
  title: "Add helpdesk ticket comment (write)",
2398
- description: "Add a comment to a helpdesk ticket. is_internal is REQUIRED and has no default \u2014 you must decide explicitly: true = internal note (never delivered to the client), false = public reply to the client. WHAT A PUBLIC REPLY DOES TO THE SLA DEPENDS ON THE KIND OF TICKET, and the two answers are opposites. On an AMS (non-improvement) ticket, ANY public reply (is_internal=false) through this endpoint sets sla_first_response_at when it is still empty \u2014 it is not gated on the author being an 'agent', so a single false stops the response SLA clock for good, and a reply that lands after the due date records the breach in the same move. On an IMPROVEMENT ticket NO message stops the response clock, ever: that phase is fulfilled only by SENDING A PROPOSAL or by a TECHNICAL REJECTION (the ticket moved to Cancelado), because 'we are looking into it' does not answer a request for an improvement. So never report the response SLA as met just because a reply went out on an improvement \u2014 the authoritative answer is the resolved deadline ruler on the ticket, which you read with lkp_helpdesk_ticket_get, not an inference from this call. An internal note stops nothing on either kind. This endpoint always records the message as the token owner (sender_type='user'); a client contact never posts through it. body accepts HTML or plain text and is sanitized server-side \u2014 do not escape it here. Returns { data: { id, responded_as } } (201) \u2014 responded_as is new in API contract 2.12 and is null for an ordinary comment. Requires the write:helpdesk scope. " + REPLY_AS_SERVICE_IDENTITY_DOC + " Signing as the identity is incompatible with an internal note: is_internal=true together with reply_as_service_identity=true is 422 validation_failed, because an internal note has no client to sign for. A signed reply is treated exactly like an unsigned one by the response clock \u2014 same rule, improvement exception included. Always show the user the exact body, whether it is internal AND whether it goes out signed as the company, and wait for approval before calling \u2014 a wrong is_internal sends internal wording to the client, and on an AMS ticket it burns the SLA first response as well.",
2618
+ description: "Add a comment to a helpdesk ticket. is_internal is REQUIRED and has no default \u2014 you must decide explicitly: true = internal note (never delivered to the client), false = public reply to the client. WHAT A PUBLIC REPLY DOES TO THE SLA DEPENDS ON THE KIND OF TICKET, and the two answers are opposites. On an AMS (non-improvement) ticket, ANY public reply (is_internal=false) through this endpoint sets sla_first_response_at when it is still empty \u2014 it is not gated on the author being an 'agent', so a single false stops the response SLA clock for good, and a reply that lands after the due date records the breach in the same move. On an IMPROVEMENT ticket NO message stops the response clock, ever: that phase is fulfilled only by SENDING A PROPOSAL or by a TECHNICAL REJECTION (the ticket moved to Cancelado), because 'we are looking into it' does not answer a request for an improvement. So never report the response SLA as met just because a reply went out on an improvement \u2014 the authoritative answer is the resolved deadline ruler on the ticket, which you read with lkp_helpdesk_ticket_get, not an inference from this call. An internal note stops nothing on either kind. This endpoint always records the message as the token owner (sender_type='user'); a client contact never posts through it. body accepts HTML or plain text and is sanitized server-side \u2014 do not escape it here. Returns { data: { id, responded_as } } (201) \u2014 responded_as is new in API contract 2.12 and is null for an ordinary comment. Requires the write:helpdesk scope. " + REPLY_AS_SERVICE_IDENTITY_DOC + " Signing as the identity is incompatible with an internal note: is_internal=true together with reply_as_service_identity=true is 422 validation_failed, because an internal note has no client to sign for. A signed reply is treated exactly like an unsigned one by the response clock \u2014 same rule, improvement exception included. " + THREAD_BOUNDARY_DOC + " Always show the user the exact body, whether it is internal AND whether it goes out signed as the company, and wait for approval before calling \u2014 a wrong is_internal sends internal wording to the client, and on an AMS ticket it burns the SLA first response as well. " + TICKET_ATTENDANT_DOC + " ON THIS ENDPOINT THE REFUSAL IS DELIBERATELY UNINFORMATIVE: a 403 forbidden here carries the GENERIC message 'You do not have access to this ticket.' and NO error.details.fields \u2014 byte for byte the same answer as 'this ticket is not visible to you'. The PATCH refusal, by contrast, names the offending fields in details.fields. So the presence of details.fields is what tells the two refusals apart, and on a 403 from THIS call you cannot tell 'I see it but may not write' from 'I do not see it' \u2014 do not report either one as certain. Reading the thread is a WIDER door than writing to it: being able to list the comments proves nothing about being able to add one.",
2399
2619
  inputSchema: {
2400
2620
  ticket_id: z12.coerce.number().int().positive(),
2401
2621
  body: z12.string().min(1),
@@ -2432,11 +2652,34 @@ function registerHelpdesk(server, client, logger) {
2432
2652
  )
2433
2653
  )
2434
2654
  );
2655
+ server.registerTool(
2656
+ "lkp_helpdesk_ticket_ask_client",
2657
+ {
2658
+ title: "Ask the client a question from a ticket (write, THREE side effects)",
2659
+ description: "\u{1F534} ONE CALL, THREE EFFECTS, AND THE TOOL NAME ONLY SUGGESTS THE FIRST. (1) It publishes your question in the CLIENT'S thread on the ticket and EMAILS THE CONTACT. (2) It moves the ticket to 'Aguardando Resposta' (10), WHICH PAUSES THE SLA CLOCK. (3) If \u2014 and only if \u2014 you pass task_id, it also BLOCKS that task. This is the ticket-side twin of lkp_task_ask_client. When you only want to say something to the client without parking the ticket, use lkp_helpdesk_ticket_comment_add with is_internal: false instead: it publishes and moves nothing. " + THREAD_BOUNDARY_DOC + " body is required and must survive server-side sanitizing \u2014 a body of pure markup can arrive empty and come back 422 validation_failed with details.body. task_id is OPTIONAL and its only job is to block a task alongside the ticket; it MUST belong to this ticket's tree, otherwise 422 task_ticket_mismatch, and a non-positive value is 422 validation_failed. Omit it and task_blocked comes back false AND blocked_task_status_id comes back null \u2014 on this tool a null there means 'you did not ask for a task to be blocked', not 'the block failed'. RETURNS { id, ticket_id, source_task_id, is_internal: false, status_changed, task_blocked, responded_as }. \u{1F534} status_changed: false IS SUCCESS \u2014 the ticket was already in Aguardando Resposta and the question went out anyway; there was simply no transition to record. Never report it as a failure and never retry because of it. \u{1F534} THE AUTHORIZATION HERE IS WIDER THAN THE ONE THAT MOVES OR COMMENTS ON THIS SAME TICKET, and that is deliberate. It lives entirely in HelpdeskTicketService::askClient and grants access to whoever may write ON THE TICKET **or** on a task in its tree \u2014 so someone refused by lkp_helpdesk_ticket_update can legitimately succeed here. Do not predict this tool's answer from the other one's. \u{1F534} THERE IS NO 404 FOR AN UNKNOWN TICKET BY DEFAULT: the sovereign point collapses 'does not exist' and 'you cannot reach it' into 403 forbidden on purpose, so this endpoint cannot be used to discover whether ticket N exists. NEVER CONCLUDE THAT A TICKET EXISTS BECAUSE YOU DID NOT GET A 404. A real 404 not_found reaches only a caller who already had the reach to be told. " + ASK_CLIENT_OUTCOME_DOC + " Other refusals by error.code: 422 task_not_blockable, 422 publish_failed (the sovereign service refused the publication after every guard passed), 422 task_ticket_mismatch (task_id is not in this ticket's tree), 403 insufficient_scope (token lacks write:helpdesk \u2014 change the TOKEN, not the person). \u{1F534} 422 status_not_changed IS A PARTIAL FAILURE: THE QUESTION WAS ALREADY PUBLISHED and only the status move failed. Do not retry blindly \u2014 you would ask the client twice, with only the 60-second duplicate guard in the way. Read the ticket, move it by hand if needed, and tell the user. Requires write:helpdesk. " + REPLY_AS_SERVICE_IDENTITY_DOC + " SHOW THE USER THE EXACT QUESTION AND SAY THAT THE TICKET WILL STOP AND WAIT ON THE CLIENT, BEFORE CALLING.",
2660
+ inputSchema: {
2661
+ ticket_id: z12.coerce.number().int().positive(),
2662
+ body: z12.string().min(1),
2663
+ // Opcional: só existe para bloquear uma tarefa junto. Positivo estrito
2664
+ // porque o backend recusa <= 0 com 422 — recusar aqui poupa a ida.
2665
+ task_id: z12.coerce.number().int().positive().optional(),
2666
+ reply_as_service_identity: ReplyAsServiceIdentity
2667
+ }
2668
+ },
2669
+ async ({ ticket_id, reply_as_service_identity, ...rest }) => runTool(
2670
+ logger,
2671
+ "lkp_helpdesk_ticket_ask_client",
2672
+ () => client.post(
2673
+ `/api/v1/helpdesk/tickets/${ticket_id}/ask-client`,
2674
+ withServiceIdentity(rest, reply_as_service_identity)
2675
+ )
2676
+ )
2677
+ );
2435
2678
  server.registerTool(
2436
2679
  "lkp_helpdesk_ticket_update",
2437
2680
  {
2438
2681
  title: "Update helpdesk ticket (write)",
2439
- description: "Update whitelisted fields on a helpdesk ticket: status_id, status_comment, priority (low|medium|high|critical), assigned_to, category_id, tags and sap_environment_id (int, or null to clear \u2014 the environment must belong to the ticket's client, otherwise 422 validation_failed). tags REPLACES the ticket's whole tag set, it does not merge: send the complete list of tag IDs the ticket should end up with, and note that tags: [] wipes every tag. recategorize_reason is REQUIRED whenever category_id is sent, and note the exact name \u2014 it is recategorize_reason HERE and plain `reason` on the dedicated route, a difference that costs a 422 if crossed. PREFER lkp_helpdesk_ticket_recategorize WHENEVER THE CATEGORY IS THE ONLY THING CHANGING, but only as a matter of intent now, not of information: since API contract 2.16 this PATCH RETURNS THE RECATEGORIZATION SERVICE'S OWN error.code and HTTP status, exactly as the dedicated route does. A 403 forbidden (you are not the ticket's Gerente Respons\xE1vel), a 404 not_found, a 422 validation_failed, a 409 converted (the opportunity already became a project) and a 409 proposal_exists each arrive here as themselves. DO NOT REPEAT A FAILED CALL THROUGH THE DEDICATED TOOL TO LEARN THE REAL CODE \u2014 you already have it, and the retry only asks the backend the same question twice. Against a server older than 2.16 those five collapse into 422 patch_failed instead; read error.code and treat patch_failed as 'the reason was not reported', never as a specific diagnosis. patch_failed also survives on 2.16 as the fallback for the service's catch-all path, which can return a null code, and for the OTHER sub-operations of this PATCH \u2014 status, priority and assignment return only {success, message} to the backend, so there is no code to pass through and patch_failed is all the information that exists. Changing the category is also NOT a metadata edit: read the side effects on lkp_helpdesk_ticket_recategorize before sending category_id from here, because they are identical and they move commercial state. status_comment (API contract 2.13) is the REASON for a status change, and THE CLIENT READS IT on the ticket \u2014 it is a public message signed by the agent, never an internal note, and it can count as the SLA first response. It only travels with status_id: sent alone it is 422 validation_failed with details.status_comment='requires status_id', and this tool rejects that combination before the call. Leaving the 'Em Atendimento' status REQUIRES it \u2014 without it the backend answers 422 patch_failed explaining that the client has to know what happened; that rule depends on the ticket's CURRENT status, which this tool does not know, so it is never second-guessed here: send the change and read the backend's answer. Note the exact name: status_comment, NOT comment \u2014 comment is the field name in the SPA form and the API rejects it with 422 field_not_allowed. Show the user the exact status_comment text and wait for approval before calling, the same as for a comment body: it reaches the client. Fields outside the whitelist (client_id, project_id, ticket_number, created_at and any sla_*) are rejected by the backend with 422 field_not_allowed and are not accepted here \u2014 since API contract 2.9 that error carries error.details.field naming the offending key, so read details.field and fall back to parsing error.message (\"Field 'X' cannot be patched.\") only for older servers. A malformed JSON body is 400 invalid_body. Returns the updated ticket in the lkp_helpdesk_ticket_get shape. ON SUCCESS WITH category_id, READ meta: since 2.16 it carries opportunity_action and quotes_archived (an integer) \u2014 what the recategorization did to the CRM. opportunity_action has FOUR values, and spec and code now say the same (\xA78.8, errata 2026-08-20 \u2014 the spec absorbed this MCP's live measurement): 'archived' (the ticket LEFT the improvement category and its opportunity was archived, quotes_archived counting the proposals that went with it), 'created' (the ticket ENTERED the improvement category and an opportunity was created for it), 'skipped_gate_off' (entered improvement but the client's improvement flow is disabled, so only the category changed), and null (no CRM effect). A fifth outcome hides behind the gate: gate ON but the improvement config incomplete (no account manager, or no improvement B1 code) aborts the WHOLE move with 422 validation_failed \u2014 nothing is left half-migrated, not even the category change. THE WHOLE meta BLOCK IS ABSENT when the PATCH did not carry category_id; it does not arrive as {}. That is the ONE documented exception to this API's rule that every key is always present, so test for the block before reading the fields, and never read a missing block as 'nothing was archived'. When the block IS there, it is the authoritative account of the side effect \u2014 do not re-read the opportunity to find out what happened. Requires the write:helpdesk scope. Confirm the change with the user before calling \u2014 especially the full tag list. " + SLA_DEADLINES_DOC,
2682
+ description: "Update whitelisted fields on a helpdesk ticket: status_id, status_comment, priority (low|medium|high|critical), assigned_to, category_id, tags and sap_environment_id (int, or null to clear \u2014 the environment must belong to the ticket's client, otherwise 422 validation_failed). tags REPLACES the ticket's whole tag set, it does not merge: send the complete list of tag IDs the ticket should end up with, and note that tags: [] wipes every tag. recategorize_reason is REQUIRED whenever category_id is sent, and note the exact name \u2014 it is recategorize_reason HERE and plain `reason` on the dedicated route, a difference that costs a 422 if crossed. PREFER lkp_helpdesk_ticket_recategorize WHENEVER THE CATEGORY IS THE ONLY THING CHANGING, but only as a matter of intent now, not of information: since API contract 2.16 this PATCH RETURNS THE RECATEGORIZATION SERVICE'S OWN error.code and HTTP status, exactly as the dedicated route does. A 403 forbidden (you are not the ticket's Gestor do Projeto), a 404 not_found, a 422 validation_failed, a 409 converted (the opportunity already became a project) and a 409 proposal_exists each arrive here as themselves. DO NOT REPEAT A FAILED CALL THROUGH THE DEDICATED TOOL TO LEARN THE REAL CODE \u2014 you already have it, and the retry only asks the backend the same question twice. Against a server older than 2.16 those five collapse into 422 patch_failed instead; read error.code and treat patch_failed as 'the reason was not reported', never as a specific diagnosis. patch_failed also survives on 2.16 as the fallback for the service's catch-all path, which can return a null code, and for the OTHER sub-operations of this PATCH \u2014 status, priority and assignment return only {success, message} to the backend, so there is no code to pass through and patch_failed is all the information that exists. Changing the category is also NOT a metadata edit: read the side effects on lkp_helpdesk_ticket_recategorize before sending category_id from here, because they are identical and they move commercial state. status_comment (API contract 2.13) is the REASON for a status change, and THE CLIENT READS IT on the ticket \u2014 it is a public message signed by the agent, never an internal note, and it can count as the SLA first response. It only travels with status_id: sent alone it is 422 validation_failed with details.status_comment='requires status_id', and this tool rejects that combination before the call. Leaving the 'Em Atendimento' status REQUIRES it \u2014 without it the backend answers 422 patch_failed explaining that the client has to know what happened; that rule depends on the ticket's CURRENT status, which this tool does not know, so it is never second-guessed here: send the change and read the backend's answer. Note the exact name: status_comment, NOT comment \u2014 comment is the field name in the SPA form and the API rejects it with 422 field_not_allowed. Show the user the exact status_comment text and wait for approval before calling, the same as for a comment body: it reaches the client. Fields outside the whitelist (client_id, project_id, ticket_number, created_at and any sla_*) are rejected by the backend with 422 field_not_allowed and are not accepted here \u2014 since API contract 2.9 that error carries error.details.field naming the offending key, so read details.field and fall back to parsing error.message (\"Field 'X' cannot be patched.\") only for older servers. A malformed JSON body is 400 invalid_body. Returns the updated ticket in the lkp_helpdesk_ticket_get shape. ON SUCCESS WITH category_id, READ meta: since 2.16 it carries opportunity_action and quotes_archived (an integer) \u2014 what the recategorization did to the CRM. opportunity_action has FOUR values, and spec and code now say the same (\xA78.8, errata 2026-08-20 \u2014 the spec absorbed this MCP's live measurement): 'archived' (the ticket LEFT the improvement category and its opportunity was archived, quotes_archived counting the proposals that went with it), 'created' (the ticket ENTERED the improvement category and an opportunity was created for it), 'skipped_gate_off' (entered improvement but the client's improvement flow is disabled, so only the category changed), and null (no CRM effect). A fifth outcome hides behind the gate: gate ON but the improvement config incomplete (no account manager, or no improvement B1 code) aborts the WHOLE move with 422 validation_failed \u2014 nothing is left half-migrated, not even the category change. THE WHOLE meta BLOCK IS ABSENT when the PATCH did not carry category_id; it does not arrive as {}. That is the ONE documented exception to this API's rule that every key is always present, so test for the block before reading the fields, and never read a missing block as 'nothing was archived'. When the block IS there, it is the authoritative account of the side effect \u2014 do not re-read the opportunity to find out what happened. Requires the write:helpdesk scope. " + TICKET_ATTENDANT_DOC + ` THE FOUR SUB-OPERATIONS OF THIS PATCH DO NOT SHARE ONE RULER, so a 403 tells you which group you touched, not that the ticket is closed to you. status_id, priority and assigned_to (movement) need the ATTENDANT ruler above, and their 403 forbidden carries error.details.fields listing which of the three you actually sent (e.g. {"fields":["status_id"]}) \u2014 the gate runs BEFORE any mutation, so NOTHING was applied and resending the same PATCH without those fields is a legitimate retry, not a duplicate. tags and sap_environment_id ride a WIDER ruler (userHasTicketAccess: administrator, helpdesk agent, a manager who manages OR IS A MEMBER of the project, or assigned_to), so they can succeed on a ticket you cannot move. category_id rides a NARROWER one (administrator or the strict Gestor do Projeto \u2014 A HELPDESK AGENT DOES NOT PASS HERE even though the same agent moves the ticket freely). All three refuse with 403 forbidden. RESENDING THE CURRENT status_id IS NO LONGER AN ERROR, AND THAT IS A TRAP FOR RETRY LOGIC (changed in API contract 2.18). It used to be 422; today it answers 200 as an idempotent no-op \u2014 no history row, no status email, no task sync, no re-stamping of sla_resolved_at \u2014 and the 200 DOES NOT SAY whether anything moved, because the backend distinguishes the no-op internally and does not publish it. But if status_comment travels with that no-op, THE COMMENT IS PUBLISHED TO THE CLIENT'S THREAD anyway, with no transition recorded in the history. So code that used to re-send this PATCH after a 422 now writes a client-visible message every time it runs. There is a 60-second same-text deduplication on that branch only \u2014 never design a retry that relies on it. To confirm that a status change actually happened, re-read the ticket; do not infer it from the 200. THREE SIDE EFFECTS OF status_id THAT THE TOOL NAME DOES NOT SUGGEST. (1) IT MOVES THE TICKET'S TASKS. changeStatus calls syncTaskStatus, which reads an ADMIN-EDITABLE MATRIX (helpdesk_status_matrix, direction ticket_to_task) at the row of the ticket's new status and the column of each active task's current status \u2014 root task and subtasks alike; an empty cell means 'leave it alone', and entering or leaving Conclu\xEDda stamps and clears completed_at. This direction is NOT gated by any setting: it always runs. The matrix is configuration, not contract \u2014 DO NOT reproduce it here, not even to give a nicer message \u2014 and the PATCH response carries no trace of where the tasks went, so read them with lkp_task_get when it matters. (2) MOVING THE TICKET TO 4 (Aguardando Homologa\xE7\xE3o) OR 10 (Aguardando Resposta) EMAILS THE CLIENT \u2014 'the delivery is released, confirm the resolution' for 4, and 'the ticket is back with you' for 10. It fires through ANY path (manual, matrix or this API) and THE API EXPOSES NO WAY TO SUPPRESS IT. (3) Entering 4 stamps sla_resolved_at, and leaving 4 for a non-closed status CLEARS IT BACK TO NULL. TWO REFUSALS THAT DEPEND ON THE TICKET'S CURRENT STATUS, both 422 patch_failed, and neither is second-guessed here because this tool does not know that status: leaving 'Em Atendimento' (3) REQUIRES status_comment, and leaving 3 towards 4, 5 or 10 REQUIRES a time entry on the ticket's task. The set of manual transitions the backend accepts is the backend's (HelpdeskTicket::ALLOWED_TRANSITIONS, rewritten in 2.18) and is deliberately NOT mirrored here \u2014 send the change and read the answer. Note also that the AUTOMATIC moves (the matrix) do not go through that list, so you can legitimately OBSERVE a ticket in a transition you could not have REQUESTED. Confirm the change with the user before calling \u2014 especially the full tag list, and especially any status_id, which is the field that emails the client and moves the tasks. ` + SLA_DEADLINES_DOC,
2440
2683
  inputSchema: {
2441
2684
  ticket_id: z12.coerce.number().int().positive(),
2442
2685
  status_id: z12.coerce.number().int().positive().optional(),
@@ -2479,7 +2722,7 @@ function registerHelpdesk(server, client, logger) {
2479
2722
  "lkp_helpdesk_ticket_recategorize",
2480
2723
  {
2481
2724
  title: "Recategorize helpdesk ticket (write)",
2482
- description: "Move a helpdesk ticket to another category, when that is the WHOLE operation. Both category_id and reason are required \u2014 note the field is `reason` here, NOT the recategorize_reason of lkp_helpdesk_ticket_update; crossing the two names is a 422. THIS IS NOT A METADATA EDIT, in either direction. Moving a ticket OUT OF the improvement category moves commercial state, in one transaction: the associated CRM opportunity is ARCHIVED, ALL of its quotes are archived with it (drafts and sent ones alike), and the ticket is returned to the client's default project with its SLA reassigned and its status reset to NOVO, taking its task tree along. None of that is reversible from this API. So state the consequences to the user and get explicit approval BEFORE calling \u2014 naming the opportunity and how many quotes it carries, which you can read with lkp_opportunity_quotes_list. Moving a ticket INTO the improvement category moves state too: when the client's improvement flow is enabled, an opportunity is CREATED for the ticket and the ticket migrates to the improvement project with its SLA reset and status back to NOVO (when the flow is disabled, only the category changes \u2014 meta says which happened). Two of the refusals exist precisely to stop that damage and must be reported, not worked around: 409 converted means the opportunity already became a project and the recategorization is refused outright; 409 proposal_exists means there is at least one non-draft (sent) quote and the caller is not an administrator \u2014 the backend also notifies the commercial team that the attempt was blocked. Neither is a retry: a 409 proposal_exists needs an admin to decide, and treating it as a transient error means asking someone to destroy a sent proposal. AUTHORIZATION IS NARROWER THAN THE SCOPE SUGGESTS. write:helpdesk is necessary and not sufficient: only an administrator or the ticket's Gerente Respons\xE1vel (the strict manager_id) may recategorize, and being a manager of something else grants nothing. Refused as 403 forbidden \u2014 distinct from 403 insufficient_scope, which means the token lacks write:helpdesk. The scope is checked first, so fixing the scope on the wrong person's token only changes the message to forbidden. Other outcomes: 404 not_found for an unknown ticket, 422 validation_failed when the target category is inactive, does not exist, or IS ALREADY THE TICKET'S CATEGORY \u2014 the backend refuses a no-op rather than reporting a success that changed nothing. A fifth outcome hides behind the gate (\xA78.8, errata 2026-08-20): moving INTO improvement with the gate ON but the improvement config incomplete (no account manager, or no improvement B1 code) aborts the WHOLE move with 422 validation_failed \u2014 nothing is left half-migrated, not even the category change. PREFER THIS TOOL OVER lkp_helpdesk_ticket_update WHEN THE CATEGORY IS THE WHOLE OPERATION \u2014 for the clarity of the errors, not because the PATCH loses them: since API contract 2.16 both routes return this service's own code and status. READ meta ON SUCCESS. It is always present on this route (recategorizing is all it does) and carries opportunity_action and quotes_archived (an integer) \u2014 the CRM side effect, reported by the service that performed it. opportunity_action has FOUR values (spec and code say the same \u2014 \xA78.8, errata 2026-08-20), one per direction of the move: 'archived' means the ticket LEFT the improvement category and its opportunity was archived with quotes_archived proposals \u2014 the destructive case, so quote it back to the user ('the opportunity was archived along with N proposals'); 'created' means the ticket ENTERED the improvement category and an opportunity was CREATED for it, with the ticket moved to the client's improvement project, its SLA reset and status back to NOVO; 'skipped_gate_off' means it entered improvement but the client's improvement flow is disabled, so only the category changed and no opportunity exists \u2014 do not go looking for one; null means the move touched no CRM state at all. null with quotes_archived 0 is a real, meaningful answer, not an omission. DO NOT re-read the opportunity to find out what happened \u2014 the answer is in this response, and a follow-up read cannot tell you what THIS call did. Against a server older than 2.16 the block is absent; only then is a re-read the way to check. RETURNS THE UPDATED TICKET IN THE SAME SHAPE AS AN ITEM OF lkp_helpdesk_tickets_list, not the detail shape \u2014 this route emits the LIST item even though it acts on one ticket. So project carries only {id} (there is no project.name to print), and description, comments_count, attachments, linked_task, sap_environment (the resolved object; the raw sap_environment_id IS here), contact.email/phone and csat are absent from this response \u2014 'every documented key is always present' is a promise of the DETAIL, and reading those keys off this payload finds nothing. When you need any of them after recategorizing, re-read the ticket with lkp_helpdesk_ticket_get; do not conclude the recategorization erased them. The full sla block, deadlines included, DOES travel here. " + SLA_DEADLINES_DOC,
2725
+ description: "Move a helpdesk ticket to another category, when that is the WHOLE operation. Both category_id and reason are required \u2014 note the field is `reason` here, NOT the recategorize_reason of lkp_helpdesk_ticket_update; crossing the two names is a 422. THIS IS NOT A METADATA EDIT, in either direction. Moving a ticket OUT OF the improvement category moves commercial state, in one transaction: the associated CRM opportunity is ARCHIVED, ALL of its quotes are archived with it (drafts and sent ones alike), and the ticket is returned to the client's default project with its SLA reassigned and its status reset to NOVO, taking its task tree along. None of that is reversible from this API. So state the consequences to the user and get explicit approval BEFORE calling \u2014 naming the opportunity and how many quotes it carries, which you can read with lkp_opportunity_quotes_list. Moving a ticket INTO the improvement category moves state too: when the client's improvement flow is enabled, an opportunity is CREATED for the ticket and the ticket migrates to the improvement project with its SLA reset and status back to NOVO (when the flow is disabled, only the category changes \u2014 meta says which happened). Two of the refusals exist precisely to stop that damage and must be reported, not worked around: 409 converted means the opportunity already became a project and the recategorization is refused outright; 409 proposal_exists means there is at least one non-draft (sent) quote and the caller is not an administrator \u2014 the backend also notifies the commercial team that the attempt was blocked. Neither is a retry: a 409 proposal_exists needs an admin to decide, and treating it as a transient error means asking someone to destroy a sent proposal. AUTHORIZATION IS NARROWER THAN THE SCOPE SUGGESTS, ON BOTH DOORS. " + WRITE_SCOPE_LITERAL_DOC + "The role door is narrower still: write:helpdesk is necessary and not sufficient \u2014 only an administrator or the ticket's Gestor do Projeto (the strict manager_id) may recategorize, and being a manager of something else grants nothing. Refused as 403 forbidden \u2014 distinct from 403 insufficient_scope, which means the token lacks the scope. The scope is checked first, so fixing the scope on the wrong person's token only changes the message to forbidden. Other outcomes: 404 not_found for an unknown ticket, 422 validation_failed when the target category is inactive, does not exist, or IS ALREADY THE TICKET'S CATEGORY \u2014 the backend refuses a no-op rather than reporting a success that changed nothing. A fifth outcome hides behind the gate (\xA78.8, errata 2026-08-20): moving INTO improvement with the gate ON but the improvement config incomplete (no account manager, or no improvement B1 code) aborts the WHOLE move with 422 validation_failed \u2014 nothing is left half-migrated, not even the category change. PREFER THIS TOOL OVER lkp_helpdesk_ticket_update WHEN THE CATEGORY IS THE WHOLE OPERATION \u2014 for the clarity of the errors, not because the PATCH loses them: since API contract 2.16 both routes return this service's own code and status. READ meta ON SUCCESS. It is always present on this route (recategorizing is all it does) and carries opportunity_action and quotes_archived (an integer) \u2014 the CRM side effect, reported by the service that performed it. opportunity_action has FOUR values (spec and code say the same \u2014 \xA78.8, errata 2026-08-20), one per direction of the move: 'archived' means the ticket LEFT the improvement category and its opportunity was archived with quotes_archived proposals \u2014 the destructive case, so quote it back to the user ('the opportunity was archived along with N proposals'); 'created' means the ticket ENTERED the improvement category and an opportunity was CREATED for it, with the ticket moved to the client's improvement project, its SLA reset and status back to NOVO; 'skipped_gate_off' means it entered improvement but the client's improvement flow is disabled, so only the category changed and no opportunity exists \u2014 do not go looking for one; null means the move touched no CRM state at all. null with quotes_archived 0 is a real, meaningful answer, not an omission. DO NOT re-read the opportunity to find out what happened \u2014 the answer is in this response, and a follow-up read cannot tell you what THIS call did. Against a server older than 2.16 the block is absent; only then is a re-read the way to check. RETURNS THE UPDATED TICKET IN THE SAME SHAPE AS AN ITEM OF lkp_helpdesk_tickets_list, not the detail shape \u2014 this route emits the LIST item even though it acts on one ticket. So project carries only {id} (there is no project.name to print), and description, comments_count, attachments, linked_task, sap_environment (the resolved object; the raw sap_environment_id IS here), contact.email/phone and csat are absent from this response \u2014 'every documented key is always present' is a promise of the DETAIL, and reading those keys off this payload finds nothing. When you need any of them after recategorizing, re-read the ticket with lkp_helpdesk_ticket_get; do not conclude the recategorization erased them. The full sla block, deadlines included, DOES travel here. " + SLA_DEADLINES_DOC,
2483
2726
  inputSchema: {
2484
2727
  ticket_id: z12.coerce.number().int().positive(),
2485
2728
  category_id: z12.coerce.number().int().positive(),
@@ -3560,126 +3803,6 @@ function registerAllPrompts(server) {
3560
3803
  registerPipelineHealthCheckPrompt(server);
3561
3804
  }
3562
3805
 
3563
- // src/contract.ts
3564
- var EXPECTED_CONTRACT = "2.17";
3565
- function minorOf(version) {
3566
- const [major = "", minor = ""] = version.split(".");
3567
- return { major, minor: Number(minor) };
3568
- }
3569
- function compareContract(serverContract, expected = EXPECTED_CONTRACT) {
3570
- if (serverContract === null) {
3571
- return {
3572
- status: "pre_contract",
3573
- server_contract: null,
3574
- message: `LKPGest\xE3o predates API contract ${expected} (no GET /api/v1/meta). Fields documented by this MCP build may be missing from responses.`
3575
- };
3576
- }
3577
- if (serverContract === expected) {
3578
- return {
3579
- status: "ok",
3580
- server_contract: serverContract,
3581
- message: `API contract ${serverContract} matches this build.`
3582
- };
3583
- }
3584
- const srv = minorOf(serverContract);
3585
- const exp = minorOf(expected);
3586
- if (srv.major !== exp.major) {
3587
- return {
3588
- status: "incompatible",
3589
- server_contract: serverContract,
3590
- message: `Incompatible API contract: server ${serverContract}, this build expects ${expected}. A major bump means a field was removed, renamed or retyped \u2014 tool responses may not match their docstrings.`
3591
- };
3592
- }
3593
- if (Number.isFinite(srv.minor) && Number.isFinite(exp.minor) && srv.minor < exp.minor) {
3594
- return {
3595
- status: "server_older",
3596
- server_contract: serverContract,
3597
- message: `API contract ${serverContract} is older than the ${expected} this build expects. Fields added after ${serverContract} may be absent from responses.`
3598
- };
3599
- }
3600
- return {
3601
- status: "server_newer",
3602
- server_contract: serverContract,
3603
- message: `API contract ${serverContract} is newer than the ${expected} this build expects (additive). New fields exist that this MCP does not document yet.`
3604
- };
3605
- }
3606
- var BLOCKING_STATUSES = /* @__PURE__ */ new Set([
3607
- "pre_contract",
3608
- "incompatible",
3609
- "server_older"
3610
- ]);
3611
- function isStartupBlocked(status, required) {
3612
- return required && BLOCKING_STATUSES.has(status);
3613
- }
3614
- async function enforceContractOnStartup(client, logger, required, expected = EXPECTED_CONTRACT) {
3615
- const result = await checkContractVersion(client, logger, expected);
3616
- if (isStartupBlocked(result.status, required)) {
3617
- logger.fatal(
3618
- {
3619
- expected_contract: expected,
3620
- server_contract: result.server_contract,
3621
- check: result.status,
3622
- require_contract: true
3623
- },
3624
- "refusing to start: LKP_REQUIRE_CONTRACT is on and the API contract does not satisfy this build"
3625
- );
3626
- throw new Error(
3627
- `LKP_REQUIRE_CONTRACT is on and the API contract check returned "${result.status}". ${result.message} Point LKP_API_BASE_URL at a deployment on contract ${expected}, or unset LKP_REQUIRE_CONTRACT to start anyway.`
3628
- );
3629
- }
3630
- return result;
3631
- }
3632
- async function checkContractVersion(client, logger, expected = EXPECTED_CONTRACT) {
3633
- let serverContract;
3634
- try {
3635
- const meta = await client.get("/api/v1/meta");
3636
- const raw = meta?.data?.contract_version;
3637
- if (typeof raw !== "string" || raw === "") {
3638
- const result2 = {
3639
- status: "unavailable",
3640
- server_contract: null,
3641
- message: `GET /api/v1/meta answered without a contract_version string.`
3642
- };
3643
- logger.warn(
3644
- { expected_contract: expected, check: result2.status },
3645
- result2.message
3646
- );
3647
- return result2;
3648
- }
3649
- serverContract = raw;
3650
- } catch (e) {
3651
- if (e instanceof LkpError && e.http_status === 404) {
3652
- serverContract = null;
3653
- } else {
3654
- const err = e instanceof LkpError ? e.toJSON() : { message: String(e) };
3655
- const result2 = {
3656
- status: "unavailable",
3657
- server_contract: null,
3658
- message: `Could not read the API contract version from GET /api/v1/meta.`
3659
- };
3660
- logger.warn(
3661
- { expected_contract: expected, check: result2.status, err },
3662
- result2.message
3663
- );
3664
- return result2;
3665
- }
3666
- }
3667
- const result = compareContract(serverContract, expected);
3668
- const fields = {
3669
- expected_contract: expected,
3670
- server_contract: result.server_contract,
3671
- check: result.status
3672
- };
3673
- if (result.status === "incompatible") {
3674
- logger.error(fields, result.message);
3675
- } else if (result.status === "ok") {
3676
- logger.info(fields, result.message);
3677
- } else {
3678
- logger.warn(fields, result.message);
3679
- }
3680
- return result;
3681
- }
3682
-
3683
3806
  // src/index.ts
3684
3807
  async function main() {
3685
3808
  const config = loadConfig();