lkpgestao-mcp 0.6.0 → 0.7.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 +106 -64
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -182,6 +182,9 @@ var LkpClient = class {
|
|
|
182
182
|
patch(path, body) {
|
|
183
183
|
return this.request("PATCH", path, { body });
|
|
184
184
|
}
|
|
185
|
+
put(path, body) {
|
|
186
|
+
return this.request("PUT", path, { body });
|
|
187
|
+
}
|
|
185
188
|
delete(path) {
|
|
186
189
|
return this.request("DELETE", path, {});
|
|
187
190
|
}
|
|
@@ -516,6 +519,29 @@ function registerResources(server, client, logger) {
|
|
|
516
519
|
})
|
|
517
520
|
)
|
|
518
521
|
);
|
|
522
|
+
server.registerTool(
|
|
523
|
+
"lkp_specialties_list",
|
|
524
|
+
{
|
|
525
|
+
title: "List specialties",
|
|
526
|
+
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 }.",
|
|
527
|
+
inputSchema: {
|
|
528
|
+
category: z3.enum([
|
|
529
|
+
"SAP_DESENVOLVIMENTO",
|
|
530
|
+
"SAP_FUNCIONAL",
|
|
531
|
+
"SAP_TECNICO",
|
|
532
|
+
"GEST\xC3O",
|
|
533
|
+
"BACKOFFICE"
|
|
534
|
+
]).optional(),
|
|
535
|
+
search: z3.string().optional(),
|
|
536
|
+
active_only: z3.coerce.boolean().default(true)
|
|
537
|
+
}
|
|
538
|
+
},
|
|
539
|
+
async (args) => runTool(
|
|
540
|
+
logger,
|
|
541
|
+
"lkp_specialties_list",
|
|
542
|
+
() => client.get("/api/v1/specialties", args)
|
|
543
|
+
)
|
|
544
|
+
);
|
|
519
545
|
server.registerTool(
|
|
520
546
|
"lkp_resource_timesheets",
|
|
521
547
|
{
|
|
@@ -934,21 +960,42 @@ var BillingModel = z6.enum([
|
|
|
934
960
|
var DiscountType = z6.enum(["PERCENT", "VALUE"]);
|
|
935
961
|
var BillingCadence = z6.enum(["monthly", "quarterly", "annual"]);
|
|
936
962
|
var QuoteItemInput = z6.object({
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
963
|
+
specialty_id: z6.coerce.number().int().positive(),
|
|
964
|
+
skill_level: SkillLevel,
|
|
965
|
+
description: z6.string().min(1).optional(),
|
|
966
|
+
quoted_hours: z6.coerce.number().nonnegative(),
|
|
967
|
+
sold_hours: z6.coerce.number().positive(),
|
|
968
|
+
hourly_rate: z6.coerce.number().nonnegative().optional(),
|
|
969
|
+
cost_rate: z6.coerce.number().nonnegative().optional(),
|
|
970
|
+
sort_order: z6.coerce.number().int().optional()
|
|
944
971
|
});
|
|
945
972
|
var PaymentMilestoneInput = z6.object({
|
|
946
973
|
description: z6.string().min(1),
|
|
974
|
+
percentage: z6.coerce.number().positive().max(100),
|
|
975
|
+
due_days: z6.coerce.number().int().nonnegative().optional(),
|
|
947
976
|
due_date: z6.string().optional(),
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
sequence: z6.coerce.number().int().nonnegative().optional()
|
|
977
|
+
notes: z6.string().optional(),
|
|
978
|
+
sort_order: z6.coerce.number().int().optional()
|
|
951
979
|
});
|
|
980
|
+
var QuoteHeaderFields = {
|
|
981
|
+
valid_until: z6.string().optional(),
|
|
982
|
+
currency: Currency.optional(),
|
|
983
|
+
billing_model: BillingModel.optional(),
|
|
984
|
+
billing_cadence: BillingCadence.optional(),
|
|
985
|
+
discount_type: DiscountType.optional(),
|
|
986
|
+
discount_percent: z6.coerce.number().nonnegative().optional(),
|
|
987
|
+
tax_rate_id: z6.coerce.number().int().positive().optional(),
|
|
988
|
+
tax_absorbed: z6.coerce.boolean().optional(),
|
|
989
|
+
notes: z6.string().optional(),
|
|
990
|
+
internal_notes: z6.string().optional(),
|
|
991
|
+
terms_and_conditions: z6.string().optional(),
|
|
992
|
+
setup_fee: z6.coerce.number().nonnegative().optional(),
|
|
993
|
+
monthly_amount: z6.coerce.number().nonnegative().optional(),
|
|
994
|
+
recurring_start_date: z6.string().optional(),
|
|
995
|
+
billing_cadence_subscription: BillingCadence.optional(),
|
|
996
|
+
contract_months: z6.coerce.number().int().positive().optional(),
|
|
997
|
+
installment_count: z6.coerce.number().int().positive().max(60).optional()
|
|
998
|
+
};
|
|
952
999
|
function registerQuotes(server, client, logger) {
|
|
953
1000
|
server.registerTool(
|
|
954
1001
|
"lkp_quotes_list",
|
|
@@ -1011,18 +1058,10 @@ function registerQuotes(server, client, logger) {
|
|
|
1011
1058
|
"lkp_quote_create",
|
|
1012
1059
|
{
|
|
1013
1060
|
title: "Create quote (write)",
|
|
1014
|
-
description: "Create a new DRAFT quote under an opportunity.
|
|
1061
|
+
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. billing_model=subscription requires monthly_amount + contract_months and items[] must be omitted. Summarize the draft (opportunity, items, totals, milestones) and wait for explicit user approval before calling.",
|
|
1015
1062
|
inputSchema: {
|
|
1016
1063
|
opportunity_id: z6.coerce.number().int().positive(),
|
|
1017
|
-
|
|
1018
|
-
billing_model: BillingModel,
|
|
1019
|
-
billing_cadence: BillingCadence.optional(),
|
|
1020
|
-
valid_until: z6.string().optional(),
|
|
1021
|
-
notes: z6.string().optional(),
|
|
1022
|
-
discount_type: DiscountType.optional(),
|
|
1023
|
-
discount_value: z6.coerce.number().nonnegative().optional(),
|
|
1024
|
-
monthly_amount: z6.coerce.number().nonnegative().optional(),
|
|
1025
|
-
contract_months: z6.coerce.number().int().positive().optional(),
|
|
1064
|
+
...QuoteHeaderFields,
|
|
1026
1065
|
items: z6.array(QuoteItemInput).optional(),
|
|
1027
1066
|
payment_milestones: z6.array(PaymentMilestoneInput).optional()
|
|
1028
1067
|
}
|
|
@@ -1040,18 +1079,10 @@ function registerQuotes(server, client, logger) {
|
|
|
1040
1079
|
"lkp_quote_update",
|
|
1041
1080
|
{
|
|
1042
1081
|
title: "Update quote (write)",
|
|
1043
|
-
description: "Update whitelisted fields on a quote. Only DRAFT quotes can be freely edited; SENT quotes are locked \u2014 clone via lkp_quote_new_version to change terms. Mutations to items[] or payment_milestones[] must go through the dedicated tools. Setting is_active=false archives the quote
|
|
1082
|
+
description: "Update whitelisted header fields on a quote. Only DRAFT quotes can be freely edited; SENT quotes are locked \u2014 clone via lkp_quote_new_version to change terms. 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.",
|
|
1044
1083
|
inputSchema: {
|
|
1045
1084
|
quote_id: z6.coerce.number().int().positive(),
|
|
1046
|
-
|
|
1047
|
-
billing_model: BillingModel.optional(),
|
|
1048
|
-
billing_cadence: BillingCadence.optional(),
|
|
1049
|
-
valid_until: z6.string().optional(),
|
|
1050
|
-
notes: z6.string().optional(),
|
|
1051
|
-
discount_type: DiscountType.optional(),
|
|
1052
|
-
discount_value: z6.coerce.number().nonnegative().optional(),
|
|
1053
|
-
monthly_amount: z6.coerce.number().nonnegative().optional(),
|
|
1054
|
-
contract_months: z6.coerce.number().int().positive().optional(),
|
|
1085
|
+
...QuoteHeaderFields,
|
|
1055
1086
|
is_active: z6.coerce.boolean().optional()
|
|
1056
1087
|
}
|
|
1057
1088
|
},
|
|
@@ -1065,7 +1096,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1065
1096
|
"lkp_quote_archive",
|
|
1066
1097
|
{
|
|
1067
1098
|
title: "Archive quote (write)",
|
|
1068
|
-
description: "Soft-archive a quote (is_active=0). Only DRAFT quotes should be archived
|
|
1099
|
+
description: "Soft-archive a quote (is_active=0). Only DRAFT quotes should be archived \u2014 if a SENT/ACCEPTED quote needs to be invalidated, use lkp_quote_new_version instead. Always ask user approval before calling.",
|
|
1069
1100
|
inputSchema: {
|
|
1070
1101
|
quote_id: z6.coerce.number().int().positive()
|
|
1071
1102
|
}
|
|
@@ -1094,7 +1125,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1094
1125
|
"lkp_quote_accept",
|
|
1095
1126
|
{
|
|
1096
1127
|
title: "Accept quote (write)",
|
|
1097
|
-
description: "Transition a SENT quote to ACCEPTED. Moves the parent opportunity to WON and cascades all sibling quotes on the same opportunity to REJECTED.
|
|
1128
|
+
description: "Transition a SENT quote to ACCEPTED. Moves the parent opportunity to WON and cascades all sibling quotes on the same opportunity to REJECTED. Commercially binding \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.",
|
|
1098
1129
|
inputSchema: {
|
|
1099
1130
|
quote_id: z6.coerce.number().int().positive()
|
|
1100
1131
|
}
|
|
@@ -1109,7 +1140,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1109
1140
|
"lkp_quote_reject",
|
|
1110
1141
|
{
|
|
1111
1142
|
title: "Reject quote (write)",
|
|
1112
|
-
description: "Transition a SENT quote to REJECTED. Always ask the user for the rejection motive before calling \u2014 reason is mandatory (API refuses empty). Reason is user-visible in the opportunity activity log
|
|
1143
|
+
description: "Transition a SENT quote to REJECTED. Always ask the user for the rejection motive before calling \u2014 reason is mandatory (API refuses empty). Reason is user-visible in the opportunity activity log.",
|
|
1113
1144
|
inputSchema: {
|
|
1114
1145
|
quote_id: z6.coerce.number().int().positive(),
|
|
1115
1146
|
reason: z6.string().min(1).max(200)
|
|
@@ -1125,7 +1156,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1125
1156
|
"lkp_quote_new_version",
|
|
1126
1157
|
{
|
|
1127
1158
|
title: "Create new version of quote (write)",
|
|
1128
|
-
description: "Clone a quote (any status) into a new DRAFT with version = prior + 1. The prior version is marked SUPERSEDED.
|
|
1159
|
+
description: "Clone a quote (any status) into a new DRAFT with version = prior + 1. The prior version is marked SUPERSEDED. Not allowed from DRAFT status (edit the existing draft instead). items[] and payment_milestones[] are copied; edit them on the new draft via the dedicated tools. Confirm the intent with the user.",
|
|
1129
1160
|
inputSchema: {
|
|
1130
1161
|
quote_id: z6.coerce.number().int().positive()
|
|
1131
1162
|
}
|
|
@@ -1140,7 +1171,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1140
1171
|
"lkp_quote_duplicate",
|
|
1141
1172
|
{
|
|
1142
1173
|
title: "Duplicate quote to another opportunity (write)",
|
|
1143
|
-
description: "Copy a quote (including items
|
|
1174
|
+
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.",
|
|
1144
1175
|
inputSchema: {
|
|
1145
1176
|
quote_id: z6.coerce.number().int().positive(),
|
|
1146
1177
|
target_opportunity_id: z6.coerce.number().int().positive()
|
|
@@ -1158,16 +1189,17 @@ function registerQuotes(server, client, logger) {
|
|
|
1158
1189
|
"lkp_quote_item_add",
|
|
1159
1190
|
{
|
|
1160
1191
|
title: "Add item to quote (write)",
|
|
1161
|
-
description: "Append a
|
|
1192
|
+
description: "Append a line item to a DRAFT quote. 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. Summarize the line (description, sold_hours \xD7 hourly_rate) and wait for user approval.",
|
|
1162
1193
|
inputSchema: {
|
|
1163
1194
|
quote_id: z6.coerce.number().int().positive(),
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1195
|
+
specialty_id: z6.coerce.number().int().positive(),
|
|
1196
|
+
skill_level: SkillLevel,
|
|
1197
|
+
description: z6.string().min(1).optional(),
|
|
1198
|
+
quoted_hours: z6.coerce.number().nonnegative(),
|
|
1199
|
+
sold_hours: z6.coerce.number().positive(),
|
|
1200
|
+
hourly_rate: z6.coerce.number().nonnegative().optional(),
|
|
1201
|
+
cost_rate: z6.coerce.number().nonnegative().optional(),
|
|
1202
|
+
sort_order: z6.coerce.number().int().optional()
|
|
1171
1203
|
}
|
|
1172
1204
|
},
|
|
1173
1205
|
async ({ quote_id, ...body }) => runTool(
|
|
@@ -1180,17 +1212,19 @@ function registerQuotes(server, client, logger) {
|
|
|
1180
1212
|
"lkp_quote_item_update",
|
|
1181
1213
|
{
|
|
1182
1214
|
title: "Update quote item (write)",
|
|
1183
|
-
description: "Update whitelisted fields on a line item of a DRAFT quote. Blocked when the parent quote is not DRAFT. Summarize the diff (field \u2192 old \u2192 new) and wait for user approval.",
|
|
1215
|
+
description: "Update whitelisted fields on a line item of a DRAFT quote. Blocked when the parent quote is not DRAFT. All fields optional (patch). Summarize the diff (field \u2192 old \u2192 new) and wait for user approval.",
|
|
1184
1216
|
inputSchema: {
|
|
1185
1217
|
quote_id: z6.coerce.number().int().positive(),
|
|
1186
1218
|
item_id: z6.coerce.number().int().positive(),
|
|
1187
|
-
|
|
1188
|
-
quantity: z6.coerce.number().positive().optional(),
|
|
1189
|
-
unit_price: z6.coerce.number().nonnegative().optional(),
|
|
1219
|
+
specialty_id: z6.coerce.number().int().positive().optional(),
|
|
1190
1220
|
skill_level: SkillLevel.optional(),
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1221
|
+
description: z6.string().min(1).optional(),
|
|
1222
|
+
quoted_hours: z6.coerce.number().nonnegative().optional(),
|
|
1223
|
+
sold_hours: z6.coerce.number().positive().optional(),
|
|
1224
|
+
hourly_rate: z6.coerce.number().nonnegative().optional(),
|
|
1225
|
+
cost_rate: z6.coerce.number().nonnegative().optional(),
|
|
1226
|
+
sort_order: z6.coerce.number().int().optional(),
|
|
1227
|
+
is_active: z6.coerce.boolean().optional()
|
|
1194
1228
|
}
|
|
1195
1229
|
},
|
|
1196
1230
|
async ({ quote_id, item_id, ...body }) => runTool(
|
|
@@ -1221,7 +1255,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1221
1255
|
"lkp_quote_milestones_replace",
|
|
1222
1256
|
{
|
|
1223
1257
|
title: "Replace all payment milestones (write)",
|
|
1224
|
-
description: "Replace the entire payment_milestones[] collection on a DRAFT quote
|
|
1258
|
+
description: "Replace the entire payment_milestones[] collection on a DRAFT quote atomically. due_days and due_date are mutually exclusive per milestone. percentages must sum to 100 (\xB10.01); amount is computed server-side \u2014 do not send it. Summarize the new schedule and wait for user approval.",
|
|
1225
1259
|
inputSchema: {
|
|
1226
1260
|
quote_id: z6.coerce.number().int().positive(),
|
|
1227
1261
|
milestones: z6.array(PaymentMilestoneInput).min(1)
|
|
@@ -1230,10 +1264,9 @@ function registerQuotes(server, client, logger) {
|
|
|
1230
1264
|
async ({ quote_id, milestones }) => runTool(
|
|
1231
1265
|
logger,
|
|
1232
1266
|
"lkp_quote_milestones_replace",
|
|
1233
|
-
() => client.
|
|
1267
|
+
() => client.put(
|
|
1234
1268
|
`/api/v1/quotes/${quote_id}/payment-milestones`,
|
|
1235
|
-
{ milestones }
|
|
1236
|
-
{ "X-HTTP-Method-Override": "PUT" }
|
|
1269
|
+
{ milestones }
|
|
1237
1270
|
)
|
|
1238
1271
|
)
|
|
1239
1272
|
);
|
|
@@ -1241,14 +1274,15 @@ function registerQuotes(server, client, logger) {
|
|
|
1241
1274
|
"lkp_quote_milestone_add",
|
|
1242
1275
|
{
|
|
1243
1276
|
title: "Add payment milestone (write)",
|
|
1244
|
-
description: "Append a single payment milestone to a DRAFT quote (additive; does not
|
|
1277
|
+
description: "Append a single payment milestone to a DRAFT quote (additive; does not enforce sum=100 \u2014 use replace for atomic rewrite). due_days and due_date are mutually exclusive. Summarize (description, percentage, due) and wait for user approval.",
|
|
1245
1278
|
inputSchema: {
|
|
1246
1279
|
quote_id: z6.coerce.number().int().positive(),
|
|
1247
1280
|
description: z6.string().min(1),
|
|
1281
|
+
percentage: z6.coerce.number().positive().max(100),
|
|
1282
|
+
due_days: z6.coerce.number().int().nonnegative().optional(),
|
|
1248
1283
|
due_date: z6.string().optional(),
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
sequence: z6.coerce.number().int().nonnegative().optional()
|
|
1284
|
+
notes: z6.string().optional(),
|
|
1285
|
+
sort_order: z6.coerce.number().int().optional()
|
|
1252
1286
|
}
|
|
1253
1287
|
},
|
|
1254
1288
|
async ({ quote_id, ...body }) => runTool(
|
|
@@ -1264,15 +1298,17 @@ function registerQuotes(server, client, logger) {
|
|
|
1264
1298
|
"lkp_quote_milestone_update",
|
|
1265
1299
|
{
|
|
1266
1300
|
title: "Update payment milestone (write)",
|
|
1267
|
-
description: "Update whitelisted fields on a payment milestone of a DRAFT quote.
|
|
1301
|
+
description: "Update whitelisted fields on a payment milestone of a DRAFT quote. due_days and due_date are mutually exclusive. Does NOT enforce sum=100 \u2014 caller is responsible. Summarize the diff and wait for user approval.",
|
|
1268
1302
|
inputSchema: {
|
|
1269
1303
|
quote_id: z6.coerce.number().int().positive(),
|
|
1270
1304
|
milestone_id: z6.coerce.number().int().positive(),
|
|
1271
|
-
description: z6.string().optional(),
|
|
1305
|
+
description: z6.string().min(1).optional(),
|
|
1306
|
+
percentage: z6.coerce.number().positive().max(100).optional(),
|
|
1307
|
+
due_days: z6.coerce.number().int().nonnegative().optional(),
|
|
1272
1308
|
due_date: z6.string().optional(),
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1309
|
+
notes: z6.string().optional(),
|
|
1310
|
+
sort_order: z6.coerce.number().int().optional(),
|
|
1311
|
+
is_active: z6.coerce.boolean().optional()
|
|
1276
1312
|
}
|
|
1277
1313
|
},
|
|
1278
1314
|
async ({ quote_id, milestone_id, ...body }) => runTool(
|
|
@@ -1288,7 +1324,7 @@ function registerQuotes(server, client, logger) {
|
|
|
1288
1324
|
"lkp_quote_milestone_delete",
|
|
1289
1325
|
{
|
|
1290
1326
|
title: "Delete payment milestone (write)",
|
|
1291
|
-
description: "Remove one payment milestone from a DRAFT quote.
|
|
1327
|
+
description: "Remove one payment milestone from a DRAFT quote. Always ask user approval before calling.",
|
|
1292
1328
|
inputSchema: {
|
|
1293
1329
|
quote_id: z6.coerce.number().int().positive(),
|
|
1294
1330
|
milestone_id: z6.coerce.number().int().positive()
|
|
@@ -2043,6 +2079,12 @@ function buildText2(quoteRef) {
|
|
|
2043
2079
|
|
|
2044
2080
|
After writing, confirm using the returned payload and suggest one concrete next step.
|
|
2045
2081
|
|
|
2082
|
+
ITEM RULES (when adding or updating items):
|
|
2083
|
+
- Call lkp_specialties_list once to resolve specialty names \u2192 specialty_id. Do NOT hardcode IDs.
|
|
2084
|
+
- skill_level (J\xFAnior | Pleno | S\xEAnior | Especialista) is REQUIRED per item \u2014 it is not derivable from specialty_id.
|
|
2085
|
+
- hourly_rate is optional: omit it to let the backend resolve via the client's price_list for (specialty_id, skill_level). Pass it explicitly only to override the rate card (e.g. promotional pricing).
|
|
2086
|
+
- If the backend returns rate_not_found_in_price_list, surface the error as-is \u2014 do not retry with a different skill_level. The client's price_list needs to be updated in LKPGest\xE3o.
|
|
2087
|
+
|
|
2046
2088
|
HARD RULES (do not violate, even if the user seems to agree):
|
|
2047
2089
|
- ACCEPT: never call lkp_quote_accept without explicit, unambiguous approval referencing the quote code (e.g. "sim, aceitar QT-2026-0007"). Accept cascades sibling quotes to REJECTED and moves the opportunity to WON \u2014 it is commercially binding.
|
|
2048
2090
|
- REJECT: always ask the user for the rejection motive before calling lkp_quote_reject. Reason is mandatory (min 1 char, max 200).
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/logger.ts","../src/http-client.ts","../src/errors.ts","../src/tools/ping.ts","../src/tools/resources.ts","../src/tools/common.ts","../src/tools/projects.ts","../src/tools/opportunities.ts","../src/tools/quotes.ts","../src/tools/clients.ts","../src/tools/helpdesk.ts","../src/tools/billing.ts","../src/tools/alerts.ts","../src/tools/reports.ts","../src/tools/financial.ts","../src/tools/composite/skill-match.ts","../src/tools/composite/weekly-brief.ts","../src/tools/composite/timesheet-anomalies.ts","../src/tools/composite/index.ts","../src/tools/index.ts","../src/prompts/weekly-brief.ts","../src/prompts/morning-standup.ts","../src/prompts/opportunity-action.ts","../src/prompts/quote-action.ts","../src/prompts/consultant-investigation.ts","../src/prompts/managers-in-trouble.ts","../src/prompts/pipeline-health-check.ts","../src/prompts/index.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { SERVER_NAME, SERVER_VERSION, loadConfig } from \"./config.js\";\nimport { createLogger } from \"./logger.js\";\nimport { LkpClient } from \"./http-client.js\";\nimport { registerAllTools } from \"./tools/index.js\";\nimport { registerAllPrompts } from \"./prompts/index.js\";\n\nasync function main(): Promise<void> {\n const config = loadConfig();\n const logger = createLogger(config);\n\n logger.info(\n {\n base_url: config.LKP_API_BASE_URL,\n log_level: config.LKP_LOG_LEVEL,\n timeout_ms: config.LKP_REQUEST_TIMEOUT_MS,\n retry_attempts: config.LKP_RETRY_ATTEMPTS,\n node: process.version,\n },\n \"starting\",\n );\n\n const client = new LkpClient({\n baseUrl: config.LKP_API_BASE_URL,\n token: config.LKP_API_TOKEN,\n timeoutMs: config.LKP_REQUEST_TIMEOUT_MS,\n retryAttempts: config.LKP_RETRY_ATTEMPTS,\n userAgent: `${SERVER_NAME}/${SERVER_VERSION} (+node ${process.version})`,\n logger,\n });\n\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n });\n\n registerAllTools(server, client, logger);\n registerAllPrompts(server);\n\n const transport = new StdioServerTransport();\n\n const shutdown = async (signal: string): Promise<void> => {\n logger.info({ signal }, \"shutdown\");\n try {\n await server.close();\n } catch (e) {\n logger.error(\n { err: e instanceof Error ? e.message : String(e) },\n \"shutdown_error\",\n );\n }\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => {\n void shutdown(\"SIGINT\");\n });\n process.on(\"SIGTERM\", () => {\n void shutdown(\"SIGTERM\");\n });\n process.on(\"uncaughtException\", (err) => {\n logger.fatal({ err: err.message, stack: err.stack }, \"uncaught_exception\");\n process.exit(1);\n });\n process.on(\"unhandledRejection\", (reason) => {\n logger.fatal({ reason: String(reason) }, \"unhandled_rejection\");\n process.exit(1);\n });\n\n await server.connect(transport);\n logger.info(\"ready\");\n}\n\nmain().catch((err) => {\n process.stderr.write(\n `[${SERVER_NAME}] fatal: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n process.exit(1);\n});\n","import { execFileSync } from \"node:child_process\";\nimport { z } from \"zod\";\n\nexport const SERVER_NAME = \"lkpgestao-mcp\";\nexport const SERVER_VERSION = \"0.1.0\";\n\nconst ConfigSchema = z.object({\n LKP_API_BASE_URL: z\n .string()\n .url(\"must be a valid URL\")\n .refine((u) => u.startsWith(\"https://\"), {\n message: \"must use https:// (TLS is mandatory)\",\n })\n .transform((u) => u.replace(/\\/+$/, \"\")),\n LKP_API_TOKEN: z.string().min(1, \"cannot be empty\"),\n LKP_LOG_LEVEL: z\n .enum([\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\", \"silent\"])\n .default(\"info\"),\n LKP_REQUEST_TIMEOUT_MS: z.coerce.number().int().positive().default(10_000),\n LKP_RETRY_ATTEMPTS: z.coerce.number().int().min(0).max(5).default(2),\n LKP_CACHE_TTL_SECONDS: z.coerce.number().int().min(0).default(30),\n});\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\nexport type KeychainLookup = (service: string, account?: string) => string;\n\nexport const defaultKeychainLookup: KeychainLookup = (service, account) => {\n const args = [\"find-generic-password\", \"-s\", service, \"-w\"];\n if (account) args.push(\"-a\", account);\n try {\n const out = execFileSync(\"security\", args, {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n return out.replace(/\\r?\\n$/, \"\");\n } catch (err: unknown) {\n const e = err as { status?: number; stderr?: Buffer | string; code?: string };\n if (e.code === \"ENOENT\") {\n throw new Error(\n \"Keychain lookup requires the macOS `security` binary (not found on PATH)\",\n );\n }\n const stderr =\n typeof e.stderr === \"string\"\n ? e.stderr\n : (e.stderr?.toString(\"utf8\") ?? \"\");\n const hint = /could not be found|SecKeychainSearchCopyNext/.test(stderr)\n ? `item \"${service}\" not found in Keychain`\n : stderr.trim() || `security exited with status ${e.status}`;\n throw new Error(`Keychain lookup failed: ${hint}`);\n }\n};\n\nexport interface LoadConfigOptions {\n keychainLookup?: KeychainLookup;\n}\n\nexport function loadConfig(\n env: NodeJS.ProcessEnv = process.env,\n options: LoadConfigOptions = {},\n): Config {\n const lookup = options.keychainLookup ?? defaultKeychainLookup;\n const resolved: NodeJS.ProcessEnv = { ...env };\n\n if (!resolved.LKP_API_TOKEN && resolved.LKP_API_TOKEN_KEYCHAIN_SERVICE) {\n try {\n resolved.LKP_API_TOKEN = lookup(\n resolved.LKP_API_TOKEN_KEYCHAIN_SERVICE,\n resolved.LKP_API_TOKEN_KEYCHAIN_ACCOUNT,\n );\n } catch (err) {\n process.stderr.write(\n `[${SERVER_NAME}] configuration error:\\n - ${(err as Error).message}\\n\\n`,\n );\n process.exit(1);\n }\n }\n\n const parsed = ConfigSchema.safeParse(resolved);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => ` - ${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n .join(\"\\n\");\n process.stderr.write(\n `[${SERVER_NAME}] configuration error:\\n${issues}\\n\\n` +\n `Required env vars: LKP_API_BASE_URL, LKP_API_TOKEN ` +\n `(or LKP_API_TOKEN_KEYCHAIN_SERVICE on macOS).\\n` +\n `See README for the full reference.\\n`,\n );\n process.exit(1);\n }\n return parsed.data;\n}\n","import pino, { type Logger as PinoLogger, type DestinationStream } from \"pino\";\nimport { SERVER_NAME, SERVER_VERSION, type Config } from \"./config.js\";\n\nexport type Logger = PinoLogger;\n\nexport const REDACT_PATHS = [\n \"authorization\",\n \"Authorization\",\n \"headers.authorization\",\n \"headers.Authorization\",\n \"token\",\n \"api_token\",\n \"bearer\",\n \"LKP_API_TOKEN\",\n \"env.LKP_API_TOKEN\",\n \"*.token\",\n \"*.api_token\",\n \"*.authorization\",\n];\n\nexport function createLogger(\n config: Config,\n destination?: DestinationStream,\n): Logger {\n return pino(\n {\n name: SERVER_NAME,\n level: config.LKP_LOG_LEVEL,\n base: {\n service: SERVER_NAME,\n version: SERVER_VERSION,\n pid: process.pid,\n },\n redact: {\n paths: REDACT_PATHS,\n censor: \"[REDACTED]\",\n remove: false,\n },\n timestamp: pino.stdTimeFunctions.isoTime,\n },\n destination ?? pino.destination({ dest: 2, sync: false }),\n );\n}\n","import { randomUUID } from \"node:crypto\";\nimport { LkpError, mapHttpStatus, type LkpErrorCode } from \"./errors.js\";\nimport type { Logger } from \"./logger.js\";\n\nexport interface LkpClientOptions {\n baseUrl: string;\n token: string;\n timeoutMs: number;\n retryAttempts: number;\n userAgent: string;\n logger: Logger;\n}\n\nexport type QueryValue = string | number | boolean | undefined | null;\nexport type Query = Record<string, QueryValue>;\n\nexport const MAX_RETRY_AFTER_SECONDS = 60;\n\ninterface RequestOptions {\n query?: Query;\n body?: unknown;\n extraHeaders?: Record<string, string>;\n}\n\ninterface ApiErrorShape {\n code?: string;\n message?: string;\n details?: unknown;\n}\n\nexport class LkpClient {\n private readonly baseUrl: string;\n private readonly token: string;\n private readonly timeoutMs: number;\n private readonly retryAttempts: number;\n private readonly userAgent: string;\n private readonly logger: Logger;\n\n constructor(opts: LkpClientOptions) {\n this.baseUrl = opts.baseUrl;\n this.token = opts.token;\n this.timeoutMs = opts.timeoutMs;\n this.retryAttempts = opts.retryAttempts;\n this.userAgent = opts.userAgent;\n this.logger = opts.logger;\n }\n\n get<T>(path: string, query?: Query): Promise<T> {\n return this.request<T>(\"GET\", path, { query });\n }\n\n post<T>(\n path: string,\n body: unknown,\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n return this.request<T>(\"POST\", path, { body, extraHeaders });\n }\n\n patch<T>(path: string, body: unknown): Promise<T> {\n return this.request<T>(\"PATCH\", path, { body });\n }\n\n delete<T = null>(path: string): Promise<T> {\n return this.request<T>(\"DELETE\", path, {});\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts: RequestOptions,\n ): Promise<T> {\n const url = this.buildUrl(path, opts.query);\n const requestId = randomUUID();\n const log = this.logger.child({ request_id: requestId, method, path });\n\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.token}`,\n \"X-Request-ID\": requestId,\n \"User-Agent\": this.userAgent,\n };\n\n let bodyStr: string | undefined;\n if (opts.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n bodyStr = JSON.stringify(opts.body);\n }\n\n if (opts.extraHeaders) {\n for (const [k, v] of Object.entries(opts.extraHeaders)) {\n headers[k] = v;\n }\n }\n\n const maxAttempts = this.retryAttempts + 1;\n let retriedOn429 = false;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n const started = Date.now();\n\n try {\n const res = await fetch(url, {\n method,\n headers,\n body: bodyStr,\n signal: controller.signal,\n });\n const duration_ms = Date.now() - started;\n const remaining = res.headers.get(\"x-ratelimit-remaining\");\n\n if (res.ok) {\n const isEmpty =\n res.status === 204 || res.headers.get(\"content-length\") === \"0\";\n const data = (isEmpty ? null : await res.json()) as T;\n log.info(\n { http_status: res.status, duration_ms, remaining, attempt },\n \"http_ok\",\n );\n if (remaining !== null) {\n const n = Number(remaining);\n if (Number.isFinite(n) && n < 10) {\n log.warn({ remaining: n }, \"rate_limit_low\");\n }\n }\n return data;\n }\n\n const body = await safeJson(res);\n const apiErr = extractApiError(body);\n const retryAfter = parseRetryAfter(res.headers.get(\"retry-after\"));\n\n if (res.status === 429 && !retriedOn429 && attempt < maxAttempts) {\n retriedOn429 = true;\n const effective = Math.min(\n retryAfter ?? 1,\n MAX_RETRY_AFTER_SECONDS,\n );\n log.warn(\n { retry_after: retryAfter, effective_wait: effective },\n \"rate_limited_retry\",\n );\n await sleep(effective * 1000);\n continue;\n }\n\n const retryable = res.status >= 500;\n if (retryable && attempt < maxAttempts) {\n const backoff = 100 * Math.pow(4, attempt - 1);\n log.warn(\n { http_status: res.status, attempt, backoff_ms: backoff },\n \"http_retry\",\n );\n await sleep(backoff);\n continue;\n }\n\n const code: LkpErrorCode = mapHttpStatus(res.status);\n const payload: ConstructorParameters<typeof LkpError>[0] = {\n code,\n message:\n apiErr?.message ??\n `HTTP ${res.status} ${res.statusText} on ${method} ${path}`,\n request_id: requestId,\n http_status: res.status,\n };\n if (apiErr?.code) payload.api_code = apiErr.code;\n if (apiErr?.details !== undefined) payload.details = apiErr.details;\n if (retryAfter !== null) payload.retry_after_seconds = retryAfter;\n\n log.error(\n {\n http_status: res.status,\n duration_ms,\n api_code: apiErr?.code,\n },\n \"http_error\",\n );\n throw new LkpError(payload);\n } catch (e) {\n clearTimeout(timer);\n if (e instanceof LkpError) throw e;\n\n const isAbort = e instanceof Error && e.name === \"AbortError\";\n const duration_ms = Date.now() - started;\n\n if (attempt < maxAttempts) {\n const backoff = 100 * Math.pow(4, attempt - 1);\n log.warn(\n {\n attempt,\n backoff_ms: backoff,\n reason: isAbort ? \"timeout\" : \"network\",\n duration_ms,\n },\n \"http_retry\",\n );\n await sleep(backoff);\n continue;\n }\n\n log.error({ duration_ms, reason: isAbort ? \"timeout\" : \"network\" }, \"http_fail\");\n throw new LkpError({\n code: isAbort ? \"timeout\" : \"network_error\",\n message: isAbort\n ? `Request to ${path} timed out after ${this.timeoutMs}ms`\n : `Could not reach LKPGestão API: ${(e as Error).message}`,\n request_id: requestId,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n throw new LkpError({\n code: \"unexpected\",\n message: \"Request loop exited without result (should be unreachable).\",\n request_id: requestId,\n });\n }\n\n private buildUrl(path: string, query?: Query): string {\n const clean = path.startsWith(\"/\") ? path : `/${path}`;\n const url = new URL(`${this.baseUrl}${clean}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined && v !== null) {\n url.searchParams.set(k, String(v));\n }\n }\n }\n return url.toString();\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport function parseRetryAfter(raw: string | null): number | null {\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : null;\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n try {\n return await res.json();\n } catch {\n return undefined;\n }\n}\n\nfunction extractApiError(body: unknown): ApiErrorShape | undefined {\n if (!body || typeof body !== \"object\") return undefined;\n const b = body as { error?: unknown; message?: unknown };\n if (b.error && typeof b.error === \"object\") {\n return b.error as ApiErrorShape;\n }\n if (typeof b.message === \"string\") {\n return { message: b.message };\n }\n return undefined;\n}\n","export type LkpErrorCode =\n | \"bad_request\"\n | \"auth_failed\"\n | \"permission_denied\"\n | \"not_found\"\n | \"validation_error\"\n | \"rate_limited\"\n | \"server_error\"\n | \"network_error\"\n | \"timeout\"\n | \"unexpected\";\n\nexport interface LkpErrorPayload {\n code: LkpErrorCode;\n message: string;\n request_id?: string;\n http_status?: number;\n api_code?: string;\n details?: unknown;\n retry_after_seconds?: number;\n}\n\nexport class LkpError extends Error {\n readonly code: LkpErrorCode;\n readonly request_id: string | undefined;\n readonly http_status: number | undefined;\n readonly api_code: string | undefined;\n readonly details: unknown;\n readonly retry_after_seconds: number | undefined;\n\n constructor(payload: LkpErrorPayload) {\n super(payload.message);\n this.name = \"LkpError\";\n this.code = payload.code;\n this.request_id = payload.request_id;\n this.http_status = payload.http_status;\n this.api_code = payload.api_code;\n this.details = payload.details;\n this.retry_after_seconds = payload.retry_after_seconds;\n }\n\n toJSON(): LkpErrorPayload {\n const out: LkpErrorPayload = { code: this.code, message: this.message };\n if (this.request_id !== undefined) out.request_id = this.request_id;\n if (this.http_status !== undefined) out.http_status = this.http_status;\n if (this.api_code !== undefined) out.api_code = this.api_code;\n if (this.details !== undefined) out.details = this.details;\n if (this.retry_after_seconds !== undefined) {\n out.retry_after_seconds = this.retry_after_seconds;\n }\n return out;\n }\n}\n\nexport function mapHttpStatus(status: number): LkpErrorCode {\n if (status === 400) return \"bad_request\";\n if (status === 401) return \"auth_failed\";\n if (status === 403) return \"permission_denied\";\n if (status === 404) return \"not_found\";\n if (status === 422) return \"validation_error\";\n if (status === 429) return \"rate_limited\";\n if (status >= 500) return \"server_error\";\n return \"unexpected\";\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { LkpError } from \"../errors.js\";\n\nconst PingUser = z\n .object({\n id: z.number().optional(),\n name: z.string().optional(),\n email: z.string().optional(),\n })\n .passthrough();\n\nconst PingToken = z\n .object({\n name: z.string().optional(),\n scopes: z.array(z.string()).optional(),\n last_used_at: z.string().optional(),\n })\n .passthrough();\n\nconst PingResponse = z\n .object({\n user: PingUser.optional(),\n token: PingToken.optional(),\n server_time: z.string().optional(),\n })\n .passthrough();\n\nexport function registerPing(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_ping\",\n {\n title: \"Ping LKPGestão\",\n description:\n \"Health check. Confirms the MCP server can reach LKPGestão and the configured API token is valid. Returns the bound user (name/email), the token's label, and the granted scopes. Use this first when unsure about connectivity or permissions.\",\n inputSchema: {},\n },\n async () => {\n const started = Date.now();\n try {\n const raw = await client.get<unknown>(\"/api/v1/ping\");\n const parsed = PingResponse.safeParse(raw);\n const payload = parsed.success ? parsed.data : raw;\n logger.info(\n { tool: \"lkp_ping\", duration_ms: Date.now() - started, ok: true },\n \"tool_ok\",\n );\n return {\n content: [\n { type: \"text\", text: JSON.stringify(payload, null, 2) },\n ],\n };\n } catch (e) {\n const err =\n e instanceof LkpError\n ? e.toJSON()\n : { code: \"unexpected\" as const, message: (e as Error).message };\n logger.error(\n { tool: \"lkp_ping\", duration_ms: Date.now() - started, err },\n \"tool_error\",\n );\n return {\n isError: true,\n content: [{ type: \"text\", text: JSON.stringify(err, null, 2) }],\n };\n }\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerResources(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_resources_list\",\n {\n title: \"List resources (consultants)\",\n description:\n \"List consultants (resources) with filters. Returns allocation status, hourly rate, specialties, weekly capacity. Use to find candidates for allocation or to audit team composition.\",\n inputSchema: {\n status: z.string().optional(),\n contract_type: z.string().optional(),\n specialty_id: z.coerce.number().int().positive().optional(),\n allocation: z\n .enum([\"available\", \"partial\", \"full\", \"overloaded\"])\n .optional(),\n role: z.string().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_resources_list\", () =>\n client.get<unknown>(\"/api/v1/resources\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_resources_summary\",\n {\n title: \"Resources operational summary\",\n description:\n \"Operational snapshot of all consultants: counts by allocation bucket (available/partial/full/overloaded), monthly cost split (total/allocated/idle), list of consultants available now, list of consultants finishing their project in ≤30 days. Use for dashboards and the Monday brief.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_resources_summary\", () =>\n client.get<unknown>(\"/api/v1/resources/summary\"),\n ),\n );\n\n server.registerTool(\n \"lkp_resource_history\",\n {\n title: \"Resource allocation history\",\n description:\n \"Allocation history for one consultant over a date range. Returns per-project periods interleaved with idle gaps, plus metrics (utilization_percent, idle_days, billed_hours, revenue). Default range: last 12 months.\",\n inputSchema: {\n resource_id: z.coerce.number().int().positive(),\n from: z.string().optional(),\n to: z.string().optional(),\n },\n },\n async ({ resource_id, from, to }) =>\n runTool(logger, \"lkp_resource_history\", () =>\n client.get<unknown>(`/api/v1/resources/${resource_id}/history`, {\n from,\n to,\n }),\n ),\n );\n\n server.registerTool(\n \"lkp_resource_timesheets\",\n {\n title: \"Resource timesheet entries\",\n description:\n \"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 ≤ 184 days; max per_page 200.\",\n inputSchema: {\n resource_id: z.coerce.number().int().positive(),\n from: z.string(),\n to: z.string(),\n project_id: z.coerce.number().int().positive().optional(),\n task_id: z.coerce.number().int().positive().optional(),\n is_approved: z.coerce.boolean().optional(),\n is_billable: z.coerce.boolean().optional(),\n source: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(50),\n },\n },\n async ({ resource_id, ...query }) =>\n runTool(logger, \"lkp_resource_timesheets\", () =>\n client.get<unknown>(\n `/api/v1/resources/${resource_id}/timesheets`,\n query,\n ),\n ),\n );\n}\n","import type { Logger } from \"../logger.js\";\nimport { LkpError } from \"../errors.js\";\n\nexport interface ToolResult {\n [key: string]: unknown;\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n}\n\nexport async function runTool<T>(\n logger: Logger,\n name: string,\n fn: () => Promise<T>,\n): Promise<ToolResult> {\n const started = Date.now();\n try {\n const result = await fn();\n logger.info(\n { tool: name, duration_ms: Date.now() - started, ok: true },\n \"tool_ok\",\n );\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (e) {\n const err =\n e instanceof LkpError\n ? e.toJSON()\n : { code: \"unexpected\" as const, message: (e as Error).message };\n logger.error(\n { tool: name, duration_ms: Date.now() - started, err },\n \"tool_error\",\n );\n return {\n isError: true,\n content: [{ type: \"text\", text: JSON.stringify(err, null, 2) }],\n };\n }\n}\n\nexport async function runToolText(\n logger: Logger,\n name: string,\n fn: () => Promise<string>,\n): Promise<ToolResult> {\n const started = Date.now();\n try {\n const text = await fn();\n logger.info(\n { tool: name, duration_ms: Date.now() - started, ok: true },\n \"tool_ok\",\n );\n return { content: [{ type: \"text\", text }] };\n } catch (e) {\n const err =\n e instanceof LkpError\n ? e.toJSON()\n : { code: \"unexpected\" as const, message: (e as Error).message };\n logger.error(\n { tool: name, duration_ms: Date.now() - started, err },\n \"tool_error\",\n );\n return {\n isError: true,\n content: [{ type: \"text\", text: JSON.stringify(err, null, 2) }],\n };\n }\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerProjects(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_projects_list\",\n {\n title: \"List projects\",\n description:\n \"List projects with filters. Returns status, client, manager, budget, progress (task completion %), source opportunity, next pending billing milestone. Use to explore the portfolio.\",\n inputSchema: {\n status_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n manager_id: z.coerce.number().int().positive().optional(),\n is_active: z.coerce.boolean().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_projects_list\", () =>\n client.get<unknown>(\"/api/v1/projects\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_projects_summary\",\n {\n title: \"Projects portfolio summary\",\n description:\n \"Portfolio dashboard: project counts by status, financial aggregate from billing milestones, upcoming milestones in the next 30 days.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_projects_summary\", () =>\n client.get<unknown>(\"/api/v1/projects/summary\"),\n ),\n );\n\n server.registerTool(\n \"lkp_project_detail\",\n {\n title: \"Project detail\",\n description:\n \"Full project detail: team, billing milestones (all, not just next), stats, source opportunity link. Use before making decisions about a specific project.\",\n inputSchema: {\n project_id: z.coerce.number().int().positive(),\n },\n },\n async ({ project_id }) =>\n runTool(logger, \"lkp_project_detail\", () =>\n client.get<unknown>(`/api/v1/projects/${project_id}`),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nconst OpportunityStatus = z.enum([\n \"NEW\",\n \"QUALIFYING\",\n \"PROPOSAL\",\n \"SENT\",\n \"NEGOTIATION\",\n \"WON\",\n \"LOST\",\n \"CANCELLED\",\n]);\n\nconst ActivityType = z.enum([\n \"CALL\",\n \"EMAIL\",\n \"MEETING\",\n \"NOTE\",\n \"FOLLOW_UP\",\n \"PRESENTATION\",\n \"NEGOTIATION\",\n \"DOCUMENT_SENT\",\n \"DOCUMENT_RECEIVED\",\n \"OTHER\",\n]);\n\nconst ContactRole = z.enum([\n \"DECISION_MAKER\",\n \"INFLUENCER\",\n \"TECHNICAL\",\n \"FINANCIAL\",\n \"USER\",\n \"SPONSOR\",\n \"GATEKEEPER\",\n \"CHAMPION\",\n \"OTHER\",\n]);\n\nconst EngagementLevel = z.enum([\"LOW\", \"MEDIUM\", \"HIGH\"]);\nconst Sentiment = z.enum([\"NEGATIVE\", \"NEUTRAL\", \"POSITIVE\", \"CHAMPION\"]);\n\nexport function registerOpportunities(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n // ── Opportunity reads ──────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunities_list\",\n {\n title: \"List sales opportunities\",\n description:\n \"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 | LOST | CANCELLED.\",\n inputSchema: {\n status: OpportunityStatus.optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n closing_before: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce.number().int().positive().max(200).default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_opportunities_list\", () =>\n client.get<unknown>(\"/api/v1/opportunities\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunities_summary\",\n {\n title: \"Opportunities pipeline summary\",\n description:\n \"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 ≥7 days).\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_opportunities_summary\", () =>\n client.get<unknown>(\"/api/v1/opportunities/summary\"),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_detail\",\n {\n title: \"Opportunity detail\",\n description:\n \"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 or (without include_inactive) when the opportunity itself is archived.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n include_inactive: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, include_inactive }) =>\n runTool(logger, \"lkp_opportunity_detail\", () =>\n client.get<unknown>(`/api/v1/opportunities/${opportunity_id}`, {\n include_inactive,\n }),\n ),\n );\n\n // ── Opportunity writes ─────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunity_create\",\n {\n title: \"Create opportunity (write)\",\n description:\n \"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 — use lkp_opportunity_update afterwards. account_manager_id defaults to the token user. Summarize the draft and wait for user approval before calling.\",\n inputSchema: {\n client_id: z.coerce.number().int().positive(),\n name: z.string().min(1),\n project_b1_code_id: z.coerce.number().int().positive(),\n description: z.string().optional(),\n status: OpportunityStatus.optional(),\n probability: z.coerce.number().min(0).max(100).optional(),\n expected_value: z.coerce.number().nonnegative().optional(),\n expected_close_date: z.string().optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n price_list_id: z.coerce.number().int().positive().optional(),\n source: z.string().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_opportunity_create\", () =>\n client.post<unknown>(\"/api/v1/opportunities\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_update\",\n {\n title: \"Update opportunity (write)\",\n description:\n \"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 — equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored. Returns the updated opportunity. Confirm any state transition with the user before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n name: z.string().optional(),\n description: z.string().optional(),\n status: OpportunityStatus.optional(),\n probability: z.coerce.number().min(0).max(100).optional(),\n expected_value: z.coerce.number().nonnegative().optional(),\n expected_close_date: z.string().optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n is_active: z.coerce.boolean().optional(),\n lost_reason: z.string().optional(),\n lost_reason_detail: z.string().optional(),\n lost_notes: z.string().optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_update\", () =>\n client.patch<unknown>(`/api/v1/opportunities/${opportunity_id}`, body),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_archive\",\n {\n title: \"Archive opportunity (write)\",\n description:\n \"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 — destructive intent.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n },\n },\n async ({ opportunity_id }) =>\n runTool(logger, \"lkp_opportunity_archive\", async () => {\n await client.delete(`/api/v1/opportunities/${opportunity_id}`);\n return { ok: true, archived: true, opportunity_id };\n }),\n );\n\n // ── Activity writes ────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunity_activity_add\",\n {\n title: \"Add activity to opportunity (write)\",\n description:\n \"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.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n type: ActivityType,\n subject: z.string().min(1),\n description: z.string().optional(),\n duration_minutes: z.coerce.number().int().nonnegative().optional(),\n follow_up_date: z.string().optional(),\n outcome: z.string().optional(),\n is_internal: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_activity_add\", () =>\n client.post<unknown>(\n `/api/v1/opportunities/${opportunity_id}/activities`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_activity_update\",\n {\n title: \"Update opportunity activity (write)\",\n description:\n \"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.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n activity_id: z.coerce.number().int().positive(),\n subject: z.string().optional(),\n description: z.string().optional(),\n activity_date: z.string().optional(),\n duration_minutes: z.coerce.number().int().nonnegative().optional(),\n follow_up_date: z.string().optional(),\n follow_up_notes: z.string().optional(),\n is_follow_up_done: z.coerce.boolean().optional(),\n outcome: z.string().optional(),\n is_internal: z.coerce.boolean().optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, activity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_activity_update\", () =>\n client.patch<unknown>(\n `/api/v1/opportunities/${opportunity_id}/activities/${activity_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_activity_delete\",\n {\n title: \"Delete opportunity activity (write)\",\n description:\n \"Soft-archive a manual activity on an opportunity. System-generated activities cannot be deleted. Returns 404 when the activity is already archived. Always ask user approval before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n activity_id: z.coerce.number().int().positive(),\n },\n },\n async ({ opportunity_id, activity_id }) =>\n runTool(logger, \"lkp_opportunity_activity_delete\", async () => {\n await client.delete(\n `/api/v1/opportunities/${opportunity_id}/activities/${activity_id}`,\n );\n return { ok: true, archived: true, opportunity_id, activity_id };\n }),\n );\n\n // ── Contact links ──────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunity_contacts_list\",\n {\n title: \"List opportunity contacts\",\n description:\n \"List contacts linked to an opportunity (with the underlying client_contact_persons record). Filters inactive links by default; pass include_inactive=true to include them.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n include_inactive: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, include_inactive }) =>\n runTool(logger, \"lkp_opportunity_contacts_list\", () =>\n client.get<unknown>(\n `/api/v1/opportunities/${opportunity_id}/contacts`,\n { include_inactive },\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_contact_attach\",\n {\n title: \"Attach contact to opportunity (write)\",\n description:\n \"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.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n contact_person_id: z.coerce.number().int().positive(),\n role: ContactRole.optional(),\n role_description: z.string().optional(),\n is_primary: z.coerce.boolean().optional(),\n notes: z.string().optional(),\n engagement_level: EngagementLevel.optional(),\n sentiment: Sentiment.optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_contact_attach\", () =>\n client.post<unknown>(\n `/api/v1/opportunities/${opportunity_id}/contacts`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_contact_update\",\n {\n title: \"Update opportunity contact link (write)\",\n description:\n \"Update attributes of a contact link on an opportunity. contact_person_id and opportunity_id are immutable on an existing link — detach + attach instead. Setting is_primary: true clears any prior primary on the same opportunity. Setting is_active: false archives the link (equivalent to detach).\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n link_id: z.coerce.number().int().positive(),\n role: ContactRole.optional(),\n role_description: z.string().optional(),\n is_primary: z.coerce.boolean().optional(),\n notes: z.string().optional(),\n engagement_level: EngagementLevel.optional(),\n sentiment: Sentiment.optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, link_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_contact_update\", () =>\n client.patch<unknown>(\n `/api/v1/opportunities/${opportunity_id}/contacts/${link_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_contact_detach\",\n {\n title: \"Detach contact from opportunity (write)\",\n description:\n \"Soft-archive a contact link on an opportunity (is_active=0). The underlying client_contact_persons record is never touched — it belongs to the client, not the opportunity. Returns 404 when the link doesn't belong to the opportunity or is already archived. Always ask user approval before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n link_id: z.coerce.number().int().positive(),\n },\n },\n async ({ opportunity_id, link_id }) =>\n runTool(logger, \"lkp_opportunity_contact_detach\", async () => {\n await client.delete(\n `/api/v1/opportunities/${opportunity_id}/contacts/${link_id}`,\n );\n return { ok: true, detached: true, opportunity_id, link_id };\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nconst QuoteStatus = z.enum([\n \"DRAFT\",\n \"SENT\",\n \"ACCEPTED\",\n \"REJECTED\",\n \"EXPIRED\",\n \"SUPERSEDED\",\n]);\n\nconst Currency = z.enum([\"BRL\", \"USD\", \"EUR\"]);\n\nconst SkillLevel = z.enum([\"Júnior\", \"Pleno\", \"Sênior\", \"Especialista\"]);\n\nconst BillingModel = z.enum([\n \"milestone\",\n \"installment\",\n \"measurement\",\n \"subscription\",\n]);\n\nconst DiscountType = z.enum([\"PERCENT\", \"VALUE\"]);\n\nconst BillingCadence = z.enum([\"monthly\", \"quarterly\", \"annual\"]);\n\nconst QuoteItemInput = z.object({\n description: z.string().min(1),\n quantity: z.coerce.number().positive(),\n unit_price: z.coerce.number().nonnegative(),\n skill_level: SkillLevel.optional(),\n discount_type: DiscountType.optional(),\n discount_value: z.coerce.number().nonnegative().optional(),\n notes: z.string().optional(),\n});\n\nconst PaymentMilestoneInput = z.object({\n description: z.string().min(1),\n due_date: z.string().optional(),\n percentage: z.coerce.number().min(0).max(100).optional(),\n amount: z.coerce.number().nonnegative().optional(),\n sequence: z.coerce.number().int().nonnegative().optional(),\n});\n\nexport function registerQuotes(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n // ── Reads ──────────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quotes_list\",\n {\n title: \"List quotes\",\n description:\n \"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 values: DRAFT | SENT | ACCEPTED | REJECTED | EXPIRED | SUPERSEDED. Use for quote portfolio review; scope to a specific opportunity with lkp_opportunity_quotes_list.\",\n inputSchema: {\n status: QuoteStatus.optional(),\n opportunity_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n billing_model: BillingModel.optional(),\n valid_until_before: z.string().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce.number().int().positive().max(200).default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_quotes_list\", () =>\n client.get<unknown>(\"/api/v1/quotes\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_detail\",\n {\n title: \"Quote detail\",\n description:\n \"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. Returns 404 when id is unknown.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_detail\", () =>\n client.get<unknown>(`/api/v1/quotes/${quote_id}`),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_quotes_list\",\n {\n title: \"List quotes on an opportunity\",\n description:\n \"List every quote (all versions, all statuses) attached to one opportunity, ordered by version desc. Use this before new_version or duplicate so you can pick the right source quote. Children default to active-only.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n include_inactive: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, include_inactive }) =>\n runTool(logger, \"lkp_opportunity_quotes_list\", () =>\n client.get<unknown>(\n `/api/v1/opportunities/${opportunity_id}/quotes`,\n { include_inactive },\n ),\n ),\n );\n\n // ── Quote CRUD ─────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_create\",\n {\n title: \"Create quote (write)\",\n description:\n \"Create a new DRAFT quote under an opportunity. items[] and payment_milestones[] can be passed inline on create (recommended) or added later via lkp_quote_item_add / lkp_quote_milestone_add. billing_model=subscription requires monthly_amount + contract_months and items[] must be omitted; any other billing_model accepts items[]. Currency defaults to BRL. Version starts at 1; use lkp_quote_new_version to branch later. Summarize the draft (opportunity, items, totals, milestones) and wait for explicit user approval before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n currency: Currency.optional(),\n billing_model: BillingModel,\n billing_cadence: BillingCadence.optional(),\n valid_until: z.string().optional(),\n notes: z.string().optional(),\n discount_type: DiscountType.optional(),\n discount_value: z.coerce.number().nonnegative().optional(),\n monthly_amount: z.coerce.number().nonnegative().optional(),\n contract_months: z.coerce.number().int().positive().optional(),\n items: z.array(QuoteItemInput).optional(),\n payment_milestones: z.array(PaymentMilestoneInput).optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_quote_create\", () =>\n client.post<unknown>(\n `/api/v1/opportunities/${opportunity_id}/quotes`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_update\",\n {\n title: \"Update quote (write)\",\n description:\n \"Update whitelisted fields on a quote. Only DRAFT quotes can be freely edited; SENT quotes are locked — clone via lkp_quote_new_version to change terms. Mutations to items[] or payment_milestones[] must go through the dedicated tools. Setting is_active=false archives the quote (soft-delete, same as lkp_quote_archive). Summarize the diff (field → old → new) and wait for user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n currency: Currency.optional(),\n billing_model: BillingModel.optional(),\n billing_cadence: BillingCadence.optional(),\n valid_until: z.string().optional(),\n notes: z.string().optional(),\n discount_type: DiscountType.optional(),\n discount_value: z.coerce.number().nonnegative().optional(),\n monthly_amount: z.coerce.number().nonnegative().optional(),\n contract_months: z.coerce.number().int().positive().optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ quote_id, ...body }) =>\n runTool(logger, \"lkp_quote_update\", () =>\n client.patch<unknown>(`/api/v1/quotes/${quote_id}`, body),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_archive\",\n {\n title: \"Archive quote (write)\",\n description:\n \"Soft-archive a quote (is_active=0). Only DRAFT quotes should be archived this way — if a SENT/ACCEPTED quote needs to be invalidated, use lkp_quote_new_version (which marks the prior version SUPERSEDED) instead. Always ask user approval before calling — destructive intent.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_archive\", async () => {\n await client.delete(`/api/v1/quotes/${quote_id}`);\n return { ok: true, archived: true, quote_id };\n }),\n );\n\n // ── Workflow ──────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_send\",\n {\n title: \"Send quote to client (write)\",\n description:\n \"Transition a DRAFT quote to SENT. Moves the parent opportunity to SENT. Locks the quote for direct edits (use lkp_quote_new_version to revise after send). Not reversible without creating a new version. Confirm the customer-facing terms (totals, valid_until, milestones) with the user before invoking.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_send\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/send`, {}),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_accept\",\n {\n title: \"Accept quote (write)\",\n description:\n \"Transition a SENT quote to ACCEPTED. Moves the parent opportunity to WON and cascades all sibling quotes on the same opportunity to REJECTED. This is a commercially binding step — ALWAYS ask for explicit, unambiguous approval from the user (e.g. 'sim, aceitar a QT-XXXX-YYYY'). Never accept a quote on inference or implicit cues. After success, surface the WON transition and the rejected siblings so the user can verify.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_accept\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/accept`, {}),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_reject\",\n {\n title: \"Reject quote (write)\",\n description:\n \"Transition a SENT quote to REJECTED. Always ask the user for the rejection motive before calling — reason is mandatory (API refuses empty). Reason is user-visible in the opportunity activity log and should summarize the client's stated objection (price, timing, scope, competitor, etc.).\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n reason: z.string().min(1).max(200),\n },\n },\n async ({ quote_id, reason }) =>\n runTool(logger, \"lkp_quote_reject\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/reject`, { reason }),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_new_version\",\n {\n title: \"Create new version of quote (write)\",\n description:\n \"Clone a quote (any status) into a new DRAFT with version = prior + 1. The prior version is marked SUPERSEDED. Use this to revise terms after a SENT quote (direct edits are blocked). items[] and payment_milestones[] are copied; edit them on the new draft via the dedicated tools. Confirm the intent with the user — this creates a new artifact and may need to be re-sent.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_new_version\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/new-version`, {}),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_duplicate\",\n {\n title: \"Duplicate quote to another opportunity (write)\",\n description:\n \"Copy a quote (including items and payment_milestones) to a DIFFERENT opportunity as a new DRAFT (version 1). Use for reusing a negotiated proposal with a similar client. Confirm the target opportunity with the user before calling — summarize opportunity name and client so the user can verify.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n target_opportunity_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id, target_opportunity_id }) =>\n runTool(logger, \"lkp_quote_duplicate\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/duplicate`, {\n target_opportunity_id,\n }),\n ),\n );\n\n // ── Items ─────────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_item_add\",\n {\n title: \"Add item to quote (write)\",\n description:\n \"Append a new line item to a DRAFT quote. Blocked on SENT/ACCEPTED/REJECTED/SUPERSEDED — create a new version first. skill_level values: Júnior | Pleno | Sênior | Especialista. discount_type values: PERCENT | VALUE. Summarize the line (description, qty × unit_price, discount) and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n description: z.string().min(1),\n quantity: z.coerce.number().positive(),\n unit_price: z.coerce.number().nonnegative(),\n skill_level: SkillLevel.optional(),\n discount_type: DiscountType.optional(),\n discount_value: z.coerce.number().nonnegative().optional(),\n notes: z.string().optional(),\n },\n },\n async ({ quote_id, ...body }) =>\n runTool(logger, \"lkp_quote_item_add\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/items`, body),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_item_update\",\n {\n title: \"Update quote item (write)\",\n description:\n \"Update whitelisted fields on a line item of a DRAFT quote. Blocked when the parent quote is not DRAFT. Summarize the diff (field → old → new) and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n item_id: z.coerce.number().int().positive(),\n description: z.string().optional(),\n quantity: z.coerce.number().positive().optional(),\n unit_price: z.coerce.number().nonnegative().optional(),\n skill_level: SkillLevel.optional(),\n discount_type: DiscountType.optional(),\n discount_value: z.coerce.number().nonnegative().optional(),\n notes: z.string().optional(),\n },\n },\n async ({ quote_id, item_id, ...body }) =>\n runTool(logger, \"lkp_quote_item_update\", () =>\n client.patch<unknown>(\n `/api/v1/quotes/${quote_id}/items/${item_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_item_delete\",\n {\n title: \"Delete quote item (write)\",\n description:\n \"Remove a line item from a DRAFT quote. Blocked when the parent quote is not DRAFT. Always ask user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n item_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id, item_id }) =>\n runTool(logger, \"lkp_quote_item_delete\", async () => {\n await client.delete(`/api/v1/quotes/${quote_id}/items/${item_id}`);\n return { ok: true, deleted: true, quote_id, item_id };\n }),\n );\n\n // ── Payment milestones ────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_milestones_replace\",\n {\n title: \"Replace all payment milestones (write)\",\n description:\n \"Replace the entire payment_milestones[] collection on a DRAFT quote in a single atomic call. Use when the schedule needs a full rewrite (e.g. switching 3 milestones to 5). Any existing milestones are deleted and the new set is inserted. Sent as POST with X-HTTP-Method-Override: PUT header. Summarize the new schedule (percentages/amounts summing correctly) and wait for user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n milestones: z.array(PaymentMilestoneInput).min(1),\n },\n },\n async ({ quote_id, milestones }) =>\n runTool(logger, \"lkp_quote_milestones_replace\", () =>\n client.post<unknown>(\n `/api/v1/quotes/${quote_id}/payment-milestones`,\n { milestones },\n { \"X-HTTP-Method-Override\": \"PUT\" },\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_milestone_add\",\n {\n title: \"Add payment milestone (write)\",\n description:\n \"Append a single payment milestone to a DRAFT quote (additive; does not touch existing milestones). Use replace when rewriting the entire schedule. Summarize (description, due_date, percentage or amount) and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n description: z.string().min(1),\n due_date: z.string().optional(),\n percentage: z.coerce.number().min(0).max(100).optional(),\n amount: z.coerce.number().nonnegative().optional(),\n sequence: z.coerce.number().int().nonnegative().optional(),\n },\n },\n async ({ quote_id, ...body }) =>\n runTool(logger, \"lkp_quote_milestone_add\", () =>\n client.post<unknown>(\n `/api/v1/quotes/${quote_id}/payment-milestones`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_milestone_update\",\n {\n title: \"Update payment milestone (write)\",\n description:\n \"Update whitelisted fields on a payment milestone of a DRAFT quote. Blocked when the parent quote is not DRAFT. Summarize the diff and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n milestone_id: z.coerce.number().int().positive(),\n description: z.string().optional(),\n due_date: z.string().optional(),\n percentage: z.coerce.number().min(0).max(100).optional(),\n amount: z.coerce.number().nonnegative().optional(),\n sequence: z.coerce.number().int().nonnegative().optional(),\n },\n },\n async ({ quote_id, milestone_id, ...body }) =>\n runTool(logger, \"lkp_quote_milestone_update\", () =>\n client.patch<unknown>(\n `/api/v1/quotes/${quote_id}/payment-milestones/${milestone_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_milestone_delete\",\n {\n title: \"Delete payment milestone (write)\",\n description:\n \"Remove one payment milestone from a DRAFT quote. Blocked when the parent quote is not DRAFT. Always ask user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n milestone_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id, milestone_id }) =>\n runTool(logger, \"lkp_quote_milestone_delete\", async () => {\n await client.delete(\n `/api/v1/quotes/${quote_id}/payment-milestones/${milestone_id}`,\n );\n return { ok: true, deleted: true, quote_id, milestone_id };\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerClients(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_clients_list\",\n {\n title: \"List clients\",\n description:\n \"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.\",\n inputSchema: {\n status: z.string().optional(),\n parent_client_id: z.coerce.number().int().positive().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_clients_list\", () =>\n client.get<unknown>(\"/api/v1/clients\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_client_detail\",\n {\n title: \"Client detail\",\n description:\n \"Full client detail including all projects (active + inactive), all B1 codes, and stats.\",\n inputSchema: {\n client_id: z.coerce.number().int().positive(),\n },\n },\n async ({ client_id }) =>\n runTool(logger, \"lkp_client_detail\", () =>\n client.get<unknown>(`/api/v1/clients/${client_id}`),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerHelpdesk(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_helpdesk_tickets_list\",\n {\n title: \"List helpdesk tickets\",\n description:\n \"List helpdesk tickets with filters. Returns SLA status (response/resolution deadlines, breach flags), priority, category, tags. Use for triage and to find tickets exceeding SLA.\",\n inputSchema: {\n status_id: z.coerce.number().int().positive().optional(),\n priority: z.string().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n assigned_to: z.coerce.number().int().positive().optional(),\n category_id: z.coerce.number().int().positive().optional(),\n sla_breached: z.coerce.boolean().optional(),\n is_open: z.coerce.boolean().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_helpdesk_tickets_list\", () =>\n client.get<unknown>(\"/api/v1/helpdesk/tickets\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_helpdesk_summary\",\n {\n title: \"Helpdesk summary\",\n description:\n \"Helpdesk dashboard: counts by status and priority, top 10 clients by open tickets, SLA breaches, resolved today.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_helpdesk_summary\", () =>\n client.get<unknown>(\"/api/v1/helpdesk/summary\"),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerBilling(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_billing_milestones\",\n {\n title: \"List billing milestones (legacy)\",\n description:\n \"LEGACY — 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 → delivered → in_progress → invoiced → paid. Includes joined project and client.\",\n inputSchema: {\n status: z.string().optional(),\n project_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n due_from: z.string().optional(),\n due_to: z.string().optional(),\n include_cancelled: z.coerce.boolean().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_billing_milestones\", () =>\n client.get<unknown>(\"/api/v1/billing/milestones\", args),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerAlerts(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_alerts\",\n {\n title: \"Operational alerts\",\n description:\n \"Live operational alerts computed on the fly: consultants idle, projects finishing (≤30d), opportunities stale (≥7d), billing milestones upcoming (≤15d) or overdue, helpdesk SLA breaches. Use first thing in the morning and before any strategic decision.\",\n inputSchema: {\n severity: z.string().optional(),\n type: z.string().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_alerts\", () =>\n client.get<unknown>(\"/api/v1/alerts\", args),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerReports(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_ceo_weekly\",\n {\n title: \"CEO weekly report\",\n description:\n \"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.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_ceo_weekly\", () =>\n client.get<unknown>(\"/api/v1/reports/ceo-weekly\"),\n ),\n );\n\n server.registerTool(\n \"lkp_managers_in_trouble\",\n {\n title: \"Managers with overdue items\",\n description:\n \"List managers with overdue items in their projects. Returns two intentionally separate layers: (1) tasks_overdue (operational — 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á devendo?' or 'quais gerentes precisam de atenção?'. The two layers have different natures — do not sum them; present in separate sections.\",\n inputSchema: {\n include_tasks: z.coerce.boolean().optional(),\n include_financial: z.coerce.boolean().optional(),\n min_days_overdue: z.coerce.number().int().min(0).optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_managers_in_trouble\", () =>\n client.get<unknown>(\"/api/v1/reports/managers-in-trouble\", args),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerFinancial(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_financial_pending\",\n {\n title: \"List pending financial entities\",\n description:\n \"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 — the legacy tool stays for backward compatibility.\",\n inputSchema: {\n entity_type: z\n .enum([\"milestone\", \"measurement\", \"subscription_invoice\"])\n .optional(),\n project_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n status: z.string().optional(),\n due_from: z.string().optional(),\n due_to: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(50),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_financial_pending\", () =>\n client.get<unknown>(\"/api/v1/financial-reports/pending\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_aging_report\",\n {\n title: \"Aging report (receivables)\",\n description:\n \"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.\",\n inputSchema: {\n group_bucket: z.coerce.boolean().optional(),\n top_clients: z.coerce.number().int().positive().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_aging_report\", () =>\n client.get<unknown>(\"/api/v1/financial-reports/aging\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_financial_overview\",\n {\n title: \"Executive financial overview\",\n description:\n \"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 — top 20 active classified projects with no billing in >60d. Single-call financial snapshot.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_financial_overview\", () =>\n client.get<unknown>(\"/api/v1/financial-reports/overview\"),\n ),\n );\n\n server.registerTool(\n \"lkp_margin_analysis\",\n {\n title: \"Margin analysis (project/client/specialty)\",\n description:\n \"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 — milestones and subscription_invoices are out of scope; for their gross numbers use lkp_financial_overview.\",\n inputSchema: {\n group_by: z\n .enum([\"project\", \"client\", \"specialty\"])\n .optional(),\n from: z.string().optional(),\n to: z.string().optional(),\n limit: z.coerce.number().int().positive().max(200).optional(),\n status: z.string().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_margin_analysis\", () =>\n client.get<unknown>(\n \"/api/v1/financial-reports/margin-analysis\",\n args,\n ),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { runTool } from \"../common.js\";\n\ninterface Consultant {\n id: number;\n name: string;\n status?: string;\n specialties?: Array<string | { name?: string }>;\n available_since?: string | null;\n expected_release_date?: string | null;\n [k: string]: unknown;\n}\n\ninterface Opportunity {\n id: number;\n name: string;\n status: string;\n description?: string;\n expected_value?: number;\n weighted_value?: number;\n expected_close_date?: string;\n [k: string]: unknown;\n}\n\ninterface ResourceSummaryBody {\n available_now?: Consultant[];\n finishing_in_30_days?: Consultant[];\n partial_allocations?: Consultant[];\n}\n\nconst OPEN_STAGES = [\"QUALIFYING\", \"PROPOSAL\", \"SENT\", \"NEGOTIATION\"] as const;\n\nfunction toSpecNames(specialties: Consultant[\"specialties\"]): string[] {\n return (specialties ?? [])\n .map((s) => (typeof s === \"string\" ? s : s?.name ?? \"\"))\n .filter((s): s is string => s.length > 0);\n}\n\nexport function registerSkillMatch(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_skill_match\",\n {\n title: \"Match idle consultants to open opportunities\",\n description:\n \"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.\",\n inputSchema: {\n horizon_days: z.coerce.number().int().positive().default(30),\n min_match_percent: z.coerce.number().int().min(0).max(100).default(50),\n include_partial: z.coerce.boolean().default(false),\n },\n },\n async ({ horizon_days, min_match_percent, include_partial }) =>\n runTool(logger, \"lkp_skill_match\", async () => {\n const [resSummaryResp, ...oppResponses] = await Promise.all([\n client.get<{ data: ResourceSummaryBody }>(\n \"/api/v1/resources/summary\",\n ),\n ...OPEN_STAGES.map((status) =>\n client.get<{ data: Opportunity[] }>(\"/api/v1/opportunities\", {\n status,\n per_page: 100,\n }),\n ),\n ]);\n\n const now = Date.now();\n const candidates: Array<Consultant & { urgency: string }> = [];\n for (const c of resSummaryResp.data.available_now ?? []) {\n candidates.push({ ...c, urgency: \"idle\" });\n }\n for (const c of resSummaryResp.data.finishing_in_30_days ?? []) {\n if (c.expected_release_date) {\n const days = Math.ceil(\n (new Date(c.expected_release_date).getTime() - now) / 86400000,\n );\n if (days > horizon_days) continue;\n }\n candidates.push({ ...c, urgency: \"finishing\" });\n }\n if (include_partial) {\n for (const c of resSummaryResp.data.partial_allocations ?? []) {\n candidates.push({ ...c, urgency: \"partial\" });\n }\n }\n\n const opportunities: Opportunity[] = oppResponses.flatMap(\n (r) => r.data ?? [],\n );\n\n const matches: Array<Record<string, unknown>> = [];\n for (const c of candidates) {\n const specs = toSpecNames(c.specialties);\n if (specs.length === 0) continue;\n for (const o of opportunities) {\n const hay = `${o.name ?? \"\"} ${o.description ?? \"\"}`.toLowerCase();\n const matched = specs.filter((s) =>\n hay.includes(s.toLowerCase()),\n );\n if (matched.length === 0) continue;\n const score = Math.round((matched.length / specs.length) * 100);\n if (score < min_match_percent) continue;\n matches.push({\n consultant: {\n id: c.id,\n name: c.name,\n status: c.status ?? null,\n urgency: c.urgency,\n available_since: c.available_since ?? null,\n expected_release_date: c.expected_release_date ?? null,\n specialties: specs,\n },\n opportunity: {\n id: o.id,\n name: o.name,\n status: o.status,\n expected_value: o.expected_value ?? null,\n weighted_value: o.weighted_value ?? null,\n expected_close_date: o.expected_close_date ?? null,\n },\n match_score: score,\n matched_skills: matched,\n opportunity_skill_inference_source: \"description\",\n });\n }\n }\n\n matches.sort((a, b) => {\n const aw =\n (a.opportunity as { weighted_value: number | null })\n .weighted_value ?? 0;\n const bw =\n (b.opportunity as { weighted_value: number | null })\n .weighted_value ?? 0;\n return (\n (b.match_score as number) / 100 * bw -\n (a.match_score as number) / 100 * aw\n );\n });\n\n return {\n matches,\n meta: {\n horizon_days,\n min_match_percent,\n include_partial,\n candidates_considered: candidates.length,\n opportunities_considered: opportunities.length,\n },\n };\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { runToolText } from \"../common.js\";\n\ninterface Alert {\n type?: string;\n severity?: string;\n title?: string;\n message?: string;\n [k: string]: unknown;\n}\n\ninterface ResSummary {\n totals?: {\n total_resources?: number;\n available?: number;\n partially_allocated?: number;\n fully_allocated?: number;\n overloaded?: number;\n idle_percent?: number;\n [k: string]: unknown;\n };\n [k: string]: unknown;\n}\n\ninterface OppSummary {\n totals?: {\n open_count?: number;\n total_pipeline?: number;\n weighted_pipeline?: number;\n [k: string]: unknown;\n };\n stale_opportunities?: unknown[];\n [k: string]: unknown;\n}\n\ninterface CeoWeekly {\n week?: string;\n period?: { label?: string; from?: string; to?: string };\n operational_health?: {\n score?: number;\n classification?: string;\n factors?: Array<{\n name?: string;\n value?: number;\n target?: number;\n factor_score?: number;\n }>;\n };\n [k: string]: unknown;\n}\n\nfunction fmtBRL(v: unknown): string {\n const n = typeof v === \"number\" ? v : Number(v);\n if (!Number.isFinite(n)) return \"—\";\n return n.toLocaleString(\"pt-BR\", { style: \"currency\", currency: \"BRL\" });\n}\n\nfunction buildMarkdown(\n ceo: CeoWeekly | undefined,\n alerts: Alert[] | undefined,\n opp: OppSummary | undefined,\n res: ResSummary | undefined,\n): string {\n const score = ceo?.operational_health?.score ?? \"—\";\n const cls = ceo?.operational_health?.classification ?? \"—\";\n const period =\n ceo?.week ??\n ceo?.period?.label ??\n (ceo?.period?.from && ceo?.period?.to\n ? `${ceo.period.from} → ${ceo.period.to}`\n : \"semana atual\");\n\n const lines: string[] = [];\n lines.push(`# Brief Semanal — ${period}`);\n lines.push(\"\");\n lines.push(`## 🌡️ Saúde Operacional: ${score}/100 (${cls})`);\n lines.push(\"\");\n\n if (alerts && alerts.length > 0) {\n lines.push(\"## 🔴 Atenção imediata\");\n for (const a of alerts.slice(0, 10)) {\n const title = a.title ?? a.type ?? \"alerta\";\n const msg = a.message ?? \"\";\n lines.push(`- **${title}**: ${msg}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## 📊 Números da semana\");\n if (res?.totals) {\n const t = res.totals;\n lines.push(\n `- Consultores: ${t.total_resources ?? \"—\"} (disponíveis ${t.available ?? \"—\"}, parciais ${t.partially_allocated ?? \"—\"}, cheios ${t.fully_allocated ?? \"—\"}, sobrecarga ${t.overloaded ?? \"—\"})`,\n );\n lines.push(`- Ociosidade: ${t.idle_percent ?? \"—\"}%`);\n }\n if (opp?.totals) {\n const t = opp.totals;\n lines.push(\n `- Pipeline aberto: ${t.open_count ?? \"—\"} oportunidades · valor ${fmtBRL(t.total_pipeline)} · ponderado ${fmtBRL(t.weighted_pipeline)}`,\n );\n }\n if (opp?.stale_opportunities) {\n lines.push(`- Oportunidades stale (≥7d sem atividade): ${opp.stale_opportunities.length}`);\n }\n lines.push(\"\");\n\n lines.push(\"## 🎯 Ações recomendadas\");\n lines.push(\n \"- Revisar consultores ociosos e alocar em oportunidades compatíveis (use `lkp_skill_match`).\",\n );\n lines.push(\n \"- Contatar as oportunidades stale antes de quinta-feira.\",\n );\n lines.push(\n \"- Verificar milestones atrasados e acionar cobrança (`lkp_billing_milestones?status=invoiced&due_to=<hoje>`).\",\n );\n\n return lines.join(\"\\n\");\n}\n\nexport function registerWeeklyBrief(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_weekly_brief\",\n {\n title: \"Monday morning CEO briefing\",\n description:\n \"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.\",\n inputSchema: {},\n },\n async () =>\n runToolText(logger, \"lkp_weekly_brief\", async () => {\n const [ceo, alerts, opp, res] = await Promise.all([\n client.get<{ data: CeoWeekly }>(\"/api/v1/reports/ceo-weekly\"),\n client.get<{ data: Alert[] }>(\"/api/v1/alerts\", {\n severity: \"high\",\n }),\n client.get<{ data: OppSummary }>(\"/api/v1/opportunities/summary\"),\n client.get<{ data: ResSummary }>(\"/api/v1/resources/summary\"),\n ]);\n return buildMarkdown(ceo.data, alerts.data, opp.data, res.data);\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { runTool } from \"../common.js\";\n\ninterface Entry {\n id?: number;\n work_date: string;\n hours: number | string;\n is_approved?: boolean;\n is_billable?: boolean;\n task_id?: number | null;\n resource?: { id: number; name: string };\n overtime_type?: string | null;\n [k: string]: unknown;\n}\n\ninterface Finding {\n type: \"long_day\" | \"weekend_work\" | \"unapproved_aged\" | \"orphaned_entry\";\n severity: \"low\" | \"medium\" | \"high\";\n resource: { id: number; name: string };\n details: Record<string, unknown>;\n}\n\nasync function fetchAllTimesheets(\n client: LkpClient,\n resourceId: number,\n from: string,\n to: string,\n): Promise<Entry[]> {\n const all: Entry[] = [];\n for (let page = 1; page <= 5; page++) {\n const r = await client.get<{\n data: Entry[];\n meta?: { last_page?: number };\n }>(`/api/v1/resources/${resourceId}/timesheets`, {\n from,\n to,\n page,\n per_page: 200,\n });\n const batch = r.data ?? [];\n all.push(...batch);\n const last = r.meta?.last_page;\n if ((last && page >= last) || batch.length < 200) break;\n }\n return all;\n}\n\nexport async function mapLimit<T, R>(\n items: T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (true) {\n const i = cursor++;\n if (i >= items.length) return;\n results[i] = await fn(items[i]!);\n }\n },\n );\n await Promise.all(workers);\n return results;\n}\n\nexport function detectAnomalies(\n entries: Entry[],\n resourceId: number,\n resourceName: string,\n unapprovedDaysThreshold: number,\n today: Date,\n): Finding[] {\n const findings: Finding[] = [];\n\n const byDate = new Map<string, { total: number; count: number }>();\n for (const e of entries) {\n const h = typeof e.hours === \"number\" ? e.hours : Number(e.hours);\n if (!Number.isFinite(h)) continue;\n const b = byDate.get(e.work_date) ?? { total: 0, count: 0 };\n b.total += h;\n b.count += 1;\n byDate.set(e.work_date, b);\n }\n for (const [date, b] of byDate) {\n if (b.total > 10) {\n findings.push({\n type: \"long_day\",\n severity: b.total > 13 ? \"high\" : \"medium\",\n resource: { id: resourceId, name: resourceName },\n details: {\n work_date: date,\n hours: Number(b.total.toFixed(2)),\n entries_count: b.count,\n },\n });\n }\n }\n\n for (const e of entries) {\n const d = new Date(`${e.work_date}T00:00:00Z`);\n const dow = d.getUTCDay();\n if (dow === 0 || dow === 6) {\n findings.push({\n type: \"weekend_work\",\n severity: \"low\",\n resource: { id: resourceId, name: resourceName },\n details: {\n work_date: e.work_date,\n hours: typeof e.hours === \"number\" ? e.hours : Number(e.hours),\n day: dow === 0 ? \"Sunday\" : \"Saturday\",\n },\n });\n }\n }\n\n for (const e of entries) {\n if (e.is_approved === false) {\n const d = new Date(`${e.work_date}T00:00:00Z`);\n const ageDays = Math.floor(\n (today.getTime() - d.getTime()) / 86_400_000,\n );\n if (ageDays > unapprovedDaysThreshold) {\n findings.push({\n type: \"unapproved_aged\",\n severity: ageDays > unapprovedDaysThreshold * 2 ? \"high\" : \"medium\",\n resource: { id: resourceId, name: resourceName },\n details: {\n work_date: e.work_date,\n age_days: ageDays,\n entry_id: e.id ?? null,\n },\n });\n }\n }\n }\n\n for (const e of entries) {\n if (e.task_id === null || e.task_id === undefined) {\n findings.push({\n type: \"orphaned_entry\",\n severity: \"low\",\n resource: { id: resourceId, name: resourceName },\n details: { work_date: e.work_date, entry_id: e.id ?? null },\n });\n }\n }\n\n return findings;\n}\n\nexport function registerTimesheetAnomalies(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_timesheet_anomalies\",\n {\n title: \"Detect timesheet anomalies\",\n description:\n \"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.\",\n inputSchema: {\n from: z.string(),\n to: z.string(),\n resource_id: z.coerce.number().int().positive().optional(),\n unapproved_days_threshold: z.coerce\n .number()\n .int()\n .positive()\n .default(15),\n },\n },\n async ({ from, to, resource_id, unapproved_days_threshold }) =>\n runTool(logger, \"lkp_timesheet_anomalies\", async () => {\n const today = new Date();\n const findings: Finding[] = [];\n const scanned: Array<{ id: number; name: string }> = [];\n let scope: \"resource\" | \"team\";\n\n if (resource_id !== undefined) {\n scope = \"resource\";\n const entries = await fetchAllTimesheets(\n client,\n resource_id,\n from,\n to,\n );\n const name = entries[0]?.resource?.name ?? `#${resource_id}`;\n scanned.push({ id: resource_id, name });\n findings.push(\n ...detectAnomalies(\n entries,\n resource_id,\n name,\n unapproved_days_threshold,\n today,\n ),\n );\n } else {\n scope = \"team\";\n const resList = await client.get<{\n data: Array<{ id: number; name: string; status?: string }>;\n }>(\"/api/v1/resources\", { per_page: 100 });\n const active = (resList.data ?? []).filter(\n (r) => r.status !== \"inactive\",\n );\n await mapLimit(active, 5, async (r) => {\n try {\n const entries = await fetchAllTimesheets(\n client,\n r.id,\n from,\n to,\n );\n scanned.push({ id: r.id, name: r.name });\n findings.push(\n ...detectAnomalies(\n entries,\n r.id,\n r.name,\n unapproved_days_threshold,\n today,\n ),\n );\n } catch (e) {\n logger.warn(\n { resource_id: r.id, err: (e as Error).message },\n \"timesheets_fetch_failed\",\n );\n }\n });\n }\n\n const byType: Record<string, number> = {};\n for (const f of findings) {\n byType[f.type] = (byType[f.type] ?? 0) + 1;\n }\n\n return {\n period: { from, to },\n scope,\n resources_scanned: scanned.length,\n findings,\n summary: { total_findings: findings.length, by_type: byType },\n };\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { registerSkillMatch } from \"./skill-match.js\";\nimport { registerWeeklyBrief } from \"./weekly-brief.js\";\nimport { registerTimesheetAnomalies } from \"./timesheet-anomalies.js\";\n\nexport function registerComposites(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n registerSkillMatch(server, client, logger);\n registerWeeklyBrief(server, client, logger);\n registerTimesheetAnomalies(server, client, logger);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { registerPing } from \"./ping.js\";\nimport { registerResources } from \"./resources.js\";\nimport { registerProjects } from \"./projects.js\";\nimport { registerOpportunities } from \"./opportunities.js\";\nimport { registerQuotes } from \"./quotes.js\";\nimport { registerClients } from \"./clients.js\";\nimport { registerHelpdesk } from \"./helpdesk.js\";\nimport { registerBilling } from \"./billing.js\";\nimport { registerAlerts } from \"./alerts.js\";\nimport { registerReports } from \"./reports.js\";\nimport { registerFinancial } from \"./financial.js\";\nimport { registerComposites } from \"./composite/index.js\";\n\nexport function registerAllTools(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n registerPing(server, client, logger);\n registerResources(server, client, logger);\n registerProjects(server, client, logger);\n registerOpportunities(server, client, logger);\n registerQuotes(server, client, logger);\n registerClients(server, client, logger);\n registerHelpdesk(server, client, logger);\n registerBilling(server, client, logger);\n registerAlerts(server, client, logger);\n registerReports(server, client, logger);\n registerFinancial(server, client, logger);\n registerComposites(server, client, logger);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Use the lkp_weekly_brief tool to generate the baseline numbers.\nThen enrich with:\n- Top 3 risks to call out now\n- Top 3 opportunities to act on this week\n- One question the CEO should ask at the leadership meeting\n\nOutput in Portuguese, markdown, max 500 words.`;\n\nexport function registerWeeklyBriefPrompt(server: McpServer): void {\n server.registerPrompt(\n \"weekly-brief\",\n {\n title: \"Weekly Brief\",\n description: \"Produce the Monday-morning briefing for the CEO.\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Check lkp_alerts for high-severity items. Then check lkp_helpdesk_summary for SLA breaches and lkp_opportunities_summary for opportunities closing in the next 7 days.\n\nRespond with a short bulleted list in Portuguese, grouped by area:\n1. 🔴 Urgente (alerts)\n2. 🎫 Helpdesk\n3. 💼 Vendas\n\nIf nothing urgent, say so explicitly.`;\n\nexport function registerMorningStandupPrompt(server: McpServer): void {\n server.registerPrompt(\n \"morning-standup\",\n {\n title: \"Morning Standup\",\n description: \"Quick morning check — what's burning today?\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nfunction buildText(opportunityRef: string): string {\n return `The user wants to update opportunity: ${opportunityRef}.\n\n1. If the ref is a name, use lkp_opportunities_list with the search filter to find it.\n2. Use lkp_opportunities_list (or a detail call if available) to fetch the current state before acting.\n3. Ask the user:\n - What happened? (→ will become the activity subject + description via lkp_opportunity_activity_add)\n - Did the stage change? (→ lkp_opportunity_update with new status)\n - Should we schedule a follow-up? (→ follow_up_date on the activity)\n\nBefore calling any write tool, SUMMARIZE the change (field → old value → new value) and wait for explicit \"sim\" / \"confirma\" / \"ok\" from the user. Do NOT assume consent.\n\nAfter writing, confirm using the returned payload and suggest one concrete next step.`;\n}\n\nexport function registerOpportunityActionPrompt(server: McpServer): void {\n server.registerPrompt(\n \"opportunity-action\",\n {\n title: \"Opportunity Action\",\n description: \"Log an activity and/or update stage for an opportunity.\",\n argsSchema: {\n opportunity_ref: z.string().describe(\"Opportunity id or name\"),\n },\n },\n ({ opportunity_ref }) => ({\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: buildText(opportunity_ref) },\n },\n ],\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nfunction buildText(quoteRef: string): string {\n return `The user wants to act on quote: ${quoteRef}.\n\n1. Resolve the ref:\n - If it looks like a code (e.g. QT-2026-0007), use lkp_quotes_list with search to find the id.\n - If it looks like a numeric id, go straight to lkp_quote_detail.\n2. Run lkp_quote_detail to load the current state — version, status, totals, items[], payment_milestones[].\n3. Infer the intent from the user's phrasing and the current status:\n - DRAFT → offer: edit fields (lkp_quote_update), add/update/delete item (lkp_quote_item_*), add/update/delete milestone (lkp_quote_milestone_*), replace full milestone schedule (lkp_quote_milestones_replace), send (lkp_quote_send), archive (lkp_quote_archive).\n - SENT → offer: accept (lkp_quote_accept), reject (lkp_quote_reject), new version to revise (lkp_quote_new_version), duplicate to another opportunity (lkp_quote_duplicate).\n - ACCEPTED / REJECTED / EXPIRED / SUPERSEDED → read-only; offer duplicate or new version only.\n4. Before calling any write tool, SUMMARIZE the change (field/line → old → new, or the state transition with its downstream effects) and wait for explicit \"sim\" / \"confirma\" / \"ok\" from the user. Do NOT assume consent.\n\nAfter writing, confirm using the returned payload and suggest one concrete next step.\n\nHARD RULES (do not violate, even if the user seems to agree):\n- ACCEPT: never call lkp_quote_accept without explicit, unambiguous approval referencing the quote code (e.g. \"sim, aceitar QT-2026-0007\"). Accept cascades sibling quotes to REJECTED and moves the opportunity to WON — it is commercially binding.\n- REJECT: always ask the user for the rejection motive before calling lkp_quote_reject. Reason is mandatory (min 1 char, max 200).\n- ARCHIVE: only offer lkp_quote_archive when status = DRAFT. For SENT/ACCEPTED/etc. use new-version/supersede flow instead.\n- NEVER attempt DRAFT → ACCEPTED directly. The quote must be SENT first (lkp_quote_send), then accepted.`;\n}\n\nexport function registerQuoteActionPrompt(server: McpServer): void {\n server.registerPrompt(\n \"quote-action\",\n {\n title: \"Quote Action\",\n description:\n \"Drive a quote through its lifecycle — edit, send, accept, reject, version.\",\n argsSchema: {\n quote_ref: z\n .string()\n .describe(\"Quote id or code (e.g. QT-2026-0007)\"),\n },\n },\n ({ quote_ref }) => ({\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: buildText(quote_ref) },\n },\n ],\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nfunction buildText(consultantRef: string): string {\n return `Investigate consultant ${consultantRef}:\n\n1. lkp_resources_list with the search filter → confirm identity and current allocation status.\n2. lkp_resource_history over the last 6 months → project timeline + idle gaps.\n3. lkp_resource_timesheets over the last 30 days → actual work pattern.\n4. If the consultant is available or soon to be released, run lkp_skill_match and filter for this consultant.\n\nProduce a structured report in Portuguese with:\n- **Status atual** (uma linha)\n- **Últimos 6 meses** (timeline)\n- **Padrão de trabalho últimas 4 semanas** (média horas/dia, dias sem apontamento, fins de semana, entradas não aprovadas)\n- **Oportunidades compatíveis** (se aplicável)\n- **Recomendação** (uma única ação concreta)`;\n}\n\nexport function registerConsultantInvestigationPrompt(\n server: McpServer,\n): void {\n server.registerPrompt(\n \"consultant-investigation\",\n {\n title: \"Consultant Investigation\",\n description:\n \"Deep-dive on one consultant — where they are, what they've done, what's next.\",\n argsSchema: {\n consultant_ref: z.string().describe(\"Consultant id or name\"),\n },\n },\n ({ consultant_ref }) => ({\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: buildText(consultant_ref) },\n },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Chame lkp_managers_in_trouble para obter a lista atual. Resposta em português, markdown, dividida em DUAS SEÇÕES separadas:\n\n## 📋 Atraso operacional (tasks)\nUm bullet por gerente com \\`tasks_overdue\\` preenchido, citando:\n- Nome + total de tasks atrasadas + projetos afetados\n- A mais antiga (quantos dias)\n\n## 💰 Atraso financeiro (faturamento)\nUm bullet por gerente com \\`financial_overdue\\` preenchido, citando:\n- Nome + contagem + valor total em R$\n- Breakdown por tipo se houver mais de um (milestone / measurement / invoice)\n- A mais antiga (quantos dias)\n\n## 🎯 Ação sugerida\nUM bullet só — o caso mais crítico (maior days_since_oldest combinado com maior valor).\n\nSe nenhuma das camadas tiver resultados, diga \"Nada atrasado hoje\".`;\n\nexport function registerManagersInTroublePrompt(server: McpServer): void {\n server.registerPrompt(\n \"managers-in-trouble\",\n {\n title: \"Managers in trouble\",\n description:\n \"Gerentes com atrasos — quem precisa de atenção agora?\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Run a full pipeline review:\n\n1. lkp_opportunities_summary → funnel + stale.\n2. For each stale opportunity, fetch context via lkp_opportunities_list (search by name or id).\n3. lkp_skill_match → identify opportunities that could absorb idle consultants.\n4. Compute:\n - Weighted pipeline vs. the health factors in lkp_ceo_weekly.\n - Stale count trend (from last_activity_at distribution).\n - Coverage: open opportunities' weighted value ÷ monthly idle cost (lkp_resources_summary).\n\nOutput Portuguese markdown. For every red indicator, propose a concrete action — NOT advice — naming the exact tool and arguments the user can approve (\"chamar lkp_opportunity_activity_add com …\").`;\n\nexport function registerPipelineHealthCheckPrompt(server: McpServer): void {\n server.registerPrompt(\n \"pipeline-health-check\",\n {\n title: \"Pipeline Health Check\",\n description: \"Comprehensive CRM review with concrete recommendations.\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { registerWeeklyBriefPrompt } from \"./weekly-brief.js\";\nimport { registerMorningStandupPrompt } from \"./morning-standup.js\";\nimport { registerOpportunityActionPrompt } from \"./opportunity-action.js\";\nimport { registerQuoteActionPrompt } from \"./quote-action.js\";\nimport { registerConsultantInvestigationPrompt } from \"./consultant-investigation.js\";\nimport { registerManagersInTroublePrompt } from \"./managers-in-trouble.js\";\nimport { registerPipelineHealthCheckPrompt } from \"./pipeline-health-check.js\";\n\nexport function registerAllPrompts(server: McpServer): void {\n registerWeeklyBriefPrompt(server);\n registerMorningStandupPrompt(server);\n registerOpportunityActionPrompt(server);\n registerQuoteActionPrompt(server);\n registerConsultantInvestigationPrompt(server);\n registerManagersInTroublePrompt(server);\n registerPipelineHealthCheckPrompt(server);\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACDrC,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAEX,IAAM,cAAc;AACpB,IAAM,iBAAiB;AAE9B,IAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,kBAAkB,EACf,OAAO,EACP,IAAI,qBAAqB,EACzB,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,GAAG;AAAA,IACvC,SAAS;AAAA,EACX,CAAC,EACA,UAAU,CAAC,MAAM,EAAE,QAAQ,QAAQ,EAAE,CAAC;AAAA,EACzC,eAAe,EAAE,OAAO,EAAE,IAAI,GAAG,iBAAiB;AAAA,EAClD,eAAe,EACZ,KAAK,CAAC,SAAS,SAAS,QAAQ,QAAQ,SAAS,SAAS,QAAQ,CAAC,EACnE,QAAQ,MAAM;AAAA,EACjB,wBAAwB,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,GAAM;AAAA,EACzE,oBAAoB,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EACnE,uBAAuB,EAAE,OAAO,OAAO,EAAE,IAAI,EAAE,IAAI,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Q,OAAO,MAAM,EAAE,GAAG,qBAAqB;AAC9D,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AAED,QAAM,OAAO,QAAQ,SAAS;AAC9B,SAAO,KAAK,OAAO;AACrB;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,OAAO;AAAA,IACb,IAAI,WAAW,YAAY,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA;AAAA,EAC7E;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","PROMPT","z","z","buildText","z","buildText","PROMPT","PROMPT"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/logger.ts","../src/http-client.ts","../src/errors.ts","../src/tools/ping.ts","../src/tools/resources.ts","../src/tools/common.ts","../src/tools/projects.ts","../src/tools/opportunities.ts","../src/tools/quotes.ts","../src/tools/clients.ts","../src/tools/helpdesk.ts","../src/tools/billing.ts","../src/tools/alerts.ts","../src/tools/reports.ts","../src/tools/financial.ts","../src/tools/composite/skill-match.ts","../src/tools/composite/weekly-brief.ts","../src/tools/composite/timesheet-anomalies.ts","../src/tools/composite/index.ts","../src/tools/index.ts","../src/prompts/weekly-brief.ts","../src/prompts/morning-standup.ts","../src/prompts/opportunity-action.ts","../src/prompts/quote-action.ts","../src/prompts/consultant-investigation.ts","../src/prompts/managers-in-trouble.ts","../src/prompts/pipeline-health-check.ts","../src/prompts/index.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { SERVER_NAME, SERVER_VERSION, loadConfig } from \"./config.js\";\nimport { createLogger } from \"./logger.js\";\nimport { LkpClient } from \"./http-client.js\";\nimport { registerAllTools } from \"./tools/index.js\";\nimport { registerAllPrompts } from \"./prompts/index.js\";\n\nasync function main(): Promise<void> {\n const config = loadConfig();\n const logger = createLogger(config);\n\n logger.info(\n {\n base_url: config.LKP_API_BASE_URL,\n log_level: config.LKP_LOG_LEVEL,\n timeout_ms: config.LKP_REQUEST_TIMEOUT_MS,\n retry_attempts: config.LKP_RETRY_ATTEMPTS,\n node: process.version,\n },\n \"starting\",\n );\n\n const client = new LkpClient({\n baseUrl: config.LKP_API_BASE_URL,\n token: config.LKP_API_TOKEN,\n timeoutMs: config.LKP_REQUEST_TIMEOUT_MS,\n retryAttempts: config.LKP_RETRY_ATTEMPTS,\n userAgent: `${SERVER_NAME}/${SERVER_VERSION} (+node ${process.version})`,\n logger,\n });\n\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n });\n\n registerAllTools(server, client, logger);\n registerAllPrompts(server);\n\n const transport = new StdioServerTransport();\n\n const shutdown = async (signal: string): Promise<void> => {\n logger.info({ signal }, \"shutdown\");\n try {\n await server.close();\n } catch (e) {\n logger.error(\n { err: e instanceof Error ? e.message : String(e) },\n \"shutdown_error\",\n );\n }\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => {\n void shutdown(\"SIGINT\");\n });\n process.on(\"SIGTERM\", () => {\n void shutdown(\"SIGTERM\");\n });\n process.on(\"uncaughtException\", (err) => {\n logger.fatal({ err: err.message, stack: err.stack }, \"uncaught_exception\");\n process.exit(1);\n });\n process.on(\"unhandledRejection\", (reason) => {\n logger.fatal({ reason: String(reason) }, \"unhandled_rejection\");\n process.exit(1);\n });\n\n await server.connect(transport);\n logger.info(\"ready\");\n}\n\nmain().catch((err) => {\n process.stderr.write(\n `[${SERVER_NAME}] fatal: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n process.exit(1);\n});\n","import { execFileSync } from \"node:child_process\";\nimport { z } from \"zod\";\n\nexport const SERVER_NAME = \"lkpgestao-mcp\";\nexport const SERVER_VERSION = \"0.1.0\";\n\nconst ConfigSchema = z.object({\n LKP_API_BASE_URL: z\n .string()\n .url(\"must be a valid URL\")\n .refine((u) => u.startsWith(\"https://\"), {\n message: \"must use https:// (TLS is mandatory)\",\n })\n .transform((u) => u.replace(/\\/+$/, \"\")),\n LKP_API_TOKEN: z.string().min(1, \"cannot be empty\"),\n LKP_LOG_LEVEL: z\n .enum([\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\", \"silent\"])\n .default(\"info\"),\n LKP_REQUEST_TIMEOUT_MS: z.coerce.number().int().positive().default(10_000),\n LKP_RETRY_ATTEMPTS: z.coerce.number().int().min(0).max(5).default(2),\n LKP_CACHE_TTL_SECONDS: z.coerce.number().int().min(0).default(30),\n});\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\nexport type KeychainLookup = (service: string, account?: string) => string;\n\nexport const defaultKeychainLookup: KeychainLookup = (service, account) => {\n const args = [\"find-generic-password\", \"-s\", service, \"-w\"];\n if (account) args.push(\"-a\", account);\n try {\n const out = execFileSync(\"security\", args, {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n return out.replace(/\\r?\\n$/, \"\");\n } catch (err: unknown) {\n const e = err as { status?: number; stderr?: Buffer | string; code?: string };\n if (e.code === \"ENOENT\") {\n throw new Error(\n \"Keychain lookup requires the macOS `security` binary (not found on PATH)\",\n );\n }\n const stderr =\n typeof e.stderr === \"string\"\n ? e.stderr\n : (e.stderr?.toString(\"utf8\") ?? \"\");\n const hint = /could not be found|SecKeychainSearchCopyNext/.test(stderr)\n ? `item \"${service}\" not found in Keychain`\n : stderr.trim() || `security exited with status ${e.status}`;\n throw new Error(`Keychain lookup failed: ${hint}`);\n }\n};\n\nexport interface LoadConfigOptions {\n keychainLookup?: KeychainLookup;\n}\n\nexport function loadConfig(\n env: NodeJS.ProcessEnv = process.env,\n options: LoadConfigOptions = {},\n): Config {\n const lookup = options.keychainLookup ?? defaultKeychainLookup;\n const resolved: NodeJS.ProcessEnv = { ...env };\n\n if (!resolved.LKP_API_TOKEN && resolved.LKP_API_TOKEN_KEYCHAIN_SERVICE) {\n try {\n resolved.LKP_API_TOKEN = lookup(\n resolved.LKP_API_TOKEN_KEYCHAIN_SERVICE,\n resolved.LKP_API_TOKEN_KEYCHAIN_ACCOUNT,\n );\n } catch (err) {\n process.stderr.write(\n `[${SERVER_NAME}] configuration error:\\n - ${(err as Error).message}\\n\\n`,\n );\n process.exit(1);\n }\n }\n\n const parsed = ConfigSchema.safeParse(resolved);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => ` - ${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n .join(\"\\n\");\n process.stderr.write(\n `[${SERVER_NAME}] configuration error:\\n${issues}\\n\\n` +\n `Required env vars: LKP_API_BASE_URL, LKP_API_TOKEN ` +\n `(or LKP_API_TOKEN_KEYCHAIN_SERVICE on macOS).\\n` +\n `See README for the full reference.\\n`,\n );\n process.exit(1);\n }\n return parsed.data;\n}\n","import pino, { type Logger as PinoLogger, type DestinationStream } from \"pino\";\nimport { SERVER_NAME, SERVER_VERSION, type Config } from \"./config.js\";\n\nexport type Logger = PinoLogger;\n\nexport const REDACT_PATHS = [\n \"authorization\",\n \"Authorization\",\n \"headers.authorization\",\n \"headers.Authorization\",\n \"token\",\n \"api_token\",\n \"bearer\",\n \"LKP_API_TOKEN\",\n \"env.LKP_API_TOKEN\",\n \"*.token\",\n \"*.api_token\",\n \"*.authorization\",\n];\n\nexport function createLogger(\n config: Config,\n destination?: DestinationStream,\n): Logger {\n return pino(\n {\n name: SERVER_NAME,\n level: config.LKP_LOG_LEVEL,\n base: {\n service: SERVER_NAME,\n version: SERVER_VERSION,\n pid: process.pid,\n },\n redact: {\n paths: REDACT_PATHS,\n censor: \"[REDACTED]\",\n remove: false,\n },\n timestamp: pino.stdTimeFunctions.isoTime,\n },\n destination ?? pino.destination({ dest: 2, sync: false }),\n );\n}\n","import { randomUUID } from \"node:crypto\";\nimport { LkpError, mapHttpStatus, type LkpErrorCode } from \"./errors.js\";\nimport type { Logger } from \"./logger.js\";\n\nexport interface LkpClientOptions {\n baseUrl: string;\n token: string;\n timeoutMs: number;\n retryAttempts: number;\n userAgent: string;\n logger: Logger;\n}\n\nexport type QueryValue = string | number | boolean | undefined | null;\nexport type Query = Record<string, QueryValue>;\n\nexport const MAX_RETRY_AFTER_SECONDS = 60;\n\ninterface RequestOptions {\n query?: Query;\n body?: unknown;\n extraHeaders?: Record<string, string>;\n}\n\ninterface ApiErrorShape {\n code?: string;\n message?: string;\n details?: unknown;\n}\n\nexport class LkpClient {\n private readonly baseUrl: string;\n private readonly token: string;\n private readonly timeoutMs: number;\n private readonly retryAttempts: number;\n private readonly userAgent: string;\n private readonly logger: Logger;\n\n constructor(opts: LkpClientOptions) {\n this.baseUrl = opts.baseUrl;\n this.token = opts.token;\n this.timeoutMs = opts.timeoutMs;\n this.retryAttempts = opts.retryAttempts;\n this.userAgent = opts.userAgent;\n this.logger = opts.logger;\n }\n\n get<T>(path: string, query?: Query): Promise<T> {\n return this.request<T>(\"GET\", path, { query });\n }\n\n post<T>(\n path: string,\n body: unknown,\n extraHeaders?: Record<string, string>,\n ): Promise<T> {\n return this.request<T>(\"POST\", path, { body, extraHeaders });\n }\n\n patch<T>(path: string, body: unknown): Promise<T> {\n return this.request<T>(\"PATCH\", path, { body });\n }\n\n put<T>(path: string, body: unknown): Promise<T> {\n return this.request<T>(\"PUT\", path, { body });\n }\n\n delete<T = null>(path: string): Promise<T> {\n return this.request<T>(\"DELETE\", path, {});\n }\n\n private async request<T>(\n method: string,\n path: string,\n opts: RequestOptions,\n ): Promise<T> {\n const url = this.buildUrl(path, opts.query);\n const requestId = randomUUID();\n const log = this.logger.child({ request_id: requestId, method, path });\n\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n Authorization: `Bearer ${this.token}`,\n \"X-Request-ID\": requestId,\n \"User-Agent\": this.userAgent,\n };\n\n let bodyStr: string | undefined;\n if (opts.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n bodyStr = JSON.stringify(opts.body);\n }\n\n if (opts.extraHeaders) {\n for (const [k, v] of Object.entries(opts.extraHeaders)) {\n headers[k] = v;\n }\n }\n\n const maxAttempts = this.retryAttempts + 1;\n let retriedOn429 = false;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n const started = Date.now();\n\n try {\n const res = await fetch(url, {\n method,\n headers,\n body: bodyStr,\n signal: controller.signal,\n });\n const duration_ms = Date.now() - started;\n const remaining = res.headers.get(\"x-ratelimit-remaining\");\n\n if (res.ok) {\n const isEmpty =\n res.status === 204 || res.headers.get(\"content-length\") === \"0\";\n const data = (isEmpty ? null : await res.json()) as T;\n log.info(\n { http_status: res.status, duration_ms, remaining, attempt },\n \"http_ok\",\n );\n if (remaining !== null) {\n const n = Number(remaining);\n if (Number.isFinite(n) && n < 10) {\n log.warn({ remaining: n }, \"rate_limit_low\");\n }\n }\n return data;\n }\n\n const body = await safeJson(res);\n const apiErr = extractApiError(body);\n const retryAfter = parseRetryAfter(res.headers.get(\"retry-after\"));\n\n if (res.status === 429 && !retriedOn429 && attempt < maxAttempts) {\n retriedOn429 = true;\n const effective = Math.min(\n retryAfter ?? 1,\n MAX_RETRY_AFTER_SECONDS,\n );\n log.warn(\n { retry_after: retryAfter, effective_wait: effective },\n \"rate_limited_retry\",\n );\n await sleep(effective * 1000);\n continue;\n }\n\n const retryable = res.status >= 500;\n if (retryable && attempt < maxAttempts) {\n const backoff = 100 * Math.pow(4, attempt - 1);\n log.warn(\n { http_status: res.status, attempt, backoff_ms: backoff },\n \"http_retry\",\n );\n await sleep(backoff);\n continue;\n }\n\n const code: LkpErrorCode = mapHttpStatus(res.status);\n const payload: ConstructorParameters<typeof LkpError>[0] = {\n code,\n message:\n apiErr?.message ??\n `HTTP ${res.status} ${res.statusText} on ${method} ${path}`,\n request_id: requestId,\n http_status: res.status,\n };\n if (apiErr?.code) payload.api_code = apiErr.code;\n if (apiErr?.details !== undefined) payload.details = apiErr.details;\n if (retryAfter !== null) payload.retry_after_seconds = retryAfter;\n\n log.error(\n {\n http_status: res.status,\n duration_ms,\n api_code: apiErr?.code,\n },\n \"http_error\",\n );\n throw new LkpError(payload);\n } catch (e) {\n clearTimeout(timer);\n if (e instanceof LkpError) throw e;\n\n const isAbort = e instanceof Error && e.name === \"AbortError\";\n const duration_ms = Date.now() - started;\n\n if (attempt < maxAttempts) {\n const backoff = 100 * Math.pow(4, attempt - 1);\n log.warn(\n {\n attempt,\n backoff_ms: backoff,\n reason: isAbort ? \"timeout\" : \"network\",\n duration_ms,\n },\n \"http_retry\",\n );\n await sleep(backoff);\n continue;\n }\n\n log.error({ duration_ms, reason: isAbort ? \"timeout\" : \"network\" }, \"http_fail\");\n throw new LkpError({\n code: isAbort ? \"timeout\" : \"network_error\",\n message: isAbort\n ? `Request to ${path} timed out after ${this.timeoutMs}ms`\n : `Could not reach LKPGestão API: ${(e as Error).message}`,\n request_id: requestId,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n throw new LkpError({\n code: \"unexpected\",\n message: \"Request loop exited without result (should be unreachable).\",\n request_id: requestId,\n });\n }\n\n private buildUrl(path: string, query?: Query): string {\n const clean = path.startsWith(\"/\") ? path : `/${path}`;\n const url = new URL(`${this.baseUrl}${clean}`);\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined && v !== null) {\n url.searchParams.set(k, String(v));\n }\n }\n }\n return url.toString();\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nexport function parseRetryAfter(raw: string | null): number | null {\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : null;\n}\n\nasync function safeJson(res: Response): Promise<unknown> {\n try {\n return await res.json();\n } catch {\n return undefined;\n }\n}\n\nfunction extractApiError(body: unknown): ApiErrorShape | undefined {\n if (!body || typeof body !== \"object\") return undefined;\n const b = body as { error?: unknown; message?: unknown };\n if (b.error && typeof b.error === \"object\") {\n return b.error as ApiErrorShape;\n }\n if (typeof b.message === \"string\") {\n return { message: b.message };\n }\n return undefined;\n}\n","export type LkpErrorCode =\n | \"bad_request\"\n | \"auth_failed\"\n | \"permission_denied\"\n | \"not_found\"\n | \"validation_error\"\n | \"rate_limited\"\n | \"server_error\"\n | \"network_error\"\n | \"timeout\"\n | \"unexpected\";\n\nexport interface LkpErrorPayload {\n code: LkpErrorCode;\n message: string;\n request_id?: string;\n http_status?: number;\n api_code?: string;\n details?: unknown;\n retry_after_seconds?: number;\n}\n\nexport class LkpError extends Error {\n readonly code: LkpErrorCode;\n readonly request_id: string | undefined;\n readonly http_status: number | undefined;\n readonly api_code: string | undefined;\n readonly details: unknown;\n readonly retry_after_seconds: number | undefined;\n\n constructor(payload: LkpErrorPayload) {\n super(payload.message);\n this.name = \"LkpError\";\n this.code = payload.code;\n this.request_id = payload.request_id;\n this.http_status = payload.http_status;\n this.api_code = payload.api_code;\n this.details = payload.details;\n this.retry_after_seconds = payload.retry_after_seconds;\n }\n\n toJSON(): LkpErrorPayload {\n const out: LkpErrorPayload = { code: this.code, message: this.message };\n if (this.request_id !== undefined) out.request_id = this.request_id;\n if (this.http_status !== undefined) out.http_status = this.http_status;\n if (this.api_code !== undefined) out.api_code = this.api_code;\n if (this.details !== undefined) out.details = this.details;\n if (this.retry_after_seconds !== undefined) {\n out.retry_after_seconds = this.retry_after_seconds;\n }\n return out;\n }\n}\n\nexport function mapHttpStatus(status: number): LkpErrorCode {\n if (status === 400) return \"bad_request\";\n if (status === 401) return \"auth_failed\";\n if (status === 403) return \"permission_denied\";\n if (status === 404) return \"not_found\";\n if (status === 422) return \"validation_error\";\n if (status === 429) return \"rate_limited\";\n if (status >= 500) return \"server_error\";\n return \"unexpected\";\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { LkpError } from \"../errors.js\";\n\nconst PingUser = z\n .object({\n id: z.number().optional(),\n name: z.string().optional(),\n email: z.string().optional(),\n })\n .passthrough();\n\nconst PingToken = z\n .object({\n name: z.string().optional(),\n scopes: z.array(z.string()).optional(),\n last_used_at: z.string().optional(),\n })\n .passthrough();\n\nconst PingResponse = z\n .object({\n user: PingUser.optional(),\n token: PingToken.optional(),\n server_time: z.string().optional(),\n })\n .passthrough();\n\nexport function registerPing(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_ping\",\n {\n title: \"Ping LKPGestão\",\n description:\n \"Health check. Confirms the MCP server can reach LKPGestão and the configured API token is valid. Returns the bound user (name/email), the token's label, and the granted scopes. Use this first when unsure about connectivity or permissions.\",\n inputSchema: {},\n },\n async () => {\n const started = Date.now();\n try {\n const raw = await client.get<unknown>(\"/api/v1/ping\");\n const parsed = PingResponse.safeParse(raw);\n const payload = parsed.success ? parsed.data : raw;\n logger.info(\n { tool: \"lkp_ping\", duration_ms: Date.now() - started, ok: true },\n \"tool_ok\",\n );\n return {\n content: [\n { type: \"text\", text: JSON.stringify(payload, null, 2) },\n ],\n };\n } catch (e) {\n const err =\n e instanceof LkpError\n ? e.toJSON()\n : { code: \"unexpected\" as const, message: (e as Error).message };\n logger.error(\n { tool: \"lkp_ping\", duration_ms: Date.now() - started, err },\n \"tool_error\",\n );\n return {\n isError: true,\n content: [{ type: \"text\", text: JSON.stringify(err, null, 2) }],\n };\n }\n },\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerResources(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_resources_list\",\n {\n title: \"List resources (consultants)\",\n description:\n \"List consultants (resources) with filters. Returns allocation status, hourly rate, specialties, weekly capacity. Use to find candidates for allocation or to audit team composition.\",\n inputSchema: {\n status: z.string().optional(),\n contract_type: z.string().optional(),\n specialty_id: z.coerce.number().int().positive().optional(),\n allocation: z\n .enum([\"available\", \"partial\", \"full\", \"overloaded\"])\n .optional(),\n role: z.string().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_resources_list\", () =>\n client.get<unknown>(\"/api/v1/resources\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_resources_summary\",\n {\n title: \"Resources operational summary\",\n description:\n \"Operational snapshot of all consultants: counts by allocation bucket (available/partial/full/overloaded), monthly cost split (total/allocated/idle), list of consultants available now, list of consultants finishing their project in ≤30 days. Use for dashboards and the Monday brief.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_resources_summary\", () =>\n client.get<unknown>(\"/api/v1/resources/summary\"),\n ),\n );\n\n server.registerTool(\n \"lkp_resource_history\",\n {\n title: \"Resource allocation history\",\n description:\n \"Allocation history for one consultant over a date range. Returns per-project periods interleaved with idle gaps, plus metrics (utilization_percent, idle_days, billed_hours, revenue). Default range: last 12 months.\",\n inputSchema: {\n resource_id: z.coerce.number().int().positive(),\n from: z.string().optional(),\n to: z.string().optional(),\n },\n },\n async ({ resource_id, from, to }) =>\n runTool(logger, \"lkp_resource_history\", () =>\n client.get<unknown>(`/api/v1/resources/${resource_id}/history`, {\n from,\n to,\n }),\n ),\n );\n\n server.registerTool(\n \"lkp_specialties_list\",\n {\n title: \"List specialties\",\n description:\n \"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 → specialty_id. Do NOT hardcode IDs — the catalog is maintained in LKPGestão and may change. Returns { id, name, category, is_active }.\",\n inputSchema: {\n category: z\n .enum([\n \"SAP_DESENVOLVIMENTO\",\n \"SAP_FUNCIONAL\",\n \"SAP_TECNICO\",\n \"GESTÃO\",\n \"BACKOFFICE\",\n ])\n .optional(),\n search: z.string().optional(),\n active_only: z.coerce.boolean().default(true),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_specialties_list\", () =>\n client.get<unknown>(\"/api/v1/specialties\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_resource_timesheets\",\n {\n title: \"Resource timesheet entries\",\n description:\n \"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 ≤ 184 days; max per_page 200.\",\n inputSchema: {\n resource_id: z.coerce.number().int().positive(),\n from: z.string(),\n to: z.string(),\n project_id: z.coerce.number().int().positive().optional(),\n task_id: z.coerce.number().int().positive().optional(),\n is_approved: z.coerce.boolean().optional(),\n is_billable: z.coerce.boolean().optional(),\n source: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(50),\n },\n },\n async ({ resource_id, ...query }) =>\n runTool(logger, \"lkp_resource_timesheets\", () =>\n client.get<unknown>(\n `/api/v1/resources/${resource_id}/timesheets`,\n query,\n ),\n ),\n );\n}\n","import type { Logger } from \"../logger.js\";\nimport { LkpError } from \"../errors.js\";\n\nexport interface ToolResult {\n [key: string]: unknown;\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n}\n\nexport async function runTool<T>(\n logger: Logger,\n name: string,\n fn: () => Promise<T>,\n): Promise<ToolResult> {\n const started = Date.now();\n try {\n const result = await fn();\n logger.info(\n { tool: name, duration_ms: Date.now() - started, ok: true },\n \"tool_ok\",\n );\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (e) {\n const err =\n e instanceof LkpError\n ? e.toJSON()\n : { code: \"unexpected\" as const, message: (e as Error).message };\n logger.error(\n { tool: name, duration_ms: Date.now() - started, err },\n \"tool_error\",\n );\n return {\n isError: true,\n content: [{ type: \"text\", text: JSON.stringify(err, null, 2) }],\n };\n }\n}\n\nexport async function runToolText(\n logger: Logger,\n name: string,\n fn: () => Promise<string>,\n): Promise<ToolResult> {\n const started = Date.now();\n try {\n const text = await fn();\n logger.info(\n { tool: name, duration_ms: Date.now() - started, ok: true },\n \"tool_ok\",\n );\n return { content: [{ type: \"text\", text }] };\n } catch (e) {\n const err =\n e instanceof LkpError\n ? e.toJSON()\n : { code: \"unexpected\" as const, message: (e as Error).message };\n logger.error(\n { tool: name, duration_ms: Date.now() - started, err },\n \"tool_error\",\n );\n return {\n isError: true,\n content: [{ type: \"text\", text: JSON.stringify(err, null, 2) }],\n };\n }\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerProjects(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_projects_list\",\n {\n title: \"List projects\",\n description:\n \"List projects with filters. Returns status, client, manager, budget, progress (task completion %), source opportunity, next pending billing milestone. Use to explore the portfolio.\",\n inputSchema: {\n status_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n manager_id: z.coerce.number().int().positive().optional(),\n is_active: z.coerce.boolean().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_projects_list\", () =>\n client.get<unknown>(\"/api/v1/projects\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_projects_summary\",\n {\n title: \"Projects portfolio summary\",\n description:\n \"Portfolio dashboard: project counts by status, financial aggregate from billing milestones, upcoming milestones in the next 30 days.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_projects_summary\", () =>\n client.get<unknown>(\"/api/v1/projects/summary\"),\n ),\n );\n\n server.registerTool(\n \"lkp_project_detail\",\n {\n title: \"Project detail\",\n description:\n \"Full project detail: team, billing milestones (all, not just next), stats, source opportunity link. Use before making decisions about a specific project.\",\n inputSchema: {\n project_id: z.coerce.number().int().positive(),\n },\n },\n async ({ project_id }) =>\n runTool(logger, \"lkp_project_detail\", () =>\n client.get<unknown>(`/api/v1/projects/${project_id}`),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nconst OpportunityStatus = z.enum([\n \"NEW\",\n \"QUALIFYING\",\n \"PROPOSAL\",\n \"SENT\",\n \"NEGOTIATION\",\n \"WON\",\n \"LOST\",\n \"CANCELLED\",\n]);\n\nconst ActivityType = z.enum([\n \"CALL\",\n \"EMAIL\",\n \"MEETING\",\n \"NOTE\",\n \"FOLLOW_UP\",\n \"PRESENTATION\",\n \"NEGOTIATION\",\n \"DOCUMENT_SENT\",\n \"DOCUMENT_RECEIVED\",\n \"OTHER\",\n]);\n\nconst ContactRole = z.enum([\n \"DECISION_MAKER\",\n \"INFLUENCER\",\n \"TECHNICAL\",\n \"FINANCIAL\",\n \"USER\",\n \"SPONSOR\",\n \"GATEKEEPER\",\n \"CHAMPION\",\n \"OTHER\",\n]);\n\nconst EngagementLevel = z.enum([\"LOW\", \"MEDIUM\", \"HIGH\"]);\nconst Sentiment = z.enum([\"NEGATIVE\", \"NEUTRAL\", \"POSITIVE\", \"CHAMPION\"]);\n\nexport function registerOpportunities(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n // ── Opportunity reads ──────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunities_list\",\n {\n title: \"List sales opportunities\",\n description:\n \"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 | LOST | CANCELLED.\",\n inputSchema: {\n status: OpportunityStatus.optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n closing_before: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce.number().int().positive().max(200).default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_opportunities_list\", () =>\n client.get<unknown>(\"/api/v1/opportunities\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunities_summary\",\n {\n title: \"Opportunities pipeline summary\",\n description:\n \"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 ≥7 days).\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_opportunities_summary\", () =>\n client.get<unknown>(\"/api/v1/opportunities/summary\"),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_detail\",\n {\n title: \"Opportunity detail\",\n description:\n \"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 or (without include_inactive) when the opportunity itself is archived.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n include_inactive: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, include_inactive }) =>\n runTool(logger, \"lkp_opportunity_detail\", () =>\n client.get<unknown>(`/api/v1/opportunities/${opportunity_id}`, {\n include_inactive,\n }),\n ),\n );\n\n // ── Opportunity writes ─────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunity_create\",\n {\n title: \"Create opportunity (write)\",\n description:\n \"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 — use lkp_opportunity_update afterwards. account_manager_id defaults to the token user. Summarize the draft and wait for user approval before calling.\",\n inputSchema: {\n client_id: z.coerce.number().int().positive(),\n name: z.string().min(1),\n project_b1_code_id: z.coerce.number().int().positive(),\n description: z.string().optional(),\n status: OpportunityStatus.optional(),\n probability: z.coerce.number().min(0).max(100).optional(),\n expected_value: z.coerce.number().nonnegative().optional(),\n expected_close_date: z.string().optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n price_list_id: z.coerce.number().int().positive().optional(),\n source: z.string().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_opportunity_create\", () =>\n client.post<unknown>(\"/api/v1/opportunities\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_update\",\n {\n title: \"Update opportunity (write)\",\n description:\n \"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 — equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored. Returns the updated opportunity. Confirm any state transition with the user before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n name: z.string().optional(),\n description: z.string().optional(),\n status: OpportunityStatus.optional(),\n probability: z.coerce.number().min(0).max(100).optional(),\n expected_value: z.coerce.number().nonnegative().optional(),\n expected_close_date: z.string().optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n is_active: z.coerce.boolean().optional(),\n lost_reason: z.string().optional(),\n lost_reason_detail: z.string().optional(),\n lost_notes: z.string().optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_update\", () =>\n client.patch<unknown>(`/api/v1/opportunities/${opportunity_id}`, body),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_archive\",\n {\n title: \"Archive opportunity (write)\",\n description:\n \"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 — destructive intent.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n },\n },\n async ({ opportunity_id }) =>\n runTool(logger, \"lkp_opportunity_archive\", async () => {\n await client.delete(`/api/v1/opportunities/${opportunity_id}`);\n return { ok: true, archived: true, opportunity_id };\n }),\n );\n\n // ── Activity writes ────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunity_activity_add\",\n {\n title: \"Add activity to opportunity (write)\",\n description:\n \"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.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n type: ActivityType,\n subject: z.string().min(1),\n description: z.string().optional(),\n duration_minutes: z.coerce.number().int().nonnegative().optional(),\n follow_up_date: z.string().optional(),\n outcome: z.string().optional(),\n is_internal: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_activity_add\", () =>\n client.post<unknown>(\n `/api/v1/opportunities/${opportunity_id}/activities`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_activity_update\",\n {\n title: \"Update opportunity activity (write)\",\n description:\n \"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.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n activity_id: z.coerce.number().int().positive(),\n subject: z.string().optional(),\n description: z.string().optional(),\n activity_date: z.string().optional(),\n duration_minutes: z.coerce.number().int().nonnegative().optional(),\n follow_up_date: z.string().optional(),\n follow_up_notes: z.string().optional(),\n is_follow_up_done: z.coerce.boolean().optional(),\n outcome: z.string().optional(),\n is_internal: z.coerce.boolean().optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, activity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_activity_update\", () =>\n client.patch<unknown>(\n `/api/v1/opportunities/${opportunity_id}/activities/${activity_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_activity_delete\",\n {\n title: \"Delete opportunity activity (write)\",\n description:\n \"Soft-archive a manual activity on an opportunity. System-generated activities cannot be deleted. Returns 404 when the activity is already archived. Always ask user approval before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n activity_id: z.coerce.number().int().positive(),\n },\n },\n async ({ opportunity_id, activity_id }) =>\n runTool(logger, \"lkp_opportunity_activity_delete\", async () => {\n await client.delete(\n `/api/v1/opportunities/${opportunity_id}/activities/${activity_id}`,\n );\n return { ok: true, archived: true, opportunity_id, activity_id };\n }),\n );\n\n // ── Contact links ──────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_opportunity_contacts_list\",\n {\n title: \"List opportunity contacts\",\n description:\n \"List contacts linked to an opportunity (with the underlying client_contact_persons record). Filters inactive links by default; pass include_inactive=true to include them.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n include_inactive: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, include_inactive }) =>\n runTool(logger, \"lkp_opportunity_contacts_list\", () =>\n client.get<unknown>(\n `/api/v1/opportunities/${opportunity_id}/contacts`,\n { include_inactive },\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_contact_attach\",\n {\n title: \"Attach contact to opportunity (write)\",\n description:\n \"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.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n contact_person_id: z.coerce.number().int().positive(),\n role: ContactRole.optional(),\n role_description: z.string().optional(),\n is_primary: z.coerce.boolean().optional(),\n notes: z.string().optional(),\n engagement_level: EngagementLevel.optional(),\n sentiment: Sentiment.optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_contact_attach\", () =>\n client.post<unknown>(\n `/api/v1/opportunities/${opportunity_id}/contacts`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_contact_update\",\n {\n title: \"Update opportunity contact link (write)\",\n description:\n \"Update attributes of a contact link on an opportunity. contact_person_id and opportunity_id are immutable on an existing link — detach + attach instead. Setting is_primary: true clears any prior primary on the same opportunity. Setting is_active: false archives the link (equivalent to detach).\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n link_id: z.coerce.number().int().positive(),\n role: ContactRole.optional(),\n role_description: z.string().optional(),\n is_primary: z.coerce.boolean().optional(),\n notes: z.string().optional(),\n engagement_level: EngagementLevel.optional(),\n sentiment: Sentiment.optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, link_id, ...body }) =>\n runTool(logger, \"lkp_opportunity_contact_update\", () =>\n client.patch<unknown>(\n `/api/v1/opportunities/${opportunity_id}/contacts/${link_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_contact_detach\",\n {\n title: \"Detach contact from opportunity (write)\",\n description:\n \"Soft-archive a contact link on an opportunity (is_active=0). The underlying client_contact_persons record is never touched — it belongs to the client, not the opportunity. Returns 404 when the link doesn't belong to the opportunity or is already archived. Always ask user approval before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n link_id: z.coerce.number().int().positive(),\n },\n },\n async ({ opportunity_id, link_id }) =>\n runTool(logger, \"lkp_opportunity_contact_detach\", async () => {\n await client.delete(\n `/api/v1/opportunities/${opportunity_id}/contacts/${link_id}`,\n );\n return { ok: true, detached: true, opportunity_id, link_id };\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nconst QuoteStatus = z.enum([\n \"DRAFT\",\n \"SENT\",\n \"ACCEPTED\",\n \"REJECTED\",\n \"EXPIRED\",\n \"SUPERSEDED\",\n]);\n\nconst Currency = z.enum([\"BRL\", \"USD\", \"EUR\"]);\n\nconst SkillLevel = z.enum([\"Júnior\", \"Pleno\", \"Sênior\", \"Especialista\"]);\n\nconst BillingModel = z.enum([\n \"milestone\",\n \"installment\",\n \"measurement\",\n \"subscription\",\n]);\n\nconst DiscountType = z.enum([\"PERCENT\", \"VALUE\"]);\n\nconst BillingCadence = z.enum([\"monthly\", \"quarterly\", \"annual\"]);\n\n// Item schema for inline items in lkp_quote_create and lkp_quote_item_add.\n// hourly_rate is optional: when omitted, backend resolves via the client's\n// active price_list for (specialty_id, skill_level). Pass it explicitly only\n// to override the rate card (e.g. promotional pricing).\nconst QuoteItemInput = z.object({\n specialty_id: z.coerce.number().int().positive(),\n skill_level: SkillLevel,\n description: z.string().min(1).optional(),\n quoted_hours: z.coerce.number().nonnegative(),\n sold_hours: z.coerce.number().positive(),\n hourly_rate: z.coerce.number().nonnegative().optional(),\n cost_rate: z.coerce.number().nonnegative().optional(),\n sort_order: z.coerce.number().int().optional(),\n});\n\nconst PaymentMilestoneInput = z.object({\n description: z.string().min(1),\n percentage: z.coerce.number().positive().max(100),\n due_days: z.coerce.number().int().nonnegative().optional(),\n due_date: z.string().optional(),\n notes: z.string().optional(),\n sort_order: z.coerce.number().int().optional(),\n});\n\n// Fields shared between lkp_quote_create and lkp_quote_update (header-level).\nconst QuoteHeaderFields = {\n valid_until: z.string().optional(),\n currency: Currency.optional(),\n billing_model: BillingModel.optional(),\n billing_cadence: BillingCadence.optional(),\n discount_type: DiscountType.optional(),\n discount_percent: z.coerce.number().nonnegative().optional(),\n tax_rate_id: z.coerce.number().int().positive().optional(),\n tax_absorbed: z.coerce.boolean().optional(),\n notes: z.string().optional(),\n internal_notes: z.string().optional(),\n terms_and_conditions: z.string().optional(),\n setup_fee: z.coerce.number().nonnegative().optional(),\n monthly_amount: z.coerce.number().nonnegative().optional(),\n recurring_start_date: z.string().optional(),\n billing_cadence_subscription: BillingCadence.optional(),\n contract_months: z.coerce.number().int().positive().optional(),\n installment_count: z.coerce.number().int().positive().max(60).optional(),\n} as const;\n\nexport function registerQuotes(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n // ── Reads ──────────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quotes_list\",\n {\n title: \"List quotes\",\n description:\n \"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 values: DRAFT | SENT | ACCEPTED | REJECTED | EXPIRED | SUPERSEDED. Use for quote portfolio review; scope to a specific opportunity with lkp_opportunity_quotes_list.\",\n inputSchema: {\n status: QuoteStatus.optional(),\n opportunity_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n account_manager_id: z.coerce.number().int().positive().optional(),\n billing_model: BillingModel.optional(),\n valid_until_before: z.string().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce.number().int().positive().max(200).default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_quotes_list\", () =>\n client.get<unknown>(\"/api/v1/quotes\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_detail\",\n {\n title: \"Quote detail\",\n description:\n \"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. Returns 404 when id is unknown.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_detail\", () =>\n client.get<unknown>(`/api/v1/quotes/${quote_id}`),\n ),\n );\n\n server.registerTool(\n \"lkp_opportunity_quotes_list\",\n {\n title: \"List quotes on an opportunity\",\n description:\n \"List every quote (all versions, all statuses) attached to one opportunity, ordered by version desc. Use this before new_version or duplicate so you can pick the right source quote. Children default to active-only.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n include_inactive: z.coerce.boolean().optional(),\n },\n },\n async ({ opportunity_id, include_inactive }) =>\n runTool(logger, \"lkp_opportunity_quotes_list\", () =>\n client.get<unknown>(\n `/api/v1/opportunities/${opportunity_id}/quotes`,\n { include_inactive },\n ),\n ),\n );\n\n // ── Quote CRUD ─────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_create\",\n {\n title: \"Create quote (write)\",\n description:\n \"Create a new DRAFT quote under an opportunity. Each item requires specialty_id (resolve via lkp_specialties_list) and skill_level (Júnior | Pleno | Sênior | Especialista — 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. billing_model=subscription requires monthly_amount + contract_months and items[] must be omitted. Summarize the draft (opportunity, items, totals, milestones) and wait for explicit user approval before calling.\",\n inputSchema: {\n opportunity_id: z.coerce.number().int().positive(),\n ...QuoteHeaderFields,\n items: z.array(QuoteItemInput).optional(),\n payment_milestones: z.array(PaymentMilestoneInput).optional(),\n },\n },\n async ({ opportunity_id, ...body }) =>\n runTool(logger, \"lkp_quote_create\", () =>\n client.post<unknown>(\n `/api/v1/opportunities/${opportunity_id}/quotes`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_update\",\n {\n title: \"Update quote (write)\",\n description:\n \"Update whitelisted header fields on a quote. Only DRAFT quotes can be freely edited; SENT quotes are locked — clone via lkp_quote_new_version to change terms. Mutations to items[] or payment_milestones[] must go through the dedicated tools. Setting is_active=false archives the quote. Summarize the diff (field → old → new) and wait for user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n ...QuoteHeaderFields,\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ quote_id, ...body }) =>\n runTool(logger, \"lkp_quote_update\", () =>\n client.patch<unknown>(`/api/v1/quotes/${quote_id}`, body),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_archive\",\n {\n title: \"Archive quote (write)\",\n description:\n \"Soft-archive a quote (is_active=0). Only DRAFT quotes should be archived — if a SENT/ACCEPTED quote needs to be invalidated, use lkp_quote_new_version instead. Always ask user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_archive\", async () => {\n await client.delete(`/api/v1/quotes/${quote_id}`);\n return { ok: true, archived: true, quote_id };\n }),\n );\n\n // ── Workflow ──────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_send\",\n {\n title: \"Send quote to client (write)\",\n description:\n \"Transition a DRAFT quote to SENT. Moves the parent opportunity to SENT. Locks the quote for direct edits (use lkp_quote_new_version to revise after send). Not reversible without creating a new version. Confirm the customer-facing terms (totals, valid_until, milestones) with the user before invoking.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_send\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/send`, {}),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_accept\",\n {\n title: \"Accept quote (write)\",\n description:\n \"Transition a SENT quote to ACCEPTED. Moves the parent opportunity to WON and cascades all sibling quotes on the same opportunity to REJECTED. Commercially binding — ALWAYS ask for explicit, unambiguous approval referencing the quote code (e.g. 'sim, aceitar QT-2026-0007'). Never accept on inference or implicit cues.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_accept\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/accept`, {}),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_reject\",\n {\n title: \"Reject quote (write)\",\n description:\n \"Transition a SENT quote to REJECTED. Always ask the user for the rejection motive before calling — reason is mandatory (API refuses empty). Reason is user-visible in the opportunity activity log.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n reason: z.string().min(1).max(200),\n },\n },\n async ({ quote_id, reason }) =>\n runTool(logger, \"lkp_quote_reject\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/reject`, { reason }),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_new_version\",\n {\n title: \"Create new version of quote (write)\",\n description:\n \"Clone a quote (any status) into a new DRAFT with version = prior + 1. The prior version is marked SUPERSEDED. Not allowed from DRAFT status (edit the existing draft instead). items[] and payment_milestones[] are copied; edit them on the new draft via the dedicated tools. Confirm the intent with the user.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id }) =>\n runTool(logger, \"lkp_quote_new_version\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/new-version`, {}),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_duplicate\",\n {\n title: \"Duplicate quote to another opportunity (write)\",\n description:\n \"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.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n target_opportunity_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id, target_opportunity_id }) =>\n runTool(logger, \"lkp_quote_duplicate\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/duplicate`, {\n target_opportunity_id,\n }),\n ),\n );\n\n // ── Items ─────────────────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_item_add\",\n {\n title: \"Add item to quote (write)\",\n description:\n \"Append a line item to a DRAFT quote. specialty_id: resolve via lkp_specialties_list. skill_level is required (Júnior | Pleno | Sênior | Especialista) — not derivable from specialty_id; the rate card has 4 rate columns per specialty. hourly_rate: optional — 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. Summarize the line (description, sold_hours × hourly_rate) and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n specialty_id: z.coerce.number().int().positive(),\n skill_level: SkillLevel,\n description: z.string().min(1).optional(),\n quoted_hours: z.coerce.number().nonnegative(),\n sold_hours: z.coerce.number().positive(),\n hourly_rate: z.coerce.number().nonnegative().optional(),\n cost_rate: z.coerce.number().nonnegative().optional(),\n sort_order: z.coerce.number().int().optional(),\n },\n },\n async ({ quote_id, ...body }) =>\n runTool(logger, \"lkp_quote_item_add\", () =>\n client.post<unknown>(`/api/v1/quotes/${quote_id}/items`, body),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_item_update\",\n {\n title: \"Update quote item (write)\",\n description:\n \"Update whitelisted fields on a line item of a DRAFT quote. Blocked when the parent quote is not DRAFT. All fields optional (patch). Summarize the diff (field → old → new) and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n item_id: z.coerce.number().int().positive(),\n specialty_id: z.coerce.number().int().positive().optional(),\n skill_level: SkillLevel.optional(),\n description: z.string().min(1).optional(),\n quoted_hours: z.coerce.number().nonnegative().optional(),\n sold_hours: z.coerce.number().positive().optional(),\n hourly_rate: z.coerce.number().nonnegative().optional(),\n cost_rate: z.coerce.number().nonnegative().optional(),\n sort_order: z.coerce.number().int().optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ quote_id, item_id, ...body }) =>\n runTool(logger, \"lkp_quote_item_update\", () =>\n client.patch<unknown>(\n `/api/v1/quotes/${quote_id}/items/${item_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_item_delete\",\n {\n title: \"Delete quote item (write)\",\n description:\n \"Remove a line item from a DRAFT quote. Blocked when the parent quote is not DRAFT. Always ask user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n item_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id, item_id }) =>\n runTool(logger, \"lkp_quote_item_delete\", async () => {\n await client.delete(`/api/v1/quotes/${quote_id}/items/${item_id}`);\n return { ok: true, deleted: true, quote_id, item_id };\n }),\n );\n\n // ── Payment milestones ────────────────────────────────────────────────\n server.registerTool(\n \"lkp_quote_milestones_replace\",\n {\n title: \"Replace all payment milestones (write)\",\n description:\n \"Replace the entire payment_milestones[] collection on a DRAFT quote atomically. due_days and due_date are mutually exclusive per milestone. percentages must sum to 100 (±0.01); amount is computed server-side — do not send it. Summarize the new schedule and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n milestones: z.array(PaymentMilestoneInput).min(1),\n },\n },\n async ({ quote_id, milestones }) =>\n runTool(logger, \"lkp_quote_milestones_replace\", () =>\n client.put<unknown>(\n `/api/v1/quotes/${quote_id}/payment-milestones`,\n { milestones },\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_milestone_add\",\n {\n title: \"Add payment milestone (write)\",\n description:\n \"Append a single payment milestone to a DRAFT quote (additive; does not enforce sum=100 — use replace for atomic rewrite). due_days and due_date are mutually exclusive. Summarize (description, percentage, due) and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n description: z.string().min(1),\n percentage: z.coerce.number().positive().max(100),\n due_days: z.coerce.number().int().nonnegative().optional(),\n due_date: z.string().optional(),\n notes: z.string().optional(),\n sort_order: z.coerce.number().int().optional(),\n },\n },\n async ({ quote_id, ...body }) =>\n runTool(logger, \"lkp_quote_milestone_add\", () =>\n client.post<unknown>(\n `/api/v1/quotes/${quote_id}/payment-milestones`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_milestone_update\",\n {\n title: \"Update payment milestone (write)\",\n description:\n \"Update whitelisted fields on a payment milestone of a DRAFT quote. due_days and due_date are mutually exclusive. Does NOT enforce sum=100 — caller is responsible. Summarize the diff and wait for user approval.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n milestone_id: z.coerce.number().int().positive(),\n description: z.string().min(1).optional(),\n percentage: z.coerce.number().positive().max(100).optional(),\n due_days: z.coerce.number().int().nonnegative().optional(),\n due_date: z.string().optional(),\n notes: z.string().optional(),\n sort_order: z.coerce.number().int().optional(),\n is_active: z.coerce.boolean().optional(),\n },\n },\n async ({ quote_id, milestone_id, ...body }) =>\n runTool(logger, \"lkp_quote_milestone_update\", () =>\n client.patch<unknown>(\n `/api/v1/quotes/${quote_id}/payment-milestones/${milestone_id}`,\n body,\n ),\n ),\n );\n\n server.registerTool(\n \"lkp_quote_milestone_delete\",\n {\n title: \"Delete payment milestone (write)\",\n description:\n \"Remove one payment milestone from a DRAFT quote. Always ask user approval before calling.\",\n inputSchema: {\n quote_id: z.coerce.number().int().positive(),\n milestone_id: z.coerce.number().int().positive(),\n },\n },\n async ({ quote_id, milestone_id }) =>\n runTool(logger, \"lkp_quote_milestone_delete\", async () => {\n await client.delete(\n `/api/v1/quotes/${quote_id}/payment-milestones/${milestone_id}`,\n );\n return { ok: true, deleted: true, quote_id, milestone_id };\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerClients(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_clients_list\",\n {\n title: \"List clients\",\n description:\n \"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.\",\n inputSchema: {\n status: z.string().optional(),\n parent_client_id: z.coerce.number().int().positive().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_clients_list\", () =>\n client.get<unknown>(\"/api/v1/clients\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_client_detail\",\n {\n title: \"Client detail\",\n description:\n \"Full client detail including all projects (active + inactive), all B1 codes, and stats.\",\n inputSchema: {\n client_id: z.coerce.number().int().positive(),\n },\n },\n async ({ client_id }) =>\n runTool(logger, \"lkp_client_detail\", () =>\n client.get<unknown>(`/api/v1/clients/${client_id}`),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerHelpdesk(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_helpdesk_tickets_list\",\n {\n title: \"List helpdesk tickets\",\n description:\n \"List helpdesk tickets with filters. Returns SLA status (response/resolution deadlines, breach flags), priority, category, tags. Use for triage and to find tickets exceeding SLA.\",\n inputSchema: {\n status_id: z.coerce.number().int().positive().optional(),\n priority: z.string().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n assigned_to: z.coerce.number().int().positive().optional(),\n category_id: z.coerce.number().int().positive().optional(),\n sla_breached: z.coerce.boolean().optional(),\n is_open: z.coerce.boolean().optional(),\n search: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_helpdesk_tickets_list\", () =>\n client.get<unknown>(\"/api/v1/helpdesk/tickets\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_helpdesk_summary\",\n {\n title: \"Helpdesk summary\",\n description:\n \"Helpdesk dashboard: counts by status and priority, top 10 clients by open tickets, SLA breaches, resolved today.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_helpdesk_summary\", () =>\n client.get<unknown>(\"/api/v1/helpdesk/summary\"),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerBilling(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_billing_milestones\",\n {\n title: \"List billing milestones (legacy)\",\n description:\n \"LEGACY — 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 → delivered → in_progress → invoiced → paid. Includes joined project and client.\",\n inputSchema: {\n status: z.string().optional(),\n project_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n due_from: z.string().optional(),\n due_to: z.string().optional(),\n include_cancelled: z.coerce.boolean().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(20),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_billing_milestones\", () =>\n client.get<unknown>(\"/api/v1/billing/milestones\", args),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerAlerts(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_alerts\",\n {\n title: \"Operational alerts\",\n description:\n \"Live operational alerts computed on the fly: consultants idle, projects finishing (≤30d), opportunities stale (≥7d), billing milestones upcoming (≤15d) or overdue, helpdesk SLA breaches. Use first thing in the morning and before any strategic decision.\",\n inputSchema: {\n severity: z.string().optional(),\n type: z.string().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_alerts\", () =>\n client.get<unknown>(\"/api/v1/alerts\", args),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerReports(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_ceo_weekly\",\n {\n title: \"CEO weekly report\",\n description:\n \"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.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_ceo_weekly\", () =>\n client.get<unknown>(\"/api/v1/reports/ceo-weekly\"),\n ),\n );\n\n server.registerTool(\n \"lkp_managers_in_trouble\",\n {\n title: \"Managers with overdue items\",\n description:\n \"List managers with overdue items in their projects. Returns two intentionally separate layers: (1) tasks_overdue (operational — 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á devendo?' or 'quais gerentes precisam de atenção?'. The two layers have different natures — do not sum them; present in separate sections.\",\n inputSchema: {\n include_tasks: z.coerce.boolean().optional(),\n include_financial: z.coerce.boolean().optional(),\n min_days_overdue: z.coerce.number().int().min(0).optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_managers_in_trouble\", () =>\n client.get<unknown>(\"/api/v1/reports/managers-in-trouble\", args),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { runTool } from \"./common.js\";\n\nexport function registerFinancial(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_financial_pending\",\n {\n title: \"List pending financial entities\",\n description:\n \"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 — the legacy tool stays for backward compatibility.\",\n inputSchema: {\n entity_type: z\n .enum([\"milestone\", \"measurement\", \"subscription_invoice\"])\n .optional(),\n project_id: z.coerce.number().int().positive().optional(),\n client_id: z.coerce.number().int().positive().optional(),\n status: z.string().optional(),\n due_from: z.string().optional(),\n due_to: z.string().optional(),\n page: z.coerce.number().int().positive().optional(),\n per_page: z.coerce\n .number()\n .int()\n .positive()\n .max(200)\n .default(50),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_financial_pending\", () =>\n client.get<unknown>(\"/api/v1/financial-reports/pending\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_aging_report\",\n {\n title: \"Aging report (receivables)\",\n description:\n \"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.\",\n inputSchema: {\n group_bucket: z.coerce.boolean().optional(),\n top_clients: z.coerce.number().int().positive().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_aging_report\", () =>\n client.get<unknown>(\"/api/v1/financial-reports/aging\", args),\n ),\n );\n\n server.registerTool(\n \"lkp_financial_overview\",\n {\n title: \"Executive financial overview\",\n description:\n \"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 — top 20 active classified projects with no billing in >60d. Single-call financial snapshot.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_financial_overview\", () =>\n client.get<unknown>(\"/api/v1/financial-reports/overview\"),\n ),\n );\n\n server.registerTool(\n \"lkp_margin_analysis\",\n {\n title: \"Margin analysis (project/client/specialty)\",\n description:\n \"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 — milestones and subscription_invoices are out of scope; for their gross numbers use lkp_financial_overview.\",\n inputSchema: {\n group_by: z\n .enum([\"project\", \"client\", \"specialty\"])\n .optional(),\n from: z.string().optional(),\n to: z.string().optional(),\n limit: z.coerce.number().int().positive().max(200).optional(),\n status: z.string().optional(),\n },\n },\n async (args) =>\n runTool(logger, \"lkp_margin_analysis\", () =>\n client.get<unknown>(\n \"/api/v1/financial-reports/margin-analysis\",\n args,\n ),\n ),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { runTool } from \"../common.js\";\n\ninterface Consultant {\n id: number;\n name: string;\n status?: string;\n specialties?: Array<string | { name?: string }>;\n available_since?: string | null;\n expected_release_date?: string | null;\n [k: string]: unknown;\n}\n\ninterface Opportunity {\n id: number;\n name: string;\n status: string;\n description?: string;\n expected_value?: number;\n weighted_value?: number;\n expected_close_date?: string;\n [k: string]: unknown;\n}\n\ninterface ResourceSummaryBody {\n available_now?: Consultant[];\n finishing_in_30_days?: Consultant[];\n partial_allocations?: Consultant[];\n}\n\nconst OPEN_STAGES = [\"QUALIFYING\", \"PROPOSAL\", \"SENT\", \"NEGOTIATION\"] as const;\n\nfunction toSpecNames(specialties: Consultant[\"specialties\"]): string[] {\n return (specialties ?? [])\n .map((s) => (typeof s === \"string\" ? s : s?.name ?? \"\"))\n .filter((s): s is string => s.length > 0);\n}\n\nexport function registerSkillMatch(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_skill_match\",\n {\n title: \"Match idle consultants to open opportunities\",\n description:\n \"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.\",\n inputSchema: {\n horizon_days: z.coerce.number().int().positive().default(30),\n min_match_percent: z.coerce.number().int().min(0).max(100).default(50),\n include_partial: z.coerce.boolean().default(false),\n },\n },\n async ({ horizon_days, min_match_percent, include_partial }) =>\n runTool(logger, \"lkp_skill_match\", async () => {\n const [resSummaryResp, ...oppResponses] = await Promise.all([\n client.get<{ data: ResourceSummaryBody }>(\n \"/api/v1/resources/summary\",\n ),\n ...OPEN_STAGES.map((status) =>\n client.get<{ data: Opportunity[] }>(\"/api/v1/opportunities\", {\n status,\n per_page: 100,\n }),\n ),\n ]);\n\n const now = Date.now();\n const candidates: Array<Consultant & { urgency: string }> = [];\n for (const c of resSummaryResp.data.available_now ?? []) {\n candidates.push({ ...c, urgency: \"idle\" });\n }\n for (const c of resSummaryResp.data.finishing_in_30_days ?? []) {\n if (c.expected_release_date) {\n const days = Math.ceil(\n (new Date(c.expected_release_date).getTime() - now) / 86400000,\n );\n if (days > horizon_days) continue;\n }\n candidates.push({ ...c, urgency: \"finishing\" });\n }\n if (include_partial) {\n for (const c of resSummaryResp.data.partial_allocations ?? []) {\n candidates.push({ ...c, urgency: \"partial\" });\n }\n }\n\n const opportunities: Opportunity[] = oppResponses.flatMap(\n (r) => r.data ?? [],\n );\n\n const matches: Array<Record<string, unknown>> = [];\n for (const c of candidates) {\n const specs = toSpecNames(c.specialties);\n if (specs.length === 0) continue;\n for (const o of opportunities) {\n const hay = `${o.name ?? \"\"} ${o.description ?? \"\"}`.toLowerCase();\n const matched = specs.filter((s) =>\n hay.includes(s.toLowerCase()),\n );\n if (matched.length === 0) continue;\n const score = Math.round((matched.length / specs.length) * 100);\n if (score < min_match_percent) continue;\n matches.push({\n consultant: {\n id: c.id,\n name: c.name,\n status: c.status ?? null,\n urgency: c.urgency,\n available_since: c.available_since ?? null,\n expected_release_date: c.expected_release_date ?? null,\n specialties: specs,\n },\n opportunity: {\n id: o.id,\n name: o.name,\n status: o.status,\n expected_value: o.expected_value ?? null,\n weighted_value: o.weighted_value ?? null,\n expected_close_date: o.expected_close_date ?? null,\n },\n match_score: score,\n matched_skills: matched,\n opportunity_skill_inference_source: \"description\",\n });\n }\n }\n\n matches.sort((a, b) => {\n const aw =\n (a.opportunity as { weighted_value: number | null })\n .weighted_value ?? 0;\n const bw =\n (b.opportunity as { weighted_value: number | null })\n .weighted_value ?? 0;\n return (\n (b.match_score as number) / 100 * bw -\n (a.match_score as number) / 100 * aw\n );\n });\n\n return {\n matches,\n meta: {\n horizon_days,\n min_match_percent,\n include_partial,\n candidates_considered: candidates.length,\n opportunities_considered: opportunities.length,\n },\n };\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { runToolText } from \"../common.js\";\n\ninterface Alert {\n type?: string;\n severity?: string;\n title?: string;\n message?: string;\n [k: string]: unknown;\n}\n\ninterface ResSummary {\n totals?: {\n total_resources?: number;\n available?: number;\n partially_allocated?: number;\n fully_allocated?: number;\n overloaded?: number;\n idle_percent?: number;\n [k: string]: unknown;\n };\n [k: string]: unknown;\n}\n\ninterface OppSummary {\n totals?: {\n open_count?: number;\n total_pipeline?: number;\n weighted_pipeline?: number;\n [k: string]: unknown;\n };\n stale_opportunities?: unknown[];\n [k: string]: unknown;\n}\n\ninterface CeoWeekly {\n week?: string;\n period?: { label?: string; from?: string; to?: string };\n operational_health?: {\n score?: number;\n classification?: string;\n factors?: Array<{\n name?: string;\n value?: number;\n target?: number;\n factor_score?: number;\n }>;\n };\n [k: string]: unknown;\n}\n\nfunction fmtBRL(v: unknown): string {\n const n = typeof v === \"number\" ? v : Number(v);\n if (!Number.isFinite(n)) return \"—\";\n return n.toLocaleString(\"pt-BR\", { style: \"currency\", currency: \"BRL\" });\n}\n\nfunction buildMarkdown(\n ceo: CeoWeekly | undefined,\n alerts: Alert[] | undefined,\n opp: OppSummary | undefined,\n res: ResSummary | undefined,\n): string {\n const score = ceo?.operational_health?.score ?? \"—\";\n const cls = ceo?.operational_health?.classification ?? \"—\";\n const period =\n ceo?.week ??\n ceo?.period?.label ??\n (ceo?.period?.from && ceo?.period?.to\n ? `${ceo.period.from} → ${ceo.period.to}`\n : \"semana atual\");\n\n const lines: string[] = [];\n lines.push(`# Brief Semanal — ${period}`);\n lines.push(\"\");\n lines.push(`## 🌡️ Saúde Operacional: ${score}/100 (${cls})`);\n lines.push(\"\");\n\n if (alerts && alerts.length > 0) {\n lines.push(\"## 🔴 Atenção imediata\");\n for (const a of alerts.slice(0, 10)) {\n const title = a.title ?? a.type ?? \"alerta\";\n const msg = a.message ?? \"\";\n lines.push(`- **${title}**: ${msg}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## 📊 Números da semana\");\n if (res?.totals) {\n const t = res.totals;\n lines.push(\n `- Consultores: ${t.total_resources ?? \"—\"} (disponíveis ${t.available ?? \"—\"}, parciais ${t.partially_allocated ?? \"—\"}, cheios ${t.fully_allocated ?? \"—\"}, sobrecarga ${t.overloaded ?? \"—\"})`,\n );\n lines.push(`- Ociosidade: ${t.idle_percent ?? \"—\"}%`);\n }\n if (opp?.totals) {\n const t = opp.totals;\n lines.push(\n `- Pipeline aberto: ${t.open_count ?? \"—\"} oportunidades · valor ${fmtBRL(t.total_pipeline)} · ponderado ${fmtBRL(t.weighted_pipeline)}`,\n );\n }\n if (opp?.stale_opportunities) {\n lines.push(`- Oportunidades stale (≥7d sem atividade): ${opp.stale_opportunities.length}`);\n }\n lines.push(\"\");\n\n lines.push(\"## 🎯 Ações recomendadas\");\n lines.push(\n \"- Revisar consultores ociosos e alocar em oportunidades compatíveis (use `lkp_skill_match`).\",\n );\n lines.push(\n \"- Contatar as oportunidades stale antes de quinta-feira.\",\n );\n lines.push(\n \"- Verificar milestones atrasados e acionar cobrança (`lkp_billing_milestones?status=invoiced&due_to=<hoje>`).\",\n );\n\n return lines.join(\"\\n\");\n}\n\nexport function registerWeeklyBrief(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_weekly_brief\",\n {\n title: \"Monday morning CEO briefing\",\n description:\n \"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.\",\n inputSchema: {},\n },\n async () =>\n runToolText(logger, \"lkp_weekly_brief\", async () => {\n const [ceo, alerts, opp, res] = await Promise.all([\n client.get<{ data: CeoWeekly }>(\"/api/v1/reports/ceo-weekly\"),\n client.get<{ data: Alert[] }>(\"/api/v1/alerts\", {\n severity: \"high\",\n }),\n client.get<{ data: OppSummary }>(\"/api/v1/opportunities/summary\"),\n client.get<{ data: ResSummary }>(\"/api/v1/resources/summary\"),\n ]);\n return buildMarkdown(ceo.data, alerts.data, opp.data, res.data);\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { runTool } from \"../common.js\";\n\ninterface Entry {\n id?: number;\n work_date: string;\n hours: number | string;\n is_approved?: boolean;\n is_billable?: boolean;\n task_id?: number | null;\n resource?: { id: number; name: string };\n overtime_type?: string | null;\n [k: string]: unknown;\n}\n\ninterface Finding {\n type: \"long_day\" | \"weekend_work\" | \"unapproved_aged\" | \"orphaned_entry\";\n severity: \"low\" | \"medium\" | \"high\";\n resource: { id: number; name: string };\n details: Record<string, unknown>;\n}\n\nasync function fetchAllTimesheets(\n client: LkpClient,\n resourceId: number,\n from: string,\n to: string,\n): Promise<Entry[]> {\n const all: Entry[] = [];\n for (let page = 1; page <= 5; page++) {\n const r = await client.get<{\n data: Entry[];\n meta?: { last_page?: number };\n }>(`/api/v1/resources/${resourceId}/timesheets`, {\n from,\n to,\n page,\n per_page: 200,\n });\n const batch = r.data ?? [];\n all.push(...batch);\n const last = r.meta?.last_page;\n if ((last && page >= last) || batch.length < 200) break;\n }\n return all;\n}\n\nexport async function mapLimit<T, R>(\n items: T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let cursor = 0;\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (true) {\n const i = cursor++;\n if (i >= items.length) return;\n results[i] = await fn(items[i]!);\n }\n },\n );\n await Promise.all(workers);\n return results;\n}\n\nexport function detectAnomalies(\n entries: Entry[],\n resourceId: number,\n resourceName: string,\n unapprovedDaysThreshold: number,\n today: Date,\n): Finding[] {\n const findings: Finding[] = [];\n\n const byDate = new Map<string, { total: number; count: number }>();\n for (const e of entries) {\n const h = typeof e.hours === \"number\" ? e.hours : Number(e.hours);\n if (!Number.isFinite(h)) continue;\n const b = byDate.get(e.work_date) ?? { total: 0, count: 0 };\n b.total += h;\n b.count += 1;\n byDate.set(e.work_date, b);\n }\n for (const [date, b] of byDate) {\n if (b.total > 10) {\n findings.push({\n type: \"long_day\",\n severity: b.total > 13 ? \"high\" : \"medium\",\n resource: { id: resourceId, name: resourceName },\n details: {\n work_date: date,\n hours: Number(b.total.toFixed(2)),\n entries_count: b.count,\n },\n });\n }\n }\n\n for (const e of entries) {\n const d = new Date(`${e.work_date}T00:00:00Z`);\n const dow = d.getUTCDay();\n if (dow === 0 || dow === 6) {\n findings.push({\n type: \"weekend_work\",\n severity: \"low\",\n resource: { id: resourceId, name: resourceName },\n details: {\n work_date: e.work_date,\n hours: typeof e.hours === \"number\" ? e.hours : Number(e.hours),\n day: dow === 0 ? \"Sunday\" : \"Saturday\",\n },\n });\n }\n }\n\n for (const e of entries) {\n if (e.is_approved === false) {\n const d = new Date(`${e.work_date}T00:00:00Z`);\n const ageDays = Math.floor(\n (today.getTime() - d.getTime()) / 86_400_000,\n );\n if (ageDays > unapprovedDaysThreshold) {\n findings.push({\n type: \"unapproved_aged\",\n severity: ageDays > unapprovedDaysThreshold * 2 ? \"high\" : \"medium\",\n resource: { id: resourceId, name: resourceName },\n details: {\n work_date: e.work_date,\n age_days: ageDays,\n entry_id: e.id ?? null,\n },\n });\n }\n }\n }\n\n for (const e of entries) {\n if (e.task_id === null || e.task_id === undefined) {\n findings.push({\n type: \"orphaned_entry\",\n severity: \"low\",\n resource: { id: resourceId, name: resourceName },\n details: { work_date: e.work_date, entry_id: e.id ?? null },\n });\n }\n }\n\n return findings;\n}\n\nexport function registerTimesheetAnomalies(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n server.registerTool(\n \"lkp_timesheet_anomalies\",\n {\n title: \"Detect timesheet anomalies\",\n description:\n \"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.\",\n inputSchema: {\n from: z.string(),\n to: z.string(),\n resource_id: z.coerce.number().int().positive().optional(),\n unapproved_days_threshold: z.coerce\n .number()\n .int()\n .positive()\n .default(15),\n },\n },\n async ({ from, to, resource_id, unapproved_days_threshold }) =>\n runTool(logger, \"lkp_timesheet_anomalies\", async () => {\n const today = new Date();\n const findings: Finding[] = [];\n const scanned: Array<{ id: number; name: string }> = [];\n let scope: \"resource\" | \"team\";\n\n if (resource_id !== undefined) {\n scope = \"resource\";\n const entries = await fetchAllTimesheets(\n client,\n resource_id,\n from,\n to,\n );\n const name = entries[0]?.resource?.name ?? `#${resource_id}`;\n scanned.push({ id: resource_id, name });\n findings.push(\n ...detectAnomalies(\n entries,\n resource_id,\n name,\n unapproved_days_threshold,\n today,\n ),\n );\n } else {\n scope = \"team\";\n const resList = await client.get<{\n data: Array<{ id: number; name: string; status?: string }>;\n }>(\"/api/v1/resources\", { per_page: 100 });\n const active = (resList.data ?? []).filter(\n (r) => r.status !== \"inactive\",\n );\n await mapLimit(active, 5, async (r) => {\n try {\n const entries = await fetchAllTimesheets(\n client,\n r.id,\n from,\n to,\n );\n scanned.push({ id: r.id, name: r.name });\n findings.push(\n ...detectAnomalies(\n entries,\n r.id,\n r.name,\n unapproved_days_threshold,\n today,\n ),\n );\n } catch (e) {\n logger.warn(\n { resource_id: r.id, err: (e as Error).message },\n \"timesheets_fetch_failed\",\n );\n }\n });\n }\n\n const byType: Record<string, number> = {};\n for (const f of findings) {\n byType[f.type] = (byType[f.type] ?? 0) + 1;\n }\n\n return {\n period: { from, to },\n scope,\n resources_scanned: scanned.length,\n findings,\n summary: { total_findings: findings.length, by_type: byType },\n };\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../../http-client.js\";\nimport type { Logger } from \"../../logger.js\";\nimport { registerSkillMatch } from \"./skill-match.js\";\nimport { registerWeeklyBrief } from \"./weekly-brief.js\";\nimport { registerTimesheetAnomalies } from \"./timesheet-anomalies.js\";\n\nexport function registerComposites(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n registerSkillMatch(server, client, logger);\n registerWeeklyBrief(server, client, logger);\n registerTimesheetAnomalies(server, client, logger);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LkpClient } from \"../http-client.js\";\nimport type { Logger } from \"../logger.js\";\nimport { registerPing } from \"./ping.js\";\nimport { registerResources } from \"./resources.js\";\nimport { registerProjects } from \"./projects.js\";\nimport { registerOpportunities } from \"./opportunities.js\";\nimport { registerQuotes } from \"./quotes.js\";\nimport { registerClients } from \"./clients.js\";\nimport { registerHelpdesk } from \"./helpdesk.js\";\nimport { registerBilling } from \"./billing.js\";\nimport { registerAlerts } from \"./alerts.js\";\nimport { registerReports } from \"./reports.js\";\nimport { registerFinancial } from \"./financial.js\";\nimport { registerComposites } from \"./composite/index.js\";\n\nexport function registerAllTools(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\n registerPing(server, client, logger);\n registerResources(server, client, logger);\n registerProjects(server, client, logger);\n registerOpportunities(server, client, logger);\n registerQuotes(server, client, logger);\n registerClients(server, client, logger);\n registerHelpdesk(server, client, logger);\n registerBilling(server, client, logger);\n registerAlerts(server, client, logger);\n registerReports(server, client, logger);\n registerFinancial(server, client, logger);\n registerComposites(server, client, logger);\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Use the lkp_weekly_brief tool to generate the baseline numbers.\nThen enrich with:\n- Top 3 risks to call out now\n- Top 3 opportunities to act on this week\n- One question the CEO should ask at the leadership meeting\n\nOutput in Portuguese, markdown, max 500 words.`;\n\nexport function registerWeeklyBriefPrompt(server: McpServer): void {\n server.registerPrompt(\n \"weekly-brief\",\n {\n title: \"Weekly Brief\",\n description: \"Produce the Monday-morning briefing for the CEO.\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Check lkp_alerts for high-severity items. Then check lkp_helpdesk_summary for SLA breaches and lkp_opportunities_summary for opportunities closing in the next 7 days.\n\nRespond with a short bulleted list in Portuguese, grouped by area:\n1. 🔴 Urgente (alerts)\n2. 🎫 Helpdesk\n3. 💼 Vendas\n\nIf nothing urgent, say so explicitly.`;\n\nexport function registerMorningStandupPrompt(server: McpServer): void {\n server.registerPrompt(\n \"morning-standup\",\n {\n title: \"Morning Standup\",\n description: \"Quick morning check — what's burning today?\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nfunction buildText(opportunityRef: string): string {\n return `The user wants to update opportunity: ${opportunityRef}.\n\n1. If the ref is a name, use lkp_opportunities_list with the search filter to find it.\n2. Use lkp_opportunities_list (or a detail call if available) to fetch the current state before acting.\n3. Ask the user:\n - What happened? (→ will become the activity subject + description via lkp_opportunity_activity_add)\n - Did the stage change? (→ lkp_opportunity_update with new status)\n - Should we schedule a follow-up? (→ follow_up_date on the activity)\n\nBefore calling any write tool, SUMMARIZE the change (field → old value → new value) and wait for explicit \"sim\" / \"confirma\" / \"ok\" from the user. Do NOT assume consent.\n\nAfter writing, confirm using the returned payload and suggest one concrete next step.`;\n}\n\nexport function registerOpportunityActionPrompt(server: McpServer): void {\n server.registerPrompt(\n \"opportunity-action\",\n {\n title: \"Opportunity Action\",\n description: \"Log an activity and/or update stage for an opportunity.\",\n argsSchema: {\n opportunity_ref: z.string().describe(\"Opportunity id or name\"),\n },\n },\n ({ opportunity_ref }) => ({\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: buildText(opportunity_ref) },\n },\n ],\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nfunction buildText(quoteRef: string): string {\n return `The user wants to act on quote: ${quoteRef}.\n\n1. Resolve the ref:\n - If it looks like a code (e.g. QT-2026-0007), use lkp_quotes_list with search to find the id.\n - If it looks like a numeric id, go straight to lkp_quote_detail.\n2. Run lkp_quote_detail to load the current state — version, status, totals, items[], payment_milestones[].\n3. Infer the intent from the user's phrasing and the current status:\n - DRAFT → offer: edit fields (lkp_quote_update), add/update/delete item (lkp_quote_item_*), add/update/delete milestone (lkp_quote_milestone_*), replace full milestone schedule (lkp_quote_milestones_replace), send (lkp_quote_send), archive (lkp_quote_archive).\n - SENT → offer: accept (lkp_quote_accept), reject (lkp_quote_reject), new version to revise (lkp_quote_new_version), duplicate to another opportunity (lkp_quote_duplicate).\n - ACCEPTED / REJECTED / EXPIRED / SUPERSEDED → read-only; offer duplicate or new version only.\n4. Before calling any write tool, SUMMARIZE the change (field/line → old → new, or the state transition with its downstream effects) and wait for explicit \"sim\" / \"confirma\" / \"ok\" from the user. Do NOT assume consent.\n\nAfter writing, confirm using the returned payload and suggest one concrete next step.\n\nITEM RULES (when adding or updating items):\n- Call lkp_specialties_list once to resolve specialty names → specialty_id. Do NOT hardcode IDs.\n- skill_level (Júnior | Pleno | Sênior | Especialista) is REQUIRED per item — it is not derivable from specialty_id.\n- hourly_rate is optional: omit it to let the backend resolve via the client's price_list for (specialty_id, skill_level). Pass it explicitly only to override the rate card (e.g. promotional pricing).\n- If the backend returns rate_not_found_in_price_list, surface the error as-is — do not retry with a different skill_level. The client's price_list needs to be updated in LKPGestão.\n\nHARD RULES (do not violate, even if the user seems to agree):\n- ACCEPT: never call lkp_quote_accept without explicit, unambiguous approval referencing the quote code (e.g. \"sim, aceitar QT-2026-0007\"). Accept cascades sibling quotes to REJECTED and moves the opportunity to WON — it is commercially binding.\n- REJECT: always ask the user for the rejection motive before calling lkp_quote_reject. Reason is mandatory (min 1 char, max 200).\n- ARCHIVE: only offer lkp_quote_archive when status = DRAFT. For SENT/ACCEPTED/etc. use new-version/supersede flow instead.\n- NEVER attempt DRAFT → ACCEPTED directly. The quote must be SENT first (lkp_quote_send), then accepted.`;\n}\n\nexport function registerQuoteActionPrompt(server: McpServer): void {\n server.registerPrompt(\n \"quote-action\",\n {\n title: \"Quote Action\",\n description:\n \"Drive a quote through its lifecycle — edit, send, accept, reject, version.\",\n argsSchema: {\n quote_ref: z\n .string()\n .describe(\"Quote id or code (e.g. QT-2026-0007)\"),\n },\n },\n ({ quote_ref }) => ({\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: buildText(quote_ref) },\n },\n ],\n }),\n );\n}\n","import { z } from \"zod\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nfunction buildText(consultantRef: string): string {\n return `Investigate consultant ${consultantRef}:\n\n1. lkp_resources_list with the search filter → confirm identity and current allocation status.\n2. lkp_resource_history over the last 6 months → project timeline + idle gaps.\n3. lkp_resource_timesheets over the last 30 days → actual work pattern.\n4. If the consultant is available or soon to be released, run lkp_skill_match and filter for this consultant.\n\nProduce a structured report in Portuguese with:\n- **Status atual** (uma linha)\n- **Últimos 6 meses** (timeline)\n- **Padrão de trabalho últimas 4 semanas** (média horas/dia, dias sem apontamento, fins de semana, entradas não aprovadas)\n- **Oportunidades compatíveis** (se aplicável)\n- **Recomendação** (uma única ação concreta)`;\n}\n\nexport function registerConsultantInvestigationPrompt(\n server: McpServer,\n): void {\n server.registerPrompt(\n \"consultant-investigation\",\n {\n title: \"Consultant Investigation\",\n description:\n \"Deep-dive on one consultant — where they are, what they've done, what's next.\",\n argsSchema: {\n consultant_ref: z.string().describe(\"Consultant id or name\"),\n },\n },\n ({ consultant_ref }) => ({\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text: buildText(consultant_ref) },\n },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Chame lkp_managers_in_trouble para obter a lista atual. Resposta em português, markdown, dividida em DUAS SEÇÕES separadas:\n\n## 📋 Atraso operacional (tasks)\nUm bullet por gerente com \\`tasks_overdue\\` preenchido, citando:\n- Nome + total de tasks atrasadas + projetos afetados\n- A mais antiga (quantos dias)\n\n## 💰 Atraso financeiro (faturamento)\nUm bullet por gerente com \\`financial_overdue\\` preenchido, citando:\n- Nome + contagem + valor total em R$\n- Breakdown por tipo se houver mais de um (milestone / measurement / invoice)\n- A mais antiga (quantos dias)\n\n## 🎯 Ação sugerida\nUM bullet só — o caso mais crítico (maior days_since_oldest combinado com maior valor).\n\nSe nenhuma das camadas tiver resultados, diga \"Nada atrasado hoje\".`;\n\nexport function registerManagersInTroublePrompt(server: McpServer): void {\n server.registerPrompt(\n \"managers-in-trouble\",\n {\n title: \"Managers in trouble\",\n description:\n \"Gerentes com atrasos — quem precisa de atenção agora?\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nconst PROMPT = `Run a full pipeline review:\n\n1. lkp_opportunities_summary → funnel + stale.\n2. For each stale opportunity, fetch context via lkp_opportunities_list (search by name or id).\n3. lkp_skill_match → identify opportunities that could absorb idle consultants.\n4. Compute:\n - Weighted pipeline vs. the health factors in lkp_ceo_weekly.\n - Stale count trend (from last_activity_at distribution).\n - Coverage: open opportunities' weighted value ÷ monthly idle cost (lkp_resources_summary).\n\nOutput Portuguese markdown. For every red indicator, propose a concrete action — NOT advice — naming the exact tool and arguments the user can approve (\"chamar lkp_opportunity_activity_add com …\").`;\n\nexport function registerPipelineHealthCheckPrompt(server: McpServer): void {\n server.registerPrompt(\n \"pipeline-health-check\",\n {\n title: \"Pipeline Health Check\",\n description: \"Comprehensive CRM review with concrete recommendations.\",\n },\n () => ({\n messages: [\n { role: \"user\", content: { type: \"text\", text: PROMPT } },\n ],\n }),\n );\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { registerWeeklyBriefPrompt } from \"./weekly-brief.js\";\nimport { registerMorningStandupPrompt } from \"./morning-standup.js\";\nimport { registerOpportunityActionPrompt } from \"./opportunity-action.js\";\nimport { registerQuoteActionPrompt } from \"./quote-action.js\";\nimport { registerConsultantInvestigationPrompt } from \"./consultant-investigation.js\";\nimport { registerManagersInTroublePrompt } from \"./managers-in-trouble.js\";\nimport { registerPipelineHealthCheckPrompt } from \"./pipeline-health-check.js\";\n\nexport function registerAllPrompts(server: McpServer): void {\n registerWeeklyBriefPrompt(server);\n registerMorningStandupPrompt(server);\n registerOpportunityActionPrompt(server);\n registerQuoteActionPrompt(server);\n registerConsultantInvestigationPrompt(server);\n registerManagersInTroublePrompt(server);\n registerPipelineHealthCheckPrompt(server);\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACDrC,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAEX,IAAM,cAAc;AACpB,IAAM,iBAAiB;AAE9B,IAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,kBAAkB,EACf,OAAO,EACP,IAAI,qBAAqB,EACzB,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,GAAG;AAAA,IACvC,SAAS;AAAA,EACX,CAAC,EACA,UAAU,CAAC,MAAM,EAAE,QAAQ,QAAQ,EAAE,CA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