lkpgestao-mcp 0.2.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 ADDED
@@ -0,0 +1,1419 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+
7
+ // src/config.ts
8
+ import { z } from "zod";
9
+ var SERVER_NAME = "lkpgestao-mcp";
10
+ var SERVER_VERSION = "0.1.0";
11
+ var ConfigSchema = z.object({
12
+ LKP_API_BASE_URL: z.string().url("must be a valid URL").refine((u) => u.startsWith("https://"), {
13
+ message: "must use https:// (TLS is mandatory)"
14
+ }).transform((u) => u.replace(/\/+$/, "")),
15
+ LKP_API_TOKEN: z.string().min(1, "cannot be empty"),
16
+ LKP_LOG_LEVEL: z.enum(["trace", "debug", "info", "warn", "error", "fatal", "silent"]).default("info"),
17
+ LKP_REQUEST_TIMEOUT_MS: z.coerce.number().int().positive().default(1e4),
18
+ LKP_RETRY_ATTEMPTS: z.coerce.number().int().min(0).max(5).default(2),
19
+ LKP_CACHE_TTL_SECONDS: z.coerce.number().int().min(0).default(30)
20
+ });
21
+ function loadConfig(env = process.env) {
22
+ const parsed = ConfigSchema.safeParse(env);
23
+ if (!parsed.success) {
24
+ const issues = parsed.error.issues.map((i) => ` - ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
25
+ process.stderr.write(
26
+ `[${SERVER_NAME}] configuration error:
27
+ ${issues}
28
+
29
+ Required env vars: LKP_API_BASE_URL, LKP_API_TOKEN.
30
+ See README for the full reference.
31
+ `
32
+ );
33
+ process.exit(1);
34
+ }
35
+ return parsed.data;
36
+ }
37
+
38
+ // src/logger.ts
39
+ import pino from "pino";
40
+ function createLogger(config) {
41
+ return pino(
42
+ {
43
+ name: SERVER_NAME,
44
+ level: config.LKP_LOG_LEVEL,
45
+ base: {
46
+ service: SERVER_NAME,
47
+ version: SERVER_VERSION,
48
+ pid: process.pid
49
+ },
50
+ redact: {
51
+ paths: [
52
+ "authorization",
53
+ "Authorization",
54
+ "headers.authorization",
55
+ "headers.Authorization",
56
+ "token",
57
+ "api_token",
58
+ "bearer",
59
+ "LKP_API_TOKEN",
60
+ "env.LKP_API_TOKEN",
61
+ "*.token",
62
+ "*.api_token",
63
+ "*.authorization"
64
+ ],
65
+ censor: "[REDACTED]",
66
+ remove: false
67
+ },
68
+ timestamp: pino.stdTimeFunctions.isoTime
69
+ },
70
+ pino.destination({ dest: 2, sync: false })
71
+ );
72
+ }
73
+
74
+ // src/http-client.ts
75
+ import { randomUUID } from "crypto";
76
+
77
+ // src/errors.ts
78
+ var LkpError = class extends Error {
79
+ code;
80
+ request_id;
81
+ http_status;
82
+ api_code;
83
+ details;
84
+ retry_after_seconds;
85
+ constructor(payload) {
86
+ super(payload.message);
87
+ this.name = "LkpError";
88
+ this.code = payload.code;
89
+ this.request_id = payload.request_id;
90
+ this.http_status = payload.http_status;
91
+ this.api_code = payload.api_code;
92
+ this.details = payload.details;
93
+ this.retry_after_seconds = payload.retry_after_seconds;
94
+ }
95
+ toJSON() {
96
+ const out = { code: this.code, message: this.message };
97
+ if (this.request_id !== void 0) out.request_id = this.request_id;
98
+ if (this.http_status !== void 0) out.http_status = this.http_status;
99
+ if (this.api_code !== void 0) out.api_code = this.api_code;
100
+ if (this.details !== void 0) out.details = this.details;
101
+ if (this.retry_after_seconds !== void 0) {
102
+ out.retry_after_seconds = this.retry_after_seconds;
103
+ }
104
+ return out;
105
+ }
106
+ };
107
+ function mapHttpStatus(status) {
108
+ if (status === 400) return "bad_request";
109
+ if (status === 401) return "auth_failed";
110
+ if (status === 403) return "permission_denied";
111
+ if (status === 404) return "not_found";
112
+ if (status === 422) return "validation_error";
113
+ if (status === 429) return "rate_limited";
114
+ if (status >= 500) return "server_error";
115
+ return "unexpected";
116
+ }
117
+
118
+ // src/http-client.ts
119
+ var LkpClient = class {
120
+ baseUrl;
121
+ token;
122
+ timeoutMs;
123
+ retryAttempts;
124
+ userAgent;
125
+ logger;
126
+ constructor(opts) {
127
+ this.baseUrl = opts.baseUrl;
128
+ this.token = opts.token;
129
+ this.timeoutMs = opts.timeoutMs;
130
+ this.retryAttempts = opts.retryAttempts;
131
+ this.userAgent = opts.userAgent;
132
+ this.logger = opts.logger;
133
+ }
134
+ get(path, query) {
135
+ return this.request("GET", path, { query });
136
+ }
137
+ post(path, body) {
138
+ return this.request("POST", path, { body });
139
+ }
140
+ patch(path, body) {
141
+ return this.request("PATCH", path, { body });
142
+ }
143
+ async request(method, path, opts) {
144
+ const url = this.buildUrl(path, opts.query);
145
+ const requestId = randomUUID();
146
+ const log = this.logger.child({ request_id: requestId, method, path });
147
+ const headers = {
148
+ Accept: "application/json",
149
+ Authorization: `Bearer ${this.token}`,
150
+ "X-Request-ID": requestId,
151
+ "User-Agent": this.userAgent
152
+ };
153
+ let bodyStr;
154
+ if (opts.body !== void 0) {
155
+ headers["Content-Type"] = "application/json";
156
+ bodyStr = JSON.stringify(opts.body);
157
+ }
158
+ const maxAttempts = this.retryAttempts + 1;
159
+ let retriedOn429 = false;
160
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
161
+ const controller = new AbortController();
162
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
163
+ const started = Date.now();
164
+ try {
165
+ const res = await fetch(url, {
166
+ method,
167
+ headers,
168
+ body: bodyStr,
169
+ signal: controller.signal
170
+ });
171
+ const duration_ms = Date.now() - started;
172
+ const remaining = res.headers.get("x-ratelimit-remaining");
173
+ if (res.ok) {
174
+ const data = await res.json();
175
+ log.info(
176
+ { http_status: res.status, duration_ms, remaining, attempt },
177
+ "http_ok"
178
+ );
179
+ if (remaining !== null) {
180
+ const n = Number(remaining);
181
+ if (Number.isFinite(n) && n < 10) {
182
+ log.warn({ remaining: n }, "rate_limit_low");
183
+ }
184
+ }
185
+ return data;
186
+ }
187
+ const body = await safeJson(res);
188
+ const apiErr = extractApiError(body);
189
+ const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
190
+ if (res.status === 429 && !retriedOn429 && attempt < maxAttempts) {
191
+ retriedOn429 = true;
192
+ const wait = (retryAfter ?? 1) * 1e3;
193
+ log.warn({ retry_after: retryAfter }, "rate_limited_retry");
194
+ await sleep(wait);
195
+ continue;
196
+ }
197
+ const retryable = res.status >= 500;
198
+ if (retryable && attempt < maxAttempts) {
199
+ const backoff = 100 * Math.pow(4, attempt - 1);
200
+ log.warn(
201
+ { http_status: res.status, attempt, backoff_ms: backoff },
202
+ "http_retry"
203
+ );
204
+ await sleep(backoff);
205
+ continue;
206
+ }
207
+ const code = mapHttpStatus(res.status);
208
+ const payload = {
209
+ code,
210
+ message: apiErr?.message ?? `HTTP ${res.status} ${res.statusText} on ${method} ${path}`,
211
+ request_id: requestId,
212
+ http_status: res.status
213
+ };
214
+ if (apiErr?.code) payload.api_code = apiErr.code;
215
+ if (apiErr?.details !== void 0) payload.details = apiErr.details;
216
+ if (retryAfter !== null) payload.retry_after_seconds = retryAfter;
217
+ log.error(
218
+ {
219
+ http_status: res.status,
220
+ duration_ms,
221
+ api_code: apiErr?.code
222
+ },
223
+ "http_error"
224
+ );
225
+ throw new LkpError(payload);
226
+ } catch (e) {
227
+ clearTimeout(timer);
228
+ if (e instanceof LkpError) throw e;
229
+ const isAbort = e instanceof Error && e.name === "AbortError";
230
+ const duration_ms = Date.now() - started;
231
+ if (attempt < maxAttempts) {
232
+ const backoff = 100 * Math.pow(4, attempt - 1);
233
+ log.warn(
234
+ {
235
+ attempt,
236
+ backoff_ms: backoff,
237
+ reason: isAbort ? "timeout" : "network",
238
+ duration_ms
239
+ },
240
+ "http_retry"
241
+ );
242
+ await sleep(backoff);
243
+ continue;
244
+ }
245
+ log.error({ duration_ms, reason: isAbort ? "timeout" : "network" }, "http_fail");
246
+ throw new LkpError({
247
+ code: isAbort ? "timeout" : "network_error",
248
+ message: isAbort ? `Request to ${path} timed out after ${this.timeoutMs}ms` : `Could not reach LKPGest\xE3o API: ${e.message}`,
249
+ request_id: requestId
250
+ });
251
+ } finally {
252
+ clearTimeout(timer);
253
+ }
254
+ }
255
+ throw new LkpError({
256
+ code: "unexpected",
257
+ message: "Request loop exited without result (should be unreachable).",
258
+ request_id: requestId
259
+ });
260
+ }
261
+ buildUrl(path, query) {
262
+ const clean = path.startsWith("/") ? path : `/${path}`;
263
+ const url = new URL(`${this.baseUrl}${clean}`);
264
+ if (query) {
265
+ for (const [k, v] of Object.entries(query)) {
266
+ if (v !== void 0 && v !== null) {
267
+ url.searchParams.set(k, String(v));
268
+ }
269
+ }
270
+ }
271
+ return url.toString();
272
+ }
273
+ };
274
+ function sleep(ms) {
275
+ return new Promise((r) => setTimeout(r, ms));
276
+ }
277
+ function parseRetryAfter(raw) {
278
+ if (!raw) return null;
279
+ const n = Number(raw);
280
+ return Number.isFinite(n) && n >= 0 ? n : null;
281
+ }
282
+ async function safeJson(res) {
283
+ try {
284
+ return await res.json();
285
+ } catch {
286
+ return void 0;
287
+ }
288
+ }
289
+ function extractApiError(body) {
290
+ if (!body || typeof body !== "object") return void 0;
291
+ const b = body;
292
+ if (b.error && typeof b.error === "object") {
293
+ return b.error;
294
+ }
295
+ if (typeof b.message === "string") {
296
+ return { message: b.message };
297
+ }
298
+ return void 0;
299
+ }
300
+
301
+ // src/tools/ping.ts
302
+ import { z as z2 } from "zod";
303
+ var PingUser = z2.object({
304
+ id: z2.number().optional(),
305
+ name: z2.string().optional(),
306
+ email: z2.string().optional()
307
+ }).passthrough();
308
+ var PingToken = z2.object({
309
+ name: z2.string().optional(),
310
+ scopes: z2.array(z2.string()).optional(),
311
+ last_used_at: z2.string().optional()
312
+ }).passthrough();
313
+ var PingResponse = z2.object({
314
+ user: PingUser.optional(),
315
+ token: PingToken.optional(),
316
+ server_time: z2.string().optional()
317
+ }).passthrough();
318
+ function registerPing(server, client, logger) {
319
+ server.registerTool(
320
+ "lkp_ping",
321
+ {
322
+ title: "Ping LKPGest\xE3o",
323
+ description: "Health check. Confirms the MCP server can reach LKPGest\xE3o and the configured API token is valid. Returns the bound user (name/email), the token's label, and the granted scopes. Use this first when unsure about connectivity or permissions.",
324
+ inputSchema: {}
325
+ },
326
+ async () => {
327
+ const started = Date.now();
328
+ try {
329
+ const raw = await client.get("/api/v1/ping");
330
+ const parsed = PingResponse.safeParse(raw);
331
+ const payload = parsed.success ? parsed.data : raw;
332
+ logger.info(
333
+ { tool: "lkp_ping", duration_ms: Date.now() - started, ok: true },
334
+ "tool_ok"
335
+ );
336
+ return {
337
+ content: [
338
+ { type: "text", text: JSON.stringify(payload, null, 2) }
339
+ ]
340
+ };
341
+ } catch (e) {
342
+ const err = e instanceof LkpError ? e.toJSON() : { code: "unexpected", message: e.message };
343
+ logger.error(
344
+ { tool: "lkp_ping", duration_ms: Date.now() - started, err },
345
+ "tool_error"
346
+ );
347
+ return {
348
+ isError: true,
349
+ content: [{ type: "text", text: JSON.stringify(err, null, 2) }]
350
+ };
351
+ }
352
+ }
353
+ );
354
+ }
355
+
356
+ // src/tools/resources.ts
357
+ import { z as z3 } from "zod";
358
+
359
+ // src/tools/common.ts
360
+ async function runTool(logger, name, fn) {
361
+ const started = Date.now();
362
+ try {
363
+ const result = await fn();
364
+ logger.info(
365
+ { tool: name, duration_ms: Date.now() - started, ok: true },
366
+ "tool_ok"
367
+ );
368
+ return {
369
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
370
+ };
371
+ } catch (e) {
372
+ const err = e instanceof LkpError ? e.toJSON() : { code: "unexpected", message: e.message };
373
+ logger.error(
374
+ { tool: name, duration_ms: Date.now() - started, err },
375
+ "tool_error"
376
+ );
377
+ return {
378
+ isError: true,
379
+ content: [{ type: "text", text: JSON.stringify(err, null, 2) }]
380
+ };
381
+ }
382
+ }
383
+ async function runToolText(logger, name, fn) {
384
+ const started = Date.now();
385
+ try {
386
+ const text = await fn();
387
+ logger.info(
388
+ { tool: name, duration_ms: Date.now() - started, ok: true },
389
+ "tool_ok"
390
+ );
391
+ return { content: [{ type: "text", text }] };
392
+ } catch (e) {
393
+ const err = e instanceof LkpError ? e.toJSON() : { code: "unexpected", message: e.message };
394
+ logger.error(
395
+ { tool: name, duration_ms: Date.now() - started, err },
396
+ "tool_error"
397
+ );
398
+ return {
399
+ isError: true,
400
+ content: [{ type: "text", text: JSON.stringify(err, null, 2) }]
401
+ };
402
+ }
403
+ }
404
+
405
+ // src/tools/resources.ts
406
+ function registerResources(server, client, logger) {
407
+ server.registerTool(
408
+ "lkp_resources_list",
409
+ {
410
+ title: "List resources (consultants)",
411
+ description: "List consultants (resources) with filters. Returns allocation status, hourly rate, specialties, weekly capacity. Use to find candidates for allocation or to audit team composition.",
412
+ inputSchema: {
413
+ status: z3.string().optional(),
414
+ contract_type: z3.string().optional(),
415
+ specialty_id: z3.coerce.number().int().positive().optional(),
416
+ allocation: z3.enum(["available", "partial", "full", "overloaded"]).optional(),
417
+ role: z3.string().optional(),
418
+ search: z3.string().optional(),
419
+ page: z3.coerce.number().int().positive().optional(),
420
+ per_page: z3.coerce.number().int().positive().max(200).default(20)
421
+ }
422
+ },
423
+ async (args) => runTool(
424
+ logger,
425
+ "lkp_resources_list",
426
+ () => client.get("/api/v1/resources", args)
427
+ )
428
+ );
429
+ server.registerTool(
430
+ "lkp_resources_summary",
431
+ {
432
+ title: "Resources operational summary",
433
+ description: "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 \u226430 days. Use for dashboards and the Monday brief.",
434
+ inputSchema: {}
435
+ },
436
+ async () => runTool(
437
+ logger,
438
+ "lkp_resources_summary",
439
+ () => client.get("/api/v1/resources/summary")
440
+ )
441
+ );
442
+ server.registerTool(
443
+ "lkp_resource_history",
444
+ {
445
+ title: "Resource allocation history",
446
+ description: "Allocation history for one consultant over a date range. Returns per-project periods interleaved with idle gaps, plus metrics (utilization_percent, idle_days, billed_hours, revenue). Default range: last 12 months.",
447
+ inputSchema: {
448
+ resource_id: z3.coerce.number().int().positive(),
449
+ from: z3.string().optional(),
450
+ to: z3.string().optional()
451
+ }
452
+ },
453
+ async ({ resource_id, from, to }) => runTool(
454
+ logger,
455
+ "lkp_resource_history",
456
+ () => client.get(`/api/v1/resources/${resource_id}/history`, {
457
+ from,
458
+ to
459
+ })
460
+ )
461
+ );
462
+ server.registerTool(
463
+ "lkp_resource_timesheets",
464
+ {
465
+ title: "Resource timesheet entries",
466
+ description: "Individual timesheet entries for one consultant. Returns line-level detail (date, hours, billable/approved flags, overtime, cost, comments) plus task/project/client. Includes aggregates block. Use for qualitative analysis: anomaly detection, unapproved entries, overtime patterns, weekend work. Range \u2264 184 days; max per_page 200.",
467
+ inputSchema: {
468
+ resource_id: z3.coerce.number().int().positive(),
469
+ from: z3.string(),
470
+ to: z3.string(),
471
+ project_id: z3.coerce.number().int().positive().optional(),
472
+ task_id: z3.coerce.number().int().positive().optional(),
473
+ is_approved: z3.coerce.boolean().optional(),
474
+ is_billable: z3.coerce.boolean().optional(),
475
+ source: z3.string().optional(),
476
+ page: z3.coerce.number().int().positive().optional(),
477
+ per_page: z3.coerce.number().int().positive().max(200).default(50)
478
+ }
479
+ },
480
+ async ({ resource_id, ...query }) => runTool(
481
+ logger,
482
+ "lkp_resource_timesheets",
483
+ () => client.get(
484
+ `/api/v1/resources/${resource_id}/timesheets`,
485
+ query
486
+ )
487
+ )
488
+ );
489
+ }
490
+
491
+ // src/tools/projects.ts
492
+ import { z as z4 } from "zod";
493
+ function registerProjects(server, client, logger) {
494
+ server.registerTool(
495
+ "lkp_projects_list",
496
+ {
497
+ title: "List projects",
498
+ description: "List projects with filters. Returns status, client, manager, budget, progress (task completion %), source opportunity, next pending billing milestone. Use to explore the portfolio.",
499
+ inputSchema: {
500
+ status_id: z4.coerce.number().int().positive().optional(),
501
+ client_id: z4.coerce.number().int().positive().optional(),
502
+ manager_id: z4.coerce.number().int().positive().optional(),
503
+ is_active: z4.coerce.boolean().optional(),
504
+ search: z4.string().optional(),
505
+ page: z4.coerce.number().int().positive().optional(),
506
+ per_page: z4.coerce.number().int().positive().max(200).default(20)
507
+ }
508
+ },
509
+ async (args) => runTool(
510
+ logger,
511
+ "lkp_projects_list",
512
+ () => client.get("/api/v1/projects", args)
513
+ )
514
+ );
515
+ server.registerTool(
516
+ "lkp_projects_summary",
517
+ {
518
+ title: "Projects portfolio summary",
519
+ description: "Portfolio dashboard: project counts by status, financial aggregate from billing milestones, upcoming milestones in the next 30 days.",
520
+ inputSchema: {}
521
+ },
522
+ async () => runTool(
523
+ logger,
524
+ "lkp_projects_summary",
525
+ () => client.get("/api/v1/projects/summary")
526
+ )
527
+ );
528
+ server.registerTool(
529
+ "lkp_project_detail",
530
+ {
531
+ title: "Project detail",
532
+ description: "Full project detail: team, billing milestones (all, not just next), stats, source opportunity link. Use before making decisions about a specific project.",
533
+ inputSchema: {
534
+ project_id: z4.coerce.number().int().positive()
535
+ }
536
+ },
537
+ async ({ project_id }) => runTool(
538
+ logger,
539
+ "lkp_project_detail",
540
+ () => client.get(`/api/v1/projects/${project_id}`)
541
+ )
542
+ );
543
+ }
544
+
545
+ // src/tools/opportunities.ts
546
+ import { z as z5 } from "zod";
547
+ var OpportunityStatus = z5.enum([
548
+ "NEW",
549
+ "QUALIFYING",
550
+ "PROPOSAL",
551
+ "SENT",
552
+ "NEGOTIATION",
553
+ "WON",
554
+ "LOST",
555
+ "CANCELLED"
556
+ ]);
557
+ var ActivityType = z5.enum([
558
+ "CALL",
559
+ "EMAIL",
560
+ "MEETING",
561
+ "NOTE",
562
+ "FOLLOW_UP",
563
+ "PRESENTATION",
564
+ "NEGOTIATION",
565
+ "DOCUMENT_SENT",
566
+ "DOCUMENT_RECEIVED",
567
+ "OTHER"
568
+ ]);
569
+ function registerOpportunities(server, client, logger) {
570
+ server.registerTool(
571
+ "lkp_opportunities_list",
572
+ {
573
+ title: "List sales opportunities",
574
+ description: "List sales opportunities (CRM pipeline) with filters. Returns stage, probability, expected_value, weighted_value, expected_close_date, account manager, last_activity_at. Use for pipeline review. Stage values: NEW | QUALIFYING | PROPOSAL | SENT | NEGOTIATION | WON | LOST | CANCELLED.",
575
+ inputSchema: {
576
+ status: OpportunityStatus.optional(),
577
+ account_manager_id: z5.coerce.number().int().positive().optional(),
578
+ client_id: z5.coerce.number().int().positive().optional(),
579
+ closing_before: z5.string().optional(),
580
+ page: z5.coerce.number().int().positive().optional(),
581
+ per_page: z5.coerce.number().int().positive().max(200).default(20)
582
+ }
583
+ },
584
+ async (args) => runTool(
585
+ logger,
586
+ "lkp_opportunities_list",
587
+ () => client.get("/api/v1/opportunities", args)
588
+ )
589
+ );
590
+ server.registerTool(
591
+ "lkp_opportunities_summary",
592
+ {
593
+ title: "Opportunities pipeline summary",
594
+ description: "Pipeline dashboard: funnel (count + total_value per open stage), totals (open count, total pipeline, weighted pipeline), closing next 30 days, stale opportunities (no activity in \u22657 days).",
595
+ inputSchema: {}
596
+ },
597
+ async () => runTool(
598
+ logger,
599
+ "lkp_opportunities_summary",
600
+ () => client.get("/api/v1/opportunities/summary")
601
+ )
602
+ );
603
+ server.registerTool(
604
+ "lkp_opportunity_activity_add",
605
+ {
606
+ title: "Add activity to opportunity (write)",
607
+ description: "Log a new activity (note, call, meeting, etc.) on an opportunity. Creates an entry in the timeline and updates last_activity_at. Use after any interaction with a prospect or to record analysis results. Allowed types: CALL | EMAIL | MEETING | NOTE | FOLLOW_UP | PRESENTATION | NEGOTIATION | DOCUMENT_SENT | DOCUMENT_RECEIVED | OTHER. Confirm with the user before calling unless they explicitly requested the activity.",
608
+ inputSchema: {
609
+ opportunity_id: z5.coerce.number().int().positive(),
610
+ type: ActivityType,
611
+ subject: z5.string().min(1),
612
+ description: z5.string().optional(),
613
+ duration_minutes: z5.coerce.number().int().nonnegative().optional(),
614
+ follow_up_date: z5.string().optional(),
615
+ outcome: z5.string().optional(),
616
+ is_internal: z5.coerce.boolean().optional()
617
+ }
618
+ },
619
+ async ({ opportunity_id, ...body }) => runTool(
620
+ logger,
621
+ "lkp_opportunity_activity_add",
622
+ () => client.post(
623
+ `/api/v1/opportunities/${opportunity_id}/activities`,
624
+ body
625
+ )
626
+ )
627
+ );
628
+ server.registerTool(
629
+ "lkp_opportunity_update",
630
+ {
631
+ title: "Update opportunity (write)",
632
+ description: "Update whitelisted fields on an opportunity. For status changes, business rules apply (e.g., LOST requires lost_reason). Returns the updated opportunity. Confirm any state transition with the user before calling.",
633
+ inputSchema: {
634
+ opportunity_id: z5.coerce.number().int().positive(),
635
+ name: z5.string().optional(),
636
+ description: z5.string().optional(),
637
+ status: OpportunityStatus.optional(),
638
+ probability: z5.coerce.number().min(0).max(100).optional(),
639
+ expected_value: z5.coerce.number().nonnegative().optional(),
640
+ expected_close_date: z5.string().optional(),
641
+ account_manager_id: z5.coerce.number().int().positive().optional(),
642
+ lost_reason: z5.string().optional(),
643
+ lost_reason_detail: z5.string().optional(),
644
+ lost_notes: z5.string().optional()
645
+ }
646
+ },
647
+ async ({ opportunity_id, ...body }) => runTool(
648
+ logger,
649
+ "lkp_opportunity_update",
650
+ () => client.patch(`/api/v1/opportunities/${opportunity_id}`, body)
651
+ )
652
+ );
653
+ }
654
+
655
+ // src/tools/clients.ts
656
+ import { z as z6 } from "zod";
657
+ function registerClients(server, client, logger) {
658
+ server.registerTool(
659
+ "lkp_clients_list",
660
+ {
661
+ title: "List clients",
662
+ description: "List clients (hierarchical). Returns active project count, B1 codes count, account manager, price list. Use to find clients by name/doc or explore the portfolio.",
663
+ inputSchema: {
664
+ status: z6.string().optional(),
665
+ parent_client_id: z6.coerce.number().int().positive().optional(),
666
+ search: z6.string().optional(),
667
+ page: z6.coerce.number().int().positive().optional(),
668
+ per_page: z6.coerce.number().int().positive().max(200).default(20)
669
+ }
670
+ },
671
+ async (args) => runTool(
672
+ logger,
673
+ "lkp_clients_list",
674
+ () => client.get("/api/v1/clients", args)
675
+ )
676
+ );
677
+ server.registerTool(
678
+ "lkp_client_detail",
679
+ {
680
+ title: "Client detail",
681
+ description: "Full client detail including all projects (active + inactive), all B1 codes, and stats.",
682
+ inputSchema: {
683
+ client_id: z6.coerce.number().int().positive()
684
+ }
685
+ },
686
+ async ({ client_id }) => runTool(
687
+ logger,
688
+ "lkp_client_detail",
689
+ () => client.get(`/api/v1/clients/${client_id}`)
690
+ )
691
+ );
692
+ }
693
+
694
+ // src/tools/helpdesk.ts
695
+ import { z as z7 } from "zod";
696
+ function registerHelpdesk(server, client, logger) {
697
+ server.registerTool(
698
+ "lkp_helpdesk_tickets_list",
699
+ {
700
+ title: "List helpdesk tickets",
701
+ description: "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.",
702
+ inputSchema: {
703
+ status_id: z7.coerce.number().int().positive().optional(),
704
+ priority: z7.string().optional(),
705
+ client_id: z7.coerce.number().int().positive().optional(),
706
+ assigned_to: z7.coerce.number().int().positive().optional(),
707
+ category_id: z7.coerce.number().int().positive().optional(),
708
+ sla_breached: z7.coerce.boolean().optional(),
709
+ is_open: z7.coerce.boolean().optional(),
710
+ search: z7.string().optional(),
711
+ page: z7.coerce.number().int().positive().optional(),
712
+ per_page: z7.coerce.number().int().positive().max(200).default(20)
713
+ }
714
+ },
715
+ async (args) => runTool(
716
+ logger,
717
+ "lkp_helpdesk_tickets_list",
718
+ () => client.get("/api/v1/helpdesk/tickets", args)
719
+ )
720
+ );
721
+ server.registerTool(
722
+ "lkp_helpdesk_summary",
723
+ {
724
+ title: "Helpdesk summary",
725
+ description: "Helpdesk dashboard: counts by status and priority, top 10 clients by open tickets, SLA breaches, resolved today.",
726
+ inputSchema: {}
727
+ },
728
+ async () => runTool(
729
+ logger,
730
+ "lkp_helpdesk_summary",
731
+ () => client.get("/api/v1/helpdesk/summary")
732
+ )
733
+ );
734
+ }
735
+
736
+ // src/tools/billing.ts
737
+ import { z as z8 } from "zod";
738
+ function registerBilling(server, client, logger) {
739
+ server.registerTool(
740
+ "lkp_billing_milestones",
741
+ {
742
+ title: "List billing milestones",
743
+ description: "List billing milestones across all projects. Status lifecycle: pending \u2192 in_progress \u2192 invoiced \u2192 paid. Includes joined project and client. Use for revenue tracking and delinquency investigation.",
744
+ inputSchema: {
745
+ status: z8.string().optional(),
746
+ project_id: z8.coerce.number().int().positive().optional(),
747
+ client_id: z8.coerce.number().int().positive().optional(),
748
+ due_from: z8.string().optional(),
749
+ due_to: z8.string().optional(),
750
+ include_cancelled: z8.coerce.boolean().optional(),
751
+ page: z8.coerce.number().int().positive().optional(),
752
+ per_page: z8.coerce.number().int().positive().max(200).default(20)
753
+ }
754
+ },
755
+ async (args) => runTool(
756
+ logger,
757
+ "lkp_billing_milestones",
758
+ () => client.get("/api/v1/billing/milestones", args)
759
+ )
760
+ );
761
+ }
762
+
763
+ // src/tools/alerts.ts
764
+ import { z as z9 } from "zod";
765
+ function registerAlerts(server, client, logger) {
766
+ server.registerTool(
767
+ "lkp_alerts",
768
+ {
769
+ title: "Operational alerts",
770
+ description: "Live operational alerts computed on the fly: consultants idle, projects finishing (\u226430d), opportunities stale (\u22657d), billing milestones upcoming (\u226415d) or overdue, helpdesk SLA breaches. Use first thing in the morning and before any strategic decision.",
771
+ inputSchema: {
772
+ severity: z9.string().optional(),
773
+ type: z9.string().optional()
774
+ }
775
+ },
776
+ async (args) => runTool(
777
+ logger,
778
+ "lkp_alerts",
779
+ () => client.get("/api/v1/alerts", args)
780
+ )
781
+ );
782
+ }
783
+
784
+ // src/tools/reports.ts
785
+ function registerReports(server, client, logger) {
786
+ server.registerTool(
787
+ "lkp_ceo_weekly",
788
+ {
789
+ title: "CEO weekly report",
790
+ description: "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.",
791
+ inputSchema: {}
792
+ },
793
+ async () => runTool(
794
+ logger,
795
+ "lkp_ceo_weekly",
796
+ () => client.get("/api/v1/reports/ceo-weekly")
797
+ )
798
+ );
799
+ }
800
+
801
+ // src/tools/composite/skill-match.ts
802
+ import { z as z10 } from "zod";
803
+ var OPEN_STAGES = ["QUALIFYING", "PROPOSAL", "SENT", "NEGOTIATION"];
804
+ function toSpecNames(specialties) {
805
+ return (specialties ?? []).map((s) => typeof s === "string" ? s : s?.name ?? "").filter((s) => s.length > 0);
806
+ }
807
+ function registerSkillMatch(server, client, logger) {
808
+ server.registerTool(
809
+ "lkp_skill_match",
810
+ {
811
+ title: "Match idle consultants to open opportunities",
812
+ 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.",
813
+ inputSchema: {
814
+ horizon_days: z10.coerce.number().int().positive().default(30),
815
+ min_match_percent: z10.coerce.number().int().min(0).max(100).default(50),
816
+ include_partial: z10.coerce.boolean().default(false)
817
+ }
818
+ },
819
+ async ({ horizon_days, min_match_percent, include_partial }) => runTool(logger, "lkp_skill_match", async () => {
820
+ const [resSummaryResp, ...oppResponses] = await Promise.all([
821
+ client.get(
822
+ "/api/v1/resources/summary"
823
+ ),
824
+ ...OPEN_STAGES.map(
825
+ (status) => client.get("/api/v1/opportunities", {
826
+ status,
827
+ per_page: 100
828
+ })
829
+ )
830
+ ]);
831
+ const now = Date.now();
832
+ const candidates = [];
833
+ for (const c of resSummaryResp.data.available_now ?? []) {
834
+ candidates.push({ ...c, urgency: "idle" });
835
+ }
836
+ for (const c of resSummaryResp.data.finishing_in_30_days ?? []) {
837
+ if (c.expected_release_date) {
838
+ const days = Math.ceil(
839
+ (new Date(c.expected_release_date).getTime() - now) / 864e5
840
+ );
841
+ if (days > horizon_days) continue;
842
+ }
843
+ candidates.push({ ...c, urgency: "finishing" });
844
+ }
845
+ if (include_partial) {
846
+ for (const c of resSummaryResp.data.partial_allocations ?? []) {
847
+ candidates.push({ ...c, urgency: "partial" });
848
+ }
849
+ }
850
+ const opportunities = oppResponses.flatMap(
851
+ (r) => r.data ?? []
852
+ );
853
+ const matches = [];
854
+ for (const c of candidates) {
855
+ const specs = toSpecNames(c.specialties);
856
+ if (specs.length === 0) continue;
857
+ for (const o of opportunities) {
858
+ const hay = `${o.name ?? ""} ${o.description ?? ""}`.toLowerCase();
859
+ const matched = specs.filter(
860
+ (s) => hay.includes(s.toLowerCase())
861
+ );
862
+ if (matched.length === 0) continue;
863
+ const score = Math.round(matched.length / specs.length * 100);
864
+ if (score < min_match_percent) continue;
865
+ matches.push({
866
+ consultant: {
867
+ id: c.id,
868
+ name: c.name,
869
+ status: c.status ?? null,
870
+ urgency: c.urgency,
871
+ available_since: c.available_since ?? null,
872
+ expected_release_date: c.expected_release_date ?? null,
873
+ specialties: specs
874
+ },
875
+ opportunity: {
876
+ id: o.id,
877
+ name: o.name,
878
+ status: o.status,
879
+ expected_value: o.expected_value ?? null,
880
+ weighted_value: o.weighted_value ?? null,
881
+ expected_close_date: o.expected_close_date ?? null
882
+ },
883
+ match_score: score,
884
+ matched_skills: matched,
885
+ opportunity_skill_inference_source: "description"
886
+ });
887
+ }
888
+ }
889
+ matches.sort((a, b) => {
890
+ const aw = a.opportunity.weighted_value ?? 0;
891
+ const bw = b.opportunity.weighted_value ?? 0;
892
+ return b.match_score / 100 * bw - a.match_score / 100 * aw;
893
+ });
894
+ return {
895
+ matches,
896
+ meta: {
897
+ horizon_days,
898
+ min_match_percent,
899
+ include_partial,
900
+ candidates_considered: candidates.length,
901
+ opportunities_considered: opportunities.length
902
+ }
903
+ };
904
+ })
905
+ );
906
+ }
907
+
908
+ // src/tools/composite/weekly-brief.ts
909
+ function fmtBRL(v) {
910
+ const n = typeof v === "number" ? v : Number(v);
911
+ if (!Number.isFinite(n)) return "\u2014";
912
+ return n.toLocaleString("pt-BR", { style: "currency", currency: "BRL" });
913
+ }
914
+ function buildMarkdown(ceo, alerts, opp, res) {
915
+ const score = ceo?.operational_health?.score ?? "\u2014";
916
+ const cls = ceo?.operational_health?.classification ?? "\u2014";
917
+ const period = ceo?.week ?? ceo?.period?.label ?? (ceo?.period?.from && ceo?.period?.to ? `${ceo.period.from} \u2192 ${ceo.period.to}` : "semana atual");
918
+ const lines = [];
919
+ lines.push(`# Brief Semanal \u2014 ${period}`);
920
+ lines.push("");
921
+ lines.push(`## \u{1F321}\uFE0F Sa\xFAde Operacional: ${score}/100 (${cls})`);
922
+ lines.push("");
923
+ if (alerts && alerts.length > 0) {
924
+ lines.push("## \u{1F534} Aten\xE7\xE3o imediata");
925
+ for (const a of alerts.slice(0, 10)) {
926
+ const title = a.title ?? a.type ?? "alerta";
927
+ const msg = a.message ?? "";
928
+ lines.push(`- **${title}**: ${msg}`);
929
+ }
930
+ lines.push("");
931
+ }
932
+ lines.push("## \u{1F4CA} N\xFAmeros da semana");
933
+ if (res?.totals) {
934
+ const t = res.totals;
935
+ lines.push(
936
+ `- Consultores: ${t.total_resources ?? "\u2014"} (dispon\xEDveis ${t.available ?? "\u2014"}, parciais ${t.partially_allocated ?? "\u2014"}, cheios ${t.fully_allocated ?? "\u2014"}, sobrecarga ${t.overloaded ?? "\u2014"})`
937
+ );
938
+ lines.push(`- Ociosidade: ${t.idle_percent ?? "\u2014"}%`);
939
+ }
940
+ if (opp?.totals) {
941
+ const t = opp.totals;
942
+ lines.push(
943
+ `- Pipeline aberto: ${t.open_count ?? "\u2014"} oportunidades \xB7 valor ${fmtBRL(t.total_pipeline)} \xB7 ponderado ${fmtBRL(t.weighted_pipeline)}`
944
+ );
945
+ }
946
+ if (opp?.stale_opportunities) {
947
+ lines.push(`- Oportunidades stale (\u22657d sem atividade): ${opp.stale_opportunities.length}`);
948
+ }
949
+ lines.push("");
950
+ lines.push("## \u{1F3AF} A\xE7\xF5es recomendadas");
951
+ lines.push(
952
+ "- Revisar consultores ociosos e alocar em oportunidades compat\xEDveis (use `lkp_skill_match`)."
953
+ );
954
+ lines.push(
955
+ "- Contatar as oportunidades stale antes de quinta-feira."
956
+ );
957
+ lines.push(
958
+ "- Verificar milestones atrasados e acionar cobran\xE7a (`lkp_billing_milestones?status=invoiced&due_to=<hoje>`)."
959
+ );
960
+ return lines.join("\n");
961
+ }
962
+ function registerWeeklyBrief(server, client, logger) {
963
+ server.registerTool(
964
+ "lkp_weekly_brief",
965
+ {
966
+ title: "Monday morning CEO briefing",
967
+ description: "Narrative Monday-morning briefing. Calls the CEO weekly report + high-severity alerts + opportunities/resources summaries and composes a pre-formatted Portuguese markdown summary ready to paste into a message or read aloud. The factual numbers come pre-assembled.",
968
+ inputSchema: {}
969
+ },
970
+ async () => runToolText(logger, "lkp_weekly_brief", async () => {
971
+ const [ceo, alerts, opp, res] = await Promise.all([
972
+ client.get("/api/v1/reports/ceo-weekly"),
973
+ client.get("/api/v1/alerts", {
974
+ severity: "high"
975
+ }),
976
+ client.get("/api/v1/opportunities/summary"),
977
+ client.get("/api/v1/resources/summary")
978
+ ]);
979
+ return buildMarkdown(ceo.data, alerts.data, opp.data, res.data);
980
+ })
981
+ );
982
+ }
983
+
984
+ // src/tools/composite/timesheet-anomalies.ts
985
+ import { z as z11 } from "zod";
986
+ async function fetchAllTimesheets(client, resourceId, from, to) {
987
+ const all = [];
988
+ for (let page = 1; page <= 5; page++) {
989
+ const r = await client.get(`/api/v1/resources/${resourceId}/timesheets`, {
990
+ from,
991
+ to,
992
+ page,
993
+ per_page: 200
994
+ });
995
+ const batch = r.data ?? [];
996
+ all.push(...batch);
997
+ const last = r.meta?.last_page;
998
+ if (last && page >= last || batch.length < 200) break;
999
+ }
1000
+ return all;
1001
+ }
1002
+ async function mapLimit(items, limit, fn) {
1003
+ const results = new Array(items.length);
1004
+ let cursor = 0;
1005
+ const workers = Array.from(
1006
+ { length: Math.min(limit, items.length) },
1007
+ async () => {
1008
+ while (true) {
1009
+ const i = cursor++;
1010
+ if (i >= items.length) return;
1011
+ results[i] = await fn(items[i]);
1012
+ }
1013
+ }
1014
+ );
1015
+ await Promise.all(workers);
1016
+ return results;
1017
+ }
1018
+ function detectAnomalies(entries, resourceId, resourceName, unapprovedDaysThreshold, today) {
1019
+ const findings = [];
1020
+ const byDate = /* @__PURE__ */ new Map();
1021
+ for (const e of entries) {
1022
+ const h = typeof e.hours === "number" ? e.hours : Number(e.hours);
1023
+ if (!Number.isFinite(h)) continue;
1024
+ const b = byDate.get(e.work_date) ?? { total: 0, count: 0 };
1025
+ b.total += h;
1026
+ b.count += 1;
1027
+ byDate.set(e.work_date, b);
1028
+ }
1029
+ for (const [date, b] of byDate) {
1030
+ if (b.total > 10) {
1031
+ findings.push({
1032
+ type: "long_day",
1033
+ severity: b.total > 13 ? "high" : "medium",
1034
+ resource: { id: resourceId, name: resourceName },
1035
+ details: {
1036
+ work_date: date,
1037
+ hours: Number(b.total.toFixed(2)),
1038
+ entries_count: b.count
1039
+ }
1040
+ });
1041
+ }
1042
+ }
1043
+ for (const e of entries) {
1044
+ const d = /* @__PURE__ */ new Date(`${e.work_date}T00:00:00Z`);
1045
+ const dow = d.getUTCDay();
1046
+ if (dow === 0 || dow === 6) {
1047
+ findings.push({
1048
+ type: "weekend_work",
1049
+ severity: "low",
1050
+ resource: { id: resourceId, name: resourceName },
1051
+ details: {
1052
+ work_date: e.work_date,
1053
+ hours: typeof e.hours === "number" ? e.hours : Number(e.hours),
1054
+ day: dow === 0 ? "Sunday" : "Saturday"
1055
+ }
1056
+ });
1057
+ }
1058
+ }
1059
+ for (const e of entries) {
1060
+ if (e.is_approved === false) {
1061
+ const d = /* @__PURE__ */ new Date(`${e.work_date}T00:00:00Z`);
1062
+ const ageDays = Math.floor(
1063
+ (today.getTime() - d.getTime()) / 864e5
1064
+ );
1065
+ if (ageDays > unapprovedDaysThreshold) {
1066
+ findings.push({
1067
+ type: "unapproved_aged",
1068
+ severity: ageDays > unapprovedDaysThreshold * 2 ? "high" : "medium",
1069
+ resource: { id: resourceId, name: resourceName },
1070
+ details: {
1071
+ work_date: e.work_date,
1072
+ age_days: ageDays,
1073
+ entry_id: e.id ?? null
1074
+ }
1075
+ });
1076
+ }
1077
+ }
1078
+ }
1079
+ for (const e of entries) {
1080
+ if (e.task_id === null || e.task_id === void 0) {
1081
+ findings.push({
1082
+ type: "orphaned_entry",
1083
+ severity: "low",
1084
+ resource: { id: resourceId, name: resourceName },
1085
+ details: { work_date: e.work_date, entry_id: e.id ?? null }
1086
+ });
1087
+ }
1088
+ }
1089
+ return findings;
1090
+ }
1091
+ function registerTimesheetAnomalies(server, client, logger) {
1092
+ server.registerTool(
1093
+ "lkp_timesheet_anomalies",
1094
+ {
1095
+ title: "Detect timesheet anomalies",
1096
+ 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.",
1097
+ inputSchema: {
1098
+ from: z11.string(),
1099
+ to: z11.string(),
1100
+ resource_id: z11.coerce.number().int().positive().optional(),
1101
+ unapproved_days_threshold: z11.coerce.number().int().positive().default(15)
1102
+ }
1103
+ },
1104
+ async ({ from, to, resource_id, unapproved_days_threshold }) => runTool(logger, "lkp_timesheet_anomalies", async () => {
1105
+ const today = /* @__PURE__ */ new Date();
1106
+ const findings = [];
1107
+ const scanned = [];
1108
+ let scope;
1109
+ if (resource_id !== void 0) {
1110
+ scope = "resource";
1111
+ const entries = await fetchAllTimesheets(
1112
+ client,
1113
+ resource_id,
1114
+ from,
1115
+ to
1116
+ );
1117
+ const name = entries[0]?.resource?.name ?? `#${resource_id}`;
1118
+ scanned.push({ id: resource_id, name });
1119
+ findings.push(
1120
+ ...detectAnomalies(
1121
+ entries,
1122
+ resource_id,
1123
+ name,
1124
+ unapproved_days_threshold,
1125
+ today
1126
+ )
1127
+ );
1128
+ } else {
1129
+ scope = "team";
1130
+ const resList = await client.get("/api/v1/resources", { per_page: 100 });
1131
+ const active = (resList.data ?? []).filter(
1132
+ (r) => r.status !== "inactive"
1133
+ );
1134
+ await mapLimit(active, 5, async (r) => {
1135
+ try {
1136
+ const entries = await fetchAllTimesheets(
1137
+ client,
1138
+ r.id,
1139
+ from,
1140
+ to
1141
+ );
1142
+ scanned.push({ id: r.id, name: r.name });
1143
+ findings.push(
1144
+ ...detectAnomalies(
1145
+ entries,
1146
+ r.id,
1147
+ r.name,
1148
+ unapproved_days_threshold,
1149
+ today
1150
+ )
1151
+ );
1152
+ } catch (e) {
1153
+ logger.warn(
1154
+ { resource_id: r.id, err: e.message },
1155
+ "timesheets_fetch_failed"
1156
+ );
1157
+ }
1158
+ });
1159
+ }
1160
+ const byType = {};
1161
+ for (const f of findings) {
1162
+ byType[f.type] = (byType[f.type] ?? 0) + 1;
1163
+ }
1164
+ return {
1165
+ period: { from, to },
1166
+ scope,
1167
+ resources_scanned: scanned.length,
1168
+ findings,
1169
+ summary: { total_findings: findings.length, by_type: byType }
1170
+ };
1171
+ })
1172
+ );
1173
+ }
1174
+
1175
+ // src/tools/composite/index.ts
1176
+ function registerComposites(server, client, logger) {
1177
+ registerSkillMatch(server, client, logger);
1178
+ registerWeeklyBrief(server, client, logger);
1179
+ registerTimesheetAnomalies(server, client, logger);
1180
+ }
1181
+
1182
+ // src/tools/index.ts
1183
+ function registerAllTools(server, client, logger) {
1184
+ registerPing(server, client, logger);
1185
+ registerResources(server, client, logger);
1186
+ registerProjects(server, client, logger);
1187
+ registerOpportunities(server, client, logger);
1188
+ registerClients(server, client, logger);
1189
+ registerHelpdesk(server, client, logger);
1190
+ registerBilling(server, client, logger);
1191
+ registerAlerts(server, client, logger);
1192
+ registerReports(server, client, logger);
1193
+ registerComposites(server, client, logger);
1194
+ }
1195
+
1196
+ // src/prompts/weekly-brief.ts
1197
+ var PROMPT = `Use the lkp_weekly_brief tool to generate the baseline numbers.
1198
+ Then enrich with:
1199
+ - Top 3 risks to call out now
1200
+ - Top 3 opportunities to act on this week
1201
+ - One question the CEO should ask at the leadership meeting
1202
+
1203
+ Output in Portuguese, markdown, max 500 words.`;
1204
+ function registerWeeklyBriefPrompt(server) {
1205
+ server.registerPrompt(
1206
+ "weekly-brief",
1207
+ {
1208
+ title: "Weekly Brief",
1209
+ description: "Produce the Monday-morning briefing for the CEO."
1210
+ },
1211
+ () => ({
1212
+ messages: [
1213
+ { role: "user", content: { type: "text", text: PROMPT } }
1214
+ ]
1215
+ })
1216
+ );
1217
+ }
1218
+
1219
+ // src/prompts/morning-standup.ts
1220
+ var PROMPT2 = `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.
1221
+
1222
+ Respond with a short bulleted list in Portuguese, grouped by area:
1223
+ 1. \u{1F534} Urgente (alerts)
1224
+ 2. \u{1F3AB} Helpdesk
1225
+ 3. \u{1F4BC} Vendas
1226
+
1227
+ If nothing urgent, say so explicitly.`;
1228
+ function registerMorningStandupPrompt(server) {
1229
+ server.registerPrompt(
1230
+ "morning-standup",
1231
+ {
1232
+ title: "Morning Standup",
1233
+ description: "Quick morning check \u2014 what's burning today?"
1234
+ },
1235
+ () => ({
1236
+ messages: [
1237
+ { role: "user", content: { type: "text", text: PROMPT2 } }
1238
+ ]
1239
+ })
1240
+ );
1241
+ }
1242
+
1243
+ // src/prompts/opportunity-action.ts
1244
+ import { z as z12 } from "zod";
1245
+ function buildText(opportunityRef) {
1246
+ return `The user wants to update opportunity: ${opportunityRef}.
1247
+
1248
+ 1. If the ref is a name, use lkp_opportunities_list with the search filter to find it.
1249
+ 2. Use lkp_opportunities_list (or a detail call if available) to fetch the current state before acting.
1250
+ 3. Ask the user:
1251
+ - What happened? (\u2192 will become the activity subject + description via lkp_opportunity_activity_add)
1252
+ - Did the stage change? (\u2192 lkp_opportunity_update with new status)
1253
+ - Should we schedule a follow-up? (\u2192 follow_up_date on the activity)
1254
+
1255
+ Before calling any write tool, SUMMARIZE the change (field \u2192 old value \u2192 new value) and wait for explicit "sim" / "confirma" / "ok" from the user. Do NOT assume consent.
1256
+
1257
+ After writing, confirm using the returned payload and suggest one concrete next step.`;
1258
+ }
1259
+ function registerOpportunityActionPrompt(server) {
1260
+ server.registerPrompt(
1261
+ "opportunity-action",
1262
+ {
1263
+ title: "Opportunity Action",
1264
+ description: "Log an activity and/or update stage for an opportunity.",
1265
+ argsSchema: {
1266
+ opportunity_ref: z12.string().describe("Opportunity id or name")
1267
+ }
1268
+ },
1269
+ ({ opportunity_ref }) => ({
1270
+ messages: [
1271
+ {
1272
+ role: "user",
1273
+ content: { type: "text", text: buildText(opportunity_ref) }
1274
+ }
1275
+ ]
1276
+ })
1277
+ );
1278
+ }
1279
+
1280
+ // src/prompts/consultant-investigation.ts
1281
+ import { z as z13 } from "zod";
1282
+ function buildText2(consultantRef) {
1283
+ return `Investigate consultant ${consultantRef}:
1284
+
1285
+ 1. lkp_resources_list with the search filter \u2192 confirm identity and current allocation status.
1286
+ 2. lkp_resource_history over the last 6 months \u2192 project timeline + idle gaps.
1287
+ 3. lkp_resource_timesheets over the last 30 days \u2192 actual work pattern.
1288
+ 4. If the consultant is available or soon to be released, run lkp_skill_match and filter for this consultant.
1289
+
1290
+ Produce a structured report in Portuguese with:
1291
+ - **Status atual** (uma linha)
1292
+ - **\xDAltimos 6 meses** (timeline)
1293
+ - **Padr\xE3o de trabalho \xFAltimas 4 semanas** (m\xE9dia horas/dia, dias sem apontamento, fins de semana, entradas n\xE3o aprovadas)
1294
+ - **Oportunidades compat\xEDveis** (se aplic\xE1vel)
1295
+ - **Recomenda\xE7\xE3o** (uma \xFAnica a\xE7\xE3o concreta)`;
1296
+ }
1297
+ function registerConsultantInvestigationPrompt(server) {
1298
+ server.registerPrompt(
1299
+ "consultant-investigation",
1300
+ {
1301
+ title: "Consultant Investigation",
1302
+ description: "Deep-dive on one consultant \u2014 where they are, what they've done, what's next.",
1303
+ argsSchema: {
1304
+ consultant_ref: z13.string().describe("Consultant id or name")
1305
+ }
1306
+ },
1307
+ ({ consultant_ref }) => ({
1308
+ messages: [
1309
+ {
1310
+ role: "user",
1311
+ content: { type: "text", text: buildText2(consultant_ref) }
1312
+ }
1313
+ ]
1314
+ })
1315
+ );
1316
+ }
1317
+
1318
+ // src/prompts/pipeline-health-check.ts
1319
+ var PROMPT3 = `Run a full pipeline review:
1320
+
1321
+ 1. lkp_opportunities_summary \u2192 funnel + stale.
1322
+ 2. For each stale opportunity, fetch context via lkp_opportunities_list (search by name or id).
1323
+ 3. lkp_skill_match \u2192 identify opportunities that could absorb idle consultants.
1324
+ 4. Compute:
1325
+ - Weighted pipeline vs. the health factors in lkp_ceo_weekly.
1326
+ - Stale count trend (from last_activity_at distribution).
1327
+ - Coverage: open opportunities' weighted value \xF7 monthly idle cost (lkp_resources_summary).
1328
+
1329
+ Output Portuguese markdown. For every red indicator, propose a concrete action \u2014 NOT advice \u2014 naming the exact tool and arguments the user can approve ("chamar lkp_opportunity_activity_add com \u2026").`;
1330
+ function registerPipelineHealthCheckPrompt(server) {
1331
+ server.registerPrompt(
1332
+ "pipeline-health-check",
1333
+ {
1334
+ title: "Pipeline Health Check",
1335
+ description: "Comprehensive CRM review with concrete recommendations."
1336
+ },
1337
+ () => ({
1338
+ messages: [
1339
+ { role: "user", content: { type: "text", text: PROMPT3 } }
1340
+ ]
1341
+ })
1342
+ );
1343
+ }
1344
+
1345
+ // src/prompts/index.ts
1346
+ function registerAllPrompts(server) {
1347
+ registerWeeklyBriefPrompt(server);
1348
+ registerMorningStandupPrompt(server);
1349
+ registerOpportunityActionPrompt(server);
1350
+ registerConsultantInvestigationPrompt(server);
1351
+ registerPipelineHealthCheckPrompt(server);
1352
+ }
1353
+
1354
+ // src/index.ts
1355
+ async function main() {
1356
+ const config = loadConfig();
1357
+ const logger = createLogger(config);
1358
+ logger.info(
1359
+ {
1360
+ base_url: config.LKP_API_BASE_URL,
1361
+ log_level: config.LKP_LOG_LEVEL,
1362
+ timeout_ms: config.LKP_REQUEST_TIMEOUT_MS,
1363
+ retry_attempts: config.LKP_RETRY_ATTEMPTS,
1364
+ node: process.version
1365
+ },
1366
+ "starting"
1367
+ );
1368
+ const client = new LkpClient({
1369
+ baseUrl: config.LKP_API_BASE_URL,
1370
+ token: config.LKP_API_TOKEN,
1371
+ timeoutMs: config.LKP_REQUEST_TIMEOUT_MS,
1372
+ retryAttempts: config.LKP_RETRY_ATTEMPTS,
1373
+ userAgent: `${SERVER_NAME}/${SERVER_VERSION} (+node ${process.version})`,
1374
+ logger
1375
+ });
1376
+ const server = new McpServer({
1377
+ name: SERVER_NAME,
1378
+ version: SERVER_VERSION
1379
+ });
1380
+ registerAllTools(server, client, logger);
1381
+ registerAllPrompts(server);
1382
+ const transport = new StdioServerTransport();
1383
+ const shutdown = async (signal) => {
1384
+ logger.info({ signal }, "shutdown");
1385
+ try {
1386
+ await server.close();
1387
+ } catch (e) {
1388
+ logger.error(
1389
+ { err: e instanceof Error ? e.message : String(e) },
1390
+ "shutdown_error"
1391
+ );
1392
+ }
1393
+ process.exit(0);
1394
+ };
1395
+ process.on("SIGINT", () => {
1396
+ void shutdown("SIGINT");
1397
+ });
1398
+ process.on("SIGTERM", () => {
1399
+ void shutdown("SIGTERM");
1400
+ });
1401
+ process.on("uncaughtException", (err) => {
1402
+ logger.fatal({ err: err.message, stack: err.stack }, "uncaught_exception");
1403
+ process.exit(1);
1404
+ });
1405
+ process.on("unhandledRejection", (reason) => {
1406
+ logger.fatal({ reason: String(reason) }, "unhandled_rejection");
1407
+ process.exit(1);
1408
+ });
1409
+ await server.connect(transport);
1410
+ logger.info("ready");
1411
+ }
1412
+ main().catch((err) => {
1413
+ process.stderr.write(
1414
+ `[${SERVER_NAME}] fatal: ${err instanceof Error ? err.message : String(err)}
1415
+ `
1416
+ );
1417
+ process.exit(1);
1418
+ });
1419
+ //# sourceMappingURL=index.js.map