lkpgestao-mcp 0.22.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 +707 -361
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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.
|
|
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(
|
|
665
|
+
{ type: "text", text: JSON.stringify(withSettings, null, 2) }
|
|
520
666
|
]
|
|
521
667
|
};
|
|
522
668
|
} catch (e) {
|
|
@@ -546,6 +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.";
|
|
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. ";
|
|
549
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.";
|
|
550
700
|
async function runTool(logger, name, fn) {
|
|
551
701
|
const started = Date.now();
|
|
@@ -598,13 +748,13 @@ function registerResources(server, client, logger) {
|
|
|
598
748
|
"lkp_resources_list",
|
|
599
749
|
{
|
|
600
750
|
title: "List resources (consultants)",
|
|
601
|
-
description: "List consultants (resources) with filters. Returns allocation status, hourly rate, specialties, weekly capacity. Use to find candidates for allocation or to audit team composition. Each item carries allocation = { allocated_hours, available_hours, utilization_percent, utilization_planned_percent, utilization_actual_percent, status }. utilization_planned_percent is what the consultant is booked for; utilization_actual_percent is what materialised. They diverge a lot in practice (a consultant can sit at planned 634% with actual 0%), so pick the one that matches the question instead of defaulting to either. utilization_percent is the pre-0.13.0 name, kept for compatibility, and tracks the PLANNED figure \u2014 prefer the explicit fields in new work. None of them is capped at 100.",
|
|
751
|
+
description: "List consultants (resources) with filters. Returns allocation status, hourly rate, specialties, weekly capacity. Use to find candidates for allocation or to audit team composition. Each item carries allocation = { allocated_hours, available_hours, utilization_percent, utilization_planned_percent, utilization_actual_percent, status }. utilization_planned_percent is what the consultant is booked for; utilization_actual_percent is what materialised. They diverge a lot in practice (a consultant can sit at planned 634% with actual 0%), so pick the one that matches the question instead of defaulting to either. utilization_percent is the pre-0.13.0 name, kept for compatibility, and tracks the PLANNED figure \u2014 prefer the explicit fields in new work. None of them is capped at 100. Two filters are CLOSED vocabularies: status is active|inactive (anything else is 400 `invalid_filter`) and role is admin|manager|consultant|client \u2014 `client` is a real role on this endpoint even though \xA74.1 of the API spec lists only three. contract_type is NOT closed but is matched as a SUFFIX of the stored label, so send the CODE by itself (PJ, CLT, COOP): the stored spelling '01 - PJ' matches nothing and comes back as an empty list with 200, which reads like 'no such consultants' rather than 'wrong filter value'.",
|
|
602
752
|
inputSchema: {
|
|
603
|
-
status: z4.
|
|
753
|
+
status: z4.enum(["active", "inactive"]).optional(),
|
|
604
754
|
contract_type: z4.string().optional(),
|
|
605
755
|
specialty_id: z4.coerce.number().int().positive().optional(),
|
|
606
756
|
allocation: z4.enum(["available", "partial", "full", "overloaded"]).optional(),
|
|
607
|
-
role: z4.
|
|
757
|
+
role: z4.enum(["admin", "manager", "consultant", "client"]).optional(),
|
|
608
758
|
search: z4.string().optional(),
|
|
609
759
|
page: z4.coerce.number().int().positive().optional(),
|
|
610
760
|
per_page: z4.coerce.number().int().positive().max(100).default(50)
|
|
@@ -653,7 +803,7 @@ function registerResources(server, client, logger) {
|
|
|
653
803
|
"lkp_specialties_list",
|
|
654
804
|
{
|
|
655
805
|
title: "List specialties",
|
|
656
|
-
description:
|
|
806
|
+
description: `List specialties (taxonomia de perfis: 'DESENVOLVEDOR SAP ABAP', 'FUNCIONAL SAP PP', 'GERENTE DE PROJETOS', etc.). Use BEFORE lkp_quote_create or lkp_quote_item_add to resolve name \u2192 specialty_id. Do NOT hardcode IDs \u2014 the catalog is maintained in LKPGest\xE3o and may change. Returns { id, name, category, is_active }. active_only defaults to true and is a STRICT boolean: pass false (the JSON literal, not the string "false") to get inactive specialties too, which is the only way is_active ever comes back false.`,
|
|
657
807
|
inputSchema: {
|
|
658
808
|
category: z4.enum([
|
|
659
809
|
"SAP_DESENVOLVIMENTO",
|
|
@@ -663,29 +813,35 @@ function registerResources(server, client, logger) {
|
|
|
663
813
|
"BACKOFFICE"
|
|
664
814
|
]).optional(),
|
|
665
815
|
search: z4.string().optional(),
|
|
666
|
-
active_only: z4.
|
|
816
|
+
active_only: z4.boolean().default(true)
|
|
667
817
|
}
|
|
668
818
|
},
|
|
669
|
-
async (
|
|
819
|
+
async ({ active_only, ...query }) => runTool(
|
|
670
820
|
logger,
|
|
671
821
|
"lkp_specialties_list",
|
|
672
|
-
() => client.get("/api/v1/specialties",
|
|
822
|
+
() => client.get("/api/v1/specialties", {
|
|
823
|
+
...query,
|
|
824
|
+
// The endpoint drops the active-only filter for the LITERAL string '0'
|
|
825
|
+
// and for no other spelling of "no", so the flag is serialised here
|
|
826
|
+
// rather than left to the query builder's String(value).
|
|
827
|
+
active_only: active_only ? "1" : "0"
|
|
828
|
+
})
|
|
673
829
|
)
|
|
674
830
|
);
|
|
675
831
|
server.registerTool(
|
|
676
832
|
"lkp_resource_timesheets",
|
|
677
833
|
{
|
|
678
834
|
title: "Resource timesheet entries",
|
|
679
|
-
description:
|
|
835
|
+
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.',
|
|
680
836
|
inputSchema: {
|
|
681
837
|
resource_id: z4.coerce.number().int().positive(),
|
|
682
838
|
from: z4.string(),
|
|
683
839
|
to: z4.string(),
|
|
684
840
|
project_id: z4.coerce.number().int().positive().optional(),
|
|
685
841
|
task_id: z4.coerce.number().int().positive().optional(),
|
|
686
|
-
is_approved: z4.
|
|
687
|
-
is_billable: z4.
|
|
688
|
-
source: z4.
|
|
842
|
+
is_approved: z4.boolean().optional(),
|
|
843
|
+
is_billable: z4.boolean().optional(),
|
|
844
|
+
source: z4.enum(["project", "crm"]).optional(),
|
|
689
845
|
page: z4.coerce.number().int().positive().optional(),
|
|
690
846
|
per_page: z4.coerce.number().int().positive().max(200).default(50)
|
|
691
847
|
}
|
|
@@ -708,16 +864,15 @@ function registerTimesheets(server, client, logger) {
|
|
|
708
864
|
"lkp_timesheet_create",
|
|
709
865
|
{
|
|
710
866
|
title: "Create timesheet entry (write)",
|
|
711
|
-
description: "Log a new timesheet entry for a consultant. `comments` is required (LKPGest\xE3o rule: no entry without a comment). The project
|
|
867
|
+
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.",
|
|
712
868
|
inputSchema: {
|
|
713
869
|
resource_id: z5.coerce.number().int().positive(),
|
|
714
870
|
work_date: z5.string(),
|
|
715
871
|
hours: z5.coerce.number(),
|
|
716
872
|
comments: z5.string().min(1, "coment\xE1rio \xE9 obrigat\xF3rio").max(1e3),
|
|
717
|
-
task_id: z5.coerce.number().int().positive()
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
source: z5.string().optional()
|
|
873
|
+
task_id: z5.coerce.number().int().positive(),
|
|
874
|
+
is_approved: z5.boolean().optional(),
|
|
875
|
+
source: z5.enum(["project", "crm"]).optional()
|
|
721
876
|
}
|
|
722
877
|
},
|
|
723
878
|
async ({ resource_id, ...body }) => runTool(
|
|
@@ -733,7 +888,7 @@ function registerTimesheets(server, client, logger) {
|
|
|
733
888
|
"lkp_timesheet_update",
|
|
734
889
|
{
|
|
735
890
|
title: "Update timesheet entry (write)",
|
|
736
|
-
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. Approved entries cannot be edited and the backend rejects edits that violate any LKPGest\xE3o rule; those errors are surfaced as-is. Routes resource_id and timesheet_id into the URL.",
|
|
891
|
+
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.",
|
|
737
892
|
inputSchema: {
|
|
738
893
|
resource_id: z5.coerce.number().int().positive(),
|
|
739
894
|
timesheet_id: z5.coerce.number().int().positive(),
|
|
@@ -741,8 +896,7 @@ function registerTimesheets(server, client, logger) {
|
|
|
741
896
|
hours: z5.coerce.number().optional(),
|
|
742
897
|
comments: z5.string().min(1).max(1e3).optional(),
|
|
743
898
|
task_id: z5.coerce.number().int().positive().optional(),
|
|
744
|
-
|
|
745
|
-
is_approved: z5.coerce.boolean().optional()
|
|
899
|
+
is_approved: z5.boolean().optional()
|
|
746
900
|
}
|
|
747
901
|
},
|
|
748
902
|
async ({ resource_id, timesheet_id, ...body }) => runTool(
|
|
@@ -775,12 +929,14 @@ function registerTimesheets(server, client, logger) {
|
|
|
775
929
|
|
|
776
930
|
// src/tools/projects.ts
|
|
777
931
|
import { z as z6 } from "zod";
|
|
932
|
+
var RateType = z6.enum(["primary", "secondary", "custom"]);
|
|
933
|
+
var MEMBERSHIP_ID_DOC = "member_id IS THE MEMBERSHIP ID \u2014 the `id` field of each item returned by lkp_project_members_list \u2014 and NEVER the user_id. Read it from that list right before calling: a user_id sent as member_id usually answers 404 not_found, but it CAN match ANOTHER member of the SAME project and hit the wrong person, because the lookup is by membership id scoped to the project. Do not take it from lkp_project_detail's team[].";
|
|
778
934
|
function registerProjects(server, client, logger) {
|
|
779
935
|
server.registerTool(
|
|
780
936
|
"lkp_projects_list",
|
|
781
937
|
{
|
|
782
938
|
title: "List projects",
|
|
783
|
-
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.",
|
|
784
940
|
inputSchema: {
|
|
785
941
|
status_id: z6.coerce.number().int().positive().optional(),
|
|
786
942
|
client_id: z6.coerce.number().int().positive().optional(),
|
|
@@ -801,7 +957,7 @@ function registerProjects(server, client, logger) {
|
|
|
801
957
|
"lkp_projects_summary",
|
|
802
958
|
{
|
|
803
959
|
title: "Projects portfolio summary",
|
|
804
|
-
description: "Portfolio dashboard: project counts by status, financial aggregate from billing milestones, upcoming milestones in the next 30 days.",
|
|
960
|
+
description: "Portfolio dashboard: project counts by status, financial aggregate from billing milestones, upcoming milestones in the next 30 days. AUTHORIZATION HAS TWO INDEPENDENT DOORS and the scope is only the first one. Beyond read:projects, the TOKEN OWNER must be entitled to FINANCIAL data \u2014 an administrator, a manager, or a user flagged as financially responsible; anybody else is refused the WHOLE tool, never a reduced version of it: there is no partial answer here, the entire dashboard is financial. Tell the two doors apart by error.code, never by the message: 'insufficient_scope' means the TOKEN lacks read:projects (reissuing it with the scope fixes it), while 'forbidden' means the scope was fine and the OWNER'S entitlement barred the call (no token can fix that \u2014 it needs a different person, or that person granted the financial right). 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 the fix is a person with the entitlement, not another token.",
|
|
805
961
|
inputSchema: {}
|
|
806
962
|
},
|
|
807
963
|
async () => runTool(
|
|
@@ -829,18 +985,22 @@ function registerProjects(server, client, logger) {
|
|
|
829
985
|
"lkp_project_create",
|
|
830
986
|
{
|
|
831
987
|
title: "Create project (write)",
|
|
832
|
-
description: "Create a new project. Requires name, client_id and
|
|
988
|
+
description: "Create a new project. Requires name, client_id, status_id, start_date and end_date \u2014 the backend validator (Project::validateData) rejects the request with 422 validation_failed when either date is missing, even though older docs listed them as optional. YYYY-MM-DD for both, and start_date <= end_date. THE FINANCIAL CLASSIFICATION IS ALSO MANDATORY at creation, and it is the requirement that turns the 'minimal' call into a 422: a project is born BILLABLE unless told otherwise, and a billable project must name its model. So send either billing_model as one of the four real models \u2014 'milestone', 'installment', 'measurement', 'subscription' \u2014 or declare the project internal with billing_model: 'none' or is_billable: false. Two asymmetries decide what happens when both fields travel together: billing_model: 'none' FORCES is_billable=0 even if is_billable: true is in the same body, and with is_billable: false a real billing_model is DISCARDED IN SILENCE, with no 422 at all \u2014 the project is created non-billable and the model is lost. Ask the user which of the two the project is instead of guessing. 422 validation_failed carries error.details keyed by field: report the named field, do not retry blind. Call lkp_clients_list first so the user can pick the right client. manager_id defaults to the token user. Requires the write:projects scope. " + CLIENT_TWO_DOORS_DOC + " Summarize the draft and wait for user approval before calling.",
|
|
833
989
|
inputSchema: {
|
|
834
990
|
name: z6.string().min(1),
|
|
835
991
|
client_id: z6.coerce.number().int().positive(),
|
|
836
992
|
status_id: z6.coerce.number().int().positive(),
|
|
837
993
|
description: z6.string().optional(),
|
|
838
994
|
manager_id: z6.coerce.number().int().positive().optional(),
|
|
839
|
-
start_date: z6.string().
|
|
840
|
-
end_date: z6.string().
|
|
995
|
+
start_date: z6.string().min(1),
|
|
996
|
+
end_date: z6.string().min(1),
|
|
841
997
|
budget: z6.coerce.number().nonnegative().optional(),
|
|
842
|
-
|
|
843
|
-
|
|
998
|
+
// Strict boolean, like is_internal and reply_as_service_identity: with
|
|
999
|
+
// z.coerce.boolean() the string "false" arrives as true, which here
|
|
1000
|
+
// creates a BILLABLE project out of a request for an internal one — or
|
|
1001
|
+
// trips the billing_model 422 that the caller was avoiding.
|
|
1002
|
+
is_billable: z6.boolean().optional(),
|
|
1003
|
+
billing_model: z6.enum(["milestone", "installment", "measurement", "subscription", "none"]).optional(),
|
|
844
1004
|
source_opportunity_id: z6.coerce.number().int().positive().optional()
|
|
845
1005
|
}
|
|
846
1006
|
},
|
|
@@ -854,7 +1014,7 @@ function registerProjects(server, client, logger) {
|
|
|
854
1014
|
"lkp_project_update",
|
|
855
1015
|
{
|
|
856
1016
|
title: "Update project (write)",
|
|
857
|
-
description: "Update whitelisted fields on a project. Setting is_active: false archives the project (
|
|
1017
|
+
description: "Update whitelisted fields on a project \u2014 name, description, status_id, manager_id, start_date, end_date, budget, is_active. The whitelist is STRICT: any other key is 422 unknown_field naming it, so never build this call by echoing an object read from lkp_project_detail or lkp_projects_list. An empty body is 422 validation_failed. Setting is_active: false archives the project and is_active: true restores it. THE EFFECT ON THE DATA IS THE SAME AS lkp_project_archive, BUT THE TWO ARE NOT EQUIVALENT \u2014 the authorization doors are different, and this one is the narrower: this PATCH needs an administrator or a manager ASSIGNED to the project (its manager of record or a team member), while lkp_project_archive only asks that the token owner be an administrator or a manager, with no link to the project at all. For a manager the role/link check runs BEFORE the record is looked up, so an unreachable or non-existent project answers 403 forbidden here and not 404. Two consequences to hold on to: RESTORING is only possible through this route, so a manager who archived an unrelated project with lkp_project_archive can be refused here and have no way to undo it; and 'already archived' is a no-op 200 here, while the DELETE answers 404. Archiving through this route is refused exactly as the DELETE is: 422 has_incomplete_tasks while the project still has an active task outside status 7 (Conclu\xEDda), with error.details.blockers naming the impediments. 422 validation_failed means the project's own rules refused the write, with error.details keyed by field \u2014 read the field and report it, do not retry blind. Works on archived projects too. Confirm any state transition with the user before calling.",
|
|
858
1018
|
inputSchema: {
|
|
859
1019
|
project_id: z6.coerce.number().int().positive(),
|
|
860
1020
|
name: z6.string().optional(),
|
|
@@ -864,7 +1024,10 @@ function registerProjects(server, client, logger) {
|
|
|
864
1024
|
start_date: z6.string().optional(),
|
|
865
1025
|
end_date: z6.string().optional(),
|
|
866
1026
|
budget: z6.coerce.number().nonnegative().optional(),
|
|
867
|
-
|
|
1027
|
+
// Strict boolean: z.coerce.boolean() reads the string "false" as true,
|
|
1028
|
+
// which on THIS field restores a project when the caller asked to
|
|
1029
|
+
// archive it (and the other way round). Same reason as is_billable.
|
|
1030
|
+
is_active: z6.boolean().optional()
|
|
868
1031
|
}
|
|
869
1032
|
},
|
|
870
1033
|
async ({ project_id, ...body }) => runTool(
|
|
@@ -877,7 +1040,7 @@ function registerProjects(server, client, logger) {
|
|
|
877
1040
|
"lkp_project_archive",
|
|
878
1041
|
{
|
|
879
1042
|
title: "Archive project (write)",
|
|
880
|
-
description: "Soft-archive a project by setting is_active=0.
|
|
1043
|
+
description: "Soft-archive a project by setting is_active=0. NOTHING IS DELETED and nothing cascades: the project, its tasks, the timesheets already booked, the billing milestones and the team all stay in the database and stay readable \u2014 say it that way to the user, archiving does not erase history. ARCHIVING IS REFUSED while the project still has any active task outside status 7 (Conclu\xEDda): 422 has_incomplete_tasks, with error.details.blockers listing the impediments. That is an EXPECTED path, not an edge case \u2014 clearing it means completing or archiving every open task first, so read the blockers back to the user instead of retrying. Requires the write:projects scope and an administrator or a manager as token owner (403 forbidden otherwise; no link to the project is needed for this route). A second DELETE of the same project answers 404 not_found \u2014 the endpoint refuses to report success for a no-op, and the same 404 covers 'does not exist', so on a 404 check the current state with lkp_project_detail before telling the user the operation failed: if it is already archived, the desired end state is already there. RESTORATION GOES THROUGH lkp_project_update WITH is_active: true, and that route has a NARROWER door \u2014 administrator or a manager ASSIGNED to the project \u2014 so whoever archived from here may be refused there and not be able to undo it. Check that before promising reversibility. Success is 204 No Content with an EMPTY body, so the { ok, archived, project_id } you get back is synthesized by this tool: do not report fields of the project from this response, there are none. Always ask user approval before calling \u2014 destructive intent.",
|
|
881
1044
|
inputSchema: {
|
|
882
1045
|
project_id: z6.coerce.number().int().positive()
|
|
883
1046
|
}
|
|
@@ -891,7 +1054,7 @@ function registerProjects(server, client, logger) {
|
|
|
891
1054
|
"lkp_project_members_list",
|
|
892
1055
|
{
|
|
893
1056
|
title: "List project team members",
|
|
894
|
-
description: "List team members of a project with their role, rate type and hourly rate.
|
|
1057
|
+
description: "List team members of a project with their role, rate type and hourly rate. include_inactive IS ABOUT THE PROJECT, NOT THE MEMBERS: pass include_inactive=true to read the team of an ARCHIVED project \u2014 without it an archived project answers 404 not_found. It never adds or hides a single member. THERE IS NO SUCH THING AS A REMOVED MEMBER HERE: lkp_project_member_remove hard-deletes the membership row, so a removed person is simply absent and no flag brings them back. The list DOES include people whose own user account is inactive, unlike team[] in lkp_project_detail, which filters them out \u2014 the two lists can legitimately differ for the same project, and this one is the wider. selected_hourly_rate and rate_type are FINANCIAL data: they are returned only to a token owner entitled to see financials (administrator, manager, or a user flagged as financially responsible) and arrive as null for anyone else. A null there means 'you may not see it', NEVER 'no rate on file' \u2014 do not report a member as having no rate from a null. 404 not_found also covers a project the token owner cannot reach: the endpoint will not confirm that a project exists when its owner should not see it. Each item's `id` is the id of the MEMBERSHIP (not the user), and it is what lkp_project_member_update and lkp_project_member_remove take as member_id; user_id is the separate field next to it.",
|
|
895
1058
|
inputSchema: {
|
|
896
1059
|
project_id: z6.coerce.number().int().positive(),
|
|
897
1060
|
include_inactive: z6.coerce.boolean().optional()
|
|
@@ -909,12 +1072,12 @@ function registerProjects(server, client, logger) {
|
|
|
909
1072
|
"lkp_project_member_add",
|
|
910
1073
|
{
|
|
911
1074
|
title: "Add member to project (write)",
|
|
912
|
-
description: "Add a consultant to the project team. user_id must be an
|
|
1075
|
+
description: "Add a consultant to the project team. user_id must be an existing and ACTIVE user \u2014 an inactive or unknown one is 422 validation_failed. role defaults to 'member' and is one of 'member', 'collaborator', 'observer'. ADDING SOMEONE WHO IS ALREADY ON THE TEAM IS HTTP 409, surfaced here as error.code 'conflict' \u2014 the single most likely failure of this tool. Read the team with lkp_project_members_list first, and treat a conflict as 'already there', never as a reason to retry. rate_type DECIDES WHERE THE PERSON'S HOURLY RATE COMES FROM AND CAN CHANGE THE PROJECT'S COST, so confirm the choice AND the number with the user before sending either: 'primary' deliberately leaves them on their GLOBAL hourly rate, so they follow later global adjustments (and a selected_hourly_rate sent along with it lands only in a legacy column that the rate resolution ignores \u2014 the effective rate stays the global one); 'secondary' and 'custom' with selected_hourly_rate > 0 write a project-SPECIFIC rate that takes effect immediately, open-ended, and overrides the global rate for this project \u2014 that is a change to the project's computed cost, not a note on the membership. Omitting rate_type leaves the person on the global rate. Requires the write:projects scope, plus an administrator or a manager ASSIGNED to the project (403 forbidden otherwise). 404 not_found means the project does not exist OR is archived \u2014 a member cannot be added to an archived project. Call lkp_resources_list first so the user can confirm the consultant. Confirm with the user before calling.",
|
|
913
1076
|
inputSchema: {
|
|
914
1077
|
project_id: z6.coerce.number().int().positive(),
|
|
915
1078
|
user_id: z6.coerce.number().int().positive(),
|
|
916
1079
|
role: z6.enum(["member", "collaborator", "observer"]).optional(),
|
|
917
|
-
rate_type:
|
|
1080
|
+
rate_type: RateType.optional(),
|
|
918
1081
|
selected_hourly_rate: z6.coerce.number().nonnegative().optional()
|
|
919
1082
|
}
|
|
920
1083
|
},
|
|
@@ -928,12 +1091,12 @@ function registerProjects(server, client, logger) {
|
|
|
928
1091
|
"lkp_project_member_update",
|
|
929
1092
|
{
|
|
930
1093
|
title: "Update project member (write)",
|
|
931
|
-
description: "Update role, rate_type or selected_hourly_rate of a project team member. user_id and project_id are immutable. Confirm with the user before changing rates.",
|
|
1094
|
+
description: "Update role, rate_type or selected_hourly_rate of a project team member. " + MEMBERSHIP_ID_DOC + " user_id and project_id are immutable (sending either is 422 immutable_field), the allowlist is exactly role, rate_type and selected_hourly_rate (anything else is 422 unknown_field), and an empty body is 422 validation_failed. WHAT selected_hourly_rate DOES HERE IS NARROWER THAN THE NAME SUGGESTS: it writes project_users.selected_hourly_rate, a LEGACY column that the rate resolution IGNORES \u2014 the effective hourly rate of a person on a project comes from the project's rate history. So this call answers 200 with the new number echoed back and the project's computed cost does NOT move: do not report a rate change to the user from this response, and do not use this tool to fix a wrong rate. The effective project rate is set on the project's rates screen, outside this API; what this tool really changes without caveats is role. Requires the write:projects scope, plus an administrator or a manager ASSIGNED to the project (403 forbidden otherwise, and for a manager that check comes BEFORE the lookup). 404 not_found means the membership does not belong to this project. Confirm with the user before changing rates.",
|
|
932
1095
|
inputSchema: {
|
|
933
1096
|
project_id: z6.coerce.number().int().positive(),
|
|
934
1097
|
member_id: z6.coerce.number().int().positive(),
|
|
935
1098
|
role: z6.enum(["member", "collaborator", "observer"]).optional(),
|
|
936
|
-
rate_type:
|
|
1099
|
+
rate_type: RateType.optional(),
|
|
937
1100
|
selected_hourly_rate: z6.coerce.number().nonnegative().optional()
|
|
938
1101
|
}
|
|
939
1102
|
},
|
|
@@ -950,7 +1113,7 @@ function registerProjects(server, client, logger) {
|
|
|
950
1113
|
"lkp_project_member_remove",
|
|
951
1114
|
{
|
|
952
1115
|
title: "Remove member from project (write)",
|
|
953
|
-
description: "Remove a consultant from the project team (hard-delete of the membership record). Always ask user approval before calling.",
|
|
1116
|
+
description: "Remove a consultant from the project team (hard-delete of the membership record \u2014 there is no 'inactive member' state and no undo; re-adding creates a NEW membership with a new id). " + MEMBERSHIP_ID_DOC + " WHAT REMOVAL DOES NOT DO is most of what the word suggests, and all of it matters: tasks assigned to the person STAY ASSIGNED to them, so the project keeps open work in the name of somebody who no longer appears in lkp_project_members_list \u2014 check with lkp_task_list filtered by assignee_id BEFORE removing, and reassign what should move; timesheets already booked STAY and keep counting hours and cost on the project, which is correct but worth telling the user, since 'remove the member' sounds like removing the participation; and the person's project-SPECIFIC hourly rate stays CURRENT in the project's rate history, which is keyed by project and user and not by the membership \u2014 so it applies again the moment they are re-added, even as 'primary'. Requires the write:projects scope, plus an administrator or a manager ASSIGNED to the project. For a manager not assigned to it the 403 forbidden comes BEFORE any lookup, so a wrong member_id or an unreachable project still answers 403 and not 404; 404 not_found means the membership does not belong to this project. Success is 204 No Content with an EMPTY body \u2014 the { ok, removed, project_id, member_id } you get back is synthesized by this tool. Always ask user approval before calling.",
|
|
954
1117
|
inputSchema: {
|
|
955
1118
|
project_id: z6.coerce.number().int().positive(),
|
|
956
1119
|
member_id: z6.coerce.number().int().positive()
|
|
@@ -969,7 +1132,8 @@ function registerProjects(server, client, logger) {
|
|
|
969
1132
|
import { z as z7 } from "zod";
|
|
970
1133
|
var SkillLevel = z7.enum(["J\xFAnior", "Pleno", "S\xEAnior", "Especialista"]);
|
|
971
1134
|
var Priority = z7.enum(["low", "medium", "high", "urgent"]);
|
|
972
|
-
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.";
|
|
973
1137
|
function registerTasks(server, client, logger) {
|
|
974
1138
|
server.registerTool(
|
|
975
1139
|
"lkp_task_list",
|
|
@@ -996,22 +1160,25 @@ function registerTasks(server, client, logger) {
|
|
|
996
1160
|
"lkp_task_get",
|
|
997
1161
|
{
|
|
998
1162
|
title: "Task detail",
|
|
999
|
-
description: "Full task detail: title, description, status, priority, assignee, dates, estimated_hours, specialty, skill_level, parent_task_id, project_b1_code_id, project. Use before making decisions about a specific task.",
|
|
1163
|
+
description: "Full task detail: title, description, status, priority, assignee, dates, estimated_hours, specialty, skill_level, parent_task_id, project_b1_code_id, project. Use before making decisions about a specific task. An ARCHIVED task answers 404 not_found unless include_inactive is true \u2014 send the flag whenever you already have reason to believe the task is archived (lkp_task_list with include_inactive listed it with is_active: false, or lkp_task_archive just succeeded on it), because this is the ONLY tool that reads the record and without the flag it contradicts the list you just read. 404 not_found here carries THREE different meanings and the response does not tell them apart: the task does not exist, it is archived and the flag was not sent, or it is outside the TOKEN OWNER'S reach \u2014 the backend answers 404 instead of 403 deliberately, so that it never confirms the existence of a task the caller should not see. So never report a 404 from here as 'the task does not exist'.",
|
|
1000
1164
|
inputSchema: {
|
|
1001
|
-
task_id: z7.coerce.number().int().positive()
|
|
1165
|
+
task_id: z7.coerce.number().int().positive(),
|
|
1166
|
+
// Strict boolean on purpose: z.coerce.boolean() would turn the string
|
|
1167
|
+
// "false" into true and hand back an archived task the caller excluded.
|
|
1168
|
+
include_inactive: z7.boolean().optional()
|
|
1002
1169
|
}
|
|
1003
1170
|
},
|
|
1004
|
-
async ({ task_id }) => runTool(
|
|
1171
|
+
async ({ task_id, ...args }) => runTool(
|
|
1005
1172
|
logger,
|
|
1006
1173
|
"lkp_task_get",
|
|
1007
|
-
() => client.get(`/api/v1/tasks/${task_id}
|
|
1174
|
+
() => client.get(`/api/v1/tasks/${task_id}`, args)
|
|
1008
1175
|
)
|
|
1009
1176
|
);
|
|
1010
1177
|
server.registerTool(
|
|
1011
1178
|
"lkp_task_create",
|
|
1012
1179
|
{
|
|
1013
1180
|
title: "Create task (write)",
|
|
1014
|
-
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. 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,
|
|
1015
1182
|
inputSchema: {
|
|
1016
1183
|
project_id: z7.coerce.number().int().positive(),
|
|
1017
1184
|
title: z7.string().min(1),
|
|
@@ -1038,7 +1205,7 @@ function registerTasks(server, client, logger) {
|
|
|
1038
1205
|
"lkp_task_update",
|
|
1039
1206
|
{
|
|
1040
1207
|
title: "Update task (write)",
|
|
1041
|
-
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). 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,
|
|
1042
1209
|
inputSchema: {
|
|
1043
1210
|
task_id: z7.coerce.number().int().positive(),
|
|
1044
1211
|
title: z7.string().optional(),
|
|
@@ -1049,7 +1216,11 @@ function registerTasks(server, client, logger) {
|
|
|
1049
1216
|
due_date: z7.string().optional(),
|
|
1050
1217
|
start_date: z7.string().optional(),
|
|
1051
1218
|
estimated_hours: z7.coerce.number().nonnegative().optional(),
|
|
1052
|
-
|
|
1219
|
+
// Strict boolean on purpose: z.coerce.boolean() would turn the string
|
|
1220
|
+
// "false" into true, the backend would compare true against an already
|
|
1221
|
+
// active task and change nothing, and the 200 would report success for
|
|
1222
|
+
// an archive that never happened.
|
|
1223
|
+
is_active: z7.boolean().optional(),
|
|
1053
1224
|
specialty_id: z7.coerce.number().int().positive().optional(),
|
|
1054
1225
|
skill_level: SkillLevel.optional(),
|
|
1055
1226
|
parent_task_id: z7.coerce.number().int().positive().optional(),
|
|
@@ -1066,7 +1237,7 @@ function registerTasks(server, client, logger) {
|
|
|
1066
1237
|
"lkp_task_archive",
|
|
1067
1238
|
{
|
|
1068
1239
|
title: "Archive task (write)",
|
|
1069
|
-
description: "Soft-archive a task by setting is_active=0. The task remains in the DB and is excluded from project progress counts. Always ask user approval before calling \u2014 destructive intent.",
|
|
1240
|
+
description: "Soft-archive a task by setting is_active=0. The task remains in the DB and is excluded from project progress counts. THE ARCHIVE IS NOT GUARANTEED: four refusals exist and each reads differently \u2014 read error.code, never the prose. 403 forbidden: the TOKEN OWNER must be an administrator or a manager. That is the person's ROLE, not a missing scope, so reissuing the token with write:tasks changes nothing \u2014 it needs a different person, or that person promoted. 404 not_found: the task does not exist, IS ALREADY ARCHIVED, or is out of the token owner's reach (the backend answers 404 rather than 403 on purpose, so as not to confirm that a task it hides exists) \u2014 a 404 from here is therefore never proof that the task does not exist. 422 linked_to_helpdesk_ticket: the task carries a helpdesk_ticket_id OF ITS OWN, and such a task is NEVER archivable through this tool \u2014 a definitive no, not a 'try again later', and there is no parameter that overrides it (a subtask that merely inherits the ticket from its parent stays archivable). 422 has_timesheets: the task has time entries and they have to go first \u2014 deleting someone's time entries is the USER'S decision to take explicitly, never something to do on their behalf to get this call through. Always ask user approval before calling \u2014 destructive intent.",
|
|
1070
1241
|
inputSchema: {
|
|
1071
1242
|
task_id: z7.coerce.number().int().positive()
|
|
1072
1243
|
}
|
|
@@ -1115,7 +1286,7 @@ function registerTasks(server, client, logger) {
|
|
|
1115
1286
|
"lkp_task_comment_add",
|
|
1116
1287
|
{
|
|
1117
1288
|
title: "Add task comment (write)",
|
|
1118
|
-
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'. 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.",
|
|
1119
1290
|
inputSchema: {
|
|
1120
1291
|
task_id: z7.coerce.number().int().positive(),
|
|
1121
1292
|
body: z7.string().min(1),
|
|
@@ -1131,6 +1302,46 @@ function registerTasks(server, client, logger) {
|
|
|
1131
1302
|
)
|
|
1132
1303
|
)
|
|
1133
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
|
+
);
|
|
1134
1345
|
}
|
|
1135
1346
|
|
|
1136
1347
|
// src/tools/opportunities.ts
|
|
@@ -1171,12 +1382,31 @@ var ContactRole = z8.enum([
|
|
|
1171
1382
|
]);
|
|
1172
1383
|
var EngagementLevel = z8.enum(["LOW", "MEDIUM", "HIGH"]);
|
|
1173
1384
|
var Sentiment = z8.enum(["NEGATIVE", "NEUTRAL", "POSITIVE", "CHAMPION"]);
|
|
1385
|
+
var OpportunitySource = z8.enum([
|
|
1386
|
+
"HELPDESK",
|
|
1387
|
+
"REFERRAL",
|
|
1388
|
+
"WEBSITE",
|
|
1389
|
+
"LINKEDIN",
|
|
1390
|
+
"EVENT",
|
|
1391
|
+
"PARTNER",
|
|
1392
|
+
"COLD_CALL",
|
|
1393
|
+
"EXISTING_CLIENT",
|
|
1394
|
+
"OTHER"
|
|
1395
|
+
]);
|
|
1396
|
+
var ActivityOutcome = z8.enum([
|
|
1397
|
+
"POSITIVE",
|
|
1398
|
+
"NEUTRAL",
|
|
1399
|
+
"NEGATIVE",
|
|
1400
|
+
"NO_ANSWER",
|
|
1401
|
+
"RESCHEDULED",
|
|
1402
|
+
"PENDING"
|
|
1403
|
+
]);
|
|
1174
1404
|
function registerOpportunities(server, client, logger) {
|
|
1175
1405
|
server.registerTool(
|
|
1176
1406
|
"lkp_opportunities_list",
|
|
1177
1407
|
{
|
|
1178
1408
|
title: "List sales opportunities",
|
|
1179
|
-
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.",
|
|
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.",
|
|
1180
1410
|
inputSchema: {
|
|
1181
1411
|
status: OpportunityStatus.optional(),
|
|
1182
1412
|
account_manager_id: z8.coerce.number().int().positive().optional(),
|
|
@@ -1196,7 +1426,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1196
1426
|
"lkp_opportunities_summary",
|
|
1197
1427
|
{
|
|
1198
1428
|
title: "Opportunities pipeline summary",
|
|
1199
|
-
description: "Pipeline dashboard: funnel (count + total_value per open stage), totals (open count, total pipeline, weighted pipeline), closing next 30 days, stale opportunities (no activity in \u22657 days).",
|
|
1429
|
+
description: "Pipeline dashboard: funnel (count + total_value per open stage), totals (open count, total pipeline, weighted pipeline), closing next 30 days, stale opportunities (no activity in \u22657 days). This is the CONSOLIDATED org-wide funnel, not a per-owner slice: unlike lkp_opportunities_list, it is not narrowed for a plain user \u2014 it is refused outright. Requires the read:opportunities scope. " + CLIENT_TWO_DOORS_DOC,
|
|
1200
1430
|
inputSchema: {}
|
|
1201
1431
|
},
|
|
1202
1432
|
async () => runTool(
|
|
@@ -1209,7 +1439,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1209
1439
|
"lkp_opportunity_detail",
|
|
1210
1440
|
{
|
|
1211
1441
|
title: "Opportunity detail",
|
|
1212
|
-
description: "Full opportunity detail: parent fields (with weighted_value, status_label, last_activity_at) plus embedded activities (latest 20) and contacts. Children default to active-only; pass include_inactive=true for audit/restore flows. Returns 404 when id is unknown
|
|
1442
|
+
description: "Full opportunity detail: parent fields (with weighted_value, status_label, last_activity_at) plus embedded activities (latest 20) and contacts. Children default to active-only; pass include_inactive=true for audit/restore flows. Returns 404 when id is unknown, when (without include_inactive) the opportunity itself is archived, or when the opportunity belongs to ANOTHER account manager and the token owner is not an administrator or a manager \u2014 the API answers 404 rather than 403 on purpose, so that it never confirms the existence of a record the caller may not see. A 404 is therefore NOT proof the id does not exist: do not walk through ids looking for one that works, check who owns the token instead.",
|
|
1213
1443
|
inputSchema: {
|
|
1214
1444
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1215
1445
|
include_inactive: z8.coerce.boolean().optional()
|
|
@@ -1227,7 +1457,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1227
1457
|
"lkp_opportunity_create",
|
|
1228
1458
|
{
|
|
1229
1459
|
title: "Create opportunity (write)",
|
|
1230
|
-
description: "Create a new opportunity. Requires client_id, name and project_b1_code_id (a B1 code bound to the client). Since the B1 code choice is rarely obvious, call lkp_client_detail first so the user can pick from the returned b1_codes list. Status defaults to NEW; terminal statuses (WON/LOST/CANCELLED) are rejected on create \u2014 use lkp_opportunity_update afterwards. account_manager_id defaults to the token user. Summarize the draft and wait for user approval before calling.",
|
|
1460
|
+
description: "Create a new opportunity. Requires client_id, name and project_b1_code_id (a B1 code bound to the client). Since the B1 code choice is rarely obvious, call lkp_client_detail first so the user can pick from the returned b1_codes list. Status defaults to NEW; terminal statuses (WON/LOST/CANCELLED) are rejected on create \u2014 use lkp_opportunity_update afterwards. account_manager_id defaults to the token user. source is a CLOSED vocabulary, not free text: HELPDESK | REFERRAL | WEBSITE | LINKEDIN | EVENT | PARTNER | COLD_CALL | EXISTING_CLIENT | OTHER \u2014 anything else is 422 validation_failed with error.details.source, so map the user's wording onto one of the nine (OTHER when none fits) instead of forwarding a phrase. Requires the write:opportunities scope. " + CLIENT_TWO_DOORS_DOC + " Summarize the draft and wait for user approval before calling.",
|
|
1231
1461
|
inputSchema: {
|
|
1232
1462
|
client_id: z8.coerce.number().int().positive(),
|
|
1233
1463
|
name: z8.string().min(1),
|
|
@@ -1239,7 +1469,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1239
1469
|
expected_close_date: z8.string().optional(),
|
|
1240
1470
|
account_manager_id: z8.coerce.number().int().positive().optional(),
|
|
1241
1471
|
price_list_id: z8.coerce.number().int().positive().optional(),
|
|
1242
|
-
source:
|
|
1472
|
+
source: OpportunitySource.optional()
|
|
1243
1473
|
}
|
|
1244
1474
|
},
|
|
1245
1475
|
async (args) => runTool(
|
|
@@ -1252,7 +1482,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1252
1482
|
"lkp_opportunity_update",
|
|
1253
1483
|
{
|
|
1254
1484
|
title: "Update opportunity (write)",
|
|
1255
|
-
description: "Update whitelisted fields on an opportunity.
|
|
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.",
|
|
1256
1486
|
inputSchema: {
|
|
1257
1487
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1258
1488
|
name: z8.string().optional(),
|
|
@@ -1278,7 +1508,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1278
1508
|
"lkp_opportunity_archive",
|
|
1279
1509
|
{
|
|
1280
1510
|
title: "Archive opportunity (write)",
|
|
1281
|
-
description: "Soft-archive (soft-delete) an opportunity by setting is_active=0. The opportunity and its children remain in the DB and can be restored with lkp_opportunity_update passing is_active: true. After archiving, lkp_opportunity_detail without include_inactive returns 404. Always ask user approval before calling \u2014 destructive intent.",
|
|
1511
|
+
description: "Soft-archive (soft-delete) an opportunity by setting is_active=0. The opportunity and its children remain in the DB and can be restored with lkp_opportunity_update passing is_active: true. After archiving, lkp_opportunity_detail without include_inactive returns 404. Requires the write:opportunities scope. " + CLIENT_TWO_DOORS_DOC + " Always ask user approval before calling \u2014 destructive intent.",
|
|
1282
1512
|
inputSchema: {
|
|
1283
1513
|
opportunity_id: z8.coerce.number().int().positive()
|
|
1284
1514
|
}
|
|
@@ -1292,15 +1522,15 @@ function registerOpportunities(server, client, logger) {
|
|
|
1292
1522
|
"lkp_opportunity_activity_add",
|
|
1293
1523
|
{
|
|
1294
1524
|
title: "Add activity to opportunity (write)",
|
|
1295
|
-
description: "Log a new activity (note, call, meeting, etc.) on an opportunity. Creates an entry in the timeline and updates last_activity_at. Use after any interaction with a prospect or to record analysis results. Allowed types: CALL | EMAIL | MEETING | NOTE | FOLLOW_UP | PRESENTATION | NEGOTIATION | DOCUMENT_SENT | DOCUMENT_RECEIVED | OTHER. Confirm with the user before calling unless they explicitly requested the activity.",
|
|
1525
|
+
description: "Log a new activity (note, call, meeting, etc.) on an opportunity. Creates an entry in the timeline and updates last_activity_at. Use after any interaction with a prospect or to record analysis results. Allowed types: CALL | EMAIL | MEETING | NOTE | FOLLOW_UP | PRESENTATION | NEGOTIATION | DOCUMENT_SENT | DOCUMENT_RECEIVED | OTHER. outcome is likewise a CLOSED vocabulary, not free text: POSITIVE | NEUTRAL | NEGATIVE | NO_ANSWER | RESCHEDULED | PENDING \u2014 how the interaction went, so put the narrative in description and pick one of the six here. subject is required and the backend caps it at 200 characters (422 validation_failed with error.details.subject): keep it a headline and let description carry the rest. Confirm with the user before calling unless they explicitly requested the activity.",
|
|
1296
1526
|
inputSchema: {
|
|
1297
1527
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1298
1528
|
type: ActivityType,
|
|
1299
|
-
subject: z8.string().min(1),
|
|
1529
|
+
subject: z8.string().min(1).max(200),
|
|
1300
1530
|
description: z8.string().optional(),
|
|
1301
1531
|
duration_minutes: z8.coerce.number().int().nonnegative().optional(),
|
|
1302
1532
|
follow_up_date: z8.string().optional(),
|
|
1303
|
-
outcome:
|
|
1533
|
+
outcome: ActivityOutcome.optional(),
|
|
1304
1534
|
is_internal: z8.coerce.boolean().optional()
|
|
1305
1535
|
}
|
|
1306
1536
|
},
|
|
@@ -1317,18 +1547,18 @@ function registerOpportunities(server, client, logger) {
|
|
|
1317
1547
|
"lkp_opportunity_activity_update",
|
|
1318
1548
|
{
|
|
1319
1549
|
title: "Update opportunity activity (write)",
|
|
1320
|
-
description: "Edit a manual activity on an opportunity. System-generated activities (STATUS_CHANGE, QUOTE_*, CONVERSION, TASK_*, CONTACT_ADDED) are immutable and return 403. activity_type is also immutable. Setting is_active=false archives the activity (same as delete). Confirm with the user before calling.",
|
|
1550
|
+
description: "Edit a manual activity on an opportunity. System-generated activities (STATUS_CHANGE, QUOTE_*, CONVERSION, TASK_*, CONTACT_ADDED) are immutable and return 403. activity_type is also immutable. Setting is_active=false archives the activity (same as delete). outcome, when sent, must be one of the six the backend accepts: POSITIVE | NEUTRAL | NEGATIVE | NO_ANSWER | RESCHEDULED | PENDING. subject must be 1-200 characters \u2014 the backend rejects both the empty string and anything longer with 422 validation_failed and error.details.subject. Confirm with the user before calling.",
|
|
1321
1551
|
inputSchema: {
|
|
1322
1552
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1323
1553
|
activity_id: z8.coerce.number().int().positive(),
|
|
1324
|
-
subject: z8.string().optional(),
|
|
1554
|
+
subject: z8.string().min(1).max(200).optional(),
|
|
1325
1555
|
description: z8.string().optional(),
|
|
1326
1556
|
activity_date: z8.string().optional(),
|
|
1327
1557
|
duration_minutes: z8.coerce.number().int().nonnegative().optional(),
|
|
1328
1558
|
follow_up_date: z8.string().optional(),
|
|
1329
1559
|
follow_up_notes: z8.string().optional(),
|
|
1330
1560
|
is_follow_up_done: z8.coerce.boolean().optional(),
|
|
1331
|
-
outcome:
|
|
1561
|
+
outcome: ActivityOutcome.optional(),
|
|
1332
1562
|
is_internal: z8.coerce.boolean().optional(),
|
|
1333
1563
|
is_active: z8.coerce.boolean().optional()
|
|
1334
1564
|
}
|
|
@@ -1382,7 +1612,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1382
1612
|
"lkp_opportunity_contact_attach",
|
|
1383
1613
|
{
|
|
1384
1614
|
title: "Attach contact to opportunity (write)",
|
|
1385
|
-
description: "Link an existing client_contact_persons record to an opportunity. The contact must belong to the same client as the opportunity. If a previously-archived link for the same (opportunity, contact) pair exists, it is reactivated with the new field values (200 OK) instead of creating a duplicate. Setting is_primary: true clears the prior primary on the same opportunity. Roles: DECISION_MAKER | INFLUENCER | TECHNICAL | FINANCIAL | USER | SPONSOR | GATEKEEPER | CHAMPION | OTHER. Engagement: LOW | MEDIUM | HIGH. Sentiment: NEGATIVE | NEUTRAL | POSITIVE | CHAMPION.",
|
|
1615
|
+
description: "Link an existing client_contact_persons record to an opportunity. The contact must belong to the same client as the opportunity. If a previously-archived link for the same (opportunity, contact) pair exists, it is reactivated with the new field values (200 OK) instead of creating a duplicate. Setting is_primary: true clears the prior primary on the same opportunity. Roles: DECISION_MAKER | INFLUENCER | TECHNICAL | FINANCIAL | USER | SPONSOR | GATEKEEPER | CHAMPION | OTHER. Engagement: LOW | MEDIUM | HIGH. Sentiment: NEGATIVE | NEUTRAL | POSITIVE | CHAMPION. ERRORS \u2014 read error.code, never the prose: 409 conflict / already_linked means an ACTIVE link for this (opportunity, contact) pair already exists, and error.details.link_id IS that link \u2014 call lkp_opportunity_contact_update on that id instead of retrying, since retrying can only produce the same 409. That is a different case from the archived link, which this endpoint reactivates and answers 200, so a 409 is never something an extra attempt clears. 422 cross_client_contact (a code of its own, NOT validation_failed) means the contact belongs to another client: list the right client's people through lkp_client_detail rather than guessing another contact_person_id. Plain 422 validation_failed with error.details.contact_person_id means the contact does not exist or is inactive. 404 means the opportunity is unknown, archived, or outside the token owner's visibility \u2014 archived opportunities accept no new links at all, so restore first with lkp_opportunity_update.",
|
|
1386
1616
|
inputSchema: {
|
|
1387
1617
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1388
1618
|
contact_person_id: z8.coerce.number().int().positive(),
|
|
@@ -1458,6 +1688,16 @@ var QuoteStatus = z9.enum([
|
|
|
1458
1688
|
"EXPIRED",
|
|
1459
1689
|
"SUPERSEDED"
|
|
1460
1690
|
]);
|
|
1691
|
+
var QuoteStatusFilter = z9.string().refine(
|
|
1692
|
+
(s) => s.split(",").every(
|
|
1693
|
+
(t) => QuoteStatus.options.includes(
|
|
1694
|
+
t.trim().toUpperCase()
|
|
1695
|
+
)
|
|
1696
|
+
),
|
|
1697
|
+
{
|
|
1698
|
+
message: "status must be DRAFT | SENT | ACCEPTED | REJECTED | EXPIRED | SUPERSEDED, or a comma-separated list of those"
|
|
1699
|
+
}
|
|
1700
|
+
);
|
|
1461
1701
|
var Currency = z9.enum(["BRL", "USD", "EUR"]);
|
|
1462
1702
|
var SkillLevel2 = z9.enum(["J\xFAnior", "Pleno", "S\xEAnior", "Especialista"]);
|
|
1463
1703
|
var BillingModel = z9.enum([
|
|
@@ -1478,13 +1718,13 @@ var QuoteItemInput = z9.object({
|
|
|
1478
1718
|
cost_rate: z9.coerce.number().nonnegative().optional(),
|
|
1479
1719
|
sort_order: z9.coerce.number().int().optional()
|
|
1480
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.";
|
|
1481
1722
|
var PaymentMilestoneInput = z9.object({
|
|
1482
1723
|
description: z9.string().min(1),
|
|
1483
1724
|
percentage: z9.coerce.number().positive().max(100),
|
|
1484
1725
|
due_days: z9.coerce.number().int().nonnegative().optional(),
|
|
1485
1726
|
due_date: z9.string().optional(),
|
|
1486
|
-
notes: z9.string().optional()
|
|
1487
|
-
sort_order: z9.coerce.number().int().optional()
|
|
1727
|
+
notes: z9.string().optional()
|
|
1488
1728
|
});
|
|
1489
1729
|
var QuoteHeaderFields = {
|
|
1490
1730
|
valid_until: z9.string().optional(),
|
|
@@ -1501,26 +1741,34 @@ var QuoteHeaderFields = {
|
|
|
1501
1741
|
setup_fee: z9.coerce.number().nonnegative().optional(),
|
|
1502
1742
|
monthly_amount: z9.coerce.number().nonnegative().optional(),
|
|
1503
1743
|
recurring_start_date: z9.string().optional(),
|
|
1504
|
-
billing_cadence_subscription: BillingCadence.optional(),
|
|
1505
1744
|
contract_months: z9.coerce.number().int().positive().optional(),
|
|
1506
|
-
installment_count: z9.coerce.number().int().positive().max(60).optional()
|
|
1745
|
+
installment_count: z9.coerce.number().int().positive().max(60).optional(),
|
|
1746
|
+
// Per-model completion fields. A measurement quote is IMPOSSIBLE without a
|
|
1747
|
+
// cadence (weekly needs the weekday, monthly the cutoff day), and a
|
|
1748
|
+
// subscription saved without subscription_due_day can never be accepted —
|
|
1749
|
+
// the backend enforces both (Quote::validate / validateForAcceptance).
|
|
1750
|
+
measurement_cadence: z9.enum(["weekly", "monthly"]).optional(),
|
|
1751
|
+
measurement_cutoff_day: z9.coerce.number().int().min(1).max(28).optional(),
|
|
1752
|
+
measurement_cutoff_weekday: z9.coerce.number().int().min(1).max(7).optional(),
|
|
1753
|
+
subscription_due_day: z9.coerce.number().int().min(1).max(28).optional()
|
|
1507
1754
|
};
|
|
1755
|
+
var QUOTE_EDITABLE_GATE_DOC = "THE PARENT QUOTE'S GATE IS DRAFT | SENT | EXPIRED \u2014 there is NO draft-only lock. Only ACCEPTED, REJECTED and SUPERSEDED are refused, with 422 not_editable and details.status (read error.code, never the prose). The flip side: on a SENT quote this tool is PERMITTED and silently rewrites the proposal the client already received, so check the status first and get explicit user confirmation NAMING the status before touching a SENT or EXPIRED quote.";
|
|
1756
|
+
var ITEM_CASCADE_DOC = "CASCADE: every item mutation recalculates the WHOLE quote \u2014 subtotal, discount_value, tax_value, total and the margin fields \u2014 and rewrites the amount of EVERY payment milestone from the new total (percentage is preserved).";
|
|
1508
1757
|
function registerQuotes(server, client, logger) {
|
|
1509
1758
|
server.registerTool(
|
|
1510
1759
|
"lkp_quotes_list",
|
|
1511
1760
|
{
|
|
1512
1761
|
title: "List quotes",
|
|
1513
|
-
description: "List quotes (proposals) across all opportunities with filters. Returns code (QT-YYYY-NNNN), version, status, currency, billing_model, total, valid_until, sent_at, accepted_at.
|
|
1762
|
+
description: "List quotes (proposals) across all opportunities with filters. Returns code (QT-YYYY-NNNN), version, status, currency, billing_model, total, valid_until, sent_at, accepted_at. status accepts a single value or a comma-separated list of DRAFT | SENT | ACCEPTED | REJECTED | EXPIRED | SUPERSEDED (an unknown token answers 400 invalid_filter). Archived quotes are hidden unless include_inactive=true. THE FILTERS ABOVE ARE THE WHOLE VOCABULARY: this endpoint has no account-manager or billing-model filter, and a query parameter it does not know is discarded IN SILENCE \u2014 the list comes back unfiltered, not erroring \u2014 so never present the result as narrowed by anything this schema does not offer. Use for quote portfolio review; scope to a specific opportunity with lkp_opportunity_quotes_list. THIS CONSOLIDATED LIST IS MANAGEMENT-ONLY: a plain seller gets 403 forbidden here even with the right scope, and reads their own quotes through lkp_opportunity_quotes_list, which applies per-account-manager visibility instead of refusing. " + CLIENT_TWO_DOORS_DOC,
|
|
1514
1763
|
inputSchema: {
|
|
1515
|
-
status:
|
|
1764
|
+
status: QuoteStatusFilter.optional(),
|
|
1516
1765
|
opportunity_id: z9.coerce.number().int().positive().optional(),
|
|
1517
1766
|
client_id: z9.coerce.number().int().positive().optional(),
|
|
1518
|
-
|
|
1519
|
-
billing_model: BillingModel.optional(),
|
|
1520
|
-
valid_until_before: z9.string().optional(),
|
|
1767
|
+
currency: Currency.optional(),
|
|
1521
1768
|
search: z9.string().optional(),
|
|
1769
|
+
include_inactive: z9.coerce.boolean().optional(),
|
|
1522
1770
|
page: z9.coerce.number().int().positive().optional(),
|
|
1523
|
-
per_page: z9.coerce.number().int().positive().max(
|
|
1771
|
+
per_page: z9.coerce.number().int().positive().max(100).default(20)
|
|
1524
1772
|
}
|
|
1525
1773
|
},
|
|
1526
1774
|
async (args) => runTool(
|
|
@@ -1533,15 +1781,18 @@ function registerQuotes(server, client, logger) {
|
|
|
1533
1781
|
"lkp_quote_detail",
|
|
1534
1782
|
{
|
|
1535
1783
|
title: "Quote detail",
|
|
1536
|
-
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.
|
|
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.",
|
|
1537
1785
|
inputSchema: {
|
|
1538
|
-
quote_id: z9.coerce.number().int().positive()
|
|
1786
|
+
quote_id: z9.coerce.number().int().positive(),
|
|
1787
|
+
include_inactive: z9.coerce.boolean().optional()
|
|
1539
1788
|
}
|
|
1540
1789
|
},
|
|
1541
|
-
async ({ quote_id }) => runTool(
|
|
1790
|
+
async ({ quote_id, include_inactive }) => runTool(
|
|
1542
1791
|
logger,
|
|
1543
1792
|
"lkp_quote_detail",
|
|
1544
|
-
() => client.get(`/api/v1/quotes/${quote_id}
|
|
1793
|
+
() => client.get(`/api/v1/quotes/${quote_id}`, {
|
|
1794
|
+
include_inactive
|
|
1795
|
+
})
|
|
1545
1796
|
)
|
|
1546
1797
|
);
|
|
1547
1798
|
server.registerTool(
|
|
@@ -1567,10 +1818,14 @@ function registerQuotes(server, client, logger) {
|
|
|
1567
1818
|
"lkp_quote_create",
|
|
1568
1819
|
{
|
|
1569
1820
|
title: "Create quote (write)",
|
|
1570
|
-
description: "Create a new DRAFT quote under an opportunity. 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.
|
|
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.",
|
|
1571
1822
|
inputSchema: {
|
|
1572
1823
|
opportunity_id: z9.coerce.number().int().positive(),
|
|
1573
1824
|
...QuoteHeaderFields,
|
|
1825
|
+
// Required here, optional in QuoteHeaderFields: on update the stored
|
|
1826
|
+
// value fills the effective state, but a quote cannot be BORN without
|
|
1827
|
+
// a billing_model (Quote::validate refuses the save).
|
|
1828
|
+
billing_model: BillingModel,
|
|
1574
1829
|
items: z9.array(QuoteItemInput).optional(),
|
|
1575
1830
|
payment_milestones: z9.array(PaymentMilestoneInput).optional()
|
|
1576
1831
|
}
|
|
@@ -1588,7 +1843,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1588
1843
|
"lkp_quote_update",
|
|
1589
1844
|
{
|
|
1590
1845
|
title: "Update quote (write)",
|
|
1591
|
-
description: "Update whitelisted header fields on a quote.
|
|
1846
|
+
description: "Update whitelisted header fields on a quote. THE GATE IS BY STATUS, and 'sent' is NOT 'locked': DRAFT, SENT and EXPIRED are writable \u2014 yes, a SENT quote can be patched directly (fixing validity or notes after sending is a supported flow), and because that edit changes terms the client already received, confirm with the user NAMING the status before patching a SENT quote; do not route them to lkp_quote_new_version for a small fix, since that SUPERSEDES the sent version \u2014 far more destructive than the PATCH they wanted. ACCEPTED is frozen (422 not_editable). REJECTED and SUPERSEDED accept ONLY an is_active toggle; any other field answers 422 not_editable with details.status. Computed and lifecycle fields (status, code, version, totals, sent_at/accepted_at/rejected_at and friends) answer 422 immutable_field, and tax_rate_id can only be changed while DRAFT. Mutations to items[] or payment_milestones[] must go through the dedicated tools. Setting is_active=false archives the quote. Summarize the diff (field \u2192 old \u2192 new) and wait for user approval before calling.",
|
|
1592
1847
|
inputSchema: {
|
|
1593
1848
|
quote_id: z9.coerce.number().int().positive(),
|
|
1594
1849
|
...QuoteHeaderFields,
|
|
@@ -1619,7 +1874,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1619
1874
|
"lkp_quote_send",
|
|
1620
1875
|
{
|
|
1621
1876
|
title: "Send quote to client (write)",
|
|
1622
|
-
description: "Transition a DRAFT quote to SENT. Moves the parent opportunity to SENT.
|
|
1877
|
+
description: "Transition a DRAFT quote to SENT. Moves the parent opportunity to SENT. Only DRAFT can be sent \u2014 anything else answers 422 invalid_transition with details.status, and a quote with no active items answers 422 no_items. Sending does NOT lock the quote: the header PATCH and the item/milestone tools keep working on a SENT quote (see lkp_quote_update), so reach for lkp_quote_new_version to reissue terms as a new version, not as the only way to touch a sent one. IMPROVEMENT-TICKET SIDE EFFECTS: when the opportunity originated from a helpdesk improvement ticket, sending ALSO (a) logs quote_sent in the ticket's history, (b) STAMPS THE TICKET'S FIRST-RESPONSE SLA as met, and (c) EMAILS THE PROPOSAL TO THE CLIENT \u2014 the send is client-visible immediately, not an internal state change; none of the three applies when the opportunity has no ticket behind it. The transition itself is not reversible. Confirm the customer-facing terms (totals, valid_until, milestones) with the user before invoking.",
|
|
1623
1878
|
inputSchema: {
|
|
1624
1879
|
quote_id: z9.coerce.number().int().positive()
|
|
1625
1880
|
}
|
|
@@ -1634,7 +1889,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1634
1889
|
"lkp_quote_accept",
|
|
1635
1890
|
{
|
|
1636
1891
|
title: "Accept quote (write)",
|
|
1637
|
-
description: "Transition a SENT quote to ACCEPTED.
|
|
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.",
|
|
1638
1893
|
inputSchema: {
|
|
1639
1894
|
quote_id: z9.coerce.number().int().positive()
|
|
1640
1895
|
}
|
|
@@ -1649,7 +1904,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1649
1904
|
"lkp_quote_reject",
|
|
1650
1905
|
{
|
|
1651
1906
|
title: "Reject quote (write)",
|
|
1652
|
-
description: "Transition a SENT quote to REJECTED. Always ask the user for the rejection motive before calling \u2014 reason is mandatory
|
|
1907
|
+
description: "Transition a SENT quote to REJECTED. Always ask the user for the rejection motive before calling \u2014 reason is mandatory, and it is checked BEFORE the status: an empty reason answers 422 reason_required even on a quote that could not be rejected anyway, while a non-SENT quote with a reason answers 422 invalid_transition. WHERE THE REASON LIVES: it is stored in the quote's rejection_reason and read back through lkp_quote_detail \u2014 the QUOTE_REJECTED entry in the opportunity activity log records only the event (version, code, currency, total), NOT the reason text, so never point users at the timeline to find it.",
|
|
1653
1908
|
inputSchema: {
|
|
1654
1909
|
quote_id: z9.coerce.number().int().positive(),
|
|
1655
1910
|
reason: z9.string().min(1).max(200)
|
|
@@ -1680,7 +1935,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1680
1935
|
"lkp_quote_duplicate",
|
|
1681
1936
|
{
|
|
1682
1937
|
title: "Duplicate quote to another opportunity (write)",
|
|
1683
|
-
description: "Copy a quote (including items) to a DIFFERENT opportunity as a new DRAFT
|
|
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.",
|
|
1684
1939
|
inputSchema: {
|
|
1685
1940
|
quote_id: z9.coerce.number().int().positive(),
|
|
1686
1941
|
target_opportunity_id: z9.coerce.number().int().positive()
|
|
@@ -1698,7 +1953,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1698
1953
|
"lkp_quote_item_add",
|
|
1699
1954
|
{
|
|
1700
1955
|
title: "Add item to quote (write)",
|
|
1701
|
-
description: "Append a line item to a DRAFT
|
|
1956
|
+
description: "Append a line item to a quote in DRAFT, SENT or EXPIRED status. specialty_id: resolve via lkp_specialties_list. skill_level is required (J\xFAnior | Pleno | S\xEAnior | Especialista) \u2014 not derivable from specialty_id; the rate card has 4 rate columns per specialty. hourly_rate: optional \u2014 when omitted, backend resolves via the client's active price_list for (specialty_id, skill_level); returns 422 rate_not_found_in_price_list if no rate is cadastred. " + ITEM_CASCADE_DOC + " Read the recalculated total from meta.quote_total in the 201. " + QUOTE_EDITABLE_GATE_DOC + " Summarize the line (description, sold_hours \xD7 hourly_rate) and wait for user approval.",
|
|
1702
1957
|
inputSchema: {
|
|
1703
1958
|
quote_id: z9.coerce.number().int().positive(),
|
|
1704
1959
|
specialty_id: z9.coerce.number().int().positive(),
|
|
@@ -1721,7 +1976,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1721
1976
|
"lkp_quote_item_update",
|
|
1722
1977
|
{
|
|
1723
1978
|
title: "Update quote item (write)",
|
|
1724
|
-
description: "Update whitelisted fields on a line item of a
|
|
1979
|
+
description: "Update whitelisted fields on a line item of a quote in DRAFT, SENT or EXPIRED status. All fields optional (patch). " + ITEM_CASCADE_DOC + " " + QUOTE_EDITABLE_GATE_DOC + " Summarize the diff (field \u2192 old \u2192 new) and wait for user approval.",
|
|
1725
1980
|
inputSchema: {
|
|
1726
1981
|
quote_id: z9.coerce.number().int().positive(),
|
|
1727
1982
|
item_id: z9.coerce.number().int().positive(),
|
|
@@ -1749,7 +2004,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1749
2004
|
"lkp_quote_item_delete",
|
|
1750
2005
|
{
|
|
1751
2006
|
title: "Delete quote item (write)",
|
|
1752
|
-
description: "Remove a line item from a DRAFT
|
|
2007
|
+
description: "Remove a line item from a quote in DRAFT, SENT or EXPIRED status. " + ITEM_CASCADE_DOC + " " + QUOTE_EDITABLE_GATE_DOC + " Always ask user approval before calling.",
|
|
1753
2008
|
inputSchema: {
|
|
1754
2009
|
quote_id: z9.coerce.number().int().positive(),
|
|
1755
2010
|
item_id: z9.coerce.number().int().positive()
|
|
@@ -1764,10 +2019,10 @@ function registerQuotes(server, client, logger) {
|
|
|
1764
2019
|
"lkp_quote_milestones_replace",
|
|
1765
2020
|
{
|
|
1766
2021
|
title: "Replace all payment milestones (write)",
|
|
1767
|
-
description: "Replace the entire payment_milestones[] collection on a DRAFT
|
|
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.",
|
|
1768
2023
|
inputSchema: {
|
|
1769
2024
|
quote_id: z9.coerce.number().int().positive(),
|
|
1770
|
-
milestones: z9.array(PaymentMilestoneInput)
|
|
2025
|
+
milestones: z9.array(PaymentMilestoneInput)
|
|
1771
2026
|
}
|
|
1772
2027
|
},
|
|
1773
2028
|
async ({ quote_id, milestones }) => runTool(
|
|
@@ -1783,7 +2038,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1783
2038
|
"lkp_quote_milestone_add",
|
|
1784
2039
|
{
|
|
1785
2040
|
title: "Add payment milestone (write)",
|
|
1786
|
-
description: "Append a single payment milestone to a DRAFT
|
|
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.",
|
|
1787
2042
|
inputSchema: {
|
|
1788
2043
|
quote_id: z9.coerce.number().int().positive(),
|
|
1789
2044
|
description: z9.string().min(1),
|
|
@@ -1807,7 +2062,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1807
2062
|
"lkp_quote_milestone_update",
|
|
1808
2063
|
{
|
|
1809
2064
|
title: "Update payment milestone (write)",
|
|
1810
|
-
description: "Update whitelisted fields on a payment milestone of a DRAFT
|
|
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.",
|
|
1811
2066
|
inputSchema: {
|
|
1812
2067
|
quote_id: z9.coerce.number().int().positive(),
|
|
1813
2068
|
milestone_id: z9.coerce.number().int().positive(),
|
|
@@ -1833,7 +2088,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1833
2088
|
"lkp_quote_milestone_delete",
|
|
1834
2089
|
{
|
|
1835
2090
|
title: "Delete payment milestone (write)",
|
|
1836
|
-
description: "Remove one payment milestone from a DRAFT
|
|
2091
|
+
description: "Remove one payment milestone from a quote in DRAFT, SENT or EXPIRED status. " + QUOTE_EDITABLE_GATE_DOC + " Always ask user approval before calling.",
|
|
1837
2092
|
inputSchema: {
|
|
1838
2093
|
quote_id: z9.coerce.number().int().positive(),
|
|
1839
2094
|
milestone_id: z9.coerce.number().int().positive()
|
|
@@ -1855,7 +2110,7 @@ import { tmpdir } from "os";
|
|
|
1855
2110
|
import { z as z10 } from "zod";
|
|
1856
2111
|
var ALLOWED_EXTENSIONS_DOC = "jpg, jpeg, png, gif, webp, pdf, doc, docx, xls, xlsx, ppt, pptx, txt, csv, zip";
|
|
1857
2112
|
var PERMISSIONS_DOC = "PERMISSIONS ON ATTACHMENTS ARE NOT THE PERMISSIONS ON THE QUOTE, and reading and writing do not match (RN-QT-A-002/003). Reading and downloading: an administrator, the opportunity's account_manager_id, OR any user flagged is_financial_responsible. Writing (upload, edit, delete): an administrator or the account_manager_id ONLY \u2014 the financial responsible can read every attachment and change none, and a manager of some other opportunity gets nothing. So 'they could see it' never implies 'they can change it'. Two different refusals reach you: 404 not_found when the opportunity itself is out of reach (the backend masks invisible quotes as missing rather than confirming they exist), and 403 forbidden when the quote is visible but this operation is not allowed on its attachments.";
|
|
1858
|
-
var ARCHIVED_QUOTE_DOC = "AN ARCHIVED QUOTE HIDES ITS ATTACHMENTS (RN-QT-A-010, API contract 2.16). If the quote is archived \u2014 is_active = 0, the quote's own soft-delete \u2014 every one of the five attachment endpoints answers 404 not_found, INCLUDING FOR AN ADMINISTRATOR. So a 404 here has three possible meanings, not two: wrong attachment id, an attachment belonging to another quote, or an ARCHIVED QUOTE. Check the quote with lkp_quote_detail before concluding the attachment was deleted \u2014 attachments of an archived quote are not destroyed, they are hidden. NOTHING IS LOST AND THERE IS A WAY BACK: restore the quote with lkp_quote_update passing is_active: true (the one route that deliberately accepts an archived quote) and the attachments come back with it. Mention that path to the user, because the web UI has no restore button and this API is the only way. THIS IS NOT THE STATUS FREEZE: RN-QT-A-001 is about COMMERCIAL status (ACCEPTED/REJECTED/EXPIRED/SUPERSEDED), where attachments stay fully writable. Archiving is a different axis. Do not conflate them, and do not warn about one when the other is what happened. Before 2.16 the rule was half-applied: an archived quote's attachment could not be listed but COULD still be downloaded by id, so a cached attachment_id that used to work may now 404.";
|
|
2113
|
+
var ARCHIVED_QUOTE_DOC = "AN ARCHIVED QUOTE HIDES ITS ATTACHMENTS (RN-QT-A-010, API contract 2.16). If the quote is archived \u2014 is_active = 0, the quote's own soft-delete \u2014 every one of the five attachment endpoints answers 404 not_found, INCLUDING FOR AN ADMINISTRATOR. So a 404 here has three possible meanings, not two: wrong attachment id, an attachment belonging to another quote, or an ARCHIVED QUOTE. Check the quote with lkp_quote_detail PASSING include_inactive: true before concluding the attachment was deleted \u2014 attachments of an archived quote are not destroyed, they are hidden. THE FLAG IS PART OF THE DIAGNOSIS, NOT AN EXTRA: without include_inactive the quote detail answers 404 not_found for an archived quote as well, and THAT 404 DOES NOT TELL 'ARCHIVED' APART FROM 'NEVER EXISTED' \u2014 so a bare lkp_quote_detail turns one unexplained 404 into two and invites exactly the wrong conclusion. With the flag, a quote that comes back carrying is_active = 0 IS the answer. When the opportunity_id is known, lkp_opportunity_quotes_list with include_inactive: true shows the same thing for every version at once. NOTHING IS LOST AND THERE IS A WAY BACK: restore the quote with lkp_quote_update passing is_active: true (the one route that deliberately accepts an archived quote) and the attachments come back with it. Mention that path to the user, because the web UI has no restore button and this API is the only way. THIS IS NOT THE STATUS FREEZE: RN-QT-A-001 is about COMMERCIAL status (ACCEPTED/REJECTED/EXPIRED/SUPERSEDED), where attachments stay fully writable. Archiving is a different axis. Do not conflate them, and do not warn about one when the other is what happened. Before 2.16 the rule was half-applied: an archived quote's attachment could not be listed but COULD still be downloaded by id, so a cached attachment_id that used to work may now 404.";
|
|
1859
2114
|
var STATUS_FREEZE_DOC = "ATTACHMENTS IGNORE THE QUOTE'S STATUS FREEZE (RN-QT-A-001). RN-QT-006 freezes commercial data once a quote is ACCEPTED, REJECTED, EXPIRED or SUPERSEDED, and attachments are exempt: they stay writable in EVERY status. Do not refuse, warn, or ask for confirmation on the grounds that the quote is closed \u2014 that would be inventing a rule the backend does not have.";
|
|
1860
2115
|
function requireAbsolute(p, field) {
|
|
1861
2116
|
if (!isAbsolute(p)) {
|
|
@@ -1867,12 +2122,13 @@ function requireAbsolute(p, field) {
|
|
|
1867
2122
|
}
|
|
1868
2123
|
return resolve(p);
|
|
1869
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.";
|
|
1870
2126
|
function registerQuoteAttachments(server, client, logger) {
|
|
1871
2127
|
server.registerTool(
|
|
1872
2128
|
"lkp_quote_attachments_list",
|
|
1873
2129
|
{
|
|
1874
2130
|
title: "List quote attachments",
|
|
1875
|
-
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 + "
|
|
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,
|
|
1876
2132
|
inputSchema: {
|
|
1877
2133
|
quote_id: z10.coerce.number().int().positive()
|
|
1878
2134
|
}
|
|
@@ -1887,13 +2143,18 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1887
2143
|
"lkp_quote_attachment_upload",
|
|
1888
2144
|
{
|
|
1889
2145
|
title: "Upload quote attachment (write)",
|
|
1890
|
-
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 +
|
|
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,
|
|
1891
2147
|
inputSchema: {
|
|
1892
2148
|
quote_id: z10.coerce.number().int().positive(),
|
|
1893
2149
|
file_path: z10.string().min(1),
|
|
1894
2150
|
// Optional and sent as a form field alongside the file. The backend
|
|
1895
2151
|
// normalizes "" to null, so an empty string is not an error here.
|
|
1896
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(),
|
|
1897
2158
|
// The name the attachment is stored under. Defaults to the basename of
|
|
1898
2159
|
// file_path, which is what a user means by "upload this file" — it is
|
|
1899
2160
|
// exposed because the local name is sometimes a temp name that would be
|
|
@@ -1901,7 +2162,7 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1901
2162
|
filename: z10.string().min(1).optional()
|
|
1902
2163
|
}
|
|
1903
2164
|
},
|
|
1904
|
-
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 () => {
|
|
1905
2166
|
const abs = requireAbsolute(file_path, "file_path");
|
|
1906
2167
|
let bytes;
|
|
1907
2168
|
try {
|
|
@@ -1917,6 +2178,7 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1917
2178
|
const form = new FormData();
|
|
1918
2179
|
form.append("file", new Blob([bytes]), name);
|
|
1919
2180
|
if (description !== void 0) form.append("description", description);
|
|
2181
|
+
if (is_visible_to_client === true) form.append("is_visible_to_client", "1");
|
|
1920
2182
|
return client.postMultipart(
|
|
1921
2183
|
`/api/v1/quotes/${quote_id}/attachments`,
|
|
1922
2184
|
form
|
|
@@ -1939,6 +2201,13 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1939
2201
|
const payload = await client.getBinary(
|
|
1940
2202
|
`/api/v1/quotes/${quote_id}/attachments/${attachment_id}/download`
|
|
1941
2203
|
);
|
|
2204
|
+
if (payload === null) {
|
|
2205
|
+
throw new LkpError({
|
|
2206
|
+
code: "server_error",
|
|
2207
|
+
message: `The server answered 200 with an EMPTY body (0 bytes) for attachment ${attachment_id} of quote ${quote_id}, so nothing was written to disk. The record exists and its file is empty on the server \u2014 the operational neighbour of file_missing, not a bad id. Report it naming the attachment and do not retry: a retry cannot put the bytes back.`,
|
|
2208
|
+
api_code: "empty_attachment_body"
|
|
2209
|
+
});
|
|
2210
|
+
}
|
|
1942
2211
|
let target;
|
|
1943
2212
|
if (save_to_path !== void 0) {
|
|
1944
2213
|
target = requireAbsolute(save_to_path, "save_to_path");
|
|
@@ -1978,25 +2247,45 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1978
2247
|
server.registerTool(
|
|
1979
2248
|
"lkp_quote_attachment_update",
|
|
1980
2249
|
{
|
|
1981
|
-
title: "Update quote attachment
|
|
1982
|
-
description: "Change
|
|
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,
|
|
1983
2252
|
inputSchema: {
|
|
1984
2253
|
quote_id: z10.coerce.number().int().positive(),
|
|
1985
2254
|
attachment_id: z10.coerce.number().int().positive(),
|
|
1986
|
-
//
|
|
1987
|
-
//
|
|
1988
|
-
//
|
|
1989
|
-
|
|
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
|
+
});
|
|
1990
2279
|
}
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
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(
|
|
1996
2285
|
`/api/v1/quotes/${quote_id}/attachments/${attachment_id}`,
|
|
1997
|
-
|
|
1998
|
-
)
|
|
1999
|
-
)
|
|
2286
|
+
body
|
|
2287
|
+
);
|
|
2288
|
+
})
|
|
2000
2289
|
);
|
|
2001
2290
|
server.registerTool(
|
|
2002
2291
|
"lkp_quote_attachment_delete",
|
|
@@ -2024,10 +2313,14 @@ function registerClients(server, client, logger) {
|
|
|
2024
2313
|
"lkp_clients_list",
|
|
2025
2314
|
{
|
|
2026
2315
|
title: "List clients",
|
|
2027
|
-
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.",
|
|
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,
|
|
2028
2317
|
inputSchema: {
|
|
2029
|
-
status: z11.
|
|
2030
|
-
|
|
2318
|
+
status: z11.enum(["active", "inactive"]).optional(),
|
|
2319
|
+
// The literal "null" is the backend's own spelling for "top-level only"
|
|
2320
|
+
// (it also accepts "0" for it, same meaning), and it has to survive as a
|
|
2321
|
+
// STRING: coercing it to a number gives NaN, and 0 is rejected as an id.
|
|
2322
|
+
// Hence the union with the literal FIRST, so the coercion never sees it.
|
|
2323
|
+
parent_client_id: z11.union([z11.literal("null"), z11.coerce.number().int().positive()]).optional(),
|
|
2031
2324
|
search: z11.string().optional(),
|
|
2032
2325
|
page: z11.coerce.number().int().positive().optional(),
|
|
2033
2326
|
per_page: z11.coerce.number().int().positive().max(100).default(50)
|
|
@@ -2043,7 +2336,7 @@ function registerClients(server, client, logger) {
|
|
|
2043
2336
|
"lkp_client_detail",
|
|
2044
2337
|
{
|
|
2045
2338
|
title: "Client detail",
|
|
2046
|
-
description: "Full client detail including all projects (
|
|
2339
|
+
description: "Full client detail including all ACTIVE projects (archived ones are not listed by this endpoint), all B1 codes, sap_environments[] and stats. sap_environments[] carries the client's SAP environments INCLUDING the deactivated ones (is_active: false), which lkp_client_sap_environments_list cannot return at all \u2014 so this is the tool to use when the question is 'every environment this client ever had', and the other one when it is 'where can I still open a ticket'. b1_codes[] likewise includes the deactivated codes; projects[] is the ONE embed that does not \u2014 it is filtered to is_active = 1 with no parameter to widen it, so an archived project of this client is invisible here. NOTE: the scalar active_projects_count and b1_codes_count fields are always 0 on this endpoint \u2014 only lkp_clients_list populates them. For counts read stats: stats.projects.total and stats.projects.active are the trustworthy pair, and projects.length equals the ACTIVE count only, never the total; stats.b1_codes.total/active says the same for the codes. 404 if the client does not exist. Requires the read:clients scope (or read:*). " + CLIENT_TWO_DOORS_DOC,
|
|
2047
2340
|
inputSchema: {
|
|
2048
2341
|
client_id: z11.coerce.number().int().positive()
|
|
2049
2342
|
}
|
|
@@ -2058,7 +2351,7 @@ function registerClients(server, client, logger) {
|
|
|
2058
2351
|
"lkp_client_create",
|
|
2059
2352
|
{
|
|
2060
2353
|
title: "Create client (write)",
|
|
2061
|
-
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'.",
|
|
2062
2355
|
inputSchema: {
|
|
2063
2356
|
name: z11.string().min(1).max(100),
|
|
2064
2357
|
document: z11.string().optional(),
|
|
@@ -2080,17 +2373,24 @@ function registerClients(server, client, logger) {
|
|
|
2080
2373
|
"lkp_client_update",
|
|
2081
2374
|
{
|
|
2082
2375
|
title: "Update client (write)",
|
|
2083
|
-
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. 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.",
|
|
2084
2377
|
inputSchema: {
|
|
2085
2378
|
client_id: z11.coerce.number().int().positive(),
|
|
2086
2379
|
name: z11.string().min(1).max(100).optional(),
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2380
|
+
// `.nullable()` on every field the backend clears with an explicit null.
|
|
2381
|
+
// It is not decoration: `z.coerce.number()` turns null into 0 and
|
|
2382
|
+
// `.positive()` then refuses it, so without the ZodNullable in front —
|
|
2383
|
+
// which short-circuits null BEFORE the coercion — the documented "send
|
|
2384
|
+
// null to clear" was unreachable and came back as a schema error instead
|
|
2385
|
+
// of a call. `name` and `status` stay non-nullable: the backend requires
|
|
2386
|
+
// a non-empty name and an exact status string.
|
|
2387
|
+
document: z11.string().nullable().optional(),
|
|
2388
|
+
phone: z11.string().max(20).nullable().optional(),
|
|
2389
|
+
address: z11.string().nullable().optional(),
|
|
2390
|
+
notes: z11.string().nullable().optional(),
|
|
2391
|
+
parent_client_id: z11.coerce.number().int().positive().nullable().optional(),
|
|
2392
|
+
negotiated_price_list_id: z11.coerce.number().int().positive().nullable().optional(),
|
|
2393
|
+
account_manager_id: z11.coerce.number().int().positive().nullable().optional(),
|
|
2094
2394
|
status: z11.enum(["active", "inactive"]).optional(),
|
|
2095
2395
|
overwrite_child_overrides: z11.boolean().optional()
|
|
2096
2396
|
}
|
|
@@ -2105,7 +2405,7 @@ function registerClients(server, client, logger) {
|
|
|
2105
2405
|
"lkp_client_deactivate",
|
|
2106
2406
|
{
|
|
2107
2407
|
title: "Deactivate client (write)",
|
|
2108
|
-
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.",
|
|
2109
2409
|
inputSchema: {
|
|
2110
2410
|
client_id: z11.coerce.number().int().positive()
|
|
2111
2411
|
}
|
|
@@ -2137,7 +2437,7 @@ function registerClients(server, client, logger) {
|
|
|
2137
2437
|
"lkp_client_b1_code_create",
|
|
2138
2438
|
{
|
|
2139
2439
|
title: "Create client B1 code (write)",
|
|
2140
|
-
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.",
|
|
2141
2441
|
inputSchema: {
|
|
2142
2442
|
client_id: z11.coerce.number().int().positive(),
|
|
2143
2443
|
// min(1) only. The 14-char ceiling used to live here too, and it had to
|
|
@@ -2162,7 +2462,7 @@ function registerClients(server, client, logger) {
|
|
|
2162
2462
|
"lkp_client_b1_code_update",
|
|
2163
2463
|
{
|
|
2164
2464
|
title: "Update client B1 code (write)",
|
|
2165
|
-
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.",
|
|
2166
2466
|
inputSchema: {
|
|
2167
2467
|
client_id: z11.coerce.number().int().positive(),
|
|
2168
2468
|
b1_code_id: z11.coerce.number().int().positive(),
|
|
@@ -2183,7 +2483,7 @@ function registerClients(server, client, logger) {
|
|
|
2183
2483
|
"lkp_client_b1_code_deactivate",
|
|
2184
2484
|
{
|
|
2185
2485
|
title: "Deactivate client B1 code (write)",
|
|
2186
|
-
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.",
|
|
2187
2487
|
inputSchema: {
|
|
2188
2488
|
client_id: z11.coerce.number().int().positive(),
|
|
2189
2489
|
b1_code_id: z11.coerce.number().int().positive()
|
|
@@ -2221,6 +2521,9 @@ var SapEnvironmentFilter = z12.union([
|
|
|
2221
2521
|
z12.number().int().positive(),
|
|
2222
2522
|
z12.string().regex(/^[1-9]\d*$/).transform((v) => Number(v))
|
|
2223
2523
|
]);
|
|
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.";
|
|
2224
2527
|
function assertSapEnvironmentFilter(value) {
|
|
2225
2528
|
if (value === void 0 || value === "none") return;
|
|
2226
2529
|
const n = typeof value === "string" && /^[1-9]\d*$/.test(value) ? Number(value) : value;
|
|
@@ -2240,7 +2543,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2240
2543
|
"lkp_helpdesk_tickets_list",
|
|
2241
2544
|
{
|
|
2242
2545
|
title: "List helpdesk tickets",
|
|
2243
|
-
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} \u2014 the 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. 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.",
|
|
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,
|
|
2244
2547
|
inputSchema: {
|
|
2245
2548
|
status_id: z12.coerce.number().int().positive().optional(),
|
|
2246
2549
|
priority: z12.string().optional(),
|
|
@@ -2264,7 +2567,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2264
2567
|
"lkp_helpdesk_summary",
|
|
2265
2568
|
{
|
|
2266
2569
|
title: "Helpdesk summary",
|
|
2267
|
-
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,
|
|
2268
2571
|
inputSchema: {}
|
|
2269
2572
|
},
|
|
2270
2573
|
async () => runTool(
|
|
@@ -2277,7 +2580,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2277
2580
|
"lkp_helpdesk_ticket_get",
|
|
2278
2581
|
{
|
|
2279
2582
|
title: "Helpdesk ticket detail",
|
|
2280
|
-
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.",
|
|
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,
|
|
2281
2584
|
inputSchema: {
|
|
2282
2585
|
ticket_id: z12.coerce.number().int().positive()
|
|
2283
2586
|
}
|
|
@@ -2312,7 +2615,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2312
2615
|
"lkp_helpdesk_ticket_comment_add",
|
|
2313
2616
|
{
|
|
2314
2617
|
title: "Add helpdesk ticket comment (write)",
|
|
2315
|
-
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. 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. An internal note
|
|
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.",
|
|
2316
2619
|
inputSchema: {
|
|
2317
2620
|
ticket_id: z12.coerce.number().int().positive(),
|
|
2318
2621
|
body: z12.string().min(1),
|
|
@@ -2349,11 +2652,34 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2349
2652
|
)
|
|
2350
2653
|
)
|
|
2351
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
|
+
);
|
|
2352
2678
|
server.registerTool(
|
|
2353
2679
|
"lkp_helpdesk_ticket_update",
|
|
2354
2680
|
{
|
|
2355
2681
|
title: "Update helpdesk ticket (write)",
|
|
2356
|
-
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
|
|
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,
|
|
2357
2683
|
inputSchema: {
|
|
2358
2684
|
ticket_id: z12.coerce.number().int().positive(),
|
|
2359
2685
|
status_id: z12.coerce.number().int().positive().optional(),
|
|
@@ -2396,7 +2722,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2396
2722
|
"lkp_helpdesk_ticket_recategorize",
|
|
2397
2723
|
{
|
|
2398
2724
|
title: "Recategorize helpdesk ticket (write)",
|
|
2399
|
-
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
|
|
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,
|
|
2400
2726
|
inputSchema: {
|
|
2401
2727
|
ticket_id: z12.coerce.number().int().positive(),
|
|
2402
2728
|
category_id: z12.coerce.number().int().positive(),
|
|
@@ -2420,7 +2746,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2420
2746
|
"lkp_helpdesk_ticket_create",
|
|
2421
2747
|
{
|
|
2422
2748
|
title: "Create helpdesk ticket (write)",
|
|
2423
|
-
description: "Open a new helpdesk ticket. Requires subject, description and client_id (an
|
|
2749
|
+
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 route entirely \u2014 the ticket is born AMS even with the improvement category. (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,
|
|
2424
2750
|
inputSchema: {
|
|
2425
2751
|
subject: z12.string().min(1).max(200),
|
|
2426
2752
|
description: z12.string().min(1),
|
|
@@ -2447,7 +2773,7 @@ function registerBilling(server, client, logger) {
|
|
|
2447
2773
|
"lkp_billing_milestones",
|
|
2448
2774
|
{
|
|
2449
2775
|
title: "List billing milestones (legacy)",
|
|
2450
|
-
description: "LEGACY \u2014 returns only project_billing_milestones (one of 3 financial entity types). For a unified view (milestones + measurements + subscription_invoices) use lkp_financial_pending instead. Status lifecycle: pending \u2192 delivered \u2192 in_progress \u2192 invoiced \u2192 paid. Includes joined project and client.",
|
|
2776
|
+
description: "LEGACY \u2014 returns only project_billing_milestones (one of 3 financial entity types). For a unified view (milestones + measurements + subscription_invoices) use lkp_financial_pending instead. Status lifecycle: pending \u2192 delivered \u2192 in_progress \u2192 invoiced \u2192 paid, with cancelled as a side branch off any stage before paid. Includes joined project and client. Requires the read:billing (or read:*) scope. THIS IS THE ONE FINANCIAL TOOL WHOSE SCOPE IS NOT read:reports: a token provisioned 'for reports' reads lkp_financial_pending fine and still takes insufficient_scope here, so a 403 on this tool alone says nothing about the other financial tools. " + FINANCIAL_TWO_DOORS_DOC + " ROWS ARE ALSO CUT BY THE TOKEN OWNER'S ROLE, and the payload carries no mark of it: an administrator sees every milestone, a manager only those of projects he is a member or the manager of, and EVERY OTHER ROLE \u2014 the financial responsible who just passed the gate included \u2014 only the milestones ASSIGNED to him. meta.total counts the ALREADY-CUT set, so never present it as a company figure unless the token owner is an administrator; say whose view it is. A total that disagrees with lkp_financial_pending is expected, because that tool queries the view with no per-user cut \u2014 the two numbers are both right about different populations. Asking for status='cancelled' also needs include_cancelled=true: the default exclusion is added ON TOP of the status filter, so the pair alone returns an empty list with HTTP 200 and no error. This tool sets the flag for you whenever status='cancelled', since the alternative is a provably empty answer.",
|
|
2451
2777
|
inputSchema: {
|
|
2452
2778
|
status: z13.string().optional(),
|
|
2453
2779
|
project_id: z13.coerce.number().int().positive().optional(),
|
|
@@ -2459,25 +2785,36 @@ function registerBilling(server, client, logger) {
|
|
|
2459
2785
|
per_page: z13.coerce.number().int().positive().max(100).default(50)
|
|
2460
2786
|
}
|
|
2461
2787
|
},
|
|
2462
|
-
async (args) =>
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2788
|
+
async (args) => {
|
|
2789
|
+
const query = args.status?.trim().toLowerCase() === "cancelled" ? { ...args, include_cancelled: true } : args;
|
|
2790
|
+
return runTool(
|
|
2791
|
+
logger,
|
|
2792
|
+
"lkp_billing_milestones",
|
|
2793
|
+
() => client.get("/api/v1/billing/milestones", query)
|
|
2794
|
+
);
|
|
2795
|
+
}
|
|
2467
2796
|
);
|
|
2468
2797
|
}
|
|
2469
2798
|
|
|
2470
2799
|
// src/tools/alerts.ts
|
|
2471
2800
|
import { z as z14 } from "zod";
|
|
2801
|
+
var ALERT_TYPES = [
|
|
2802
|
+
"consultant_idle",
|
|
2803
|
+
"project_finishing",
|
|
2804
|
+
"opportunity_stale",
|
|
2805
|
+
"milestone_upcoming",
|
|
2806
|
+
"milestone_overdue",
|
|
2807
|
+
"helpdesk_sla_breach"
|
|
2808
|
+
];
|
|
2472
2809
|
function registerAlerts(server, client, logger) {
|
|
2473
2810
|
server.registerTool(
|
|
2474
2811
|
"lkp_alerts",
|
|
2475
2812
|
{
|
|
2476
2813
|
title: "Operational alerts",
|
|
2477
|
-
description: "Live operational alerts computed on the fly: consultants idle, projects finishing (\u226430d), opportunities stale (\u22657d), billing milestones upcoming (\u226415d) or overdue, helpdesk SLA breaches. Use first thing in the morning and before any strategic decision.",
|
|
2814
|
+
description: "Live operational alerts computed on the fly: consultants idle, projects finishing (\u226430d), opportunities stale (\u22657d), billing milestones upcoming (\u226415d) or overdue, helpdesk SLA breaches. Use first thing in the morning and before any strategic decision. BOTH FILTERS ARE CLOSED VOCABULARIES \u2014 a value outside the list is 400 invalid_filter, never a quiet empty list. type is one of consultant_idle, project_finishing, opportunity_stale, milestone_upcoming, milestone_overdue, helpdesk_sla_breach: use the identifier, not the prose above. severity is high, medium or low, and it is FIXED PER TYPE rather than per occurrence \u2014 project_finishing, milestone_overdue and helpdesk_sla_breach are always high, consultant_idle, opportunity_stale and milestone_upcoming always medium, and NO type is ever low. So severity='low' is a VALID filter that always answers an empty list: read that as 'no such severity exists', never as 'nothing is wrong'. Requires the read:alerts (or read:*) scope. " + CLIENT_TWO_DOORS_DOC + " That role door is administrator-or-manager ONLY, and this endpoint is deliberately STRICTER than the financial reports (lkp_ceo_weekly, lkp_managers_in_trouble, lkp_billing_milestones, lkp_financial_*), whose door also admits the financial responsible. Being flagged is_financial_responsible does NOT open this one, so a token that reads the whole aging report can still come back 'forbidden' here \u2014 that is the contract, not a misconfigured token.",
|
|
2478
2815
|
inputSchema: {
|
|
2479
|
-
severity: z14.
|
|
2480
|
-
type: z14.
|
|
2816
|
+
severity: z14.enum(["high", "medium", "low"]).optional(),
|
|
2817
|
+
type: z14.enum(ALERT_TYPES).optional()
|
|
2481
2818
|
}
|
|
2482
2819
|
},
|
|
2483
2820
|
async (args) => runTool(
|
|
@@ -2495,7 +2832,7 @@ function registerReports(server, client, logger) {
|
|
|
2495
2832
|
"lkp_ceo_weekly",
|
|
2496
2833
|
{
|
|
2497
2834
|
title: "CEO weekly report",
|
|
2498
|
-
description: "Consolidated weekly report for the CEO. Includes operational health score (0-100, classified healthy/attention/critical) across 4 factors, plus sections: resources, projects, pipeline, helpdesk, financial (MRR, gross revenue 30d, projected revenue 30d, overdue consolidated, billing gap), and high-severity alerts. Single call for Monday morning. For financial drill-down use lkp_financial_overview or lkp_aging_report.",
|
|
2835
|
+
description: "Consolidated weekly report for the CEO. Includes operational health score (0-100, classified healthy/attention/critical) across 4 factors, plus sections: resources, projects, pipeline, helpdesk, financial (MRR, gross revenue 30d, projected revenue 30d, overdue consolidated, billing gap), and high-severity alerts. Single call for Monday morning. For financial drill-down use lkp_financial_overview or lkp_aging_report. Requires the read:reports (or read:*) scope. " + FINANCIAL_TWO_DOORS_DOC,
|
|
2499
2836
|
inputSchema: {}
|
|
2500
2837
|
},
|
|
2501
2838
|
async () => runTool(
|
|
@@ -2508,7 +2845,7 @@ function registerReports(server, client, logger) {
|
|
|
2508
2845
|
"lkp_managers_in_trouble",
|
|
2509
2846
|
{
|
|
2510
2847
|
title: "Managers with overdue items",
|
|
2511
|
-
description: "List managers with overdue items in their projects. Returns two intentionally separate layers: (1) tasks_overdue (operational \u2014 tasks past due_date still not complete) and (2) financial_overdue (milestones / measurements / subscription_invoices past due). Ordered by oldest overdue first. Use when asked 'quem est\xE1 devendo?' or 'quais gerentes precisam de aten\xE7\xE3o?'. The two layers have different natures \u2014 do not sum them; present in separate sections.",
|
|
2848
|
+
description: "List managers with overdue items in their projects. Returns two intentionally separate layers: (1) tasks_overdue (operational \u2014 tasks past due_date still not complete) and (2) financial_overdue (milestones / measurements / subscription_invoices past due). Ordered by oldest overdue first. Use when asked 'quem est\xE1 devendo?' or 'quais gerentes precisam de aten\xE7\xE3o?'. The two layers have different natures \u2014 do not sum them; present in separate sections. Both layers are ON by default and at least one must stay on: include_tasks=false TOGETHER WITH include_financial=false is 400 bad_request, not an empty report, so to look at a single layer switch OFF the other one and leave this one alone. Requires the read:reports (or read:*) scope. " + FINANCIAL_TWO_DOORS_DOC,
|
|
2512
2849
|
inputSchema: {
|
|
2513
2850
|
include_tasks: z15.coerce.boolean().optional(),
|
|
2514
2851
|
include_financial: z15.coerce.boolean().optional(),
|
|
@@ -2530,7 +2867,7 @@ function registerFinancial(server, client, logger) {
|
|
|
2530
2867
|
"lkp_financial_pending",
|
|
2531
2868
|
{
|
|
2532
2869
|
title: "List pending financial entities",
|
|
2533
|
-
description: "List all pending financial entities (milestones + measurements + subscription invoices) in a unified paginated view. Each row is enriched with is_overdue. Replaces lkp_billing_milestones for unified views \u2014 the legacy tool stays for backward compatibility.",
|
|
2870
|
+
description: "List all pending financial entities (milestones + measurements + subscription invoices) in a unified paginated view. Each row is enriched with is_overdue. Replaces lkp_billing_milestones for unified views \u2014 the legacy tool stays for backward compatibility. Requires the read:reports (or read:*) scope. " + FINANCIAL_TWO_DOORS_DOC,
|
|
2534
2871
|
inputSchema: {
|
|
2535
2872
|
entity_type: z16.enum(["milestone", "measurement", "subscription_invoice"]).optional(),
|
|
2536
2873
|
project_id: z16.coerce.number().int().positive().optional(),
|
|
@@ -2552,10 +2889,10 @@ function registerFinancial(server, client, logger) {
|
|
|
2552
2889
|
"lkp_aging_report",
|
|
2553
2890
|
{
|
|
2554
2891
|
title: "Aging report (receivables)",
|
|
2555
|
-
description: "Aging report over overdue financial items. Returns (1) buckets 0-30 / 31-60 / 61-90 / 90+ by entity_type with count + amount, (2) overdue totals (count, amount, avg_days, oldest_days), (3) DSO (days sales outstanding) over last 90d for measurements and subscription_invoices, (4) top clients-at-risk ranked by overdue amount.",
|
|
2892
|
+
description: "Aging report over overdue financial items. Returns (1) buckets 0-30 / 31-60 / 61-90 / 90+ by entity_type with count + amount, (2) overdue totals (count, amount, avg_days, oldest_days), (3) DSO (days sales outstanding) over last 90d for measurements and subscription_invoices, (4) top clients-at-risk ranked by overdue amount. group_bucket defaults to TRUE and decides whether the bucket breakdown is computed at all \u2014 pass false to get only the totals and the DSO. top_clients defaults to 10 and the server CAPS IT AT 50 without saying so: asking for 200 returns 50 rows and no warning, so never read the row count as 'that is all the clients at risk'. Requires the read:reports (or read:*) scope. " + FINANCIAL_TWO_DOORS_DOC,
|
|
2556
2893
|
inputSchema: {
|
|
2557
2894
|
group_bucket: z16.coerce.boolean().optional(),
|
|
2558
|
-
top_clients: z16.coerce.number().int().positive().optional()
|
|
2895
|
+
top_clients: z16.coerce.number().int().positive().max(50).optional()
|
|
2559
2896
|
}
|
|
2560
2897
|
},
|
|
2561
2898
|
async (args) => runTool(
|
|
@@ -2568,7 +2905,7 @@ function registerFinancial(server, client, logger) {
|
|
|
2568
2905
|
"lkp_financial_overview",
|
|
2569
2906
|
{
|
|
2570
2907
|
title: "Executive financial overview",
|
|
2571
|
-
description: "Executive financial dashboard: MRR (sum of active subscription monthly_amount) + active_subscriptions count; churn last 90d (subscriptions ended + mrr_lost); gross revenue last 30d split by entity type; projected revenue next 30/60/90d (pending items with due_date in range); billing gap \u2014 top 20 active classified projects with no billing in >60d. Single-call financial snapshot.",
|
|
2908
|
+
description: "Executive financial dashboard: MRR (sum of active subscription monthly_amount) + active_subscriptions count; churn last 90d (subscriptions ended + mrr_lost); gross revenue last 30d split by entity type; projected revenue next 30/60/90d (pending items with due_date in range); billing gap \u2014 top 20 active classified projects with no billing in >60d. Single-call financial snapshot. Requires the read:reports (or read:*) scope. " + FINANCIAL_TWO_DOORS_DOC,
|
|
2572
2909
|
inputSchema: {}
|
|
2573
2910
|
},
|
|
2574
2911
|
async () => runTool(
|
|
@@ -2581,12 +2918,12 @@ function registerFinancial(server, client, logger) {
|
|
|
2581
2918
|
"lkp_margin_analysis",
|
|
2582
2919
|
{
|
|
2583
2920
|
title: "Margin analysis (project/client/specialty)",
|
|
2584
|
-
description: "Aggregate margin by project, client, or specialty using the per_user_breakdown JSON persisted in each measurement. Returns top N rows with gross_amount, cost_amount, margin_amount, margin_percent, measurement_count. Default window: last 180 days. Default status: paid,invoiced,sent,approved. Only measurements carry line-level cost \u2014 milestones and subscription_invoices are out of scope; for their gross numbers use lkp_financial_overview.",
|
|
2921
|
+
description: "Aggregate margin by project, client, or specialty using the per_user_breakdown JSON persisted in each measurement. Returns top N rows with gross_amount, cost_amount, margin_amount, margin_percent, measurement_count. Default window: last 180 days. Default status: paid,invoiced,sent,approved. Only measurements carry line-level cost \u2014 milestones and subscription_invoices are out of scope; for their gross numbers use lkp_financial_overview. limit defaults to 20 and the ceiling is 100: a larger value comes back TRUNCATED to 100 rows, with the applied value echoed in filters.limit \u2014 check it there before calling the ranking complete. Requires the read:reports (or read:*) scope. " + FINANCIAL_TWO_DOORS_DOC,
|
|
2585
2922
|
inputSchema: {
|
|
2586
2923
|
group_by: z16.enum(["project", "client", "specialty"]).optional(),
|
|
2587
2924
|
from: z16.string().optional(),
|
|
2588
2925
|
to: z16.string().optional(),
|
|
2589
|
-
limit: z16.coerce.number().int().positive().max(
|
|
2926
|
+
limit: z16.coerce.number().int().positive().max(100).optional(),
|
|
2590
2927
|
status: z16.string().optional()
|
|
2591
2928
|
}
|
|
2592
2929
|
},
|
|
@@ -2603,106 +2940,114 @@ function registerFinancial(server, client, logger) {
|
|
|
2603
2940
|
|
|
2604
2941
|
// src/tools/composite/skill-match.ts
|
|
2605
2942
|
import { z as z17 } from "zod";
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
const year = Number(m[1]);
|
|
2616
|
-
const month = Number(m[2]);
|
|
2617
|
-
const day = Number(m[3]);
|
|
2618
|
-
const utc = Date.UTC(year, month - 1, day);
|
|
2619
|
-
const back = new Date(utc);
|
|
2620
|
-
if (back.getUTCFullYear() !== year || back.getUTCMonth() !== month - 1 || back.getUTCDate() !== day) {
|
|
2621
|
-
return null;
|
|
2622
|
-
}
|
|
2623
|
-
return utc / MS_PER_DAY;
|
|
2624
|
-
}
|
|
2625
|
-
function dayOfWeek(calendarDay) {
|
|
2626
|
-
return new Date(calendarDay * MS_PER_DAY).getUTCDay();
|
|
2943
|
+
var OPEN_STAGES = [
|
|
2944
|
+
"NEW",
|
|
2945
|
+
"QUALIFYING",
|
|
2946
|
+
"PROPOSAL",
|
|
2947
|
+
"SENT",
|
|
2948
|
+
"NEGOTIATION"
|
|
2949
|
+
];
|
|
2950
|
+
function toSpecNames(specialties) {
|
|
2951
|
+
return (specialties ?? []).map((s) => typeof s === "string" ? s : s?.name ?? "").filter((s) => s.length > 0);
|
|
2627
2952
|
}
|
|
2628
|
-
function
|
|
2629
|
-
const
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
throw new Error(
|
|
2639
|
-
`Could not resolve today in ${API_TIMEZONE} (Intl returned ${JSON.stringify(parts)}).`
|
|
2640
|
-
);
|
|
2953
|
+
async function fetchStageOpportunities(client, status) {
|
|
2954
|
+
const perPage = 100;
|
|
2955
|
+
const all = [];
|
|
2956
|
+
for (let page = 1; page <= 50; page++) {
|
|
2957
|
+
const r = await client.get("/api/v1/opportunities", { status, page, per_page: perPage });
|
|
2958
|
+
const batch = r.data ?? [];
|
|
2959
|
+
all.push(...batch);
|
|
2960
|
+
if (batch.length < perPage) break;
|
|
2961
|
+
const total = r.meta?.total;
|
|
2962
|
+
if (typeof total === "number" && all.length >= total) break;
|
|
2641
2963
|
}
|
|
2642
|
-
return
|
|
2964
|
+
return all;
|
|
2643
2965
|
}
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2966
|
+
async function fetchPartialResources(client) {
|
|
2967
|
+
const perPage = 100;
|
|
2968
|
+
const all = [];
|
|
2969
|
+
for (let page = 1; page <= 50; page++) {
|
|
2970
|
+
const r = await client.get("/api/v1/resources", {
|
|
2971
|
+
allocation: "partial",
|
|
2972
|
+
status: "active",
|
|
2973
|
+
page,
|
|
2974
|
+
per_page: perPage
|
|
2975
|
+
});
|
|
2976
|
+
const batch = r.data ?? [];
|
|
2977
|
+
all.push(...batch);
|
|
2978
|
+
if (batch.length < perPage) break;
|
|
2979
|
+
const total = r.meta?.total;
|
|
2980
|
+
if (typeof total === "number" && all.length >= total) break;
|
|
2981
|
+
}
|
|
2982
|
+
return all;
|
|
2649
2983
|
}
|
|
2650
2984
|
function registerSkillMatch(server, client, logger) {
|
|
2651
2985
|
server.registerTool(
|
|
2652
2986
|
"lkp_skill_match",
|
|
2653
2987
|
{
|
|
2654
2988
|
title: "Match idle consultants to open opportunities",
|
|
2655
|
-
description: "Match idle or soon-to-finish consultants with open opportunities by skill compatibility. Returns a ranked list of (consultant, opportunity) pairs with a match score. Skill inference for v1 is based on substring match of consultant specialties against the opportunity name and description. Critical for the 'queima de caixa' problem.",
|
|
2989
|
+
description: "Match idle or soon-to-finish consultants with open opportunities by skill compatibility. Returns a ranked list of (consultant, opportunity) pairs with a match score. Skill inference for v1 is based on substring match of consultant specialties against the opportunity name and description. Critical for the 'queima de caixa' problem. 'Open' is the backend's own definition: the five stages NEW, QUALIFYING, PROPOSAL, SENT, NEGOTIATION. horizon_days can only NARROW the soon-to-finish window \u2014 the backend fixes that window at 30 days, so values above 30 are rejected here instead of pretending to widen it. include_partial=true also considers consultants in the 'partial' allocation bucket (1\u201379% utilized) as candidates, fetched from the resources listing at the cost of extra calls. If listing one opportunity stage fails, the match still runs on the stages that answered and meta.stages_failed names the missing ones \u2014 read a non-empty stages_failed as an INCOMPLETE pipeline, never as 'nothing open in those stages'; if the resource lists fail the whole tool fails with that error, and if EVERY stage fails it also fails rather than reporting 'no matches' over zero opportunities. MANAGEMENT-ONLY: needs the read:resources AND read:opportunities scopes, and beyond the scopes the resource endpoints refuse plain users. GET /opportunities does something quieter than refusing: it applies ROW-LEVEL visibility, answering a token whose owner is not an admin or manager with ONLY the opportunities that owner is the account manager of \u2014 under such a token the match covers that person's slice of the portfolio, not the pipeline, so 'few matches' proves nothing about the pipeline being short. " + CLIENT_TWO_DOORS_DOC,
|
|
2656
2990
|
inputSchema: {
|
|
2657
|
-
|
|
2991
|
+
// max(30) is the backend's ceiling, not a choice made here: the summary
|
|
2992
|
+
// computes finishing_in_30_days with a literal 30-day window, so a
|
|
2993
|
+
// larger horizon cannot surface anyone new — rejecting it locally beats
|
|
2994
|
+
// silently answering with the 30-day set.
|
|
2995
|
+
horizon_days: z17.coerce.number().int().positive().max(30).default(30),
|
|
2658
2996
|
min_match_percent: z17.coerce.number().int().min(0).max(100).default(50),
|
|
2659
2997
|
include_partial: z17.coerce.boolean().default(false)
|
|
2660
2998
|
}
|
|
2661
2999
|
},
|
|
2662
3000
|
async ({ horizon_days, min_match_percent, include_partial }) => runTool(logger, "lkp_skill_match", async () => {
|
|
2663
|
-
const
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
)
|
|
3001
|
+
const summaryPromise = client.get(
|
|
3002
|
+
"/api/v1/resources/summary"
|
|
3003
|
+
);
|
|
3004
|
+
const partialPromise = include_partial ? fetchPartialResources(client) : Promise.resolve([]);
|
|
3005
|
+
const stagePromises = OPEN_STAGES.map(
|
|
3006
|
+
(status) => fetchStageOpportunities(client, status)
|
|
3007
|
+
);
|
|
3008
|
+
const [[summaryResult, partialResult], stageResults] = await Promise.all([
|
|
3009
|
+
Promise.allSettled([summaryPromise, partialPromise]),
|
|
3010
|
+
Promise.allSettled(stagePromises)
|
|
2673
3011
|
]);
|
|
2674
|
-
|
|
3012
|
+
if (summaryResult.status === "rejected") throw summaryResult.reason;
|
|
3013
|
+
if (partialResult.status === "rejected") throw partialResult.reason;
|
|
3014
|
+
const resSummary = summaryResult.value.data;
|
|
3015
|
+
const partials = partialResult.value;
|
|
3016
|
+
const opportunities = [];
|
|
3017
|
+
const stagesFailed = [];
|
|
3018
|
+
stageResults.forEach((r, i) => {
|
|
3019
|
+
if (r.status === "fulfilled") {
|
|
3020
|
+
opportunities.push(...r.value);
|
|
3021
|
+
} else {
|
|
3022
|
+
stagesFailed.push(OPEN_STAGES[i]);
|
|
3023
|
+
}
|
|
3024
|
+
});
|
|
3025
|
+
if (stagesFailed.length === OPEN_STAGES.length) {
|
|
3026
|
+
const firstFailure = stageResults.find(
|
|
3027
|
+
(r) => r.status === "rejected"
|
|
3028
|
+
);
|
|
3029
|
+
throw firstFailure.reason;
|
|
3030
|
+
}
|
|
2675
3031
|
const candidates = [];
|
|
2676
|
-
for (const c of
|
|
3032
|
+
for (const c of resSummary.available_now ?? []) {
|
|
2677
3033
|
candidates.push({ ...c, urgency: "idle", release_horizon_days: null });
|
|
2678
3034
|
}
|
|
2679
|
-
for (const c of
|
|
2680
|
-
|
|
2681
|
-
if (
|
|
2682
|
-
const day = apiCalendarDay(c.expected_release_date);
|
|
2683
|
-
if (day !== null) {
|
|
2684
|
-
horizon = day - today;
|
|
2685
|
-
if (horizon > horizon_days) continue;
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
3035
|
+
for (const c of resSummary.finishing_in_30_days ?? []) {
|
|
3036
|
+
const days = typeof c.days_remaining === "number" ? c.days_remaining : null;
|
|
3037
|
+
if (days !== null && days > horizon_days) continue;
|
|
2688
3038
|
candidates.push({
|
|
2689
3039
|
...c,
|
|
2690
3040
|
urgency: "finishing",
|
|
2691
|
-
release_horizon_days:
|
|
3041
|
+
release_horizon_days: days
|
|
2692
3042
|
});
|
|
2693
3043
|
}
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
});
|
|
2701
|
-
}
|
|
3044
|
+
for (const c of partials) {
|
|
3045
|
+
candidates.push({
|
|
3046
|
+
...c,
|
|
3047
|
+
urgency: "partial",
|
|
3048
|
+
release_horizon_days: null
|
|
3049
|
+
});
|
|
2702
3050
|
}
|
|
2703
|
-
const opportunities = oppResponses.flatMap(
|
|
2704
|
-
(r) => r.data ?? []
|
|
2705
|
-
);
|
|
2706
3051
|
const matches = [];
|
|
2707
3052
|
for (const c of candidates) {
|
|
2708
3053
|
const specs = toSpecNames(c.specialties);
|
|
@@ -2722,10 +3067,13 @@ function registerSkillMatch(server, client, logger) {
|
|
|
2722
3067
|
status: c.status ?? null,
|
|
2723
3068
|
urgency: c.urgency,
|
|
2724
3069
|
available_since: c.available_since ?? null,
|
|
2725
|
-
expected_release_date:
|
|
3070
|
+
// The summary emits no expected_release_date key: the release
|
|
3071
|
+
// date IS the end date of the project being finished, so it is
|
|
3072
|
+
// null for idle and partial candidates.
|
|
3073
|
+
expected_release_date: c.current_project?.end_date ?? null,
|
|
2726
3074
|
// null = the horizon filter did not apply to this consultant:
|
|
2727
|
-
//
|
|
2728
|
-
//
|
|
3075
|
+
// they are idle or partially allocated, not finishing a
|
|
3076
|
+
// project. Not "released today".
|
|
2729
3077
|
release_horizon_days: c.release_horizon_days,
|
|
2730
3078
|
specialties: specs
|
|
2731
3079
|
},
|
|
@@ -2755,7 +3103,10 @@ function registerSkillMatch(server, client, logger) {
|
|
|
2755
3103
|
min_match_percent,
|
|
2756
3104
|
include_partial,
|
|
2757
3105
|
candidates_considered: candidates.length,
|
|
2758
|
-
opportunities_considered: opportunities.length
|
|
3106
|
+
opportunities_considered: opportunities.length,
|
|
3107
|
+
// Stages whose listing failed: the match above ran WITHOUT them.
|
|
3108
|
+
// Empty means the full open pipeline was seen.
|
|
3109
|
+
stages_failed: stagesFailed
|
|
2759
3110
|
}
|
|
2760
3111
|
};
|
|
2761
3112
|
})
|
|
@@ -2768,7 +3119,11 @@ function fmtBRL(v) {
|
|
|
2768
3119
|
if (!Number.isFinite(n)) return "\u2014";
|
|
2769
3120
|
return n.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
|
|
2770
3121
|
}
|
|
2771
|
-
function
|
|
3122
|
+
function reasonLabel(e) {
|
|
3123
|
+
if (e instanceof LkpError) return `${e.code}: ${e.message}`;
|
|
3124
|
+
return e instanceof Error ? e.message : String(e);
|
|
3125
|
+
}
|
|
3126
|
+
function buildMarkdown(ceo, alerts, opp, res, unavailable) {
|
|
2772
3127
|
const score = ceo?.operational_health?.score ?? "\u2014";
|
|
2773
3128
|
const cls = ceo?.operational_health?.classification ?? "\u2014";
|
|
2774
3129
|
const period = ceo?.week ?? ceo?.period?.label ?? (ceo?.period?.from && ceo?.period?.to ? `${ceo.period.from} \u2192 ${ceo.period.to}` : "semana atual");
|
|
@@ -2777,6 +3132,13 @@ function buildMarkdown(ceo, alerts, opp, res) {
|
|
|
2777
3132
|
lines.push("");
|
|
2778
3133
|
lines.push(`## \u{1F321}\uFE0F Sa\xFAde Operacional: ${score}/100 (${cls})`);
|
|
2779
3134
|
lines.push("");
|
|
3135
|
+
if (unavailable.length > 0) {
|
|
3136
|
+
lines.push("## \u26A0\uFE0F N\xE3o foi poss\xEDvel apurar");
|
|
3137
|
+
for (const u of unavailable) {
|
|
3138
|
+
lines.push(`- ${u}`);
|
|
3139
|
+
}
|
|
3140
|
+
lines.push("");
|
|
3141
|
+
}
|
|
2780
3142
|
if (alerts && alerts.length > 0) {
|
|
2781
3143
|
lines.push("## \u{1F534} Aten\xE7\xE3o imediata");
|
|
2782
3144
|
for (const a of alerts.slice(0, 10)) {
|
|
@@ -2797,7 +3159,7 @@ function buildMarkdown(ceo, alerts, opp, res) {
|
|
|
2797
3159
|
if (opp?.totals) {
|
|
2798
3160
|
const t = opp.totals;
|
|
2799
3161
|
lines.push(
|
|
2800
|
-
`- Pipeline aberto: ${t.
|
|
3162
|
+
`- Pipeline aberto: ${t.open_opportunities ?? "\u2014"} oportunidades \xB7 valor ${fmtBRL(t.total_pipeline_value)} \xB7 ponderado ${fmtBRL(t.weighted_pipeline_value)}`
|
|
2801
3163
|
);
|
|
2802
3164
|
}
|
|
2803
3165
|
if (opp?.stale_opportunities) {
|
|
@@ -2821,11 +3183,11 @@ function registerWeeklyBrief(server, client, logger) {
|
|
|
2821
3183
|
"lkp_weekly_brief",
|
|
2822
3184
|
{
|
|
2823
3185
|
title: "Monday morning CEO briefing",
|
|
2824
|
-
description: "Narrative Monday-morning briefing. Calls the CEO weekly report + high-severity alerts + opportunities/resources summaries and composes a pre-formatted Portuguese markdown summary ready to paste into a message or read aloud. The factual numbers come pre-assembled.",
|
|
3186
|
+
description: "Narrative Monday-morning briefing. Calls the CEO weekly report + high-severity alerts + opportunities/resources summaries and composes a pre-formatted Portuguese markdown summary ready to paste into a message or read aloud. The factual numbers come pre-assembled. FOUR scopes are involved \u2014 read:reports, read:alerts, read:opportunities, read:resources \u2014 and each block has a ROLE door beyond its scope: alerts, the pipeline summary and the resource summary open only to admins and managers, while the CEO report also opens to the user marked as financially responsible. Tell the two doors apart by error.code, never the prose: 'insufficient_scope' means the TOKEN lacks that block's scope (reissuing it with the scope fixes it), 'forbidden' means the scope was fine and the OWNER'S ROLE was refused \u2014 no token fixes that. The scope is checked FIRST, so after adding a scope the SAME refusal can come back as 'forbidden'; that is the second door, not the API contradicting itself. A refused or failed block does not cost the rest of the brief: it still renders from the blocks that answered, and a 'N\xE3o foi poss\xEDvel apurar' section names each missing block with its error \u2014 only all four failing makes the tool fail.",
|
|
2825
3187
|
inputSchema: {}
|
|
2826
3188
|
},
|
|
2827
3189
|
async () => runToolText(logger, "lkp_weekly_brief", async () => {
|
|
2828
|
-
const [ceo, alerts, opp, res] = await Promise.
|
|
3190
|
+
const [ceo, alerts, opp, res] = await Promise.allSettled([
|
|
2829
3191
|
client.get("/api/v1/reports/ceo-weekly"),
|
|
2830
3192
|
client.get("/api/v1/alerts", {
|
|
2831
3193
|
severity: "high"
|
|
@@ -2833,13 +3195,68 @@ function registerWeeklyBrief(server, client, logger) {
|
|
|
2833
3195
|
client.get("/api/v1/opportunities/summary"),
|
|
2834
3196
|
client.get("/api/v1/resources/summary")
|
|
2835
3197
|
]);
|
|
2836
|
-
|
|
3198
|
+
if (ceo.status === "rejected" && alerts.status === "rejected" && opp.status === "rejected" && res.status === "rejected") {
|
|
3199
|
+
throw ceo.reason;
|
|
3200
|
+
}
|
|
3201
|
+
const unavailable = [];
|
|
3202
|
+
function pick(r, block) {
|
|
3203
|
+
if (r.status === "fulfilled") return r.value.data;
|
|
3204
|
+
unavailable.push(`${block} \u2014 ${reasonLabel(r.reason)}`);
|
|
3205
|
+
return void 0;
|
|
3206
|
+
}
|
|
3207
|
+
return buildMarkdown(
|
|
3208
|
+
pick(ceo, "sa\xFAde operacional e per\xEDodo (reports/ceo-weekly)"),
|
|
3209
|
+
pick(alerts, "alertas de severidade alta (alerts)"),
|
|
3210
|
+
pick(opp, "pipeline e oportunidades stale (opportunities/summary)"),
|
|
3211
|
+
pick(res, "capacidade de consultores (resources/summary)"),
|
|
3212
|
+
unavailable
|
|
3213
|
+
);
|
|
2837
3214
|
})
|
|
2838
3215
|
);
|
|
2839
3216
|
}
|
|
2840
3217
|
|
|
2841
3218
|
// src/tools/composite/timesheet-anomalies.ts
|
|
2842
3219
|
import { z as z18 } from "zod";
|
|
3220
|
+
|
|
3221
|
+
// src/api-date.ts
|
|
3222
|
+
var API_TIMEZONE = "America/Sao_Paulo";
|
|
3223
|
+
var MS_PER_DAY = 864e5;
|
|
3224
|
+
var CALENDAR_DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[ T].*)?$/;
|
|
3225
|
+
function apiCalendarDay(raw) {
|
|
3226
|
+
if (typeof raw !== "string") return null;
|
|
3227
|
+
const m = CALENDAR_DATE.exec(raw.trim());
|
|
3228
|
+
if (!m) return null;
|
|
3229
|
+
const year = Number(m[1]);
|
|
3230
|
+
const month = Number(m[2]);
|
|
3231
|
+
const day = Number(m[3]);
|
|
3232
|
+
const utc = Date.UTC(year, month - 1, day);
|
|
3233
|
+
const back = new Date(utc);
|
|
3234
|
+
if (back.getUTCFullYear() !== year || back.getUTCMonth() !== month - 1 || back.getUTCDate() !== day) {
|
|
3235
|
+
return null;
|
|
3236
|
+
}
|
|
3237
|
+
return utc / MS_PER_DAY;
|
|
3238
|
+
}
|
|
3239
|
+
function dayOfWeek(calendarDay) {
|
|
3240
|
+
return new Date(calendarDay * MS_PER_DAY).getUTCDay();
|
|
3241
|
+
}
|
|
3242
|
+
function todayInApiCalendar(now = Date.now()) {
|
|
3243
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
3244
|
+
timeZone: API_TIMEZONE,
|
|
3245
|
+
year: "numeric",
|
|
3246
|
+
month: "2-digit",
|
|
3247
|
+
day: "2-digit"
|
|
3248
|
+
}).formatToParts(new Date(now));
|
|
3249
|
+
const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
|
|
3250
|
+
const day = apiCalendarDay(`${get("year")}-${get("month")}-${get("day")}`);
|
|
3251
|
+
if (day === null) {
|
|
3252
|
+
throw new Error(
|
|
3253
|
+
`Could not resolve today in ${API_TIMEZONE} (Intl returned ${JSON.stringify(parts)}).`
|
|
3254
|
+
);
|
|
3255
|
+
}
|
|
3256
|
+
return day;
|
|
3257
|
+
}
|
|
3258
|
+
|
|
3259
|
+
// src/tools/composite/timesheet-anomalies.ts
|
|
2843
3260
|
function linkedTaskId(e) {
|
|
2844
3261
|
for (const raw of [e.task?.id, e.task_id]) {
|
|
2845
3262
|
if (raw === null || raw === void 0) continue;
|
|
@@ -2850,6 +3267,7 @@ function linkedTaskId(e) {
|
|
|
2850
3267
|
}
|
|
2851
3268
|
async function fetchAllTimesheets(client, resourceId, from, to) {
|
|
2852
3269
|
const all = [];
|
|
3270
|
+
let resourceName = null;
|
|
2853
3271
|
for (let page = 1; page <= 5; page++) {
|
|
2854
3272
|
const r = await client.get(`/api/v1/resources/${resourceId}/timesheets`, {
|
|
2855
3273
|
from,
|
|
@@ -2859,10 +3277,11 @@ async function fetchAllTimesheets(client, resourceId, from, to) {
|
|
|
2859
3277
|
});
|
|
2860
3278
|
const batch = r.data ?? [];
|
|
2861
3279
|
all.push(...batch);
|
|
3280
|
+
resourceName ??= r.meta?.resource?.name ?? null;
|
|
2862
3281
|
const last = r.meta?.last_page;
|
|
2863
3282
|
if (last && page >= last || batch.length < 200) break;
|
|
2864
3283
|
}
|
|
2865
|
-
return all;
|
|
3284
|
+
return { entries: all, resourceName };
|
|
2866
3285
|
}
|
|
2867
3286
|
async function fetchAllResources(client) {
|
|
2868
3287
|
const perPage = 100;
|
|
@@ -2990,29 +3409,58 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
2990
3409
|
"lkp_timesheet_anomalies",
|
|
2991
3410
|
{
|
|
2992
3411
|
title: "Detect timesheet anomalies",
|
|
2993
|
-
description: "Detect suspicious timesheet patterns for one consultant or across the team over a date range. Flags: days with >10h, weekend work, unapproved entries older than N days, orphaned entries (no task link). Use before closing a payroll period or when investigating a specific consultant.",
|
|
3412
|
+
description: "Detect suspicious timesheet patterns for one consultant or across the team over a date range. Flags: days with >10h, weekend work, unapproved entries older than N days, orphaned entries (no task link). Use before closing a payroll period or when investigating a specific consultant. from/to are calendar dates in YYYY-MM-DD with from \u2264 to, spanning AT MOST 184 days (~6 months) \u2014 the backend refuses anything else with 400 invalid_filter, and this tool refuses the same shapes locally before spending a single request of the scan; there is no way to ask for 'the whole year' in one call. In team scope a consultant whose timesheets could not be fetched is NOT silently dropped: resources_failed lists each one by name and summary.coverage reads scanned/attempted \u2014 findings attest ONLY to the resources_scanned and entries_scanned reported next to them, so an empty findings list with a short coverage is a partial view, never a clean bill.",
|
|
2994
3413
|
inputSchema: {
|
|
2995
|
-
|
|
2996
|
-
|
|
3414
|
+
// The regex mirrors the backend's own format gate; calendar validity,
|
|
3415
|
+
// ordering and the 184-day ceiling are checked in the handler, where
|
|
3416
|
+
// both values are in hand.
|
|
3417
|
+
from: z18.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD"),
|
|
3418
|
+
to: z18.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD"),
|
|
2997
3419
|
resource_id: z18.coerce.number().int().positive().optional(),
|
|
2998
3420
|
unapproved_days_threshold: z18.coerce.number().int().positive().default(15)
|
|
2999
3421
|
}
|
|
3000
3422
|
},
|
|
3001
3423
|
async ({ from, to, resource_id, unapproved_days_threshold }) => runTool(logger, "lkp_timesheet_anomalies", async () => {
|
|
3002
3424
|
const today = todayInApiCalendar();
|
|
3425
|
+
const fromDay = apiCalendarDay(from);
|
|
3426
|
+
const toDay = apiCalendarDay(to);
|
|
3427
|
+
if (fromDay === null || toDay === null) {
|
|
3428
|
+
throw new LkpError({
|
|
3429
|
+
code: "bad_request",
|
|
3430
|
+
api_code: "invalid_filter",
|
|
3431
|
+
message: `${fromDay === null ? "from" : "to"} is not a real calendar date (YYYY-MM-DD).`
|
|
3432
|
+
});
|
|
3433
|
+
}
|
|
3434
|
+
if (fromDay > toDay) {
|
|
3435
|
+
throw new LkpError({
|
|
3436
|
+
code: "bad_request",
|
|
3437
|
+
api_code: "invalid_filter",
|
|
3438
|
+
message: "from must be \u2264 to."
|
|
3439
|
+
});
|
|
3440
|
+
}
|
|
3441
|
+
if (toDay - fromDay + 1 > 184) {
|
|
3442
|
+
throw new LkpError({
|
|
3443
|
+
code: "bad_request",
|
|
3444
|
+
api_code: "invalid_filter",
|
|
3445
|
+
message: "Range cannot exceed 184 days (~6 months)."
|
|
3446
|
+
});
|
|
3447
|
+
}
|
|
3003
3448
|
const findings = [];
|
|
3004
3449
|
const scanned = [];
|
|
3450
|
+
const failed = [];
|
|
3451
|
+
let entriesScanned = 0;
|
|
3005
3452
|
let scope;
|
|
3006
3453
|
if (resource_id !== void 0) {
|
|
3007
3454
|
scope = "resource";
|
|
3008
|
-
const entries = await fetchAllTimesheets(
|
|
3455
|
+
const { entries, resourceName } = await fetchAllTimesheets(
|
|
3009
3456
|
client,
|
|
3010
3457
|
resource_id,
|
|
3011
3458
|
from,
|
|
3012
3459
|
to
|
|
3013
3460
|
);
|
|
3014
|
-
const name =
|
|
3461
|
+
const name = resourceName ?? `#${resource_id}`;
|
|
3015
3462
|
scanned.push({ id: resource_id, name });
|
|
3463
|
+
entriesScanned += entries.length;
|
|
3016
3464
|
findings.push(
|
|
3017
3465
|
...detectAnomalies(
|
|
3018
3466
|
entries,
|
|
@@ -3029,13 +3477,14 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
3029
3477
|
);
|
|
3030
3478
|
await mapLimit(active, 5, async (r) => {
|
|
3031
3479
|
try {
|
|
3032
|
-
const entries = await fetchAllTimesheets(
|
|
3480
|
+
const { entries } = await fetchAllTimesheets(
|
|
3033
3481
|
client,
|
|
3034
3482
|
r.id,
|
|
3035
3483
|
from,
|
|
3036
3484
|
to
|
|
3037
3485
|
);
|
|
3038
3486
|
scanned.push({ id: r.id, name: r.name });
|
|
3487
|
+
entriesScanned += entries.length;
|
|
3039
3488
|
findings.push(
|
|
3040
3489
|
...detectAnomalies(
|
|
3041
3490
|
entries,
|
|
@@ -3046,6 +3495,12 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
3046
3495
|
)
|
|
3047
3496
|
);
|
|
3048
3497
|
} catch (e) {
|
|
3498
|
+
if (e instanceof LkpError && e.http_status === 400) throw e;
|
|
3499
|
+
failed.push({
|
|
3500
|
+
resource_id: r.id,
|
|
3501
|
+
name: r.name,
|
|
3502
|
+
error: e instanceof LkpError ? `${e.code}: ${e.message}` : e.message
|
|
3503
|
+
});
|
|
3049
3504
|
logger.warn(
|
|
3050
3505
|
{ resource_id: r.id, err: e.message },
|
|
3051
3506
|
"timesheets_fetch_failed"
|
|
@@ -3061,8 +3516,19 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
3061
3516
|
period: { from, to },
|
|
3062
3517
|
scope,
|
|
3063
3518
|
resources_scanned: scanned.length,
|
|
3519
|
+
// Every consultant whose timesheets could not be fetched, by name.
|
|
3520
|
+
// An empty list is the only thing that lets findings be read as
|
|
3521
|
+
// covering the whole scope.
|
|
3522
|
+
resources_failed: failed,
|
|
3523
|
+
entries_scanned: entriesScanned,
|
|
3064
3524
|
findings,
|
|
3065
|
-
summary: {
|
|
3525
|
+
summary: {
|
|
3526
|
+
total_findings: findings.length,
|
|
3527
|
+
by_type: byType,
|
|
3528
|
+
// scanned/attempted — anything below N/N marks findings as a
|
|
3529
|
+
// PARTIAL view of the period, whatever total_findings says.
|
|
3530
|
+
coverage: `${scanned.length}/${scanned.length + failed.length}`
|
|
3531
|
+
}
|
|
3066
3532
|
};
|
|
3067
3533
|
})
|
|
3068
3534
|
);
|
|
@@ -3337,126 +3803,6 @@ function registerAllPrompts(server) {
|
|
|
3337
3803
|
registerPipelineHealthCheckPrompt(server);
|
|
3338
3804
|
}
|
|
3339
3805
|
|
|
3340
|
-
// src/contract.ts
|
|
3341
|
-
var EXPECTED_CONTRACT = "2.16";
|
|
3342
|
-
function minorOf(version) {
|
|
3343
|
-
const [major = "", minor = ""] = version.split(".");
|
|
3344
|
-
return { major, minor: Number(minor) };
|
|
3345
|
-
}
|
|
3346
|
-
function compareContract(serverContract, expected = EXPECTED_CONTRACT) {
|
|
3347
|
-
if (serverContract === null) {
|
|
3348
|
-
return {
|
|
3349
|
-
status: "pre_contract",
|
|
3350
|
-
server_contract: null,
|
|
3351
|
-
message: `LKPGest\xE3o predates API contract ${expected} (no GET /api/v1/meta). Fields documented by this MCP build may be missing from responses.`
|
|
3352
|
-
};
|
|
3353
|
-
}
|
|
3354
|
-
if (serverContract === expected) {
|
|
3355
|
-
return {
|
|
3356
|
-
status: "ok",
|
|
3357
|
-
server_contract: serverContract,
|
|
3358
|
-
message: `API contract ${serverContract} matches this build.`
|
|
3359
|
-
};
|
|
3360
|
-
}
|
|
3361
|
-
const srv = minorOf(serverContract);
|
|
3362
|
-
const exp = minorOf(expected);
|
|
3363
|
-
if (srv.major !== exp.major) {
|
|
3364
|
-
return {
|
|
3365
|
-
status: "incompatible",
|
|
3366
|
-
server_contract: serverContract,
|
|
3367
|
-
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.`
|
|
3368
|
-
};
|
|
3369
|
-
}
|
|
3370
|
-
if (Number.isFinite(srv.minor) && Number.isFinite(exp.minor) && srv.minor < exp.minor) {
|
|
3371
|
-
return {
|
|
3372
|
-
status: "server_older",
|
|
3373
|
-
server_contract: serverContract,
|
|
3374
|
-
message: `API contract ${serverContract} is older than the ${expected} this build expects. Fields added after ${serverContract} may be absent from responses.`
|
|
3375
|
-
};
|
|
3376
|
-
}
|
|
3377
|
-
return {
|
|
3378
|
-
status: "server_newer",
|
|
3379
|
-
server_contract: serverContract,
|
|
3380
|
-
message: `API contract ${serverContract} is newer than the ${expected} this build expects (additive). New fields exist that this MCP does not document yet.`
|
|
3381
|
-
};
|
|
3382
|
-
}
|
|
3383
|
-
var BLOCKING_STATUSES = /* @__PURE__ */ new Set([
|
|
3384
|
-
"pre_contract",
|
|
3385
|
-
"incompatible",
|
|
3386
|
-
"server_older"
|
|
3387
|
-
]);
|
|
3388
|
-
function isStartupBlocked(status, required) {
|
|
3389
|
-
return required && BLOCKING_STATUSES.has(status);
|
|
3390
|
-
}
|
|
3391
|
-
async function enforceContractOnStartup(client, logger, required, expected = EXPECTED_CONTRACT) {
|
|
3392
|
-
const result = await checkContractVersion(client, logger, expected);
|
|
3393
|
-
if (isStartupBlocked(result.status, required)) {
|
|
3394
|
-
logger.fatal(
|
|
3395
|
-
{
|
|
3396
|
-
expected_contract: expected,
|
|
3397
|
-
server_contract: result.server_contract,
|
|
3398
|
-
check: result.status,
|
|
3399
|
-
require_contract: true
|
|
3400
|
-
},
|
|
3401
|
-
"refusing to start: LKP_REQUIRE_CONTRACT is on and the API contract does not satisfy this build"
|
|
3402
|
-
);
|
|
3403
|
-
throw new Error(
|
|
3404
|
-
`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.`
|
|
3405
|
-
);
|
|
3406
|
-
}
|
|
3407
|
-
return result;
|
|
3408
|
-
}
|
|
3409
|
-
async function checkContractVersion(client, logger, expected = EXPECTED_CONTRACT) {
|
|
3410
|
-
let serverContract;
|
|
3411
|
-
try {
|
|
3412
|
-
const meta = await client.get("/api/v1/meta");
|
|
3413
|
-
const raw = meta?.data?.contract_version;
|
|
3414
|
-
if (typeof raw !== "string" || raw === "") {
|
|
3415
|
-
const result2 = {
|
|
3416
|
-
status: "unavailable",
|
|
3417
|
-
server_contract: null,
|
|
3418
|
-
message: `GET /api/v1/meta answered without a contract_version string.`
|
|
3419
|
-
};
|
|
3420
|
-
logger.warn(
|
|
3421
|
-
{ expected_contract: expected, check: result2.status },
|
|
3422
|
-
result2.message
|
|
3423
|
-
);
|
|
3424
|
-
return result2;
|
|
3425
|
-
}
|
|
3426
|
-
serverContract = raw;
|
|
3427
|
-
} catch (e) {
|
|
3428
|
-
if (e instanceof LkpError && e.http_status === 404) {
|
|
3429
|
-
serverContract = null;
|
|
3430
|
-
} else {
|
|
3431
|
-
const err = e instanceof LkpError ? e.toJSON() : { message: String(e) };
|
|
3432
|
-
const result2 = {
|
|
3433
|
-
status: "unavailable",
|
|
3434
|
-
server_contract: null,
|
|
3435
|
-
message: `Could not read the API contract version from GET /api/v1/meta.`
|
|
3436
|
-
};
|
|
3437
|
-
logger.warn(
|
|
3438
|
-
{ expected_contract: expected, check: result2.status, err },
|
|
3439
|
-
result2.message
|
|
3440
|
-
);
|
|
3441
|
-
return result2;
|
|
3442
|
-
}
|
|
3443
|
-
}
|
|
3444
|
-
const result = compareContract(serverContract, expected);
|
|
3445
|
-
const fields = {
|
|
3446
|
-
expected_contract: expected,
|
|
3447
|
-
server_contract: result.server_contract,
|
|
3448
|
-
check: result.status
|
|
3449
|
-
};
|
|
3450
|
-
if (result.status === "incompatible") {
|
|
3451
|
-
logger.error(fields, result.message);
|
|
3452
|
-
} else if (result.status === "ok") {
|
|
3453
|
-
logger.info(fields, result.message);
|
|
3454
|
-
} else {
|
|
3455
|
-
logger.warn(fields, result.message);
|
|
3456
|
-
}
|
|
3457
|
-
return result;
|
|
3458
|
-
}
|
|
3459
|
-
|
|
3460
3806
|
// src/index.ts
|
|
3461
3807
|
async function main() {
|
|
3462
3808
|
const config = loadConfig();
|