lkpgestao-mcp 0.30.0 → 0.31.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/README.md CHANGED
@@ -4,7 +4,7 @@ MCP server for **LKPGestão** — exposes the management API (projects, opportun
4
4
 
5
5
  ## Instalação
6
6
 
7
- > ### ⚠️ A 0.15.x–0.20.x é DEV-only até a release do contrato 2.14 em produção
7
+ > ### ⚠️ A 0.15.x–0.31.x é DEV-only até a release do contrato 4.2 em produção
8
8
  >
9
9
  > Os contratos **2.11** a **2.14** existem hoje só na branch `dev` do backend; a `main` ainda serve **2.10**, e a release do backend leva os quatro de uma vez. Em produção **nem o `GET /api/v1/meta` existe** — os commits que levam o 2.9 em diante, e os do SP-1 de helpdesk, estão todos fora da `main`. Por isso os exemplos abaixo apontam para `lkpgestaodev`.
10
10
  >
@@ -61,7 +61,7 @@ Adicione a entrada `lkpgestao` em `mcpServers`:
61
61
  "mcpServers": {
62
62
  "lkpgestao": {
63
63
  "command": "npx",
64
- "args": ["-y", "lkpgestao-mcp@0.20.1"],
64
+ "args": ["-y", "lkpgestao-mcp@0.31.0"],
65
65
  "env": {
66
66
  "LKP_API_BASE_URL": "https://lkpgestaodev.linkupconsultoria.com",
67
67
  "LKP_API_TOKEN": "<cole o token de /settings/api-tokens>",
@@ -72,7 +72,7 @@ Adicione a entrada `lkpgestao` em `mcpServers`:
72
72
  }
73
73
  ```
74
74
 
75
- > **Sempre pine a versão** (`lkpgestao-mcp@0.20.1`) — veja [Instalação pinada](#instalação-pinada-evite-rodar-uma-versão-defasada). `npx -y lkpgestao-mcp` **sem** versão prefere um binário já presente no `PATH` e pode rodar uma versão antiga silenciosamente.
75
+ > **Sempre pine a versão** (`lkpgestao-mcp@0.31.0`) — veja [Instalação pinada](#instalação-pinada-evite-rodar-uma-versão-defasada). `npx -y lkpgestao-mcp` **sem** versão prefere um binário já presente no `PATH` e pode rodar uma versão antiga silenciosamente.
76
76
 
77
77
  > **Windows**: se o Claude não encontrar o `npx`, troque `"command": "npx"` por `"command": "npx.cmd"`.
78
78
 
@@ -87,7 +87,7 @@ claude mcp add lkpgestao -s user \
87
87
  -e LKP_API_BASE_URL=https://lkpgestaodev.linkupconsultoria.com \
88
88
  -e LKP_API_TOKEN=<seu-token> \
89
89
  -e LKP_LOG_LEVEL=info \
90
- -- npx -y lkpgestao-mcp@0.20.1
90
+ -- npx -y lkpgestao-mcp@0.31.0
91
91
  ```
92
92
 
93
93
  > `-s user` registra o servidor no escopo do usuário (disponível em todos os projetos). Use `-s project` para gravar num `.mcp.json` versionado no repositório, ou omita para o escopo `local` (só neste projeto).
@@ -100,7 +100,7 @@ Incidente real: um `lkpgestao-mcp` **0.7.0** instalado globalmente no `PATH` con
100
100
 
101
101
  Regras para não repetir:
102
102
 
103
- 1. **Pine a versão** em toda configuração: `npx -y lkpgestao-mcp@0.20.1`. Com a versão explícita o `npx` resolve pelo registry e ignora o binário velho do `PATH`.
103
+ 1. **Pine a versão** em toda configuração: `npx -y lkpgestao-mcp@0.31.0`. Com a versão explícita o `npx` resolve pelo registry e ignora o binário velho do `PATH`.
104
104
  2. **Remova instalações globais antigas** — elas são a origem do problema:
105
105
 
106
106
  ```bash
@@ -111,8 +111,8 @@ Regras para não repetir:
111
111
  3. **Confira a versão que está realmente rodando**: a primeira linha de log em stderr (`"starting"`) traz `server_version`. No Claude Desktop / Cowork, veja o log do servidor MCP; no terminal:
112
112
 
113
113
  ```bash
114
- npx -y lkpgestao-mcp@0.20.1 </dev/null
115
- # → {"level":30,...,"server_version":"0.20.1",...,"msg":"starting"}
114
+ npx -y lkpgestao-mcp@0.31.0 </dev/null
115
+ # → {"level":30,...,"server_version":"0.31.0",...,"msg":"starting"}
116
116
  ```
117
117
 
118
118
  4. **Ao subir uma versão nova da API com endpoints novos**, atualize o pin em todos os consumidores no mesmo dia — o casamento endpoint↔tool tem que sair junto.
package/dist/index.js CHANGED
@@ -51,7 +51,7 @@ function mapHttpStatus(status) {
51
51
  }
52
52
 
53
53
  // src/contract.ts
54
- var EXPECTED_CONTRACT = "4.1";
54
+ var EXPECTED_CONTRACT = "4.2";
55
55
  var serverSettings = null;
56
56
  function getServerSettings() {
57
57
  return serverSettings;
@@ -192,7 +192,7 @@ async function checkContractVersion(client, logger, expected = EXPECTED_CONTRACT
192
192
 
193
193
  // src/config.ts
194
194
  var SERVER_NAME = "lkpgestao-mcp";
195
- var SERVER_VERSION = "0.30.0";
195
+ var SERVER_VERSION = "0.31.0";
196
196
  var ConfigSchema = z.object({
197
197
  LKP_API_BASE_URL: z.string().url("must be a valid URL").refine((u) => u.startsWith("https://"), {
198
198
  message: "must use https:// (TLS is mandatory)"
@@ -770,6 +770,7 @@ function assertTagExclusivity(body) {
770
770
  });
771
771
  }
772
772
  }
773
+ var TIMESHEET_BILLABILITY_DOC = `\u{1F534} is_billable, meta.aggregates.billable_hours AND metrics.billed_hours ARE DERIVED, NOT STORED (API contract 4.2), AND THIS CHANGED THEIR ANSWER WITHOUT CHANGING THEIR SHAPE. Until 4.1 they read a column that was constant 0 on every row in production, so 'always false' was accidentally true and no financial rule read them. The column was DROPPED in 4.2; the keys stayed, with the same names and the same types, and now carry the real answer, computed as: the task is NOT exempt from hours measurement AND the project has is_billable = 1 AND its billing_model is 'measurement'. So NEVER cache, assert or hard-code is_billable === false (or billable_hours === 0) as if it were a constant \u2014 measured on the 4.2 server, entries of the SAME consultant in the SAME range come back with BOTH values. An hour is billable ONLY when the project is billed by hours measurement AND its ticket was not exempted (see measurement_exempt on lkp_helpdesk_ticket_update). Hours on a project billed by milestone, installment or subscription are false because that project is not measured by the hour \u2014 false means 'does not count towards an hours measurement', it does NOT mean 'unpaid', 'courtesy' or 'free', and reporting it to a user as unbilled work would be wrong on most of the base. Pre-sales hours (source: 'crm') are exempt by birth. THE ?is_billable= FILTER RUNS THAT SAME EXPRESSION \u2014 it is not a column filter, so it discriminates rather than returning everything or nothing, and it needs the JSON literals true/false, never the strings: "false" as a string would read as true and hand back exactly the opposite set. \u{1F534} IT IS NOT WRITABLE HERE AND NEVER WAS. PATCH .../timesheets/{id} carrying is_billable answers 422 unknown_field (NOT validation_failed) with details.fields naming it \u2014 do not retry, and do not look for another field name. Billability is not per-entry data: the decision lives on the TICKET (PATCH /helpdesk/tickets/{id} with measurement_exempt, Project Manager or admin) or on the project's financial classification. So an entry can never be reported to the user as logged billable or non-billable on the strength of a create or update call \u2014 read it back.`;
773
774
 
774
775
  // src/tools/resources.ts
775
776
  function registerResources(server, client, logger) {
@@ -812,7 +813,7 @@ function registerResources(server, client, logger) {
812
813
  "lkp_resource_history",
813
814
  {
814
815
  title: "Resource allocation history",
815
- description: "Allocation history for one consultant over a date range. Returns per-project periods interleaved with idle gaps, plus metrics (utilization_percent, idle_days, billed_hours, revenue). Default range: last 12 months.",
816
+ description: "Allocation history for one consultant over a date range. Returns per-project periods interleaved with idle gaps, plus metrics (utilization_percent, idle_days, billed_hours, revenue). Default range: last 12 months. " + TIMESHEET_BILLABILITY_DOC,
816
817
  inputSchema: {
817
818
  resource_id: z4.coerce.number().int().positive(),
818
819
  from: z4.string().optional(),
@@ -861,7 +862,7 @@ function registerResources(server, client, logger) {
861
862
  "lkp_resource_timesheets",
862
863
  {
863
864
  title: "Resource timesheet entries",
864
- description: 'Individual timesheet entries for one consultant. Returns line-level detail (date, hours, billable/approved flags, overtime, cost, comments) plus task/project/client. Includes aggregates block. Use for qualitative analysis: anomaly detection, unapproved entries, overtime patterns, weekend work. Range \u2264 184 days; max per_page 200. source is a CLOSED vocabulary \u2014 project|crm, anything else is 400 `invalid_filter`. is_approved and is_billable are STRICT booleans: pass the JSON literals true/false, never the strings, because "false" as a string would read as true and hand back exactly the opposite set of entries.',
865
+ description: "Individual timesheet entries for one consultant. Returns line-level detail (date, hours, billable/approved flags, overtime, cost, comments) plus task/project/client. Includes aggregates block. Use for qualitative analysis: anomaly detection, unapproved entries, overtime patterns, weekend work. Range \u2264 184 days; max per_page 200. source is a CLOSED vocabulary \u2014 project|crm, anything else is 400 `invalid_filter`. is_approved is a STRICT boolean: pass the JSON literals true/false, never the strings. " + TIMESHEET_BILLABILITY_DOC,
865
866
  inputSchema: {
866
867
  resource_id: z4.coerce.number().int().positive(),
867
868
  from: z4.string(),
@@ -893,7 +894,7 @@ function registerTimesheets(server, client, logger) {
893
894
  "lkp_timesheet_create",
894
895
  {
895
896
  title: "Create timesheet entry (write)",
896
- description: "Log a new timesheet entry for a consultant. `task_id` is REQUIRED and is the key to everything else: the project, the \"Em Execu\xE7\xE3o\" status check, the estimated-hours cap and the earliest allowed work_date are all derived from the task, and only tasks the RESOURCE may log on are accepted \u2014 anything else is 403 `forbidden`. `comments` is required (LKPGest\xE3o rule: no entry without a comment). The project and the normal/overtime hour breakdown are computed server-side and are not accepted as input; the BILLABLE flag is the backend's too \u2014 it is decided by LKPGest\xE3o's billing recalculation, there is no field for it here, and an entry must never be reported to the user as logged billable or non-billable on the strength of this call. `is_approved: true` creates an ALREADY-APPROVED entry and is ADMINISTRATOR-ONLY: every other role gets 403 `forbidden` telling you to create it first and approve afterwards, which is the normal path (lkp_timesheet_update). Prefer that path even as an admin, because an approved entry can no longer be edited or deleted through this API. `source` is project|crm (default project) and records where the entry ORIGINATED \u2014 omit it for ordinary project work: an entry on a project task written as 'crm' drops out of the consultant's allocation history and real-utilisation figures, which read source='project'. All other rules \u2014 period/payroll lock, hours increments and daily cap, task status, estimated-hours cap, date window \u2014 are enforced by LKPGest\xE3o and returned as errors; read error.code, never the prose. Routes resource_id into the URL.",
897
+ description: "Log a new timesheet entry for a consultant. `task_id` is REQUIRED and is the key to everything else: the project, the \"Em Execu\xE7\xE3o\" status check, the estimated-hours cap and the earliest allowed work_date are all derived from the task, and only tasks the RESOURCE may log on are accepted \u2014 anything else is 403 `forbidden`. `comments` is required (LKPGest\xE3o rule: no entry without a comment). The project and the normal/overtime hour breakdown are computed server-side and are not accepted as input; the BILLABLE flag is not input either \u2014 there is no field for it here. `is_approved: true` creates an ALREADY-APPROVED entry and is ADMINISTRATOR-ONLY: every other role gets 403 `forbidden` telling you to create it first and approve afterwards, which is the normal path (lkp_timesheet_update). Prefer that path even as an admin, because an approved entry can no longer be edited or deleted through this API. `source` is project|crm (default project) and records where the entry ORIGINATED \u2014 omit it for ordinary project work: an entry on a project task written as 'crm' drops out of the consultant's allocation history and real-utilisation figures, which read source='project'. All other rules \u2014 period/payroll lock, hours increments and daily cap, task status, estimated-hours cap, date window \u2014 are enforced by LKPGest\xE3o and returned as errors; read error.code, never the prose. Routes resource_id into the URL. " + TIMESHEET_BILLABILITY_DOC,
897
898
  inputSchema: {
898
899
  resource_id: z5.coerce.number().int().positive(),
899
900
  work_date: z5.string(),
@@ -917,7 +918,7 @@ function registerTimesheets(server, client, logger) {
917
918
  "lkp_timesheet_update",
918
919
  {
919
920
  title: "Update timesheet entry (write)",
920
- description: "Edit a timesheet entry. If `comments` is sent it must be non-empty (the comment can never be blanked out). The normal/overtime hour breakdown is recalculated server-side and is not accepted as input; the BILLABLE flag is not editable through this API either \u2014 it belongs to LKPGest\xE3o's billing recalculation and there is no field for it here. `is_approved: true` is NOT a field edit, it is a STANDALONE GOVERNED APPROVAL: the call is routed to the approval action (B1-code gate, approved_by/approved_at, audit log) and RETURNS THERE, so work_date/hours/comments/task_id sent in the same body are discarded in silence. Send an approval ALONE, never bundled with an edit, and expect 403 `forbidden` when the token owner may not approve that entry or 422 `validation_failed` when the B1-code gate refuses it; once it succeeds the entry is immutable and undeletable. `is_approved: false` does NOT unapprove anything \u2014 this API has no unapprove, so a false is a no-op on the approval state while the rest of the PATCH still runs. Approved entries cannot be edited and the backend rejects edits that violate any LKPGest\xE3o rule; those errors are surfaced as-is \u2014 read error.code, never the prose. Routes resource_id and timesheet_id into the URL.",
921
+ description: "Edit a timesheet entry. If `comments` is sent it must be non-empty (the comment can never be blanked out). The normal/overtime hour breakdown is recalculated server-side and is not accepted as input. `is_approved: true` is NOT a field edit, it is a STANDALONE GOVERNED APPROVAL: the call is routed to the approval action (B1-code gate, approved_by/approved_at, audit log) and RETURNS THERE, so work_date/hours/comments/task_id sent in the same body are discarded in silence. Send an approval ALONE, never bundled with an edit, and expect 403 `forbidden` when the token owner may not approve that entry or 422 `validation_failed` when the B1-code gate refuses it; once it succeeds the entry is immutable and undeletable. `is_approved: false` does NOT unapprove anything \u2014 this API has no unapprove, so a false is a no-op on the approval state while the rest of the PATCH still runs. Approved entries cannot be edited and the backend rejects edits that violate any LKPGest\xE3o rule; those errors are surfaced as-is \u2014 read error.code, never the prose. Routes resource_id and timesheet_id into the URL. " + TIMESHEET_BILLABILITY_DOC,
921
922
  inputSchema: {
922
923
  resource_id: z5.coerce.number().int().positive(),
923
924
  timesheet_id: z5.coerce.number().int().positive(),
@@ -2571,6 +2572,8 @@ var SapEnvironmentFilter = z12.union([
2571
2572
  z12.string().regex(/^[1-9]\d*$/).transform((v) => Number(v))
2572
2573
  ]);
2573
2574
  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.";
2575
+ var MEASUREMENT_EXEMPT_DOC = "measurement_exempt (API contract 4.2) IS A BOOLEAN AND IS NEVER OMITTED \u2014 it carries false, never null and never 0/1, so its ABSENCE means the server is OLDER than 4.2, never 'this ticket has no exemption'. It says the Project Manager declared that THIS TICKET WILL NOT HAVE ITS HOURS MEASURED (the case it was built for: a defect in a LINKUP product handled inside the client's AMS). \u{1F534} IT IS NOT A LABEL ON THE TICKET \u2014 IT IS THE SWITCH THAT ANSWERS FOR THE HOURS. The mark descends the ticket's WHOLE TASK TREE, and from there every timesheet entry on those tasks reports is_billable: false (\xA74.4 \u2014 the same expression feeds billable_hours, billed_hours and the ?is_billable= filter). So a true here means the hours logged under this ticket stop counting towards the project's hours measurement; read as cosmetic metadata it loses exactly the financial consequence that is its whole point. To CHANGE it, see lkp_helpdesk_ticket_update, which is the only route that writes it and has a narrower door than the rest of that PATCH.";
2576
+ var MEASUREMENT_EXEMPT_WRITE_DOC = `\u{1F534} measurement_exempt (API contract 4.2) IS THE 9TH FIELD OF THIS PATCH AND THE ONE WHOSE NAME HIDES THE MOST. Setting it true does FOUR things, and only the first is about this ticket: (1) it marks the ticket; (2) IT PUSHES THE MARK DOWN THE WHOLE TASK TREE \u2014 the service reports how many tasks it touched; (3) EVERY TIMESHEET ENTRY ON THOSE TASKS FLIPS TO is_billable: false, because \xA74.4 derives billability from this very flag, so this is a FINANCIAL write, not a metadata edit; (4) it writes both task_history and the ticket's history under the token owner's authorship. Say all of that to the user and get approval BEFORE calling \u2014 the tool name promises an 'update' and delivers a change in what the client is billed for. \u{1F534} MARKING AND UNMARKING ARE NOT SYMMETRIC, AND THIS IS THE TRAP. Turning it ON is validated against the project's billing model: if the ticket's project is not billed by hours measurement (is_billable = 1 AND billing_model = 'measurement') the call is 422 validation_failed with details.field = 'measurement_exempt' (SINGULAR) \u2014 there is no measurement to exempt it from. Turning it OFF is ALWAYS allowed to whoever holds the door, on any project, by design: a recategorization can carry an exempt ticket onto a project billed by milestone, and a symmetric 422 would strand the flag there with no way out. So NEVER infer one direction from the other, and never treat a 422 on true as a reason not to try false. \u{1F534} THIS FIELD HAS ITS OWN DOOR, NARROWER THAN EVERY OTHER FIELD OF THIS PATCH AND NOT THE ATTENDANT RULER. It is Authz::canManageProject: the STRICT projects.manager_id of the ticket's project, or an administrator. A HELP DESK AGENT DOES NOT PASS HERE even though the same agent moves, assigns and comments on the ticket freely \u2014 measured on the 4.2 server, where an agent who is not the manager gets 403. Being a MEMBER of the project grants nothing either. THREE REFUSALS SHARE THE 403 AND MEAN OPPOSITE THINGS \u2014 DISCRIMINATE, DO NOT RETRY: error.code 'insufficient_scope' means the TOKEN lacks write:helpdesk (another token fixes it, another person does not); error.code 'forbidden' WITH details.fields = ['measurement_exempt'] (PLURAL, a list) is this role door \u2014 the person is not the Project Manager nor an admin, so another PERSON fixes it and no token will; error.code 'forbidden' WITHOUT details.fields is the outer access door (userHasTicketAccess) \u2014 the caller cannot reach this ticket at all, and never got as far as the field. Branch on error.code plus the presence of details.fields, never on the message. Note the shape difference that tells the two gates apart everywhere here: details.fields (plural, list) is the ROLE gate, details.field (singular, string) is the service's own validation. THE VALUE IS A STRICT BOOLEAN ON BOTH SIDES. This tool rejects anything else before the call, and so does the backend: 1 (integer) and "true" (string) each come back 422 validation_failed with details.measurement_exempt = 'must be a boolean'. Never send the string spellings. READ meta.warnings[] ON SUCCESS \u2014 ITS PRESENCE IS SEMANTIC, NOT DECORATION. When the PATCH TOUCHED this field, meta.warnings is ALWAYS there, as an EMPTY LIST when there is nothing to warn about; when the PATCH did not touch it, the key is ABSENT. That is how you tell 'no warning' from 'the field was not written' without guessing from an absence. Each element is {code, hours, measurements, message} and code has exactly TWO values: 'hours_already_measured' \u2014 hours on those tasks are ALREADY LINKED TO A SENT OR APPROVED MEASUREMENT and are NEVER removed by this flag, so the past did not undo itself and someone has to decide what to do about it; and 'draft_measurement_needs_recalc' \u2014 a DRAFT measurement covers those hours and has to be recalculated. Both mean THE OPERATION SUCCEEDED AND A HUMAN STILL HAS TO LOOK: report them to the user verbatim, with the hours, instead of reporting a clean 200. `;
2574
2577
  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.";
2575
2578
  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 11 keys: {phase, rule, due_at, met_at, breached, open, granularity, label, cycle_no, reopened_at, reopen_reason} \u2014 the last three were born in API contract 4.1 and are NEVER OMITTED: they carry null when they do not apply, so their ABSENCE means the server is OLDER than 4.1 and never 'this ticket has no cycles'. \u{1F534} FROM 4.1 deadlines[] CAN CARRY MORE THAN ONE ENTRY WITH THE SAME phase, AND THIS IS THE ONE CHANGE THAT BREAKS A CLIENT THAT IGNORES IT. An SLA that hit its target closes as 'Met' and NEVER reopens; a return by the client instantiates a NEW cycle with a new deadline, and both records LIVE TOGETHER on the ticket (before 4.1 the old one was destroyed, which is the defect 4.1 fixed). So NEVER SELECT AN ENTRY BY phase ALONE \u2014 deadlines.find(d => d.phase === 'delivery') reads an ARBITRARY entry on a returned ticket, with no error and no symptom, because the frozen one comes FIRST. Branch on cycle_no: THE RUNNING CYCLE IS THE HIGHEST cycle_no AMONG THE ENTRIES WITH reopened_at === null. cycle_no is int or null, and it is null ON THE 'response' PHASE, which is not a cycle (null there, never 0). reopened_at (when the client returned that delivery) and reopen_reason (why) are filled ONLY on a CLOSED cycle's entry and are null on the running one. WHICH PHASE MULTIPLIES DEPENDS ON THE TICKET KIND, so do not guard only 'delivery': cycles are emitted on 'resolution' with rule 'sla_policy' for an AMS ticket AND on 'delivery' with rule 'task_tree' for an improvement \u2014 measured on the 4.1 server, where the AMS case is the one carrying four resolution entries. AN ENTRY WITH reopened_at FILLED IS FROZEN HISTORY: its breached and met_at describe a cycle that already ended and are NEVER recomputed, so a breached: true THERE DOES NOT MEAN THE TICKET IS LATE TODAY. Reporting 'SLA breached' off a frozen entry is exactly the bug 4.1 removed from the screen \u2014 do not reintroduce it through this API; answer 'is it late?' from the running cycle only. reopened_at is 'YYYY-MM-DD HH:MM:SS' in -03 like every other stamp in this API, NOT ISO-8601 with a zone, so never hand it to new Date() expecting UTC. WHAT 4.1 DID NOT CHANGE, so you do not 'fix' what works: the 8 older keys keep shape, type and value; the array order still follows the ticket's life (oldest \u2192 newest) and deadlines[0] IS STILL THE RESPONSE PHASE; granularity 'date' still falls due at the END of the day; and the open COUNT rule below is untouched, because a closed-cycle entry always carries met_at and is therefore open: false by construction. FINALLY, reopened_count IS NOT THE DISCRIMINATOR FOR 'does this ticket have several cycles?' \u2014 measured on the 4.1 DEV server, tickets with reopened_count: 1 whose reopens predate 4.1 carry a SINGLE entry, while tickets carrying four cycle entries report reopened_count: 0. Count the entries of the phase, never the counter. phase has THREE values \u2014 'response', 'resolution', 'delivery' \u2014 never two: 'delivery' appears only on an improvement and never on an AMS ticket, so a consumer that assumes response|resolution will reject real payloads months later. WHETHER 'delivery' NEEDS A RECORDED ACCEPTANCE DEPENDS ON THE FLOW (API contract 3.0): INSIDE the commercial flow \u2014 the ticket sits in the client's improvements project, so a proposal exists \u2014 the phase also requires a recorded acceptance (quote_accepted in the ticket history; a root task alone does not prove it, because adoption/backfill preserves a pre-existing task), since promising a date before the client approves would be a commitment nobody made. OUTSIDE it \u2014 an improvement CATEGORY ticket handled in the AMS project \u2014 there is no proposal at all, so the phase appears with no acceptance; requiring one would leave those tickets permanently without a deadline. Do not read a 'delivery' entry as proof that the client accepted a proposal. 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) carry 'response' + 'resolution', both rule 'sla_policy', both granularity 'datetime', with due_at null when no policy applies \u2014 the array is never empty there. \u{1F534} THAT USED TO BE 'EXACTLY 2 ENTRIES' AND IS NO LONGER: from 4.1 an AMS ticket whose delivery was returned carries one FROZEN 'resolution' entry per closed cycle plus the running one, so 2 is the MINIMUM, not the count (four resolution entries measured on one DEV ticket). Count what arrived; never hard-code the length. WHICH KIND IS THIS TICKET? NEVER RE-DERIVE IT \u2014 READ rule AND granularity, WHICH THE SERVER ALREADY RESOLVED. This is the MAJOR change in API contract 3.0 and it changed no key, no type and no value set, only which ticket falls under which ruler: a ticket counts as an improvement when it is in the improvement CATEGORY ('Solicita\xE7\xE3o de Melhoria') OR in the client's improvements PROJECT \u2014 either one is enough. Until 2.24 the project alone decided, so inferring 'improvement <=> ticket is in the improvements project' was ACCIDENTALLY right; from 3.0 it is wrong for a measured population (47 tickets in PRD, 50 in DEV) \u2014 improvements handled inside the AMS project, moved there by the 'Mover para AMS' button or opened for a client with improvement_enabled = 0. Those publish 'improvement_business_days' while sitting in an AMS project, and can carry a 'delivery' entry with a bare date. sla.policy_id SURVIVES on them and is NOT read by the new ruler \u2014 it records which ruler governed the ticket before, so derive nothing from it. 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. FINALLY, DO NOT TURN breached: true INTO ALARM LANGUAGE ON A CLOSED IMPROVEMENT. The 'response' phase reads a STORED column (sla_response_due_at / sla_response_breached), stamped when the ticket was written, whereas the 'delivery' phase is derived at read time and corrected itself. The backend's 3.0 data-fix only recomputes OPEN tickets \u2014 closed history is a record, not a live indicator, and it will NEVER be corrected (40 of the 47 affected tickets in PRD are closed). So an entry with rule 'improvement_business_days' on a ticket whose status.is_closed is true can carry a due_at measured against the RETIRED AMS ruler, and a breached: true that the improvement ruler would not have produced. The value is the server reporting faithfully what it stored, so never suppress or recompute it \u2014 but when status.is_closed is true and rule is not 'sla_policy', report it as recorded history ('recorded as breached against the SLA ruler in force at the time'), never as 'this ticket missed its deadline'.";
2576
2579
  function assertSapEnvironmentFilter(value) {
@@ -2613,7 +2616,7 @@ function registerHelpdesk(server, client, logger) {
2613
2616
  "lkp_helpdesk_tickets_list",
2614
2617
  {
2615
2618
  title: "List helpdesk tickets",
2616
- 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,
2619
+ 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 + " " + MEASUREMENT_EXEMPT_DOC,
2617
2620
  inputSchema: {
2618
2621
  status_id: z12.coerce.number().int().positive().optional(),
2619
2622
  priority: z12.string().optional(),
@@ -2650,7 +2653,7 @@ function registerHelpdesk(server, client, logger) {
2650
2653
  "lkp_helpdesk_ticket_get",
2651
2654
  {
2652
2655
  title: "Helpdesk ticket detail",
2653
- 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,
2656
+ 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 + " " + MEASUREMENT_EXEMPT_DOC,
2654
2657
  inputSchema: {
2655
2658
  ticket_id: z12.coerce.number().int().positive()
2656
2659
  }
@@ -2754,7 +2757,7 @@ function registerHelpdesk(server, client, logger) {
2754
2757
  "lkp_helpdesk_ticket_update",
2755
2758
  {
2756
2759
  title: "Update helpdesk ticket (write)",
2757
- 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 no opportunity was created \u2014 but note that since API contract 3.0 the category alone flips the SLA ruler to 'improvement_business_days', so this outcome is NOT 'nothing but a label changed'; re-read sla.deadlines[]), 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,
2760
+ 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 no opportunity was created \u2014 but note that since API contract 3.0 the category alone flips the SLA ruler to 'improvement_business_days', so this outcome is NOT 'nothing but a label changed'; re-read sla.deadlines[]), 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. \u{1F534} SINCE API CONTRACT 4.2 meta HAS TWO INDEPENDENT CAUSES, so 'meta is here' NO LONGER MEANS 'a recategorization happened' \u2014 the block also arrives when the PATCH touched measurement_exempt, and then it carries warnings[] instead (see below). Branch on WHICH KEY is inside it, never on the block's presence: opportunity_action/quotes_archived are the recategorization's account, warnings[] is the exemption's. It is still ABSENT when the PATCH carried NEITHER field, and it never arrives as {}; it remains this API's one documented exception to 'every key is always present', so test before reading and never read a missing block as 'nothing was archived'. When the recategorization fields ARE there, they are the authoritative account of that 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. ` + MEASUREMENT_EXEMPT_WRITE_DOC + "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 + " " + MEASUREMENT_EXEMPT_DOC,
2758
2761
  inputSchema: {
2759
2762
  ticket_id: z12.coerce.number().int().positive(),
2760
2763
  status_id: z12.coerce.number().int().positive().optional(),
@@ -2765,7 +2768,15 @@ function registerHelpdesk(server, client, logger) {
2765
2768
  category_id: z12.coerce.number().int().positive().optional(),
2766
2769
  recategorize_reason: z12.string().min(1).optional(),
2767
2770
  tags: z12.array(z12.coerce.number().int().positive()).optional(),
2768
- sap_environment_id: z12.coerce.number().int().positive().nullable().optional()
2771
+ sap_environment_id: z12.coerce.number().int().positive().nullable().optional(),
2772
+ // Booleano ESTRITO, sem coerce, e a razão é a mesma do is_internal e do
2773
+ // reply_as_service_identity: z.coerce.boolean() transforma a string
2774
+ // "false" em true, e aqui isso ISENTARIA um chamado quando o chamador
2775
+ // pediu o contrário — escrita financeira, no sentido errado, sem erro.
2776
+ // O backend também recusa (422 validation_failed com
2777
+ // details.measurement_exempt), então a trava existe nos DOIS níveis de
2778
+ // propósito: esta poupa a ida e nomeia o campo, a dele é a soberana.
2779
+ measurement_exempt: z12.boolean().optional()
2769
2780
  }
2770
2781
  },
2771
2782
  async ({ ticket_id, ...body }) => runTool(logger, "lkp_helpdesk_ticket_update", async () => {
@@ -2797,7 +2808,7 @@ function registerHelpdesk(server, client, logger) {
2797
2808
  "lkp_helpdesk_ticket_recategorize",
2798
2809
  {
2799
2810
  title: "Recategorize helpdesk ticket (write)",
2800
- 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 no opportunity is created and the ticket keeps its project \u2014 meta says which happened \u2014 but since API contract 3.0 the category by itself already moves the ticket onto the improvement SLA ruler, so this direction is never a pure metadata edit either). 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 no opportunity exists \u2014 do not go looking for one. 'Only the category changed' IS NO LONGER THE WHOLE STORY (API contract 3.0): since the improvement ruler is now chosen by CATEGORY OR project, moving a ticket into the improvement category FLIPS ITS SLA RULER even when the gate is off and the ticket stays in the AMS project \u2014 sla.deadlines[] comes back with rule 'improvement_business_days' and can gain a 'delivery' entry in bare-date granularity. Re-read deadlines[] after this move instead of assuming the ruler survived; 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,
2811
+ 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 no opportunity is created and the ticket keeps its project \u2014 meta says which happened \u2014 but since API contract 3.0 the category by itself already moves the ticket onto the improvement SLA ruler, so this direction is never a pure metadata edit either). 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 no opportunity exists \u2014 do not go looking for one. 'Only the category changed' IS NO LONGER THE WHOLE STORY (API contract 3.0): since the improvement ruler is now chosen by CATEGORY OR project, moving a ticket into the improvement category FLIPS ITS SLA RULER even when the gate is off and the ticket stays in the AMS project \u2014 sla.deadlines[] comes back with rule 'improvement_business_days' and can gain a 'delivery' entry in bare-date granularity. Re-read deadlines[] after this move instead of assuming the ruler survived; 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 + " " + MEASUREMENT_EXEMPT_DOC,
2801
2812
  inputSchema: {
2802
2813
  ticket_id: z12.coerce.number().int().positive(),
2803
2814
  category_id: z12.coerce.number().int().positive(),
@@ -2821,7 +2832,7 @@ function registerHelpdesk(server, client, logger) {
2821
2832
  "lkp_helpdesk_ticket_create",
2822
2833
  {
2823
2834
  title: "Create helpdesk ticket (write)",
2824
- description: "Open a new helpdesk ticket. Requires subject (at most 200 characters), description and client_id (an ACTIVE client). priority defaults to 'medium' (low | medium | high | critical). Optional category_id (an active category), project_id (must belong to the client), contact_person_id (must belong to the client) and tags (array of ACTIVE tag IDs). Server-derived fields are NOT accepted: ticket_number, status, SLA deadlines, created_at and assigned_to are set by the server. Returns the created ticket (201) in the same shape as lkp_helpdesk_tickets_list. " + CLIENT_TWO_DOORS_DOC + " On this endpoint the first door is the write:helpdesk scope and the role door answers 403 forbidden with 'Only admins or managers can create tickets.' \u2014 the API once checked the scope alone, so a plain user's token that used to open tickets is now refused here and no reissue fixes it. The other outcomes, read by error.code and never by the prose: 422 validation_failed for a missing or blank subject or description, a subject over 200 characters, a missing client_id, a priority outside the four values, or a tags value that is not an array of positive integer ids; 404 not_found for a reference that does not resolve \u2014 client_id unknown OR INACTIVE, category_id unknown or inactive, project_id not belonging to client_id, contact_person_id not belonging to client_id, or tag ids unknown/inactive (the message names the offending ids); 400 invalid_body for a malformed JSON body; 500 create_failed when the domain layer refuses the ticket. Note that an inactive client or category is a 404 here, not a 422 \u2014 do not read it as 'bad input format'. CREATING IS NOT A NEUTRAL INSERT: three side effects fire that nothing in the request names. (1) IMPROVEMENT INTAKE. When category_id points at the improvement category (the backend matches it BY NAME, 'Solicita\xE7\xE3o de Melhoria'), the client's improvement flow is enabled (improvement_enabled plus an improvement project) and NO explicit project_id was sent, the ticket is routed to the client's IMPROVEMENTS project, its AMS SLA policy is dropped (sla_policy_id null, resolution_due_at NULL by design, response deadline counted in business days instead) and AN OPPORTUNITY IS CREATED IN THE CRM linked to the ticket \u2014 the same commercial move lkp_helpdesk_ticket_recategorize reports as opportunity_action 'created'. That opportunity is BEST-EFFORT: if the client has no account manager, or no improvement B1 billing code configured, it is skipped in silence and the ticket is still created with 201, so never tell the user an opportunity exists without reading it (lkp_opportunities_list by client). Sending project_id explicitly SUPPRESSES the improvement ROUTING entirely \u2014 no opportunity, no migration to the improvements project. IT DOES NOT MAKE THE TICKET AMS (API contract 3.0): the SLA ruler is chosen by improvement CATEGORY OR improvements project, so a ticket born in an AMS project under the improvement category still resolves to rule 'improvement_business_days' and can publish a bare-date 'delivery' entry. Read sla.deadlines[] off the response rather than inferring the ruler from the project you sent. (2) AUTO-ASSIGN IS CONFIG-DRIVEN and invisible in the request: when the client's helpdesk config carries auto_assign_to, the ticket comes back ALREADY ASSIGNED and with status 'Em Atendimento' rather than 'Novo', and a linked TASK is created in its project; on the improvement route the assignee comes from improvement_auto_assign_to, the status STAYS 'Novo' and no task is created (the task is born when a proposal is approved). Read status, assigned_to and project off the RESPONSE \u2014 never report the ticket as new and unassigned because you did not ask for an assignee. (3) An EMAIL announcing the ticket goes out to the CLIENT's contacts (plus any addresses in the client's notify_on_new_ticket setting) right after the commit: opening a ticket is a client-visible act, not a private draft. Summarize the draft \u2014 naming which of these effects the chosen category and client imply \u2014 and wait for user approval before calling. " + SLA_DEADLINES_DOC,
2835
+ description: "Open a new helpdesk ticket. Requires subject (at most 200 characters), description and client_id (an ACTIVE client). priority defaults to 'medium' (low | medium | high | critical). Optional category_id (an active category), project_id (must belong to the client), contact_person_id (must belong to the client) and tags (array of ACTIVE tag IDs). Server-derived fields are NOT accepted: ticket_number, status, SLA deadlines, created_at and assigned_to are set by the server. Returns the created ticket (201) in the same shape as lkp_helpdesk_tickets_list. " + CLIENT_TWO_DOORS_DOC + " On this endpoint the first door is the write:helpdesk scope and the role door answers 403 forbidden with 'Only admins or managers can create tickets.' \u2014 the API once checked the scope alone, so a plain user's token that used to open tickets is now refused here and no reissue fixes it. The other outcomes, read by error.code and never by the prose: 422 validation_failed for a missing or blank subject or description, a subject over 200 characters, a missing client_id, a priority outside the four values, or a tags value that is not an array of positive integer ids; 404 not_found for a reference that does not resolve \u2014 client_id unknown OR INACTIVE, category_id unknown or inactive, project_id not belonging to client_id, contact_person_id not belonging to client_id, or tag ids unknown/inactive (the message names the offending ids); 400 invalid_body for a malformed JSON body; 500 create_failed when the domain layer refuses the ticket. Note that an inactive client or category is a 404 here, not a 422 \u2014 do not read it as 'bad input format'. CREATING IS NOT A NEUTRAL INSERT: three side effects fire that nothing in the request names. (1) IMPROVEMENT INTAKE. When category_id points at the improvement category (the backend matches it BY NAME, 'Solicita\xE7\xE3o de Melhoria'), the client's improvement flow is enabled (improvement_enabled plus an improvement project) and NO explicit project_id was sent, the ticket is routed to the client's IMPROVEMENTS project, its AMS SLA policy is dropped (sla_policy_id null, resolution_due_at NULL by design, response deadline counted in business days instead) and AN OPPORTUNITY IS CREATED IN THE CRM linked to the ticket \u2014 the same commercial move lkp_helpdesk_ticket_recategorize reports as opportunity_action 'created'. That opportunity is BEST-EFFORT: if the client has no account manager, or no improvement B1 billing code configured, it is skipped in silence and the ticket is still created with 201, so never tell the user an opportunity exists without reading it (lkp_opportunities_list by client). Sending project_id explicitly SUPPRESSES the improvement ROUTING entirely \u2014 no opportunity, no migration to the improvements project. IT DOES NOT MAKE THE TICKET AMS (API contract 3.0): the SLA ruler is chosen by improvement CATEGORY OR improvements project, so a ticket born in an AMS project under the improvement category still resolves to rule 'improvement_business_days' and can publish a bare-date 'delivery' entry. Read sla.deadlines[] off the response rather than inferring the ruler from the project you sent. (2) AUTO-ASSIGN IS CONFIG-DRIVEN and invisible in the request: when the client's helpdesk config carries auto_assign_to, the ticket comes back ALREADY ASSIGNED and with status 'Em Atendimento' rather than 'Novo', and a linked TASK is created in its project; on the improvement route the assignee comes from improvement_auto_assign_to, the status STAYS 'Novo' and no task is created (the task is born when a proposal is approved). Read status, assigned_to and project off the RESPONSE \u2014 never report the ticket as new and unassigned because you did not ask for an assignee. (3) An EMAIL announcing the ticket goes out to the CLIENT's contacts (plus any addresses in the client's notify_on_new_ticket setting) right after the commit: opening a ticket is a client-visible act, not a private draft. Summarize the draft \u2014 naming which of these effects the chosen category and client imply \u2014 and wait for user approval before calling. " + SLA_DEADLINES_DOC + " " + MEASUREMENT_EXEMPT_DOC,
2825
2836
  inputSchema: {
2826
2837
  subject: z12.string().min(1).max(200),
2827
2838
  description: z12.string().min(1),