lkpgestao-mcp 0.4.0 → 0.5.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 +149 -18
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -995,8 +995,8 @@ function registerBilling(server, client, logger) {
|
|
|
995
995
|
server.registerTool(
|
|
996
996
|
"lkp_billing_milestones",
|
|
997
997
|
{
|
|
998
|
-
title: "List billing milestones",
|
|
999
|
-
description: "
|
|
998
|
+
title: "List billing milestones (legacy)",
|
|
999
|
+
description: "LEGACY \u2014 returns only project_billing_milestones (one of 3 financial entity types). For a unified view (milestones + measurements + subscription_invoices) use lkp_financial_pending instead. Status lifecycle: pending \u2192 delivered \u2192 in_progress \u2192 invoiced \u2192 paid. Includes joined project and client.",
|
|
1000
1000
|
inputSchema: {
|
|
1001
1001
|
status: z8.string().optional(),
|
|
1002
1002
|
project_id: z8.coerce.number().int().positive().optional(),
|
|
@@ -1038,12 +1038,13 @@ function registerAlerts(server, client, logger) {
|
|
|
1038
1038
|
}
|
|
1039
1039
|
|
|
1040
1040
|
// src/tools/reports.ts
|
|
1041
|
+
import { z as z10 } from "zod";
|
|
1041
1042
|
function registerReports(server, client, logger) {
|
|
1042
1043
|
server.registerTool(
|
|
1043
1044
|
"lkp_ceo_weekly",
|
|
1044
1045
|
{
|
|
1045
1046
|
title: "CEO weekly report",
|
|
1046
|
-
description: "Consolidated weekly report for the CEO. Includes operational health score (0-100, classified healthy/attention/critical) across 4 factors, plus sections
|
|
1047
|
+
description: "Consolidated weekly report for the CEO. Includes operational health score (0-100, classified healthy/attention/critical) across 4 factors, plus sections: resources, projects, pipeline, helpdesk, financial (MRR, gross revenue 30d, projected revenue 30d, overdue consolidated, billing gap), and high-severity alerts. Single call for Monday morning. For financial drill-down use lkp_financial_overview or lkp_aging_report.",
|
|
1047
1048
|
inputSchema: {}
|
|
1048
1049
|
},
|
|
1049
1050
|
async () => runTool(
|
|
@@ -1052,10 +1053,105 @@ function registerReports(server, client, logger) {
|
|
|
1052
1053
|
() => client.get("/api/v1/reports/ceo-weekly")
|
|
1053
1054
|
)
|
|
1054
1055
|
);
|
|
1056
|
+
server.registerTool(
|
|
1057
|
+
"lkp_managers_in_trouble",
|
|
1058
|
+
{
|
|
1059
|
+
title: "Managers with overdue items",
|
|
1060
|
+
description: "List managers with overdue items in their projects. Returns two intentionally separate layers: (1) tasks_overdue (operational \u2014 tasks past due_date still not complete) and (2) financial_overdue (milestones / measurements / subscription_invoices past due). Ordered by oldest overdue first. Use when asked 'quem est\xE1 devendo?' or 'quais gerentes precisam de aten\xE7\xE3o?'. The two layers have different natures \u2014 do not sum them; present in separate sections.",
|
|
1061
|
+
inputSchema: {
|
|
1062
|
+
include_tasks: z10.coerce.boolean().optional(),
|
|
1063
|
+
include_financial: z10.coerce.boolean().optional(),
|
|
1064
|
+
min_days_overdue: z10.coerce.number().int().min(0).optional()
|
|
1065
|
+
}
|
|
1066
|
+
},
|
|
1067
|
+
async (args) => runTool(
|
|
1068
|
+
logger,
|
|
1069
|
+
"lkp_managers_in_trouble",
|
|
1070
|
+
() => client.get("/api/v1/reports/managers-in-trouble", args)
|
|
1071
|
+
)
|
|
1072
|
+
);
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// src/tools/financial.ts
|
|
1076
|
+
import { z as z11 } from "zod";
|
|
1077
|
+
function registerFinancial(server, client, logger) {
|
|
1078
|
+
server.registerTool(
|
|
1079
|
+
"lkp_financial_pending",
|
|
1080
|
+
{
|
|
1081
|
+
title: "List pending financial entities",
|
|
1082
|
+
description: "List all pending financial entities (milestones + measurements + subscription invoices) in a unified paginated view. Each row is enriched with is_overdue. Replaces lkp_billing_milestones for unified views \u2014 the legacy tool stays for backward compatibility.",
|
|
1083
|
+
inputSchema: {
|
|
1084
|
+
entity_type: z11.enum(["milestone", "measurement", "subscription_invoice"]).optional(),
|
|
1085
|
+
project_id: z11.coerce.number().int().positive().optional(),
|
|
1086
|
+
client_id: z11.coerce.number().int().positive().optional(),
|
|
1087
|
+
status: z11.string().optional(),
|
|
1088
|
+
due_from: z11.string().optional(),
|
|
1089
|
+
due_to: z11.string().optional(),
|
|
1090
|
+
page: z11.coerce.number().int().positive().optional(),
|
|
1091
|
+
per_page: z11.coerce.number().int().positive().max(200).default(50)
|
|
1092
|
+
}
|
|
1093
|
+
},
|
|
1094
|
+
async (args) => runTool(
|
|
1095
|
+
logger,
|
|
1096
|
+
"lkp_financial_pending",
|
|
1097
|
+
() => client.get("/api/v1/financial-reports/pending", args)
|
|
1098
|
+
)
|
|
1099
|
+
);
|
|
1100
|
+
server.registerTool(
|
|
1101
|
+
"lkp_aging_report",
|
|
1102
|
+
{
|
|
1103
|
+
title: "Aging report (receivables)",
|
|
1104
|
+
description: "Aging report over overdue financial items. Returns (1) buckets 0-30 / 31-60 / 61-90 / 90+ by entity_type with count + amount, (2) overdue totals (count, amount, avg_days, oldest_days), (3) DSO (days sales outstanding) over last 90d for measurements and subscription_invoices, (4) top clients-at-risk ranked by overdue amount.",
|
|
1105
|
+
inputSchema: {
|
|
1106
|
+
group_bucket: z11.coerce.boolean().optional(),
|
|
1107
|
+
top_clients: z11.coerce.number().int().positive().optional()
|
|
1108
|
+
}
|
|
1109
|
+
},
|
|
1110
|
+
async (args) => runTool(
|
|
1111
|
+
logger,
|
|
1112
|
+
"lkp_aging_report",
|
|
1113
|
+
() => client.get("/api/v1/financial-reports/aging", args)
|
|
1114
|
+
)
|
|
1115
|
+
);
|
|
1116
|
+
server.registerTool(
|
|
1117
|
+
"lkp_financial_overview",
|
|
1118
|
+
{
|
|
1119
|
+
title: "Executive financial overview",
|
|
1120
|
+
description: "Executive financial dashboard: MRR (sum of active subscription monthly_amount) + active_subscriptions count; churn last 90d (subscriptions ended + mrr_lost); gross revenue last 30d split by entity type; projected revenue next 30/60/90d (pending items with due_date in range); billing gap \u2014 top 20 active classified projects with no billing in >60d. Single-call financial snapshot.",
|
|
1121
|
+
inputSchema: {}
|
|
1122
|
+
},
|
|
1123
|
+
async () => runTool(
|
|
1124
|
+
logger,
|
|
1125
|
+
"lkp_financial_overview",
|
|
1126
|
+
() => client.get("/api/v1/financial-reports/overview")
|
|
1127
|
+
)
|
|
1128
|
+
);
|
|
1129
|
+
server.registerTool(
|
|
1130
|
+
"lkp_margin_analysis",
|
|
1131
|
+
{
|
|
1132
|
+
title: "Margin analysis (project/client/specialty)",
|
|
1133
|
+
description: "Aggregate margin by project, client, or specialty using the per_user_breakdown JSON persisted in each measurement. Returns top N rows with gross_amount, cost_amount, margin_amount, margin_percent, measurement_count. Default window: last 180 days. Default status: paid,invoiced,sent,approved. Only measurements carry line-level cost \u2014 milestones and subscription_invoices are out of scope; for their gross numbers use lkp_financial_overview.",
|
|
1134
|
+
inputSchema: {
|
|
1135
|
+
group_by: z11.enum(["project", "client", "specialty"]).optional(),
|
|
1136
|
+
from: z11.string().optional(),
|
|
1137
|
+
to: z11.string().optional(),
|
|
1138
|
+
limit: z11.coerce.number().int().positive().max(200).optional(),
|
|
1139
|
+
status: z11.string().optional()
|
|
1140
|
+
}
|
|
1141
|
+
},
|
|
1142
|
+
async (args) => runTool(
|
|
1143
|
+
logger,
|
|
1144
|
+
"lkp_margin_analysis",
|
|
1145
|
+
() => client.get(
|
|
1146
|
+
"/api/v1/financial-reports/margin-analysis",
|
|
1147
|
+
args
|
|
1148
|
+
)
|
|
1149
|
+
)
|
|
1150
|
+
);
|
|
1055
1151
|
}
|
|
1056
1152
|
|
|
1057
1153
|
// src/tools/composite/skill-match.ts
|
|
1058
|
-
import { z as
|
|
1154
|
+
import { z as z12 } from "zod";
|
|
1059
1155
|
var OPEN_STAGES = ["QUALIFYING", "PROPOSAL", "SENT", "NEGOTIATION"];
|
|
1060
1156
|
function toSpecNames(specialties) {
|
|
1061
1157
|
return (specialties ?? []).map((s) => typeof s === "string" ? s : s?.name ?? "").filter((s) => s.length > 0);
|
|
@@ -1067,9 +1163,9 @@ function registerSkillMatch(server, client, logger) {
|
|
|
1067
1163
|
title: "Match idle consultants to open opportunities",
|
|
1068
1164
|
description: "Match idle or soon-to-finish consultants with open opportunities by skill compatibility. Returns a ranked list of (consultant, opportunity) pairs with a match score. Skill inference for v1 is based on substring match of consultant specialties against the opportunity name and description. Critical for the 'queima de caixa' problem.",
|
|
1069
1165
|
inputSchema: {
|
|
1070
|
-
horizon_days:
|
|
1071
|
-
min_match_percent:
|
|
1072
|
-
include_partial:
|
|
1166
|
+
horizon_days: z12.coerce.number().int().positive().default(30),
|
|
1167
|
+
min_match_percent: z12.coerce.number().int().min(0).max(100).default(50),
|
|
1168
|
+
include_partial: z12.coerce.boolean().default(false)
|
|
1073
1169
|
}
|
|
1074
1170
|
},
|
|
1075
1171
|
async ({ horizon_days, min_match_percent, include_partial }) => runTool(logger, "lkp_skill_match", async () => {
|
|
@@ -1238,7 +1334,7 @@ function registerWeeklyBrief(server, client, logger) {
|
|
|
1238
1334
|
}
|
|
1239
1335
|
|
|
1240
1336
|
// src/tools/composite/timesheet-anomalies.ts
|
|
1241
|
-
import { z as
|
|
1337
|
+
import { z as z13 } from "zod";
|
|
1242
1338
|
async function fetchAllTimesheets(client, resourceId, from, to) {
|
|
1243
1339
|
const all = [];
|
|
1244
1340
|
for (let page = 1; page <= 5; page++) {
|
|
@@ -1351,10 +1447,10 @@ function registerTimesheetAnomalies(server, client, logger) {
|
|
|
1351
1447
|
title: "Detect timesheet anomalies",
|
|
1352
1448
|
description: "Detect suspicious timesheet patterns for one consultant or across the team over a date range. Flags: days with >10h, weekend work, unapproved entries older than N days, orphaned entries (no task link). Use before closing a payroll period or when investigating a specific consultant.",
|
|
1353
1449
|
inputSchema: {
|
|
1354
|
-
from:
|
|
1355
|
-
to:
|
|
1356
|
-
resource_id:
|
|
1357
|
-
unapproved_days_threshold:
|
|
1450
|
+
from: z13.string(),
|
|
1451
|
+
to: z13.string(),
|
|
1452
|
+
resource_id: z13.coerce.number().int().positive().optional(),
|
|
1453
|
+
unapproved_days_threshold: z13.coerce.number().int().positive().default(15)
|
|
1358
1454
|
}
|
|
1359
1455
|
},
|
|
1360
1456
|
async ({ from, to, resource_id, unapproved_days_threshold }) => runTool(logger, "lkp_timesheet_anomalies", async () => {
|
|
@@ -1446,6 +1542,7 @@ function registerAllTools(server, client, logger) {
|
|
|
1446
1542
|
registerBilling(server, client, logger);
|
|
1447
1543
|
registerAlerts(server, client, logger);
|
|
1448
1544
|
registerReports(server, client, logger);
|
|
1545
|
+
registerFinancial(server, client, logger);
|
|
1449
1546
|
registerComposites(server, client, logger);
|
|
1450
1547
|
}
|
|
1451
1548
|
|
|
@@ -1497,7 +1594,7 @@ function registerMorningStandupPrompt(server) {
|
|
|
1497
1594
|
}
|
|
1498
1595
|
|
|
1499
1596
|
// src/prompts/opportunity-action.ts
|
|
1500
|
-
import { z as
|
|
1597
|
+
import { z as z14 } from "zod";
|
|
1501
1598
|
function buildText(opportunityRef) {
|
|
1502
1599
|
return `The user wants to update opportunity: ${opportunityRef}.
|
|
1503
1600
|
|
|
@@ -1519,7 +1616,7 @@ function registerOpportunityActionPrompt(server) {
|
|
|
1519
1616
|
title: "Opportunity Action",
|
|
1520
1617
|
description: "Log an activity and/or update stage for an opportunity.",
|
|
1521
1618
|
argsSchema: {
|
|
1522
|
-
opportunity_ref:
|
|
1619
|
+
opportunity_ref: z14.string().describe("Opportunity id or name")
|
|
1523
1620
|
}
|
|
1524
1621
|
},
|
|
1525
1622
|
({ opportunity_ref }) => ({
|
|
@@ -1534,7 +1631,7 @@ function registerOpportunityActionPrompt(server) {
|
|
|
1534
1631
|
}
|
|
1535
1632
|
|
|
1536
1633
|
// src/prompts/consultant-investigation.ts
|
|
1537
|
-
import { z as
|
|
1634
|
+
import { z as z15 } from "zod";
|
|
1538
1635
|
function buildText2(consultantRef) {
|
|
1539
1636
|
return `Investigate consultant ${consultantRef}:
|
|
1540
1637
|
|
|
@@ -1557,7 +1654,7 @@ function registerConsultantInvestigationPrompt(server) {
|
|
|
1557
1654
|
title: "Consultant Investigation",
|
|
1558
1655
|
description: "Deep-dive on one consultant \u2014 where they are, what they've done, what's next.",
|
|
1559
1656
|
argsSchema: {
|
|
1560
|
-
consultant_ref:
|
|
1657
|
+
consultant_ref: z15.string().describe("Consultant id or name")
|
|
1561
1658
|
}
|
|
1562
1659
|
},
|
|
1563
1660
|
({ consultant_ref }) => ({
|
|
@@ -1571,8 +1668,41 @@ function registerConsultantInvestigationPrompt(server) {
|
|
|
1571
1668
|
);
|
|
1572
1669
|
}
|
|
1573
1670
|
|
|
1671
|
+
// src/prompts/managers-in-trouble.ts
|
|
1672
|
+
var PROMPT3 = `Chame lkp_managers_in_trouble para obter a lista atual. Resposta em portugu\xEAs, markdown, dividida em DUAS SE\xC7\xD5ES separadas:
|
|
1673
|
+
|
|
1674
|
+
## \u{1F4CB} Atraso operacional (tasks)
|
|
1675
|
+
Um bullet por gerente com \`tasks_overdue\` preenchido, citando:
|
|
1676
|
+
- Nome + total de tasks atrasadas + projetos afetados
|
|
1677
|
+
- A mais antiga (quantos dias)
|
|
1678
|
+
|
|
1679
|
+
## \u{1F4B0} Atraso financeiro (faturamento)
|
|
1680
|
+
Um bullet por gerente com \`financial_overdue\` preenchido, citando:
|
|
1681
|
+
- Nome + contagem + valor total em R$
|
|
1682
|
+
- Breakdown por tipo se houver mais de um (milestone / measurement / invoice)
|
|
1683
|
+
- A mais antiga (quantos dias)
|
|
1684
|
+
|
|
1685
|
+
## \u{1F3AF} A\xE7\xE3o sugerida
|
|
1686
|
+
UM bullet s\xF3 \u2014 o caso mais cr\xEDtico (maior days_since_oldest combinado com maior valor).
|
|
1687
|
+
|
|
1688
|
+
Se nenhuma das camadas tiver resultados, diga "Nada atrasado hoje".`;
|
|
1689
|
+
function registerManagersInTroublePrompt(server) {
|
|
1690
|
+
server.registerPrompt(
|
|
1691
|
+
"managers-in-trouble",
|
|
1692
|
+
{
|
|
1693
|
+
title: "Managers in trouble",
|
|
1694
|
+
description: "Gerentes com atrasos \u2014 quem precisa de aten\xE7\xE3o agora?"
|
|
1695
|
+
},
|
|
1696
|
+
() => ({
|
|
1697
|
+
messages: [
|
|
1698
|
+
{ role: "user", content: { type: "text", text: PROMPT3 } }
|
|
1699
|
+
]
|
|
1700
|
+
})
|
|
1701
|
+
);
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1574
1704
|
// src/prompts/pipeline-health-check.ts
|
|
1575
|
-
var
|
|
1705
|
+
var PROMPT4 = `Run a full pipeline review:
|
|
1576
1706
|
|
|
1577
1707
|
1. lkp_opportunities_summary \u2192 funnel + stale.
|
|
1578
1708
|
2. For each stale opportunity, fetch context via lkp_opportunities_list (search by name or id).
|
|
@@ -1592,7 +1722,7 @@ function registerPipelineHealthCheckPrompt(server) {
|
|
|
1592
1722
|
},
|
|
1593
1723
|
() => ({
|
|
1594
1724
|
messages: [
|
|
1595
|
-
{ role: "user", content: { type: "text", text:
|
|
1725
|
+
{ role: "user", content: { type: "text", text: PROMPT4 } }
|
|
1596
1726
|
]
|
|
1597
1727
|
})
|
|
1598
1728
|
);
|
|
@@ -1604,6 +1734,7 @@ function registerAllPrompts(server) {
|
|
|
1604
1734
|
registerMorningStandupPrompt(server);
|
|
1605
1735
|
registerOpportunityActionPrompt(server);
|
|
1606
1736
|
registerConsultantInvestigationPrompt(server);
|
|
1737
|
+
registerManagersInTroublePrompt(server);
|
|
1607
1738
|
registerPipelineHealthCheckPrompt(server);
|
|
1608
1739
|
}
|
|
1609
1740
|
|
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/clients.ts","../src/tools/helpdesk.ts","../src/tools/billing.ts","../src/tools/alerts.ts","../src/tools/reports.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/consultant-investigation.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}\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>(path: string, body: unknown): Promise<T> {\n return this.request<T>(\"POST\", path, { body });\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 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\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\",\n description:\n \"List billing milestones across all projects. Status lifecycle: pending → in_progress → invoiced → paid. Includes joined project and client. Use for revenue tracking and delinquency investigation.\",\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 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 for resources, projects, pipeline, helpdesk, and high-severity alerts. Single call that surfaces everything to discuss on Monday.\",\n inputSchema: {},\n },\n async () =>\n runTool(logger, \"lkp_ceo_weekly\", () =>\n client.get<unknown>(\"/api/v1/reports/ceo-weekly\"),\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 { 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 { 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 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 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(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 = `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 { registerConsultantInvestigationPrompt } from \"./consultant-investigation.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 registerConsultantInvestigationPrompt(server);\n registerPipelineHealthCheckPrompt(server);\n}\n"],"mappings":";;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACDrC,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAEX,IAAM,cAAc;AACp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D,UAAQ,GAAG,sBAAsB,CAAC,WAAW;AAC3C,WAAO,MAAM,EAAE,QAAQ,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","PROMPT","z","z","buildText","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/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/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}\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>(path: string, body: unknown): Promise<T> {\n return this.request<T>(\"POST\", path, { body });\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 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\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 { 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 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(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 { 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 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,CAAC,EAAE,QAAQ,EAAE;AAClE,CAAC;AAMM,IAAM,wBAAwC,CAAC,SAAS,YAAY;AACzE,QAAM,OAAO,CAAC,yBAAyB,MAAM,SAAS,IAAI;AAC1D,MAAI,QAAS,MAAK,KAAK,MAAM,OAAO;AACpC,MAAI;AACF,UAAM,MAAM,aAAa,YAAY,M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