lkpgestao-mcp 0.22.0 → 0.23.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 +439 -216
- 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.23.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)"
|
|
@@ -546,6 +546,7 @@ var COMMENT_DELETE_DOC = "Deleting a comment is NOT reversible through this API:
|
|
|
546
546
|
function withServiceIdentity(body, replyAsServiceIdentity) {
|
|
547
547
|
return replyAsServiceIdentity === true ? { ...body, reply_as_service_identity: true } : body;
|
|
548
548
|
}
|
|
549
|
+
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.";
|
|
549
550
|
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
551
|
async function runTool(logger, name, fn) {
|
|
551
552
|
const started = Date.now();
|
|
@@ -598,13 +599,13 @@ function registerResources(server, client, logger) {
|
|
|
598
599
|
"lkp_resources_list",
|
|
599
600
|
{
|
|
600
601
|
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.",
|
|
602
|
+
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
603
|
inputSchema: {
|
|
603
|
-
status: z4.
|
|
604
|
+
status: z4.enum(["active", "inactive"]).optional(),
|
|
604
605
|
contract_type: z4.string().optional(),
|
|
605
606
|
specialty_id: z4.coerce.number().int().positive().optional(),
|
|
606
607
|
allocation: z4.enum(["available", "partial", "full", "overloaded"]).optional(),
|
|
607
|
-
role: z4.
|
|
608
|
+
role: z4.enum(["admin", "manager", "consultant", "client"]).optional(),
|
|
608
609
|
search: z4.string().optional(),
|
|
609
610
|
page: z4.coerce.number().int().positive().optional(),
|
|
610
611
|
per_page: z4.coerce.number().int().positive().max(100).default(50)
|
|
@@ -653,7 +654,7 @@ function registerResources(server, client, logger) {
|
|
|
653
654
|
"lkp_specialties_list",
|
|
654
655
|
{
|
|
655
656
|
title: "List specialties",
|
|
656
|
-
description:
|
|
657
|
+
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
658
|
inputSchema: {
|
|
658
659
|
category: z4.enum([
|
|
659
660
|
"SAP_DESENVOLVIMENTO",
|
|
@@ -663,29 +664,35 @@ function registerResources(server, client, logger) {
|
|
|
663
664
|
"BACKOFFICE"
|
|
664
665
|
]).optional(),
|
|
665
666
|
search: z4.string().optional(),
|
|
666
|
-
active_only: z4.
|
|
667
|
+
active_only: z4.boolean().default(true)
|
|
667
668
|
}
|
|
668
669
|
},
|
|
669
|
-
async (
|
|
670
|
+
async ({ active_only, ...query }) => runTool(
|
|
670
671
|
logger,
|
|
671
672
|
"lkp_specialties_list",
|
|
672
|
-
() => client.get("/api/v1/specialties",
|
|
673
|
+
() => client.get("/api/v1/specialties", {
|
|
674
|
+
...query,
|
|
675
|
+
// The endpoint drops the active-only filter for the LITERAL string '0'
|
|
676
|
+
// and for no other spelling of "no", so the flag is serialised here
|
|
677
|
+
// rather than left to the query builder's String(value).
|
|
678
|
+
active_only: active_only ? "1" : "0"
|
|
679
|
+
})
|
|
673
680
|
)
|
|
674
681
|
);
|
|
675
682
|
server.registerTool(
|
|
676
683
|
"lkp_resource_timesheets",
|
|
677
684
|
{
|
|
678
685
|
title: "Resource timesheet entries",
|
|
679
|
-
description:
|
|
686
|
+
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
687
|
inputSchema: {
|
|
681
688
|
resource_id: z4.coerce.number().int().positive(),
|
|
682
689
|
from: z4.string(),
|
|
683
690
|
to: z4.string(),
|
|
684
691
|
project_id: z4.coerce.number().int().positive().optional(),
|
|
685
692
|
task_id: z4.coerce.number().int().positive().optional(),
|
|
686
|
-
is_approved: z4.
|
|
687
|
-
is_billable: z4.
|
|
688
|
-
source: z4.
|
|
693
|
+
is_approved: z4.boolean().optional(),
|
|
694
|
+
is_billable: z4.boolean().optional(),
|
|
695
|
+
source: z4.enum(["project", "crm"]).optional(),
|
|
689
696
|
page: z4.coerce.number().int().positive().optional(),
|
|
690
697
|
per_page: z4.coerce.number().int().positive().max(200).default(50)
|
|
691
698
|
}
|
|
@@ -708,16 +715,15 @@ function registerTimesheets(server, client, logger) {
|
|
|
708
715
|
"lkp_timesheet_create",
|
|
709
716
|
{
|
|
710
717
|
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
|
|
718
|
+
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
719
|
inputSchema: {
|
|
713
720
|
resource_id: z5.coerce.number().int().positive(),
|
|
714
721
|
work_date: z5.string(),
|
|
715
722
|
hours: z5.coerce.number(),
|
|
716
723
|
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()
|
|
724
|
+
task_id: z5.coerce.number().int().positive(),
|
|
725
|
+
is_approved: z5.boolean().optional(),
|
|
726
|
+
source: z5.enum(["project", "crm"]).optional()
|
|
721
727
|
}
|
|
722
728
|
},
|
|
723
729
|
async ({ resource_id, ...body }) => runTool(
|
|
@@ -733,7 +739,7 @@ function registerTimesheets(server, client, logger) {
|
|
|
733
739
|
"lkp_timesheet_update",
|
|
734
740
|
{
|
|
735
741
|
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.",
|
|
742
|
+
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
743
|
inputSchema: {
|
|
738
744
|
resource_id: z5.coerce.number().int().positive(),
|
|
739
745
|
timesheet_id: z5.coerce.number().int().positive(),
|
|
@@ -741,8 +747,7 @@ function registerTimesheets(server, client, logger) {
|
|
|
741
747
|
hours: z5.coerce.number().optional(),
|
|
742
748
|
comments: z5.string().min(1).max(1e3).optional(),
|
|
743
749
|
task_id: z5.coerce.number().int().positive().optional(),
|
|
744
|
-
|
|
745
|
-
is_approved: z5.coerce.boolean().optional()
|
|
750
|
+
is_approved: z5.boolean().optional()
|
|
746
751
|
}
|
|
747
752
|
},
|
|
748
753
|
async ({ resource_id, timesheet_id, ...body }) => runTool(
|
|
@@ -775,6 +780,8 @@ function registerTimesheets(server, client, logger) {
|
|
|
775
780
|
|
|
776
781
|
// src/tools/projects.ts
|
|
777
782
|
import { z as z6 } from "zod";
|
|
783
|
+
var RateType = z6.enum(["primary", "secondary", "custom"]);
|
|
784
|
+
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
785
|
function registerProjects(server, client, logger) {
|
|
779
786
|
server.registerTool(
|
|
780
787
|
"lkp_projects_list",
|
|
@@ -801,7 +808,7 @@ function registerProjects(server, client, logger) {
|
|
|
801
808
|
"lkp_projects_summary",
|
|
802
809
|
{
|
|
803
810
|
title: "Projects portfolio summary",
|
|
804
|
-
description: "Portfolio dashboard: project counts by status, financial aggregate from billing milestones, upcoming milestones in the next 30 days.",
|
|
811
|
+
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
812
|
inputSchema: {}
|
|
806
813
|
},
|
|
807
814
|
async () => runTool(
|
|
@@ -829,18 +836,22 @@ function registerProjects(server, client, logger) {
|
|
|
829
836
|
"lkp_project_create",
|
|
830
837
|
{
|
|
831
838
|
title: "Create project (write)",
|
|
832
|
-
description: "Create a new project. Requires name, client_id and
|
|
839
|
+
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
840
|
inputSchema: {
|
|
834
841
|
name: z6.string().min(1),
|
|
835
842
|
client_id: z6.coerce.number().int().positive(),
|
|
836
843
|
status_id: z6.coerce.number().int().positive(),
|
|
837
844
|
description: z6.string().optional(),
|
|
838
845
|
manager_id: z6.coerce.number().int().positive().optional(),
|
|
839
|
-
start_date: z6.string().
|
|
840
|
-
end_date: z6.string().
|
|
846
|
+
start_date: z6.string().min(1),
|
|
847
|
+
end_date: z6.string().min(1),
|
|
841
848
|
budget: z6.coerce.number().nonnegative().optional(),
|
|
842
|
-
|
|
843
|
-
|
|
849
|
+
// Strict boolean, like is_internal and reply_as_service_identity: with
|
|
850
|
+
// z.coerce.boolean() the string "false" arrives as true, which here
|
|
851
|
+
// creates a BILLABLE project out of a request for an internal one — or
|
|
852
|
+
// trips the billing_model 422 that the caller was avoiding.
|
|
853
|
+
is_billable: z6.boolean().optional(),
|
|
854
|
+
billing_model: z6.enum(["milestone", "installment", "measurement", "subscription", "none"]).optional(),
|
|
844
855
|
source_opportunity_id: z6.coerce.number().int().positive().optional()
|
|
845
856
|
}
|
|
846
857
|
},
|
|
@@ -854,7 +865,7 @@ function registerProjects(server, client, logger) {
|
|
|
854
865
|
"lkp_project_update",
|
|
855
866
|
{
|
|
856
867
|
title: "Update project (write)",
|
|
857
|
-
description: "Update whitelisted fields on a project. Setting is_active: false archives the project (
|
|
868
|
+
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
869
|
inputSchema: {
|
|
859
870
|
project_id: z6.coerce.number().int().positive(),
|
|
860
871
|
name: z6.string().optional(),
|
|
@@ -864,7 +875,10 @@ function registerProjects(server, client, logger) {
|
|
|
864
875
|
start_date: z6.string().optional(),
|
|
865
876
|
end_date: z6.string().optional(),
|
|
866
877
|
budget: z6.coerce.number().nonnegative().optional(),
|
|
867
|
-
|
|
878
|
+
// Strict boolean: z.coerce.boolean() reads the string "false" as true,
|
|
879
|
+
// which on THIS field restores a project when the caller asked to
|
|
880
|
+
// archive it (and the other way round). Same reason as is_billable.
|
|
881
|
+
is_active: z6.boolean().optional()
|
|
868
882
|
}
|
|
869
883
|
},
|
|
870
884
|
async ({ project_id, ...body }) => runTool(
|
|
@@ -877,7 +891,7 @@ function registerProjects(server, client, logger) {
|
|
|
877
891
|
"lkp_project_archive",
|
|
878
892
|
{
|
|
879
893
|
title: "Archive project (write)",
|
|
880
|
-
description: "Soft-archive a project by setting is_active=0.
|
|
894
|
+
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
895
|
inputSchema: {
|
|
882
896
|
project_id: z6.coerce.number().int().positive()
|
|
883
897
|
}
|
|
@@ -891,7 +905,7 @@ function registerProjects(server, client, logger) {
|
|
|
891
905
|
"lkp_project_members_list",
|
|
892
906
|
{
|
|
893
907
|
title: "List project team members",
|
|
894
|
-
description: "List team members of a project with their role, rate type and hourly rate.
|
|
908
|
+
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
909
|
inputSchema: {
|
|
896
910
|
project_id: z6.coerce.number().int().positive(),
|
|
897
911
|
include_inactive: z6.coerce.boolean().optional()
|
|
@@ -909,12 +923,12 @@ function registerProjects(server, client, logger) {
|
|
|
909
923
|
"lkp_project_member_add",
|
|
910
924
|
{
|
|
911
925
|
title: "Add member to project (write)",
|
|
912
|
-
description: "Add a consultant to the project team. user_id must be an
|
|
926
|
+
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
927
|
inputSchema: {
|
|
914
928
|
project_id: z6.coerce.number().int().positive(),
|
|
915
929
|
user_id: z6.coerce.number().int().positive(),
|
|
916
930
|
role: z6.enum(["member", "collaborator", "observer"]).optional(),
|
|
917
|
-
rate_type:
|
|
931
|
+
rate_type: RateType.optional(),
|
|
918
932
|
selected_hourly_rate: z6.coerce.number().nonnegative().optional()
|
|
919
933
|
}
|
|
920
934
|
},
|
|
@@ -928,12 +942,12 @@ function registerProjects(server, client, logger) {
|
|
|
928
942
|
"lkp_project_member_update",
|
|
929
943
|
{
|
|
930
944
|
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.",
|
|
945
|
+
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
946
|
inputSchema: {
|
|
933
947
|
project_id: z6.coerce.number().int().positive(),
|
|
934
948
|
member_id: z6.coerce.number().int().positive(),
|
|
935
949
|
role: z6.enum(["member", "collaborator", "observer"]).optional(),
|
|
936
|
-
rate_type:
|
|
950
|
+
rate_type: RateType.optional(),
|
|
937
951
|
selected_hourly_rate: z6.coerce.number().nonnegative().optional()
|
|
938
952
|
}
|
|
939
953
|
},
|
|
@@ -950,7 +964,7 @@ function registerProjects(server, client, logger) {
|
|
|
950
964
|
"lkp_project_member_remove",
|
|
951
965
|
{
|
|
952
966
|
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.",
|
|
967
|
+
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
968
|
inputSchema: {
|
|
955
969
|
project_id: z6.coerce.number().int().positive(),
|
|
956
970
|
member_id: z6.coerce.number().int().positive()
|
|
@@ -996,22 +1010,25 @@ function registerTasks(server, client, logger) {
|
|
|
996
1010
|
"lkp_task_get",
|
|
997
1011
|
{
|
|
998
1012
|
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.",
|
|
1013
|
+
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
1014
|
inputSchema: {
|
|
1001
|
-
task_id: z7.coerce.number().int().positive()
|
|
1015
|
+
task_id: z7.coerce.number().int().positive(),
|
|
1016
|
+
// Strict boolean on purpose: z.coerce.boolean() would turn the string
|
|
1017
|
+
// "false" into true and hand back an archived task the caller excluded.
|
|
1018
|
+
include_inactive: z7.boolean().optional()
|
|
1002
1019
|
}
|
|
1003
1020
|
},
|
|
1004
|
-
async ({ task_id }) => runTool(
|
|
1021
|
+
async ({ task_id, ...args }) => runTool(
|
|
1005
1022
|
logger,
|
|
1006
1023
|
"lkp_task_get",
|
|
1007
|
-
() => client.get(`/api/v1/tasks/${task_id}
|
|
1024
|
+
() => client.get(`/api/v1/tasks/${task_id}`, args)
|
|
1008
1025
|
)
|
|
1009
1026
|
);
|
|
1010
1027
|
server.registerTool(
|
|
1011
1028
|
"lkp_task_create",
|
|
1012
1029
|
{
|
|
1013
1030
|
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,
|
|
1031
|
+
description: "Create a new task in a project. Required: title, start_date, due_date and estimated_hours (YYYY-MM-DD for the dates, start_date <= due_date) \u2014 the backend validator (Task::validateData) rejects the request with 422 when any of them is missing, even though older docs listed them as optional. estimated_hours: 0 is only accepted when the target status is Em Planejamento (1) or Conclu\xEDda (7); a create defaults to Em Planejamento (1) so 0 goes through here, but the same 0 is rejected once the task moves to any other status. Dates that are individually valid can still fail with 422 when they fall outside the project window or outside the subtasks' range \u2014 that check is the server's, do not try to replicate it. status_id defaults to 1 (Em Planejamento), priority defaults to 'medium'. If specialty_id is provided, skill_level is required (J\xFAnior/Pleno/S\xEAnior/Especialista). parent_task_id must belong to the same project and cannot be nested more than 1 level deep. project_b1_code_id must belong to the same client as the project. status_id >= 2 (Liberado para Execu\xE7\xE3o) TURNS assignee_id, specialty_id (which in turn requires skill_level) AND project_b1_code_id INTO REQUIRED FIELDS \u2014 creating a task already released for execution means supplying the whole task, so to create just the skeleton leave status_id at its default 1; a create with status_id: 2 carrying only the four fields listed as required above comes back 422 validation_failed naming three fields this schema presents as optional. CREATING A TASK IS AN ADMIN/MANAGER ACTION and write:tasks is only the first door: the TOKEN OWNER must be an administrator, or a MANAGER LINKED TO THIS PROJECT (a member in project_users, or its manager_id) \u2014 a plain user holding write:tasks is refused with 403 forbidden, and no token fixes that, only a different person or that person promoted. 404 not_found means the project does not exist OR IS ARCHIVED: tasks are created in ACTIVE projects only. 422 helpdesk_ticket_no_new_subtask means the parent_task_id belongs to a task whose helpdesk ticket is already resolved, closed or cancelled \u2014 the way forward is to REOPEN THE TICKET, never to retry the create or to reword it. Ask the user for the dates and the estimate if they were not given \u2014 do not invent them. Confirm the draft with the user before calling. " + TASK_STATUS_REF,
|
|
1015
1032
|
inputSchema: {
|
|
1016
1033
|
project_id: z7.coerce.number().int().positive(),
|
|
1017
1034
|
title: z7.string().min(1),
|
|
@@ -1038,7 +1055,7 @@ function registerTasks(server, client, logger) {
|
|
|
1038
1055
|
"lkp_task_update",
|
|
1039
1056
|
{
|
|
1040
1057
|
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,
|
|
1058
|
+
description: "Update whitelisted fields on a task. project_id is immutable. Moving the task INTO status_id 7 (Conclu\xEDda) automatically records completed_at and completed_by on the server side, and moving it OUT of 7 clears them again. estimated_hours: 0 is only accepted when the target status is Em Planejamento (1) or Conclu\xEDda (7) \u2014 any other target status requires a value > 0. Setting is_active: false archives the task (equivalent to lkp_task_archive). MOVING A TICKET-LINKED TASK INTO 4, 5 OR 7 CAN CLOSE THE HELPDESK TICKET AND WRITE TO THE CLIENT. When the task resolves a helpdesk_ticket_id \u2014 its own, or one inherited from its parent \u2014 and it was the LAST pending task of that ticket, the server can move the ticket to Resolvido, publish a note VISIBLE TO THE CLIENT naming the consultants who worked on it, and fire the resolution email. The whole package sits behind a server-side setting (helpdesk_task_ticket_autosync_enabled, default OFF) that THIS API CANNOT READ, so treat it as POSSIBLE rather than certain and confirm with the user before advancing a ticket-linked task. The sync failure is swallowed on the server: the PATCH answers 200 either way and the payload carries no trace of what happened to the ticket \u2014 read the ticket with lkp_helpdesk_ticket_get when you need to know. NONE OF THIS ENDPOINT'S REFUSALS IS RETRYABLE, and there are 13 of them \u2014 read error.code, never the prose. Authorization splits across TWO DIFFERENT 403s that need opposite answers: 'forbidden' means the PERSON may not do it (a plain member may only change status_id, and only on a task assigned to them; deactivating needs an administrator or a manager), while 'invalid_status_transition' means the TRANSITION does not exist for that role from the current status \u2014 the way out of the first is another person or another tool, the way out of the second is another target status, or a manager. Body shape, all 422: 'immutable_field' (project_id was sent), 'unknown_field' (a key outside the whitelist), 'validation_failed' (empty body, bad enum, dates, or the sovereign Task::validateData, whose details name the offending fields). Ticket locks, all 422 and all with the SAME way out \u2014 act on the TICKET, not on the task: 'helpdesk_ticket_closed' (the linked ticket is closed or cancelled), 'helpdesk_ticket_resolved' (a backwards move while the ticket is resolved), 'helpdesk_ticket_no_regression' (a ticket-linked task does not regress). Process locks, 422: 'test_evidence_required' (evidence is required before Enviado para Testes or Conclu\xEDda) and 'timesheet_required' (3 -> 4 needs at least one time entry ON THE TASK, logged by anyone). Deactivation locks, 422: 'linked_to_helpdesk_ticket' and 'has_timesheets'. Do not read the two timesheet codes as the same wall: 'has_timesheets' means the task HAS entries so it cannot be deactivated, and 'timesheet_required' means it has NONE so it cannot advance. 404 not_found means the task does not exist or is out of the token owner's reach \u2014 the two are not distinguished on purpose. Confirm with the user before calling. " + TASK_STATUS_REF,
|
|
1042
1059
|
inputSchema: {
|
|
1043
1060
|
task_id: z7.coerce.number().int().positive(),
|
|
1044
1061
|
title: z7.string().optional(),
|
|
@@ -1049,7 +1066,11 @@ function registerTasks(server, client, logger) {
|
|
|
1049
1066
|
due_date: z7.string().optional(),
|
|
1050
1067
|
start_date: z7.string().optional(),
|
|
1051
1068
|
estimated_hours: z7.coerce.number().nonnegative().optional(),
|
|
1052
|
-
|
|
1069
|
+
// Strict boolean on purpose: z.coerce.boolean() would turn the string
|
|
1070
|
+
// "false" into true, the backend would compare true against an already
|
|
1071
|
+
// active task and change nothing, and the 200 would report success for
|
|
1072
|
+
// an archive that never happened.
|
|
1073
|
+
is_active: z7.boolean().optional(),
|
|
1053
1074
|
specialty_id: z7.coerce.number().int().positive().optional(),
|
|
1054
1075
|
skill_level: SkillLevel.optional(),
|
|
1055
1076
|
parent_task_id: z7.coerce.number().int().positive().optional(),
|
|
@@ -1066,7 +1087,7 @@ function registerTasks(server, client, logger) {
|
|
|
1066
1087
|
"lkp_task_archive",
|
|
1067
1088
|
{
|
|
1068
1089
|
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.",
|
|
1090
|
+
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
1091
|
inputSchema: {
|
|
1071
1092
|
task_id: z7.coerce.number().int().positive()
|
|
1072
1093
|
}
|
|
@@ -1115,7 +1136,7 @@ function registerTasks(server, client, logger) {
|
|
|
1115
1136
|
"lkp_task_comment_add",
|
|
1116
1137
|
{
|
|
1117
1138
|
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.",
|
|
1139
|
+
description: "Adiciona um coment\xE1rio ao hist\xF3rico da tarefa (aba Coment\xE1rios), SEM alterar a descri\xE7\xE3o. The author is the token owner. body accepts HTML or plain text. Returns the created comment. " + REPLY_AS_SERVICE_IDENTITY_DOC + " On this endpoint the created comment comes back with author = the REAL author (the token owner), never the service identity, even when the flag was accepted \u2014 that is the contract, not a bug, so do not 'correct' the name. Since API contract 2.12 the created comment also carries responded_as, which is where the identity shows up: author and responded_as are the two halves of the internal 'X responded as Y' badge, and reading them as if one should overwrite the other loses the audit trail. The endpoint also still accepts the older responded_as_user_id (an explicit identity id, since contract 2.5), but this tool deliberately does NOT expose it: the boolean is the supported path, and sending both in one call is 422 validation_failed with details.reply_as_service_identity='mutually exclusive with responded_as_user_id'. PUBLISHING EMAILS THE TASK'S ASSIGNEE \u2014 not the client \u2014 WITH THE COMMENT TEXT EMBEDDED IN THE MESSAGE BODY, sent synchronously inside the request. There is no way to unsend it: deleting the comment afterwards removes it from the thread and never recalls the email. No email goes out when the author IS the assignee, and an email failure is logged without failing the call, so a 201 confirms the comment, never the delivery. An IDENTICAL comment from the SAME author on the same task WITHIN 60 SECONDS is absorbed as a duplicate: the 201 hands back THE COMMENT THAT ALREADY EXISTS, with no new row and no second email. That is what makes a retry after a timeout safe \u2014 but it also means deliberately posting the same text twice inside a minute does NOT produce two comments, so do not read the second 201 as a second publication; change the wording, or wait the window out, when two are really wanted. Confirm with the user before calling.",
|
|
1119
1140
|
inputSchema: {
|
|
1120
1141
|
task_id: z7.coerce.number().int().positive(),
|
|
1121
1142
|
body: z7.string().min(1),
|
|
@@ -1171,12 +1192,31 @@ var ContactRole = z8.enum([
|
|
|
1171
1192
|
]);
|
|
1172
1193
|
var EngagementLevel = z8.enum(["LOW", "MEDIUM", "HIGH"]);
|
|
1173
1194
|
var Sentiment = z8.enum(["NEGATIVE", "NEUTRAL", "POSITIVE", "CHAMPION"]);
|
|
1195
|
+
var OpportunitySource = z8.enum([
|
|
1196
|
+
"HELPDESK",
|
|
1197
|
+
"REFERRAL",
|
|
1198
|
+
"WEBSITE",
|
|
1199
|
+
"LINKEDIN",
|
|
1200
|
+
"EVENT",
|
|
1201
|
+
"PARTNER",
|
|
1202
|
+
"COLD_CALL",
|
|
1203
|
+
"EXISTING_CLIENT",
|
|
1204
|
+
"OTHER"
|
|
1205
|
+
]);
|
|
1206
|
+
var ActivityOutcome = z8.enum([
|
|
1207
|
+
"POSITIVE",
|
|
1208
|
+
"NEUTRAL",
|
|
1209
|
+
"NEGATIVE",
|
|
1210
|
+
"NO_ANSWER",
|
|
1211
|
+
"RESCHEDULED",
|
|
1212
|
+
"PENDING"
|
|
1213
|
+
]);
|
|
1174
1214
|
function registerOpportunities(server, client, logger) {
|
|
1175
1215
|
server.registerTool(
|
|
1176
1216
|
"lkp_opportunities_list",
|
|
1177
1217
|
{
|
|
1178
1218
|
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.",
|
|
1219
|
+
description: "List sales opportunities (CRM pipeline) with filters. Returns stage, probability, expected_value, weighted_value, expected_close_date, account manager, last_activity_at. Use for pipeline review. Stage values: NEW | QUALIFYING | PROPOSAL | SENT | NEGOTIATION | WON | PARTIALLY_WON | LOST | CANCELLED. ROW-LEVEL VISIBILITY: if the token owner is not an administrator or a manager, the result contains ONLY the opportunities where they are the account manager, and an explicit account_manager_id is overridden by the backend with the token owner's own id. Nothing in the payload says so \u2014 meta.total counts that slice as if it were everything \u2014 so a short list is NOT evidence of a short pipeline, and this same call answers differently for different tokens. Establish whose token is in use before reporting a pipeline as the company's, and never conclude 'manager 5 has nothing' from a filtered call made with a plain user's token.",
|
|
1180
1220
|
inputSchema: {
|
|
1181
1221
|
status: OpportunityStatus.optional(),
|
|
1182
1222
|
account_manager_id: z8.coerce.number().int().positive().optional(),
|
|
@@ -1196,7 +1236,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1196
1236
|
"lkp_opportunities_summary",
|
|
1197
1237
|
{
|
|
1198
1238
|
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).",
|
|
1239
|
+
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
1240
|
inputSchema: {}
|
|
1201
1241
|
},
|
|
1202
1242
|
async () => runTool(
|
|
@@ -1209,7 +1249,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1209
1249
|
"lkp_opportunity_detail",
|
|
1210
1250
|
{
|
|
1211
1251
|
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
|
|
1252
|
+
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
1253
|
inputSchema: {
|
|
1214
1254
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1215
1255
|
include_inactive: z8.coerce.boolean().optional()
|
|
@@ -1227,7 +1267,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1227
1267
|
"lkp_opportunity_create",
|
|
1228
1268
|
{
|
|
1229
1269
|
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.",
|
|
1270
|
+
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
1271
|
inputSchema: {
|
|
1232
1272
|
client_id: z8.coerce.number().int().positive(),
|
|
1233
1273
|
name: z8.string().min(1),
|
|
@@ -1239,7 +1279,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1239
1279
|
expected_close_date: z8.string().optional(),
|
|
1240
1280
|
account_manager_id: z8.coerce.number().int().positive().optional(),
|
|
1241
1281
|
price_list_id: z8.coerce.number().int().positive().optional(),
|
|
1242
|
-
source:
|
|
1282
|
+
source: OpportunitySource.optional()
|
|
1243
1283
|
}
|
|
1244
1284
|
},
|
|
1245
1285
|
async (args) => runTool(
|
|
@@ -1252,7 +1292,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1252
1292
|
"lkp_opportunity_update",
|
|
1253
1293
|
{
|
|
1254
1294
|
title: "Update opportunity (write)",
|
|
1255
|
-
description: "Update whitelisted fields on an opportunity. For status changes, business rules apply (e.g., LOST requires lost_reason). Setting is_active toggles archive/restore (true = restore, false = archive \u2014 equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored.
|
|
1295
|
+
description: "Update whitelisted fields on an opportunity. For status changes, business rules apply (e.g., LOST requires lost_reason). Setting is_active toggles archive/restore (true = restore, false = archive \u2014 equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored. RESPONSE SHAPE \u2014 returns a FLAT SUBSET of the opportunity (id, code, name, description, status, probability, expected_value, expected_close_date, actual_close_date, account_manager_id, lost_reason, is_active, updated_at), NOT the object lkp_opportunity_detail and lkp_opportunities_list return: there is no client, no status_label, no weighted_value, no source, no last_activity_at, no counts, and account_manager arrives as a bare id instead of {id, name}. Do not report a field as missing or emptied because it is absent here \u2014 re-read with lkp_opportunity_detail whenever the full shape matters. Requires the write:opportunities scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling.",
|
|
1256
1296
|
inputSchema: {
|
|
1257
1297
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1258
1298
|
name: z8.string().optional(),
|
|
@@ -1278,7 +1318,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1278
1318
|
"lkp_opportunity_archive",
|
|
1279
1319
|
{
|
|
1280
1320
|
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.",
|
|
1321
|
+
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
1322
|
inputSchema: {
|
|
1283
1323
|
opportunity_id: z8.coerce.number().int().positive()
|
|
1284
1324
|
}
|
|
@@ -1292,15 +1332,15 @@ function registerOpportunities(server, client, logger) {
|
|
|
1292
1332
|
"lkp_opportunity_activity_add",
|
|
1293
1333
|
{
|
|
1294
1334
|
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.",
|
|
1335
|
+
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
1336
|
inputSchema: {
|
|
1297
1337
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1298
1338
|
type: ActivityType,
|
|
1299
|
-
subject: z8.string().min(1),
|
|
1339
|
+
subject: z8.string().min(1).max(200),
|
|
1300
1340
|
description: z8.string().optional(),
|
|
1301
1341
|
duration_minutes: z8.coerce.number().int().nonnegative().optional(),
|
|
1302
1342
|
follow_up_date: z8.string().optional(),
|
|
1303
|
-
outcome:
|
|
1343
|
+
outcome: ActivityOutcome.optional(),
|
|
1304
1344
|
is_internal: z8.coerce.boolean().optional()
|
|
1305
1345
|
}
|
|
1306
1346
|
},
|
|
@@ -1317,18 +1357,18 @@ function registerOpportunities(server, client, logger) {
|
|
|
1317
1357
|
"lkp_opportunity_activity_update",
|
|
1318
1358
|
{
|
|
1319
1359
|
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.",
|
|
1360
|
+
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
1361
|
inputSchema: {
|
|
1322
1362
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1323
1363
|
activity_id: z8.coerce.number().int().positive(),
|
|
1324
|
-
subject: z8.string().optional(),
|
|
1364
|
+
subject: z8.string().min(1).max(200).optional(),
|
|
1325
1365
|
description: z8.string().optional(),
|
|
1326
1366
|
activity_date: z8.string().optional(),
|
|
1327
1367
|
duration_minutes: z8.coerce.number().int().nonnegative().optional(),
|
|
1328
1368
|
follow_up_date: z8.string().optional(),
|
|
1329
1369
|
follow_up_notes: z8.string().optional(),
|
|
1330
1370
|
is_follow_up_done: z8.coerce.boolean().optional(),
|
|
1331
|
-
outcome:
|
|
1371
|
+
outcome: ActivityOutcome.optional(),
|
|
1332
1372
|
is_internal: z8.coerce.boolean().optional(),
|
|
1333
1373
|
is_active: z8.coerce.boolean().optional()
|
|
1334
1374
|
}
|
|
@@ -1382,7 +1422,7 @@ function registerOpportunities(server, client, logger) {
|
|
|
1382
1422
|
"lkp_opportunity_contact_attach",
|
|
1383
1423
|
{
|
|
1384
1424
|
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.",
|
|
1425
|
+
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
1426
|
inputSchema: {
|
|
1387
1427
|
opportunity_id: z8.coerce.number().int().positive(),
|
|
1388
1428
|
contact_person_id: z8.coerce.number().int().positive(),
|
|
@@ -1458,6 +1498,16 @@ var QuoteStatus = z9.enum([
|
|
|
1458
1498
|
"EXPIRED",
|
|
1459
1499
|
"SUPERSEDED"
|
|
1460
1500
|
]);
|
|
1501
|
+
var QuoteStatusFilter = z9.string().refine(
|
|
1502
|
+
(s) => s.split(",").every(
|
|
1503
|
+
(t) => QuoteStatus.options.includes(
|
|
1504
|
+
t.trim().toUpperCase()
|
|
1505
|
+
)
|
|
1506
|
+
),
|
|
1507
|
+
{
|
|
1508
|
+
message: "status must be DRAFT | SENT | ACCEPTED | REJECTED | EXPIRED | SUPERSEDED, or a comma-separated list of those"
|
|
1509
|
+
}
|
|
1510
|
+
);
|
|
1461
1511
|
var Currency = z9.enum(["BRL", "USD", "EUR"]);
|
|
1462
1512
|
var SkillLevel2 = z9.enum(["J\xFAnior", "Pleno", "S\xEAnior", "Especialista"]);
|
|
1463
1513
|
var BillingModel = z9.enum([
|
|
@@ -1483,8 +1533,7 @@ var PaymentMilestoneInput = z9.object({
|
|
|
1483
1533
|
percentage: z9.coerce.number().positive().max(100),
|
|
1484
1534
|
due_days: z9.coerce.number().int().nonnegative().optional(),
|
|
1485
1535
|
due_date: z9.string().optional(),
|
|
1486
|
-
notes: z9.string().optional()
|
|
1487
|
-
sort_order: z9.coerce.number().int().optional()
|
|
1536
|
+
notes: z9.string().optional()
|
|
1488
1537
|
});
|
|
1489
1538
|
var QuoteHeaderFields = {
|
|
1490
1539
|
valid_until: z9.string().optional(),
|
|
@@ -1501,26 +1550,34 @@ var QuoteHeaderFields = {
|
|
|
1501
1550
|
setup_fee: z9.coerce.number().nonnegative().optional(),
|
|
1502
1551
|
monthly_amount: z9.coerce.number().nonnegative().optional(),
|
|
1503
1552
|
recurring_start_date: z9.string().optional(),
|
|
1504
|
-
billing_cadence_subscription: BillingCadence.optional(),
|
|
1505
1553
|
contract_months: z9.coerce.number().int().positive().optional(),
|
|
1506
|
-
installment_count: z9.coerce.number().int().positive().max(60).optional()
|
|
1554
|
+
installment_count: z9.coerce.number().int().positive().max(60).optional(),
|
|
1555
|
+
// Per-model completion fields. A measurement quote is IMPOSSIBLE without a
|
|
1556
|
+
// cadence (weekly needs the weekday, monthly the cutoff day), and a
|
|
1557
|
+
// subscription saved without subscription_due_day can never be accepted —
|
|
1558
|
+
// the backend enforces both (Quote::validate / validateForAcceptance).
|
|
1559
|
+
measurement_cadence: z9.enum(["weekly", "monthly"]).optional(),
|
|
1560
|
+
measurement_cutoff_day: z9.coerce.number().int().min(1).max(28).optional(),
|
|
1561
|
+
measurement_cutoff_weekday: z9.coerce.number().int().min(1).max(7).optional(),
|
|
1562
|
+
subscription_due_day: z9.coerce.number().int().min(1).max(28).optional()
|
|
1507
1563
|
};
|
|
1564
|
+
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.";
|
|
1565
|
+
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
1566
|
function registerQuotes(server, client, logger) {
|
|
1509
1567
|
server.registerTool(
|
|
1510
1568
|
"lkp_quotes_list",
|
|
1511
1569
|
{
|
|
1512
1570
|
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.
|
|
1571
|
+
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
1572
|
inputSchema: {
|
|
1515
|
-
status:
|
|
1573
|
+
status: QuoteStatusFilter.optional(),
|
|
1516
1574
|
opportunity_id: z9.coerce.number().int().positive().optional(),
|
|
1517
1575
|
client_id: z9.coerce.number().int().positive().optional(),
|
|
1518
|
-
|
|
1519
|
-
billing_model: BillingModel.optional(),
|
|
1520
|
-
valid_until_before: z9.string().optional(),
|
|
1576
|
+
currency: Currency.optional(),
|
|
1521
1577
|
search: z9.string().optional(),
|
|
1578
|
+
include_inactive: z9.coerce.boolean().optional(),
|
|
1522
1579
|
page: z9.coerce.number().int().positive().optional(),
|
|
1523
|
-
per_page: z9.coerce.number().int().positive().max(
|
|
1580
|
+
per_page: z9.coerce.number().int().positive().max(100).default(20)
|
|
1524
1581
|
}
|
|
1525
1582
|
},
|
|
1526
1583
|
async (args) => runTool(
|
|
@@ -1533,15 +1590,18 @@ function registerQuotes(server, client, logger) {
|
|
|
1533
1590
|
"lkp_quote_detail",
|
|
1534
1591
|
{
|
|
1535
1592
|
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.
|
|
1593
|
+
description: "Full quote detail: parent fields (version, status, totals, discount, valid_until, timestamps) plus embedded items[] and payment_milestones[]. Use before any write on a quote (send, accept, update, item/milestone mutation) to verify current state and avoid stale edits. 404 HAS THREE CAUSES, not one: an id that does not exist, a quote the token owner may not see (the API never confirms existence), and \u2014 without include_inactive \u2014 an ARCHIVED quote. Before concluding an id is gone, retry with include_inactive=true: an archived quote then comes back carrying is_active=0, and the flag also includes archived items and milestones in the children.",
|
|
1537
1594
|
inputSchema: {
|
|
1538
|
-
quote_id: z9.coerce.number().int().positive()
|
|
1595
|
+
quote_id: z9.coerce.number().int().positive(),
|
|
1596
|
+
include_inactive: z9.coerce.boolean().optional()
|
|
1539
1597
|
}
|
|
1540
1598
|
},
|
|
1541
|
-
async ({ quote_id }) => runTool(
|
|
1599
|
+
async ({ quote_id, include_inactive }) => runTool(
|
|
1542
1600
|
logger,
|
|
1543
1601
|
"lkp_quote_detail",
|
|
1544
|
-
() => client.get(`/api/v1/quotes/${quote_id}
|
|
1602
|
+
() => client.get(`/api/v1/quotes/${quote_id}`, {
|
|
1603
|
+
include_inactive
|
|
1604
|
+
})
|
|
1545
1605
|
)
|
|
1546
1606
|
);
|
|
1547
1607
|
server.registerTool(
|
|
@@ -1567,10 +1627,14 @@ function registerQuotes(server, client, logger) {
|
|
|
1567
1627
|
"lkp_quote_create",
|
|
1568
1628
|
{
|
|
1569
1629
|
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.
|
|
1630
|
+
description: "Create a new DRAFT quote under an opportunity. billing_model is REQUIRED (milestone | installment | measurement | subscription): the backend refuses to save an unclassified quote (422 validation_failed). Each item requires specialty_id (resolve via lkp_specialties_list) and skill_level (J\xFAnior | Pleno | S\xEAnior | Especialista \u2014 required; rate card indexes both dimensions). hourly_rate is optional per item: when omitted, backend resolves via the client's active price_list for (specialty_id, skill_level); pass it explicitly to override the rate card. PER-MODEL FIELDS: subscription requires monthly_amount + contract_months and items[] must be omitted \u2014 and needs billing_cadence, recurring_start_date and subscription_due_day (1-28) to ever be ACCEPTED, so a subscription created without them reaches the client impossible to accept; measurement requires measurement_cadence ('weekly' \u2192 measurement_cutoff_weekday 1-7, 'monthly' \u2192 measurement_cutoff_day 1-28). SIDE EFFECTS: when the opportunity already has quotes, EVERY previous DRAFT of that opportunity is marked SUPERSEDED in the same transaction; and an opportunity in NEW or QUALIFYING is auto-advanced to PROPOSAL, announced in meta.opportunity_status_changed. meta also carries items_rate_from_caller / items_rate_from_price_list \u2014 the proof of which rate entered each line. Refusals to expect, all 422 (read error.code, never the prose): no_items (items[] empty outside subscription), milestones_invalid_total (payment_milestones present and not summing to 100, details.total_percentage), opportunity_stage_forbids_quote (terminal stage), and opportunity_has_pending_tasks \u2014 open CRM tasks on the opportunity block quote creation, NOTHING in the payload reveals that, and the fix is resolving the tasks, not reshaping the quote. Summarize the draft (opportunity, items, totals, milestones) and wait for explicit user approval before calling.",
|
|
1571
1631
|
inputSchema: {
|
|
1572
1632
|
opportunity_id: z9.coerce.number().int().positive(),
|
|
1573
1633
|
...QuoteHeaderFields,
|
|
1634
|
+
// Required here, optional in QuoteHeaderFields: on update the stored
|
|
1635
|
+
// value fills the effective state, but a quote cannot be BORN without
|
|
1636
|
+
// a billing_model (Quote::validate refuses the save).
|
|
1637
|
+
billing_model: BillingModel,
|
|
1574
1638
|
items: z9.array(QuoteItemInput).optional(),
|
|
1575
1639
|
payment_milestones: z9.array(PaymentMilestoneInput).optional()
|
|
1576
1640
|
}
|
|
@@ -1588,7 +1652,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1588
1652
|
"lkp_quote_update",
|
|
1589
1653
|
{
|
|
1590
1654
|
title: "Update quote (write)",
|
|
1591
|
-
description: "Update whitelisted header fields on a quote.
|
|
1655
|
+
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
1656
|
inputSchema: {
|
|
1593
1657
|
quote_id: z9.coerce.number().int().positive(),
|
|
1594
1658
|
...QuoteHeaderFields,
|
|
@@ -1619,7 +1683,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1619
1683
|
"lkp_quote_send",
|
|
1620
1684
|
{
|
|
1621
1685
|
title: "Send quote to client (write)",
|
|
1622
|
-
description: "Transition a DRAFT quote to SENT. Moves the parent opportunity to SENT.
|
|
1686
|
+
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
1687
|
inputSchema: {
|
|
1624
1688
|
quote_id: z9.coerce.number().int().positive()
|
|
1625
1689
|
}
|
|
@@ -1634,7 +1698,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1634
1698
|
"lkp_quote_accept",
|
|
1635
1699
|
{
|
|
1636
1700
|
title: "Accept quote (write)",
|
|
1637
|
-
description: "Transition a SENT quote to ACCEPTED.
|
|
1701
|
+
description: "Transition a SENT quote to ACCEPTED (only SENT \u2014 anything else answers 422 invalid_transition; send first if DRAFT). THIS CALL MATERIALIZES THE DEAL, in one transaction: the quote is CONVERTED INTO A PROJECT \u2014 items become project tasks, contacts and team are carried over, the payment milestones become project billing milestones, measurement/subscription config is created, and converted_project_id is stamped on the quote and the opportunity \u2014 and FINANCE IS EMAILED right after the response. The parent opportunity moves to PARTIALLY_WON, not WON: closing it as WON stays a manual user decision. The cascade hits ONLY sibling quotes in SENT status, which become REJECTED ('Outra vers\xE3o foi aceita'); sibling DRAFTs are left untouched. Commercially binding and the most expensive side effect in this API \u2014 ALWAYS ask for explicit, unambiguous approval referencing the quote code (e.g. 'sim, aceitar QT-2026-0007'). Never accept on inference or implicit cues.",
|
|
1638
1702
|
inputSchema: {
|
|
1639
1703
|
quote_id: z9.coerce.number().int().positive()
|
|
1640
1704
|
}
|
|
@@ -1649,7 +1713,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1649
1713
|
"lkp_quote_reject",
|
|
1650
1714
|
{
|
|
1651
1715
|
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
|
|
1716
|
+
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
1717
|
inputSchema: {
|
|
1654
1718
|
quote_id: z9.coerce.number().int().positive(),
|
|
1655
1719
|
reason: z9.string().min(1).max(200)
|
|
@@ -1680,7 +1744,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1680
1744
|
"lkp_quote_duplicate",
|
|
1681
1745
|
{
|
|
1682
1746
|
title: "Duplicate quote to another opportunity (write)",
|
|
1683
|
-
description: "Copy a quote (including items) to a DIFFERENT opportunity as a new DRAFT (version 1). Milestones are NOT copied. Confirm the target opportunity with the user before calling.",
|
|
1747
|
+
description: "Copy a quote (including items) to a DIFFERENT opportunity as a new DRAFT (version 1). Milestones are NOT copied. The 201 carries meta.source_quote_id as the trace back to the origin. REFUSALS ABOUT THE TARGET (read error.code, never the prose): 422 validation_failed when target_opportunity_id is missing or not a positive integer; 404 not_found \u2014 which covers the source quote AND a target opportunity the token owner has no visibility of, because the API never confirms the existence of what the caller may not see; 422 target_opportunity_invalid when the target does not exist, is archived, or sits in a terminal stage (details.target_status); and 422 target_opportunity_no_b1 when the target has no project_b1_code_id. Confirm the target opportunity with the user before calling.",
|
|
1684
1748
|
inputSchema: {
|
|
1685
1749
|
quote_id: z9.coerce.number().int().positive(),
|
|
1686
1750
|
target_opportunity_id: z9.coerce.number().int().positive()
|
|
@@ -1698,7 +1762,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1698
1762
|
"lkp_quote_item_add",
|
|
1699
1763
|
{
|
|
1700
1764
|
title: "Add item to quote (write)",
|
|
1701
|
-
description: "Append a line item to a DRAFT
|
|
1765
|
+
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
1766
|
inputSchema: {
|
|
1703
1767
|
quote_id: z9.coerce.number().int().positive(),
|
|
1704
1768
|
specialty_id: z9.coerce.number().int().positive(),
|
|
@@ -1721,7 +1785,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1721
1785
|
"lkp_quote_item_update",
|
|
1722
1786
|
{
|
|
1723
1787
|
title: "Update quote item (write)",
|
|
1724
|
-
description: "Update whitelisted fields on a line item of a
|
|
1788
|
+
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
1789
|
inputSchema: {
|
|
1726
1790
|
quote_id: z9.coerce.number().int().positive(),
|
|
1727
1791
|
item_id: z9.coerce.number().int().positive(),
|
|
@@ -1749,7 +1813,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1749
1813
|
"lkp_quote_item_delete",
|
|
1750
1814
|
{
|
|
1751
1815
|
title: "Delete quote item (write)",
|
|
1752
|
-
description: "Remove a line item from a DRAFT
|
|
1816
|
+
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
1817
|
inputSchema: {
|
|
1754
1818
|
quote_id: z9.coerce.number().int().positive(),
|
|
1755
1819
|
item_id: z9.coerce.number().int().positive()
|
|
@@ -1764,10 +1828,10 @@ function registerQuotes(server, client, logger) {
|
|
|
1764
1828
|
"lkp_quote_milestones_replace",
|
|
1765
1829
|
{
|
|
1766
1830
|
title: "Replace all payment milestones (write)",
|
|
1767
|
-
description: "Replace the entire payment_milestones[] collection on a DRAFT
|
|
1831
|
+
description: "Replace the entire payment_milestones[] collection on a quote in DRAFT, SENT or EXPIRED status, atomically. due_days and due_date are mutually exclusive per milestone. percentages must sum to 100 (\xB10.01), or the call answers 422 milestones_invalid_total with details.total_percentage; amount is computed server-side \u2014 do not send it. milestones: [] is ALLOWED and clears the whole schedule \u2014 it is the only atomic way to zero it, and it is destructive, so require explicit user confirmation before sending an empty array. ORDER IS THE ARRAY ORDER: the backend renumbers sort_order 0..n-1 exactly as sent, which is why the milestones here carry no sort_order field \u2014 the endpoint discards that value in silence (the single-milestone add/update tools are where sort_order is honored). " + QUOTE_EDITABLE_GATE_DOC + " Summarize the new schedule and wait for user approval.",
|
|
1768
1832
|
inputSchema: {
|
|
1769
1833
|
quote_id: z9.coerce.number().int().positive(),
|
|
1770
|
-
milestones: z9.array(PaymentMilestoneInput)
|
|
1834
|
+
milestones: z9.array(PaymentMilestoneInput)
|
|
1771
1835
|
}
|
|
1772
1836
|
},
|
|
1773
1837
|
async ({ quote_id, milestones }) => runTool(
|
|
@@ -1783,7 +1847,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1783
1847
|
"lkp_quote_milestone_add",
|
|
1784
1848
|
{
|
|
1785
1849
|
title: "Add payment milestone (write)",
|
|
1786
|
-
description: "Append a single payment milestone to a DRAFT
|
|
1850
|
+
description: "Append a single payment milestone to a quote in DRAFT, SENT or EXPIRED status (additive; does not enforce sum=100 \u2014 use replace for atomic rewrite). due_days and due_date are mutually exclusive. " + QUOTE_EDITABLE_GATE_DOC + " Summarize (description, percentage, due) and wait for user approval.",
|
|
1787
1851
|
inputSchema: {
|
|
1788
1852
|
quote_id: z9.coerce.number().int().positive(),
|
|
1789
1853
|
description: z9.string().min(1),
|
|
@@ -1807,7 +1871,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1807
1871
|
"lkp_quote_milestone_update",
|
|
1808
1872
|
{
|
|
1809
1873
|
title: "Update payment milestone (write)",
|
|
1810
|
-
description: "Update whitelisted fields on a payment milestone of a DRAFT
|
|
1874
|
+
description: "Update whitelisted fields on a payment milestone of a quote in DRAFT, SENT or EXPIRED status. due_days and due_date are mutually exclusive. Does NOT enforce sum=100 \u2014 caller is responsible. " + QUOTE_EDITABLE_GATE_DOC + " Summarize the diff and wait for user approval.",
|
|
1811
1875
|
inputSchema: {
|
|
1812
1876
|
quote_id: z9.coerce.number().int().positive(),
|
|
1813
1877
|
milestone_id: z9.coerce.number().int().positive(),
|
|
@@ -1833,7 +1897,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1833
1897
|
"lkp_quote_milestone_delete",
|
|
1834
1898
|
{
|
|
1835
1899
|
title: "Delete payment milestone (write)",
|
|
1836
|
-
description: "Remove one payment milestone from a DRAFT
|
|
1900
|
+
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
1901
|
inputSchema: {
|
|
1838
1902
|
quote_id: z9.coerce.number().int().positive(),
|
|
1839
1903
|
milestone_id: z9.coerce.number().int().positive()
|
|
@@ -1855,7 +1919,7 @@ import { tmpdir } from "os";
|
|
|
1855
1919
|
import { z as z10 } from "zod";
|
|
1856
1920
|
var ALLOWED_EXTENSIONS_DOC = "jpg, jpeg, png, gif, webp, pdf, doc, docx, xls, xlsx, ppt, pptx, txt, csv, zip";
|
|
1857
1921
|
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.";
|
|
1922
|
+
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
1923
|
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
1924
|
function requireAbsolute(p, field) {
|
|
1861
1925
|
if (!isAbsolute(p)) {
|
|
@@ -1887,7 +1951,7 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1887
1951
|
"lkp_quote_attachment_upload",
|
|
1888
1952
|
{
|
|
1889
1953
|
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 +
|
|
1954
|
+
description: "Attach a LOCAL FILE to a proposal. file_path is an absolute path on the machine running this MCP server, which the server reads and sends as multipart/form-data \u2014 this is the only endpoint of the API that is not JSON. You cannot pass file contents inline; if the file is not on this machine, it has to get here first. THE BACKEND ENFORCES A TYPE ALLOWLIST, whatever you may have read elsewhere, and IT is the authority \u2014 not this text. It checks the extension AND the real content type (sniffed from the bytes, not from the name), and refuses with 422 invalid_file_type. Renaming a file to a permitted extension does not get it through, because the sniff reads the content. Nothing is checked here before the call, so DO NOT refuse a file on your own: send it and read the answer. As last observed the permitted extensions were " + ALLOWED_EXTENSIONS_DOC + ` \u2014 treat that as a hint for choosing a format, never as a reason to skip an upload the user asked for, since the list can change on the server without this text moving (zip, listed above, was added in 2.16 and this text is the second version of it). WHEN invalid_file_type COMES BACK, REPORT IT AND STOP. Do NOT repackage the refused file into a zip to get it through. That would now SUCCEED \u2014 zip is on the list and the backend does not inspect an archive's contents \u2014 and succeeding is exactly the problem: the allowlist exists to keep executable content (.svg, .html, .php) from being served under the web root, so zipping a refused file defeats a security control rather than solving the user's problem. If the user asks for the zip explicitly, that is their call to make and theirs to state; it is never a workaround you choose on your own. filename is optional and defaults to the basename of file_path \u2014 but WHATEVER YOU PASS THERE DECIDES THE EXTENSION HALF OF THE ALLOWLIST, because the backend reads the extension from THE NAME SENT and never from the local file. So a rename must keep an extension from the list: filename: "Proposta assinada" (no extension) or "Proposta.rar" makes a perfectly valid PDF come back 422 invalid_file_type. Use it to replace a meaningless temp name, and carry the original extension over when you do. Size: the ceiling is the max_file_size published by lkp_quote_attachments_list. Over it, 413 file_too_large \u2014 which the backend also returns when the PHP upload limit is the lower of the two, so a 413 is not proof the file exceeded max_file_size specifically. 400 upload_failed means no file arrived at all. ` + STATUS_FREEZE_DOC + " " + PERMISSIONS_DOC + " description is optional and travels with the file in the same request. Returns the created attachment (201) in the same shape lkp_quote_attachments_list returns. Confirm the file and the target quote with the user before calling. " + ARCHIVED_QUOTE_DOC,
|
|
1891
1955
|
inputSchema: {
|
|
1892
1956
|
quote_id: z10.coerce.number().int().positive(),
|
|
1893
1957
|
file_path: z10.string().min(1),
|
|
@@ -1939,6 +2003,13 @@ function registerQuoteAttachments(server, client, logger) {
|
|
|
1939
2003
|
const payload = await client.getBinary(
|
|
1940
2004
|
`/api/v1/quotes/${quote_id}/attachments/${attachment_id}/download`
|
|
1941
2005
|
);
|
|
2006
|
+
if (payload === null) {
|
|
2007
|
+
throw new LkpError({
|
|
2008
|
+
code: "server_error",
|
|
2009
|
+
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.`,
|
|
2010
|
+
api_code: "empty_attachment_body"
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
1942
2013
|
let target;
|
|
1943
2014
|
if (save_to_path !== void 0) {
|
|
1944
2015
|
target = requireAbsolute(save_to_path, "save_to_path");
|
|
@@ -2024,10 +2095,14 @@ function registerClients(server, client, logger) {
|
|
|
2024
2095
|
"lkp_clients_list",
|
|
2025
2096
|
{
|
|
2026
2097
|
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.",
|
|
2098
|
+
description: "List clients (hierarchical). Returns active project count, B1 codes count, account manager, price list. Use to find clients by name/doc or explore the portfolio. WITHOUT status THIS LISTS ACTIVE CLIENTS ONLY \u2014 the backend applies status = 1 whenever the filter is absent or empty, so never report a page of this as 'every client of the portfolio' unless you also asked for status: 'inactive'. status is the STRING 'active' | 'inactive' (the backend still tolerates '0' and '1' for backwards compatibility; they are not offered here because they mean the same two things), and any other value is 400 invalid_filter \u2014 not an empty list. parent_client_id narrows the list to the children of that client; the LITERAL STRING 'null' asks instead for the TOP-LEVEL clients, the ones with no parent of their own. Requires the read:clients scope (or read:*). " + CLIENT_TWO_DOORS_DOC,
|
|
2028
2099
|
inputSchema: {
|
|
2029
|
-
status: z11.
|
|
2030
|
-
|
|
2100
|
+
status: z11.enum(["active", "inactive"]).optional(),
|
|
2101
|
+
// The literal "null" is the backend's own spelling for "top-level only"
|
|
2102
|
+
// (it also accepts "0" for it, same meaning), and it has to survive as a
|
|
2103
|
+
// STRING: coercing it to a number gives NaN, and 0 is rejected as an id.
|
|
2104
|
+
// Hence the union with the literal FIRST, so the coercion never sees it.
|
|
2105
|
+
parent_client_id: z11.union([z11.literal("null"), z11.coerce.number().int().positive()]).optional(),
|
|
2031
2106
|
search: z11.string().optional(),
|
|
2032
2107
|
page: z11.coerce.number().int().positive().optional(),
|
|
2033
2108
|
per_page: z11.coerce.number().int().positive().max(100).default(50)
|
|
@@ -2043,7 +2118,7 @@ function registerClients(server, client, logger) {
|
|
|
2043
2118
|
"lkp_client_detail",
|
|
2044
2119
|
{
|
|
2045
2120
|
title: "Client detail",
|
|
2046
|
-
description: "Full client detail including all projects (
|
|
2121
|
+
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
2122
|
inputSchema: {
|
|
2048
2123
|
client_id: z11.coerce.number().int().positive()
|
|
2049
2124
|
}
|
|
@@ -2080,17 +2155,24 @@ function registerClients(server, client, logger) {
|
|
|
2080
2155
|
"lkp_client_update",
|
|
2081
2156
|
{
|
|
2082
2157
|
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.",
|
|
2158
|
+
description: "Update allowlisted fields on a client. status here is the STRING 'active' | 'inactive' \u2014 NOT the 1/0 integer of the database column and NOT a boolean, whatever a read of the record may suggest; anything else is 422. status: 'inactive' deactivates (soft delete, same effect and same guard as lkp_client_deactivate) and status: 'active' reactivates. Deactivating a client that still has active projects, children or tasks fails with 422 cannot_deactivate \u2014 propagate error.details.reason verbatim to the user, it names the actual blocker and is the only way to know what to clear first. overwrite_child_overrides is a BEHAVIOUR FLAG, not a field of the client: it decides whether a negotiated_price_list_id change CASCADES over children that carry their own list. Without it, children that follow the parent still get the new list and children with a specific one keep theirs; with it, the specific ones are overwritten too. It does nothing unless the price list actually changes. negotiated_price_list_id distinguishes omitted from null on THIS endpoint (unlike lkp_client_create): omit it to leave the current value untouched, send null to clear it and RE-INHERIT the parent's list. THE SAME OMITTED-VERSUS-NULL RULE GOVERNS parent_client_id, account_manager_id, document, phone, address and notes: omit the field to leave the stored value alone, send an explicit null to ERASE it. parent_client_id: null promotes a child to TOP-LEVEL, a hierarchy change \u2014 confirm it with the user instead of sending it to 'tidy up' a payload. document accepts CPF/CNPJ with or without mask. THE ALLOWLIST IS STRICT \u2014 name, document, phone, address, notes, parent_client_id, negotiated_price_list_id, account_manager_id, status, overwrite_child_overrides \u2014 and any other key is 422 unknown_field naming the offending keys, so NEVER build this call by echoing back an object read from lkp_client_detail or lkp_clients_list: id, created_at, status as an object, account_manager, price_list and the two *_count fields would all be rejected. Send only the fields being changed. Calling with no field at all sends an empty body and is 422 validation_failed ('Request body is empty'). 404 if the client does not exist. Requires the write:clients scope. " + CLIENT_TWO_DOORS_DOC + " Confirm any state transition with the user before calling. RESPONSE SHAPE \u2014 same caveat as lkp_client_create: the flat shape, WITHOUT projects[], b1_codes[], stats or sap_environments[]; active_projects_count and b1_codes_count are always 0 here. notes and address DO come back, here and on every read, since API contract 2.16.",
|
|
2084
2159
|
inputSchema: {
|
|
2085
2160
|
client_id: z11.coerce.number().int().positive(),
|
|
2086
2161
|
name: z11.string().min(1).max(100).optional(),
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2162
|
+
// `.nullable()` on every field the backend clears with an explicit null.
|
|
2163
|
+
// It is not decoration: `z.coerce.number()` turns null into 0 and
|
|
2164
|
+
// `.positive()` then refuses it, so without the ZodNullable in front —
|
|
2165
|
+
// which short-circuits null BEFORE the coercion — the documented "send
|
|
2166
|
+
// null to clear" was unreachable and came back as a schema error instead
|
|
2167
|
+
// of a call. `name` and `status` stay non-nullable: the backend requires
|
|
2168
|
+
// a non-empty name and an exact status string.
|
|
2169
|
+
document: z11.string().nullable().optional(),
|
|
2170
|
+
phone: z11.string().max(20).nullable().optional(),
|
|
2171
|
+
address: z11.string().nullable().optional(),
|
|
2172
|
+
notes: z11.string().nullable().optional(),
|
|
2173
|
+
parent_client_id: z11.coerce.number().int().positive().nullable().optional(),
|
|
2174
|
+
negotiated_price_list_id: z11.coerce.number().int().positive().nullable().optional(),
|
|
2175
|
+
account_manager_id: z11.coerce.number().int().positive().nullable().optional(),
|
|
2094
2176
|
status: z11.enum(["active", "inactive"]).optional(),
|
|
2095
2177
|
overwrite_child_overrides: z11.boolean().optional()
|
|
2096
2178
|
}
|
|
@@ -2221,6 +2303,7 @@ var SapEnvironmentFilter = z12.union([
|
|
|
2221
2303
|
z12.number().int().positive(),
|
|
2222
2304
|
z12.string().regex(/^[1-9]\d*$/).transform((v) => Number(v))
|
|
2223
2305
|
]);
|
|
2306
|
+
var SLA_DEADLINES_DOC = "sla ALSO CARRIES deadlines[] (API contract 2.17): the deadline ruler resolved server-side, and THE answer to 'what is the deadline?'. The 8 scalar sla.* keys LIE for an improvement ticket BY DESIGN, not by accident \u2014 improvements use no SLA policy, so resolution_due_at is NULL on purpose and the delivery forecast lives ONLY in deadlines[] ({phase: 'delivery'}, derived at read time from the ticket's task tree); when the question is a deadline, read the ruler, never the scalars. Each entry has exactly 8 keys: {phase, rule, due_at, met_at, breached, open, granularity, label}. phase has THREE values \u2014 'response', 'resolution', 'delivery' \u2014 never two: 'delivery' exists only on an improvement with a RECORDED ACCEPTANCE and never appears on an AMS ticket, so a consumer that assumes response|resolution will reject real payloads months later. rule says which ruler applies, and has three values: 'sla_policy' (AMS), 'improvement_business_days' (the improvement response phase, and an improvement resolved without acceptance), 'task_tree' (the improvement delivery phase). granularity CHANGES THE FORMAT of due_at: 'datetime' entries carry 'YYYY-MM-DD HH:MM:SS' and are due at that instant; 'date' entries (today only the delivery phase) carry a bare 'YYYY-MM-DD' \u2014 the ONE exception to this API's timestamp format \u2014 and are due at the END of that day (23:59:59), so parsing the bare date as a datetime silently concludes 'breached' about a day early. An entry with due_at: null is HISTORY, never a running clock \u2014 open is always false there. The documented edge case: an improvement RESOLVED WITHOUT ACCEPTANCE (rejected technically, or closed with no approved proposal) publishes {phase: 'resolution', rule: 'improvement_business_days', due_at: null, met_at: the instant of resolution} \u2014 the entry exists to carry the FULFILLMENT, not a deadline, because without an acceptance there is no delivery commitment. How many clocks run at once depends on the ticket kind: on an IMPROVEMENT at most ONE entry has open: true \u2014 whenever a second phase exists, the 'response' entry is FORCED to open: false even when no fulfillment was recorded (e.g. a ticket adopted by backfill); on an AMS ticket the response and resolution clocks run IN PARALLEL, and BOTH entries can arrive open: true until the first response is recorded \u2014 'which deadline is running?' can legitimately have two answers on a fresh AMS ticket, and that is the server's real behaviour, not a payload error. Everywhere, open is only ever true with due_at present, met_at absent and the ticket not closed/cancelled. AMS tickets (non-improvement) always carry EXACTLY 2 entries \u2014 'response' + 'resolution', both rule 'sla_policy', both granularity 'datetime', with due_at null when no policy applies \u2014 the array is never empty there. The ruler follows the improvements PROJECT, not the category: after a 'skipped_gate_off' recategorization the ticket has an improvement category but keeps the AMS ruler (2 'sla_policy' entries). label arrives ALREADY TRANSLATED from the server (a token consumer has no access to the app's i18n) \u2014 do not re-translate it, do not build an enum over it, and never use it as a discriminator: the discriminators are phase + rule.";
|
|
2224
2307
|
function assertSapEnvironmentFilter(value) {
|
|
2225
2308
|
if (value === void 0 || value === "none") return;
|
|
2226
2309
|
const n = typeof value === "string" && /^[1-9]\d*$/.test(value) ? Number(value) : value;
|
|
@@ -2240,7 +2323,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2240
2323
|
"lkp_helpdesk_tickets_list",
|
|
2241
2324
|
{
|
|
2242
2325
|
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.",
|
|
2326
|
+
description: "List helpdesk tickets with filters. Use for triage and to find tickets exceeding SLA. Each item is {id, ticket_number ('HD-AAAA-NNN'), subject, priority, status, client, category, project, assigned_to, contact, sla, closed_at, reopened_count, created_by, created_at, updated_at, tags}. Four of those have a shape that is easy to guess wrong, so read them literally: status is an OBJECT {id, name, color, is_closed, pauses_sla} and NEVER a bare string like 'in_progress' \u2014 compare status.id, and use status.is_closed rather than inferring closure from the name. tags is an array of OBJECTS {id, name, color}, not of strings. project on a LIST item carries only {id}: project.name exists on the detail (lkp_helpdesk_ticket_get) and nowhere else, so never print a project name from the list. sla is {policy_id, response_due_at, resolution_due_at, first_response_at, resolved_at, response_breached, resolution_breached, paused_minutes, deadlines} \u2014 the scalar deadline keys are response_due_at/resolution_due_at (there are no *_deadline keys), and 'is it late?' is the boolean response_breached/resolution_breached, computed server-side; do not re-derive it by comparing a due date against the clock. Every date in this payload is 'YYYY-MM-DD HH:MM:SS' in America/Sao_Paulo with NO 'T' and NO offset \u2014 it is not ISO 8601 and never was, so do not feed it to a date parser that assumes UTC; the single exception is a deadlines[] entry with granularity 'date', described below. meta here is {total, page, per_page} and carries NO has_more and NO returned, unlike lkp_helpdesk_ticket_comments_list which does: to know whether more pages exist, compare page * per_page against total; reading a missing has_more as false stops pagination after the first page. sap_environment_id filters by SAP environment: a positive int for a single environment, or the exact lowercase string 'none' for tickets with no environment informed; omit it to get all. Any other value is rejected here before the call, and the backend also rejects it with 400 invalid_filter since API contract 2.9 \u2014 it used to cast the value to int (so 'all' became 0) and answer 200 with an empty list, which reads as 'no tickets' rather than 'bad filter'. The client-side check only turns that into a clearer error without a round trip. An unknown priority is validated the same way. That filter is a convenience only \u2014 the security boundary is still the server-side role/line scoping. Use lkp_helpdesk_ticket_get for the full body, comments count and attachments of one ticket. " + SLA_DEADLINES_DOC,
|
|
2244
2327
|
inputSchema: {
|
|
2245
2328
|
status_id: z12.coerce.number().int().positive().optional(),
|
|
2246
2329
|
priority: z12.string().optional(),
|
|
@@ -2277,7 +2360,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2277
2360
|
"lkp_helpdesk_ticket_get",
|
|
2278
2361
|
{
|
|
2279
2362
|
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.",
|
|
2363
|
+
description: "Full detail of one helpdesk ticket: the same shape as an item of lkp_helpdesk_tickets_list plus description (the original body), comments_count, attachments[] ({id, file_name, file_size, mime_type, message_id, uploaded_by, created_at}), project.name, contact.email/phone, linked_task, sap_environment_id, sap_environment, csat, and requester {type: 'user'|'contact'|null, id, name}. Every documented key is ALWAYS present in the payload \u2014 only the value varies, and it is null when there is nothing to report. A missing key means the server is older than this contract, never 'this ticket has no value'. linked_task is {id, title, status_id}, or null when no task is linked: under API contract < 2.9 that key was omitted entirely instead of null, so never read its absence as a value. sap_environment_id is the raw int or null; sap_environment is the resolved {id, nome, sid} or null, and it resolves environments that have since been DEACTIVATED, so display sap_environment.nome (+ sid) rather than the bare id. csat is {rating (1-5), comment, created_at}, or null when the client has not rated the ticket; inside a non-null csat, rating is never null but comment can be. requester is {type: null, id: null, name: null} on legacy tickets whose created_by and contact_person_id are both empty. attachments[].uploaded_by is the uploader's DISPLAY NAME as a string, and can be null when that user/contact was removed \u2014 it is not an id and not an object, so never use it to look a user up. There is NO resolution field \u2014 the outcome lives in the comments (lkp_helpdesk_ticket_comments_list); that is the one documented key which is genuinely absent rather than null. Requires read:helpdesk (or read:*); 404 if the ticket does not exist, 403 if the token user has no access to it. " + SLA_DEADLINES_DOC,
|
|
2281
2364
|
inputSchema: {
|
|
2282
2365
|
ticket_id: z12.coerce.number().int().positive()
|
|
2283
2366
|
}
|
|
@@ -2312,7 +2395,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2312
2395
|
"lkp_helpdesk_ticket_comment_add",
|
|
2313
2396
|
{
|
|
2314
2397
|
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
|
|
2398
|
+
description: "Add a comment to a helpdesk ticket. is_internal is REQUIRED and has no default \u2014 you must decide explicitly: true = internal note (never delivered to the client), false = public reply to the client. WHAT A PUBLIC REPLY DOES TO THE SLA DEPENDS ON THE KIND OF TICKET, and the two answers are opposites. On an AMS (non-improvement) ticket, ANY public reply (is_internal=false) through this endpoint sets sla_first_response_at when it is still empty \u2014 it is not gated on the author being an 'agent', so a single false stops the response SLA clock for good, and a reply that lands after the due date records the breach in the same move. On an IMPROVEMENT ticket NO message stops the response clock, ever: that phase is fulfilled only by SENDING A PROPOSAL or by a TECHNICAL REJECTION (the ticket moved to Cancelado), because 'we are looking into it' does not answer a request for an improvement. So never report the response SLA as met just because a reply went out on an improvement \u2014 the authoritative answer is the resolved deadline ruler on the ticket, which you read with lkp_helpdesk_ticket_get, not an inference from this call. An internal note stops nothing on either kind. This endpoint always records the message as the token owner (sender_type='user'); a client contact never posts through it. body accepts HTML or plain text and is sanitized server-side \u2014 do not escape it here. Returns { data: { id, responded_as } } (201) \u2014 responded_as is new in API contract 2.12 and is null for an ordinary comment. Requires the write:helpdesk scope. " + REPLY_AS_SERVICE_IDENTITY_DOC + " Signing as the identity is incompatible with an internal note: is_internal=true together with reply_as_service_identity=true is 422 validation_failed, because an internal note has no client to sign for. A signed reply is treated exactly like an unsigned one by the response clock \u2014 same rule, improvement exception included. Always show the user the exact body, whether it is internal AND whether it goes out signed as the company, and wait for approval before calling \u2014 a wrong is_internal sends internal wording to the client, and on an AMS ticket it burns the SLA first response as well.",
|
|
2316
2399
|
inputSchema: {
|
|
2317
2400
|
ticket_id: z12.coerce.number().int().positive(),
|
|
2318
2401
|
body: z12.string().min(1),
|
|
@@ -2353,7 +2436,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2353
2436
|
"lkp_helpdesk_ticket_update",
|
|
2354
2437
|
{
|
|
2355
2438
|
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 Gerente Respons\xE1vel), a 404 not_found, a 422 validation_failed, a 409 converted (the opportunity already became a project) and a 409 proposal_exists each arrive here as themselves. DO NOT REPEAT A FAILED CALL THROUGH THE DEDICATED TOOL TO LEARN THE REAL CODE \u2014 you already have it, and the retry only asks the backend the same question twice. Against a server older than 2.16 those five collapse into 422 patch_failed instead; read error.code and treat patch_failed as 'the reason was not reported', never as a specific diagnosis. patch_failed also survives on 2.16 as the fallback for the service's catch-all path, which can return a null code, and for the OTHER sub-operations of this PATCH \u2014 status, priority and assignment return only {success, message} to the backend, so there is no code to pass through and patch_failed is all the information that exists. Changing the category is also NOT a metadata edit: read the side effects on lkp_helpdesk_ticket_recategorize before sending category_id from here, because they are identical and they move commercial state. status_comment (API contract 2.13) is the REASON for a status change, and THE CLIENT READS IT on the ticket \u2014 it is a public message signed by the agent, never an internal note, and it can count as the SLA first response. It only travels with status_id: sent alone it is 422 validation_failed with details.status_comment='requires status_id', and this tool rejects that combination before the call. Leaving the 'Em Atendimento' status REQUIRES it \u2014 without it the backend answers 422 patch_failed explaining that the client has to know what happened; that rule depends on the ticket's CURRENT status, which this tool does not know, so it is never second-guessed here: send the change and read the backend's answer. Note the exact name: status_comment, NOT comment \u2014 comment is the field name in the SPA form and the API rejects it with 422 field_not_allowed. Show the user the exact status_comment text and wait for approval before calling, the same as for a comment body: it reaches the client. Fields outside the whitelist (client_id, project_id, ticket_number, created_at and any sla_*) are rejected by the backend with 422 field_not_allowed and are not accepted here \u2014 since API contract 2.9 that error carries error.details.field naming the offending key, so read details.field and fall back to parsing error.message (\"Field 'X' cannot be patched.\") only for older servers. A malformed JSON body is 400 invalid_body. Returns the updated ticket in the lkp_helpdesk_ticket_get shape. ON SUCCESS WITH category_id, READ meta: since 2.16 it carries opportunity_action and quotes_archived (an integer) \u2014 what the recategorization did to the CRM. opportunity_action has FOUR values,
|
|
2439
|
+
description: "Update whitelisted fields on a helpdesk ticket: status_id, status_comment, priority (low|medium|high|critical), assigned_to, category_id, tags and sap_environment_id (int, or null to clear \u2014 the environment must belong to the ticket's client, otherwise 422 validation_failed). tags REPLACES the ticket's whole tag set, it does not merge: send the complete list of tag IDs the ticket should end up with, and note that tags: [] wipes every tag. recategorize_reason is REQUIRED whenever category_id is sent, and note the exact name \u2014 it is recategorize_reason HERE and plain `reason` on the dedicated route, a difference that costs a 422 if crossed. PREFER lkp_helpdesk_ticket_recategorize WHENEVER THE CATEGORY IS THE ONLY THING CHANGING, but only as a matter of intent now, not of information: since API contract 2.16 this PATCH RETURNS THE RECATEGORIZATION SERVICE'S OWN error.code and HTTP status, exactly as the dedicated route does. A 403 forbidden (you are not the ticket's Gerente Respons\xE1vel), a 404 not_found, a 422 validation_failed, a 409 converted (the opportunity already became a project) and a 409 proposal_exists each arrive here as themselves. DO NOT REPEAT A FAILED CALL THROUGH THE DEDICATED TOOL TO LEARN THE REAL CODE \u2014 you already have it, and the retry only asks the backend the same question twice. Against a server older than 2.16 those five collapse into 422 patch_failed instead; read error.code and treat patch_failed as 'the reason was not reported', never as a specific diagnosis. patch_failed also survives on 2.16 as the fallback for the service's catch-all path, which can return a null code, and for the OTHER sub-operations of this PATCH \u2014 status, priority and assignment return only {success, message} to the backend, so there is no code to pass through and patch_failed is all the information that exists. Changing the category is also NOT a metadata edit: read the side effects on lkp_helpdesk_ticket_recategorize before sending category_id from here, because they are identical and they move commercial state. status_comment (API contract 2.13) is the REASON for a status change, and THE CLIENT READS IT on the ticket \u2014 it is a public message signed by the agent, never an internal note, and it can count as the SLA first response. It only travels with status_id: sent alone it is 422 validation_failed with details.status_comment='requires status_id', and this tool rejects that combination before the call. Leaving the 'Em Atendimento' status REQUIRES it \u2014 without it the backend answers 422 patch_failed explaining that the client has to know what happened; that rule depends on the ticket's CURRENT status, which this tool does not know, so it is never second-guessed here: send the change and read the backend's answer. Note the exact name: status_comment, NOT comment \u2014 comment is the field name in the SPA form and the API rejects it with 422 field_not_allowed. Show the user the exact status_comment text and wait for approval before calling, the same as for a comment body: it reaches the client. Fields outside the whitelist (client_id, project_id, ticket_number, created_at and any sla_*) are rejected by the backend with 422 field_not_allowed and are not accepted here \u2014 since API contract 2.9 that error carries error.details.field naming the offending key, so read details.field and fall back to parsing error.message (\"Field 'X' cannot be patched.\") only for older servers. A malformed JSON body is 400 invalid_body. Returns the updated ticket in the lkp_helpdesk_ticket_get shape. ON SUCCESS WITH category_id, READ meta: since 2.16 it carries opportunity_action and quotes_archived (an integer) \u2014 what the recategorization did to the CRM. opportunity_action has FOUR values, and spec and code now say the same (\xA78.8, errata 2026-08-20 \u2014 the spec absorbed this MCP's live measurement): 'archived' (the ticket LEFT the improvement category and its opportunity was archived, quotes_archived counting the proposals that went with it), 'created' (the ticket ENTERED the improvement category and an opportunity was created for it), 'skipped_gate_off' (entered improvement but the client's improvement flow is disabled, so only the category changed), and null (no CRM effect). A fifth outcome hides behind the gate: gate ON but the improvement config incomplete (no account manager, or no improvement B1 code) aborts the WHOLE move with 422 validation_failed \u2014 nothing is left half-migrated, not even the category change. THE WHOLE meta BLOCK IS ABSENT when the PATCH did not carry category_id; it does not arrive as {}. That is the ONE documented exception to this API's rule that every key is always present, so test for the block before reading the fields, and never read a missing block as 'nothing was archived'. When the block IS there, it is the authoritative account of the side effect \u2014 do not re-read the opportunity to find out what happened. Requires the write:helpdesk scope. Confirm the change with the user before calling \u2014 especially the full tag list. " + SLA_DEADLINES_DOC,
|
|
2357
2440
|
inputSchema: {
|
|
2358
2441
|
ticket_id: z12.coerce.number().int().positive(),
|
|
2359
2442
|
status_id: z12.coerce.number().int().positive().optional(),
|
|
@@ -2396,7 +2479,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2396
2479
|
"lkp_helpdesk_ticket_recategorize",
|
|
2397
2480
|
{
|
|
2398
2481
|
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: only an administrator or the ticket's Gerente Respons\xE1vel (the strict manager_id) may recategorize, and being a manager of something else grants nothing. Refused as 403 forbidden \u2014 distinct from 403 insufficient_scope, which means the token lacks write:helpdesk. The scope is checked first, so fixing the scope on the wrong person's token only changes the message to forbidden. Other outcomes: 404 not_found for an unknown ticket, 422 validation_failed when the target category is inactive, does not exist, or IS ALREADY THE TICKET'S CATEGORY \u2014 the backend refuses a no-op rather than reporting a success that changed nothing. 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, 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.
|
|
2482
|
+
description: "Move a helpdesk ticket to another category, when that is the WHOLE operation. Both category_id and reason are required \u2014 note the field is `reason` here, NOT the recategorize_reason of lkp_helpdesk_ticket_update; crossing the two names is a 422. THIS IS NOT A METADATA EDIT, in either direction. Moving a ticket OUT OF the improvement category moves commercial state, in one transaction: the associated CRM opportunity is ARCHIVED, ALL of its quotes are archived with it (drafts and sent ones alike), and the ticket is returned to the client's default project with its SLA reassigned and its status reset to NOVO, taking its task tree along. None of that is reversible from this API. So state the consequences to the user and get explicit approval BEFORE calling \u2014 naming the opportunity and how many quotes it carries, which you can read with lkp_opportunity_quotes_list. Moving a ticket INTO the improvement category moves state too: when the client's improvement flow is enabled, an opportunity is CREATED for the ticket and the ticket migrates to the improvement project with its SLA reset and status back to NOVO (when the flow is disabled, only the category changes \u2014 meta says which happened). Two of the refusals exist precisely to stop that damage and must be reported, not worked around: 409 converted means the opportunity already became a project and the recategorization is refused outright; 409 proposal_exists means there is at least one non-draft (sent) quote and the caller is not an administrator \u2014 the backend also notifies the commercial team that the attempt was blocked. Neither is a retry: a 409 proposal_exists needs an admin to decide, and treating it as a transient error means asking someone to destroy a sent proposal. AUTHORIZATION IS NARROWER THAN THE SCOPE SUGGESTS. write:helpdesk is necessary and not sufficient: only an administrator or the ticket's Gerente Respons\xE1vel (the strict manager_id) may recategorize, and being a manager of something else grants nothing. Refused as 403 forbidden \u2014 distinct from 403 insufficient_scope, which means the token lacks write:helpdesk. The scope is checked first, so fixing the scope on the wrong person's token only changes the message to forbidden. Other outcomes: 404 not_found for an unknown ticket, 422 validation_failed when the target category is inactive, does not exist, or IS ALREADY THE TICKET'S CATEGORY \u2014 the backend refuses a no-op rather than reporting a success that changed nothing. A fifth outcome hides behind the gate (\xA78.8, errata 2026-08-20): moving INTO improvement with the gate ON but the improvement config incomplete (no account manager, or no improvement B1 code) aborts the WHOLE move with 422 validation_failed \u2014 nothing is left half-migrated, not even the category change. PREFER THIS TOOL OVER lkp_helpdesk_ticket_update WHEN THE CATEGORY IS THE WHOLE OPERATION \u2014 for the clarity of the errors, not because the PATCH loses them: since API contract 2.16 both routes return this service's own code and status. READ meta ON SUCCESS. It is always present on this route (recategorizing is all it does) and carries opportunity_action and quotes_archived (an integer) \u2014 the CRM side effect, reported by the service that performed it. opportunity_action has FOUR values (spec and code say the same \u2014 \xA78.8, errata 2026-08-20), one per direction of the move: 'archived' means the ticket LEFT the improvement category and its opportunity was archived with quotes_archived proposals \u2014 the destructive case, so quote it back to the user ('the opportunity was archived along with N proposals'); 'created' means the ticket ENTERED the improvement category and an opportunity was CREATED for it, with the ticket moved to the client's improvement project, its SLA reset and status back to NOVO; 'skipped_gate_off' means it entered improvement but the client's improvement flow is disabled, so only the category changed and no opportunity exists \u2014 do not go looking for one; null means the move touched no CRM state at all. null with quotes_archived 0 is a real, meaningful answer, not an omission. DO NOT re-read the opportunity to find out what happened \u2014 the answer is in this response, and a follow-up read cannot tell you what THIS call did. Against a server older than 2.16 the block is absent; only then is a re-read the way to check. RETURNS THE UPDATED TICKET IN THE SAME SHAPE AS AN ITEM OF lkp_helpdesk_tickets_list, not the detail shape \u2014 this route emits the LIST item even though it acts on one ticket. So project carries only {id} (there is no project.name to print), and description, comments_count, attachments, linked_task, sap_environment (the resolved object; the raw sap_environment_id IS here), contact.email/phone and csat are absent from this response \u2014 'every documented key is always present' is a promise of the DETAIL, and reading those keys off this payload finds nothing. When you need any of them after recategorizing, re-read the ticket with lkp_helpdesk_ticket_get; do not conclude the recategorization erased them. The full sla block, deadlines included, DOES travel here. " + SLA_DEADLINES_DOC,
|
|
2400
2483
|
inputSchema: {
|
|
2401
2484
|
ticket_id: z12.coerce.number().int().positive(),
|
|
2402
2485
|
category_id: z12.coerce.number().int().positive(),
|
|
@@ -2420,7 +2503,7 @@ function registerHelpdesk(server, client, logger) {
|
|
|
2420
2503
|
"lkp_helpdesk_ticket_create",
|
|
2421
2504
|
{
|
|
2422
2505
|
title: "Create helpdesk ticket (write)",
|
|
2423
|
-
description: "Open a new helpdesk ticket. Requires subject, description and client_id (an
|
|
2506
|
+
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
2507
|
inputSchema: {
|
|
2425
2508
|
subject: z12.string().min(1).max(200),
|
|
2426
2509
|
description: z12.string().min(1),
|
|
@@ -2447,7 +2530,7 @@ function registerBilling(server, client, logger) {
|
|
|
2447
2530
|
"lkp_billing_milestones",
|
|
2448
2531
|
{
|
|
2449
2532
|
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.",
|
|
2533
|
+
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
2534
|
inputSchema: {
|
|
2452
2535
|
status: z13.string().optional(),
|
|
2453
2536
|
project_id: z13.coerce.number().int().positive().optional(),
|
|
@@ -2459,25 +2542,36 @@ function registerBilling(server, client, logger) {
|
|
|
2459
2542
|
per_page: z13.coerce.number().int().positive().max(100).default(50)
|
|
2460
2543
|
}
|
|
2461
2544
|
},
|
|
2462
|
-
async (args) =>
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2545
|
+
async (args) => {
|
|
2546
|
+
const query = args.status?.trim().toLowerCase() === "cancelled" ? { ...args, include_cancelled: true } : args;
|
|
2547
|
+
return runTool(
|
|
2548
|
+
logger,
|
|
2549
|
+
"lkp_billing_milestones",
|
|
2550
|
+
() => client.get("/api/v1/billing/milestones", query)
|
|
2551
|
+
);
|
|
2552
|
+
}
|
|
2467
2553
|
);
|
|
2468
2554
|
}
|
|
2469
2555
|
|
|
2470
2556
|
// src/tools/alerts.ts
|
|
2471
2557
|
import { z as z14 } from "zod";
|
|
2558
|
+
var ALERT_TYPES = [
|
|
2559
|
+
"consultant_idle",
|
|
2560
|
+
"project_finishing",
|
|
2561
|
+
"opportunity_stale",
|
|
2562
|
+
"milestone_upcoming",
|
|
2563
|
+
"milestone_overdue",
|
|
2564
|
+
"helpdesk_sla_breach"
|
|
2565
|
+
];
|
|
2472
2566
|
function registerAlerts(server, client, logger) {
|
|
2473
2567
|
server.registerTool(
|
|
2474
2568
|
"lkp_alerts",
|
|
2475
2569
|
{
|
|
2476
2570
|
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.",
|
|
2571
|
+
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
2572
|
inputSchema: {
|
|
2479
|
-
severity: z14.
|
|
2480
|
-
type: z14.
|
|
2573
|
+
severity: z14.enum(["high", "medium", "low"]).optional(),
|
|
2574
|
+
type: z14.enum(ALERT_TYPES).optional()
|
|
2481
2575
|
}
|
|
2482
2576
|
},
|
|
2483
2577
|
async (args) => runTool(
|
|
@@ -2495,7 +2589,7 @@ function registerReports(server, client, logger) {
|
|
|
2495
2589
|
"lkp_ceo_weekly",
|
|
2496
2590
|
{
|
|
2497
2591
|
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.",
|
|
2592
|
+
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
2593
|
inputSchema: {}
|
|
2500
2594
|
},
|
|
2501
2595
|
async () => runTool(
|
|
@@ -2508,7 +2602,7 @@ function registerReports(server, client, logger) {
|
|
|
2508
2602
|
"lkp_managers_in_trouble",
|
|
2509
2603
|
{
|
|
2510
2604
|
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.",
|
|
2605
|
+
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
2606
|
inputSchema: {
|
|
2513
2607
|
include_tasks: z15.coerce.boolean().optional(),
|
|
2514
2608
|
include_financial: z15.coerce.boolean().optional(),
|
|
@@ -2530,7 +2624,7 @@ function registerFinancial(server, client, logger) {
|
|
|
2530
2624
|
"lkp_financial_pending",
|
|
2531
2625
|
{
|
|
2532
2626
|
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.",
|
|
2627
|
+
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
2628
|
inputSchema: {
|
|
2535
2629
|
entity_type: z16.enum(["milestone", "measurement", "subscription_invoice"]).optional(),
|
|
2536
2630
|
project_id: z16.coerce.number().int().positive().optional(),
|
|
@@ -2552,10 +2646,10 @@ function registerFinancial(server, client, logger) {
|
|
|
2552
2646
|
"lkp_aging_report",
|
|
2553
2647
|
{
|
|
2554
2648
|
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.",
|
|
2649
|
+
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
2650
|
inputSchema: {
|
|
2557
2651
|
group_bucket: z16.coerce.boolean().optional(),
|
|
2558
|
-
top_clients: z16.coerce.number().int().positive().optional()
|
|
2652
|
+
top_clients: z16.coerce.number().int().positive().max(50).optional()
|
|
2559
2653
|
}
|
|
2560
2654
|
},
|
|
2561
2655
|
async (args) => runTool(
|
|
@@ -2568,7 +2662,7 @@ function registerFinancial(server, client, logger) {
|
|
|
2568
2662
|
"lkp_financial_overview",
|
|
2569
2663
|
{
|
|
2570
2664
|
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.",
|
|
2665
|
+
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
2666
|
inputSchema: {}
|
|
2573
2667
|
},
|
|
2574
2668
|
async () => runTool(
|
|
@@ -2581,12 +2675,12 @@ function registerFinancial(server, client, logger) {
|
|
|
2581
2675
|
"lkp_margin_analysis",
|
|
2582
2676
|
{
|
|
2583
2677
|
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.",
|
|
2678
|
+
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
2679
|
inputSchema: {
|
|
2586
2680
|
group_by: z16.enum(["project", "client", "specialty"]).optional(),
|
|
2587
2681
|
from: z16.string().optional(),
|
|
2588
2682
|
to: z16.string().optional(),
|
|
2589
|
-
limit: z16.coerce.number().int().positive().max(
|
|
2683
|
+
limit: z16.coerce.number().int().positive().max(100).optional(),
|
|
2590
2684
|
status: z16.string().optional()
|
|
2591
2685
|
}
|
|
2592
2686
|
},
|
|
@@ -2603,106 +2697,114 @@ function registerFinancial(server, client, logger) {
|
|
|
2603
2697
|
|
|
2604
2698
|
// src/tools/composite/skill-match.ts
|
|
2605
2699
|
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();
|
|
2700
|
+
var OPEN_STAGES = [
|
|
2701
|
+
"NEW",
|
|
2702
|
+
"QUALIFYING",
|
|
2703
|
+
"PROPOSAL",
|
|
2704
|
+
"SENT",
|
|
2705
|
+
"NEGOTIATION"
|
|
2706
|
+
];
|
|
2707
|
+
function toSpecNames(specialties) {
|
|
2708
|
+
return (specialties ?? []).map((s) => typeof s === "string" ? s : s?.name ?? "").filter((s) => s.length > 0);
|
|
2627
2709
|
}
|
|
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
|
-
);
|
|
2710
|
+
async function fetchStageOpportunities(client, status) {
|
|
2711
|
+
const perPage = 100;
|
|
2712
|
+
const all = [];
|
|
2713
|
+
for (let page = 1; page <= 50; page++) {
|
|
2714
|
+
const r = await client.get("/api/v1/opportunities", { status, page, per_page: perPage });
|
|
2715
|
+
const batch = r.data ?? [];
|
|
2716
|
+
all.push(...batch);
|
|
2717
|
+
if (batch.length < perPage) break;
|
|
2718
|
+
const total = r.meta?.total;
|
|
2719
|
+
if (typeof total === "number" && all.length >= total) break;
|
|
2641
2720
|
}
|
|
2642
|
-
return
|
|
2721
|
+
return all;
|
|
2643
2722
|
}
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2723
|
+
async function fetchPartialResources(client) {
|
|
2724
|
+
const perPage = 100;
|
|
2725
|
+
const all = [];
|
|
2726
|
+
for (let page = 1; page <= 50; page++) {
|
|
2727
|
+
const r = await client.get("/api/v1/resources", {
|
|
2728
|
+
allocation: "partial",
|
|
2729
|
+
status: "active",
|
|
2730
|
+
page,
|
|
2731
|
+
per_page: perPage
|
|
2732
|
+
});
|
|
2733
|
+
const batch = r.data ?? [];
|
|
2734
|
+
all.push(...batch);
|
|
2735
|
+
if (batch.length < perPage) break;
|
|
2736
|
+
const total = r.meta?.total;
|
|
2737
|
+
if (typeof total === "number" && all.length >= total) break;
|
|
2738
|
+
}
|
|
2739
|
+
return all;
|
|
2649
2740
|
}
|
|
2650
2741
|
function registerSkillMatch(server, client, logger) {
|
|
2651
2742
|
server.registerTool(
|
|
2652
2743
|
"lkp_skill_match",
|
|
2653
2744
|
{
|
|
2654
2745
|
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.",
|
|
2746
|
+
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
2747
|
inputSchema: {
|
|
2657
|
-
|
|
2748
|
+
// max(30) is the backend's ceiling, not a choice made here: the summary
|
|
2749
|
+
// computes finishing_in_30_days with a literal 30-day window, so a
|
|
2750
|
+
// larger horizon cannot surface anyone new — rejecting it locally beats
|
|
2751
|
+
// silently answering with the 30-day set.
|
|
2752
|
+
horizon_days: z17.coerce.number().int().positive().max(30).default(30),
|
|
2658
2753
|
min_match_percent: z17.coerce.number().int().min(0).max(100).default(50),
|
|
2659
2754
|
include_partial: z17.coerce.boolean().default(false)
|
|
2660
2755
|
}
|
|
2661
2756
|
},
|
|
2662
2757
|
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
|
-
)
|
|
2758
|
+
const summaryPromise = client.get(
|
|
2759
|
+
"/api/v1/resources/summary"
|
|
2760
|
+
);
|
|
2761
|
+
const partialPromise = include_partial ? fetchPartialResources(client) : Promise.resolve([]);
|
|
2762
|
+
const stagePromises = OPEN_STAGES.map(
|
|
2763
|
+
(status) => fetchStageOpportunities(client, status)
|
|
2764
|
+
);
|
|
2765
|
+
const [[summaryResult, partialResult], stageResults] = await Promise.all([
|
|
2766
|
+
Promise.allSettled([summaryPromise, partialPromise]),
|
|
2767
|
+
Promise.allSettled(stagePromises)
|
|
2673
2768
|
]);
|
|
2674
|
-
|
|
2769
|
+
if (summaryResult.status === "rejected") throw summaryResult.reason;
|
|
2770
|
+
if (partialResult.status === "rejected") throw partialResult.reason;
|
|
2771
|
+
const resSummary = summaryResult.value.data;
|
|
2772
|
+
const partials = partialResult.value;
|
|
2773
|
+
const opportunities = [];
|
|
2774
|
+
const stagesFailed = [];
|
|
2775
|
+
stageResults.forEach((r, i) => {
|
|
2776
|
+
if (r.status === "fulfilled") {
|
|
2777
|
+
opportunities.push(...r.value);
|
|
2778
|
+
} else {
|
|
2779
|
+
stagesFailed.push(OPEN_STAGES[i]);
|
|
2780
|
+
}
|
|
2781
|
+
});
|
|
2782
|
+
if (stagesFailed.length === OPEN_STAGES.length) {
|
|
2783
|
+
const firstFailure = stageResults.find(
|
|
2784
|
+
(r) => r.status === "rejected"
|
|
2785
|
+
);
|
|
2786
|
+
throw firstFailure.reason;
|
|
2787
|
+
}
|
|
2675
2788
|
const candidates = [];
|
|
2676
|
-
for (const c of
|
|
2789
|
+
for (const c of resSummary.available_now ?? []) {
|
|
2677
2790
|
candidates.push({ ...c, urgency: "idle", release_horizon_days: null });
|
|
2678
2791
|
}
|
|
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
|
-
}
|
|
2792
|
+
for (const c of resSummary.finishing_in_30_days ?? []) {
|
|
2793
|
+
const days = typeof c.days_remaining === "number" ? c.days_remaining : null;
|
|
2794
|
+
if (days !== null && days > horizon_days) continue;
|
|
2688
2795
|
candidates.push({
|
|
2689
2796
|
...c,
|
|
2690
2797
|
urgency: "finishing",
|
|
2691
|
-
release_horizon_days:
|
|
2798
|
+
release_horizon_days: days
|
|
2692
2799
|
});
|
|
2693
2800
|
}
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
});
|
|
2701
|
-
}
|
|
2801
|
+
for (const c of partials) {
|
|
2802
|
+
candidates.push({
|
|
2803
|
+
...c,
|
|
2804
|
+
urgency: "partial",
|
|
2805
|
+
release_horizon_days: null
|
|
2806
|
+
});
|
|
2702
2807
|
}
|
|
2703
|
-
const opportunities = oppResponses.flatMap(
|
|
2704
|
-
(r) => r.data ?? []
|
|
2705
|
-
);
|
|
2706
2808
|
const matches = [];
|
|
2707
2809
|
for (const c of candidates) {
|
|
2708
2810
|
const specs = toSpecNames(c.specialties);
|
|
@@ -2722,10 +2824,13 @@ function registerSkillMatch(server, client, logger) {
|
|
|
2722
2824
|
status: c.status ?? null,
|
|
2723
2825
|
urgency: c.urgency,
|
|
2724
2826
|
available_since: c.available_since ?? null,
|
|
2725
|
-
expected_release_date:
|
|
2827
|
+
// The summary emits no expected_release_date key: the release
|
|
2828
|
+
// date IS the end date of the project being finished, so it is
|
|
2829
|
+
// null for idle and partial candidates.
|
|
2830
|
+
expected_release_date: c.current_project?.end_date ?? null,
|
|
2726
2831
|
// null = the horizon filter did not apply to this consultant:
|
|
2727
|
-
//
|
|
2728
|
-
//
|
|
2832
|
+
// they are idle or partially allocated, not finishing a
|
|
2833
|
+
// project. Not "released today".
|
|
2729
2834
|
release_horizon_days: c.release_horizon_days,
|
|
2730
2835
|
specialties: specs
|
|
2731
2836
|
},
|
|
@@ -2755,7 +2860,10 @@ function registerSkillMatch(server, client, logger) {
|
|
|
2755
2860
|
min_match_percent,
|
|
2756
2861
|
include_partial,
|
|
2757
2862
|
candidates_considered: candidates.length,
|
|
2758
|
-
opportunities_considered: opportunities.length
|
|
2863
|
+
opportunities_considered: opportunities.length,
|
|
2864
|
+
// Stages whose listing failed: the match above ran WITHOUT them.
|
|
2865
|
+
// Empty means the full open pipeline was seen.
|
|
2866
|
+
stages_failed: stagesFailed
|
|
2759
2867
|
}
|
|
2760
2868
|
};
|
|
2761
2869
|
})
|
|
@@ -2768,7 +2876,11 @@ function fmtBRL(v) {
|
|
|
2768
2876
|
if (!Number.isFinite(n)) return "\u2014";
|
|
2769
2877
|
return n.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
|
|
2770
2878
|
}
|
|
2771
|
-
function
|
|
2879
|
+
function reasonLabel(e) {
|
|
2880
|
+
if (e instanceof LkpError) return `${e.code}: ${e.message}`;
|
|
2881
|
+
return e instanceof Error ? e.message : String(e);
|
|
2882
|
+
}
|
|
2883
|
+
function buildMarkdown(ceo, alerts, opp, res, unavailable) {
|
|
2772
2884
|
const score = ceo?.operational_health?.score ?? "\u2014";
|
|
2773
2885
|
const cls = ceo?.operational_health?.classification ?? "\u2014";
|
|
2774
2886
|
const period = ceo?.week ?? ceo?.period?.label ?? (ceo?.period?.from && ceo?.period?.to ? `${ceo.period.from} \u2192 ${ceo.period.to}` : "semana atual");
|
|
@@ -2777,6 +2889,13 @@ function buildMarkdown(ceo, alerts, opp, res) {
|
|
|
2777
2889
|
lines.push("");
|
|
2778
2890
|
lines.push(`## \u{1F321}\uFE0F Sa\xFAde Operacional: ${score}/100 (${cls})`);
|
|
2779
2891
|
lines.push("");
|
|
2892
|
+
if (unavailable.length > 0) {
|
|
2893
|
+
lines.push("## \u26A0\uFE0F N\xE3o foi poss\xEDvel apurar");
|
|
2894
|
+
for (const u of unavailable) {
|
|
2895
|
+
lines.push(`- ${u}`);
|
|
2896
|
+
}
|
|
2897
|
+
lines.push("");
|
|
2898
|
+
}
|
|
2780
2899
|
if (alerts && alerts.length > 0) {
|
|
2781
2900
|
lines.push("## \u{1F534} Aten\xE7\xE3o imediata");
|
|
2782
2901
|
for (const a of alerts.slice(0, 10)) {
|
|
@@ -2797,7 +2916,7 @@ function buildMarkdown(ceo, alerts, opp, res) {
|
|
|
2797
2916
|
if (opp?.totals) {
|
|
2798
2917
|
const t = opp.totals;
|
|
2799
2918
|
lines.push(
|
|
2800
|
-
`- Pipeline aberto: ${t.
|
|
2919
|
+
`- Pipeline aberto: ${t.open_opportunities ?? "\u2014"} oportunidades \xB7 valor ${fmtBRL(t.total_pipeline_value)} \xB7 ponderado ${fmtBRL(t.weighted_pipeline_value)}`
|
|
2801
2920
|
);
|
|
2802
2921
|
}
|
|
2803
2922
|
if (opp?.stale_opportunities) {
|
|
@@ -2821,11 +2940,11 @@ function registerWeeklyBrief(server, client, logger) {
|
|
|
2821
2940
|
"lkp_weekly_brief",
|
|
2822
2941
|
{
|
|
2823
2942
|
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.",
|
|
2943
|
+
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
2944
|
inputSchema: {}
|
|
2826
2945
|
},
|
|
2827
2946
|
async () => runToolText(logger, "lkp_weekly_brief", async () => {
|
|
2828
|
-
const [ceo, alerts, opp, res] = await Promise.
|
|
2947
|
+
const [ceo, alerts, opp, res] = await Promise.allSettled([
|
|
2829
2948
|
client.get("/api/v1/reports/ceo-weekly"),
|
|
2830
2949
|
client.get("/api/v1/alerts", {
|
|
2831
2950
|
severity: "high"
|
|
@@ -2833,13 +2952,68 @@ function registerWeeklyBrief(server, client, logger) {
|
|
|
2833
2952
|
client.get("/api/v1/opportunities/summary"),
|
|
2834
2953
|
client.get("/api/v1/resources/summary")
|
|
2835
2954
|
]);
|
|
2836
|
-
|
|
2955
|
+
if (ceo.status === "rejected" && alerts.status === "rejected" && opp.status === "rejected" && res.status === "rejected") {
|
|
2956
|
+
throw ceo.reason;
|
|
2957
|
+
}
|
|
2958
|
+
const unavailable = [];
|
|
2959
|
+
function pick(r, block) {
|
|
2960
|
+
if (r.status === "fulfilled") return r.value.data;
|
|
2961
|
+
unavailable.push(`${block} \u2014 ${reasonLabel(r.reason)}`);
|
|
2962
|
+
return void 0;
|
|
2963
|
+
}
|
|
2964
|
+
return buildMarkdown(
|
|
2965
|
+
pick(ceo, "sa\xFAde operacional e per\xEDodo (reports/ceo-weekly)"),
|
|
2966
|
+
pick(alerts, "alertas de severidade alta (alerts)"),
|
|
2967
|
+
pick(opp, "pipeline e oportunidades stale (opportunities/summary)"),
|
|
2968
|
+
pick(res, "capacidade de consultores (resources/summary)"),
|
|
2969
|
+
unavailable
|
|
2970
|
+
);
|
|
2837
2971
|
})
|
|
2838
2972
|
);
|
|
2839
2973
|
}
|
|
2840
2974
|
|
|
2841
2975
|
// src/tools/composite/timesheet-anomalies.ts
|
|
2842
2976
|
import { z as z18 } from "zod";
|
|
2977
|
+
|
|
2978
|
+
// src/api-date.ts
|
|
2979
|
+
var API_TIMEZONE = "America/Sao_Paulo";
|
|
2980
|
+
var MS_PER_DAY = 864e5;
|
|
2981
|
+
var CALENDAR_DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[ T].*)?$/;
|
|
2982
|
+
function apiCalendarDay(raw) {
|
|
2983
|
+
if (typeof raw !== "string") return null;
|
|
2984
|
+
const m = CALENDAR_DATE.exec(raw.trim());
|
|
2985
|
+
if (!m) return null;
|
|
2986
|
+
const year = Number(m[1]);
|
|
2987
|
+
const month = Number(m[2]);
|
|
2988
|
+
const day = Number(m[3]);
|
|
2989
|
+
const utc = Date.UTC(year, month - 1, day);
|
|
2990
|
+
const back = new Date(utc);
|
|
2991
|
+
if (back.getUTCFullYear() !== year || back.getUTCMonth() !== month - 1 || back.getUTCDate() !== day) {
|
|
2992
|
+
return null;
|
|
2993
|
+
}
|
|
2994
|
+
return utc / MS_PER_DAY;
|
|
2995
|
+
}
|
|
2996
|
+
function dayOfWeek(calendarDay) {
|
|
2997
|
+
return new Date(calendarDay * MS_PER_DAY).getUTCDay();
|
|
2998
|
+
}
|
|
2999
|
+
function todayInApiCalendar(now = Date.now()) {
|
|
3000
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
3001
|
+
timeZone: API_TIMEZONE,
|
|
3002
|
+
year: "numeric",
|
|
3003
|
+
month: "2-digit",
|
|
3004
|
+
day: "2-digit"
|
|
3005
|
+
}).formatToParts(new Date(now));
|
|
3006
|
+
const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
|
|
3007
|
+
const day = apiCalendarDay(`${get("year")}-${get("month")}-${get("day")}`);
|
|
3008
|
+
if (day === null) {
|
|
3009
|
+
throw new Error(
|
|
3010
|
+
`Could not resolve today in ${API_TIMEZONE} (Intl returned ${JSON.stringify(parts)}).`
|
|
3011
|
+
);
|
|
3012
|
+
}
|
|
3013
|
+
return day;
|
|
3014
|
+
}
|
|
3015
|
+
|
|
3016
|
+
// src/tools/composite/timesheet-anomalies.ts
|
|
2843
3017
|
function linkedTaskId(e) {
|
|
2844
3018
|
for (const raw of [e.task?.id, e.task_id]) {
|
|
2845
3019
|
if (raw === null || raw === void 0) continue;
|
|
@@ -2850,6 +3024,7 @@ function linkedTaskId(e) {
|
|
|
2850
3024
|
}
|
|
2851
3025
|
async function fetchAllTimesheets(client, resourceId, from, to) {
|
|
2852
3026
|
const all = [];
|
|
3027
|
+
let resourceName = null;
|
|
2853
3028
|
for (let page = 1; page <= 5; page++) {
|
|
2854
3029
|
const r = await client.get(`/api/v1/resources/${resourceId}/timesheets`, {
|
|
2855
3030
|
from,
|
|
@@ -2859,10 +3034,11 @@ async function fetchAllTimesheets(client, resourceId, from, to) {
|
|
|
2859
3034
|
});
|
|
2860
3035
|
const batch = r.data ?? [];
|
|
2861
3036
|
all.push(...batch);
|
|
3037
|
+
resourceName ??= r.meta?.resource?.name ?? null;
|
|
2862
3038
|
const last = r.meta?.last_page;
|
|
2863
3039
|
if (last && page >= last || batch.length < 200) break;
|
|
2864
3040
|
}
|
|
2865
|
-
return all;
|
|
3041
|
+
return { entries: all, resourceName };
|
|
2866
3042
|
}
|
|
2867
3043
|
async function fetchAllResources(client) {
|
|
2868
3044
|
const perPage = 100;
|
|
@@ -2990,29 +3166,58 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
2990
3166
|
"lkp_timesheet_anomalies",
|
|
2991
3167
|
{
|
|
2992
3168
|
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.",
|
|
3169
|
+
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
3170
|
inputSchema: {
|
|
2995
|
-
|
|
2996
|
-
|
|
3171
|
+
// The regex mirrors the backend's own format gate; calendar validity,
|
|
3172
|
+
// ordering and the 184-day ceiling are checked in the handler, where
|
|
3173
|
+
// both values are in hand.
|
|
3174
|
+
from: z18.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD"),
|
|
3175
|
+
to: z18.string().regex(/^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD"),
|
|
2997
3176
|
resource_id: z18.coerce.number().int().positive().optional(),
|
|
2998
3177
|
unapproved_days_threshold: z18.coerce.number().int().positive().default(15)
|
|
2999
3178
|
}
|
|
3000
3179
|
},
|
|
3001
3180
|
async ({ from, to, resource_id, unapproved_days_threshold }) => runTool(logger, "lkp_timesheet_anomalies", async () => {
|
|
3002
3181
|
const today = todayInApiCalendar();
|
|
3182
|
+
const fromDay = apiCalendarDay(from);
|
|
3183
|
+
const toDay = apiCalendarDay(to);
|
|
3184
|
+
if (fromDay === null || toDay === null) {
|
|
3185
|
+
throw new LkpError({
|
|
3186
|
+
code: "bad_request",
|
|
3187
|
+
api_code: "invalid_filter",
|
|
3188
|
+
message: `${fromDay === null ? "from" : "to"} is not a real calendar date (YYYY-MM-DD).`
|
|
3189
|
+
});
|
|
3190
|
+
}
|
|
3191
|
+
if (fromDay > toDay) {
|
|
3192
|
+
throw new LkpError({
|
|
3193
|
+
code: "bad_request",
|
|
3194
|
+
api_code: "invalid_filter",
|
|
3195
|
+
message: "from must be \u2264 to."
|
|
3196
|
+
});
|
|
3197
|
+
}
|
|
3198
|
+
if (toDay - fromDay + 1 > 184) {
|
|
3199
|
+
throw new LkpError({
|
|
3200
|
+
code: "bad_request",
|
|
3201
|
+
api_code: "invalid_filter",
|
|
3202
|
+
message: "Range cannot exceed 184 days (~6 months)."
|
|
3203
|
+
});
|
|
3204
|
+
}
|
|
3003
3205
|
const findings = [];
|
|
3004
3206
|
const scanned = [];
|
|
3207
|
+
const failed = [];
|
|
3208
|
+
let entriesScanned = 0;
|
|
3005
3209
|
let scope;
|
|
3006
3210
|
if (resource_id !== void 0) {
|
|
3007
3211
|
scope = "resource";
|
|
3008
|
-
const entries = await fetchAllTimesheets(
|
|
3212
|
+
const { entries, resourceName } = await fetchAllTimesheets(
|
|
3009
3213
|
client,
|
|
3010
3214
|
resource_id,
|
|
3011
3215
|
from,
|
|
3012
3216
|
to
|
|
3013
3217
|
);
|
|
3014
|
-
const name =
|
|
3218
|
+
const name = resourceName ?? `#${resource_id}`;
|
|
3015
3219
|
scanned.push({ id: resource_id, name });
|
|
3220
|
+
entriesScanned += entries.length;
|
|
3016
3221
|
findings.push(
|
|
3017
3222
|
...detectAnomalies(
|
|
3018
3223
|
entries,
|
|
@@ -3029,13 +3234,14 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
3029
3234
|
);
|
|
3030
3235
|
await mapLimit(active, 5, async (r) => {
|
|
3031
3236
|
try {
|
|
3032
|
-
const entries = await fetchAllTimesheets(
|
|
3237
|
+
const { entries } = await fetchAllTimesheets(
|
|
3033
3238
|
client,
|
|
3034
3239
|
r.id,
|
|
3035
3240
|
from,
|
|
3036
3241
|
to
|
|
3037
3242
|
);
|
|
3038
3243
|
scanned.push({ id: r.id, name: r.name });
|
|
3244
|
+
entriesScanned += entries.length;
|
|
3039
3245
|
findings.push(
|
|
3040
3246
|
...detectAnomalies(
|
|
3041
3247
|
entries,
|
|
@@ -3046,6 +3252,12 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
3046
3252
|
)
|
|
3047
3253
|
);
|
|
3048
3254
|
} catch (e) {
|
|
3255
|
+
if (e instanceof LkpError && e.http_status === 400) throw e;
|
|
3256
|
+
failed.push({
|
|
3257
|
+
resource_id: r.id,
|
|
3258
|
+
name: r.name,
|
|
3259
|
+
error: e instanceof LkpError ? `${e.code}: ${e.message}` : e.message
|
|
3260
|
+
});
|
|
3049
3261
|
logger.warn(
|
|
3050
3262
|
{ resource_id: r.id, err: e.message },
|
|
3051
3263
|
"timesheets_fetch_failed"
|
|
@@ -3061,8 +3273,19 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
3061
3273
|
period: { from, to },
|
|
3062
3274
|
scope,
|
|
3063
3275
|
resources_scanned: scanned.length,
|
|
3276
|
+
// Every consultant whose timesheets could not be fetched, by name.
|
|
3277
|
+
// An empty list is the only thing that lets findings be read as
|
|
3278
|
+
// covering the whole scope.
|
|
3279
|
+
resources_failed: failed,
|
|
3280
|
+
entries_scanned: entriesScanned,
|
|
3064
3281
|
findings,
|
|
3065
|
-
summary: {
|
|
3282
|
+
summary: {
|
|
3283
|
+
total_findings: findings.length,
|
|
3284
|
+
by_type: byType,
|
|
3285
|
+
// scanned/attempted — anything below N/N marks findings as a
|
|
3286
|
+
// PARTIAL view of the period, whatever total_findings says.
|
|
3287
|
+
coverage: `${scanned.length}/${scanned.length + failed.length}`
|
|
3288
|
+
}
|
|
3066
3289
|
};
|
|
3067
3290
|
})
|
|
3068
3291
|
);
|
|
@@ -3338,7 +3561,7 @@ function registerAllPrompts(server) {
|
|
|
3338
3561
|
}
|
|
3339
3562
|
|
|
3340
3563
|
// src/contract.ts
|
|
3341
|
-
var EXPECTED_CONTRACT = "2.
|
|
3564
|
+
var EXPECTED_CONTRACT = "2.17";
|
|
3342
3565
|
function minorOf(version) {
|
|
3343
3566
|
const [major = "", minor = ""] = version.split(".");
|
|
3344
3567
|
return { major, minor: Number(minor) };
|