lkpgestao-mcp 0.2.0 → 0.4.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/README.md +37 -6
- package/dist/index.js +293 -37
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
MCP server for **LKPGestão** — exposes the CEO cockpit API to Claude Cowork / Claude Desktop as tools and prompts.
|
|
4
4
|
|
|
5
|
-
- **
|
|
5
|
+
- **31 tools** covering resources, projects, opportunities (full CRUD incl. 11 writes across opp / activity / contact), clients, helpdesk, billing, alerts, CEO weekly report, and 3 composites (`lkp_skill_match`, `lkp_weekly_brief`, `lkp_timesheet_anomalies`).
|
|
6
6
|
- **5 slash prompts**: `/weekly-brief`, `/morning-standup`, `/opportunity-action`, `/consultant-investigation`, `/pipeline-health-check`.
|
|
7
7
|
- Stdio JSON-RPC transport, zero network exposure.
|
|
8
8
|
- Structured stderr logs (pino) with token redaction; never leaks `Authorization` headers.
|
|
@@ -39,7 +39,9 @@ Restart the client. First launch downloads the package via `npx`.
|
|
|
39
39
|
| Var | Required | Default | Description |
|
|
40
40
|
|---|---|---|---|
|
|
41
41
|
| `LKP_API_BASE_URL` | ✓ | — | HTTPS base URL (trailing slashes stripped). HTTP is rejected. |
|
|
42
|
-
| `LKP_API_TOKEN` |
|
|
42
|
+
| `LKP_API_TOKEN` | ✓* | — | Bearer token (without `Bearer ` prefix). *Required unless `LKP_API_TOKEN_KEYCHAIN_SERVICE` is set. |
|
|
43
|
+
| `LKP_API_TOKEN_KEYCHAIN_SERVICE` | | — | macOS only. Service name in the Keychain (`-s` flag of `security find-generic-password`). Used when `LKP_API_TOKEN` is absent. |
|
|
44
|
+
| `LKP_API_TOKEN_KEYCHAIN_ACCOUNT` | | — | Optional account name (`-a` flag) to disambiguate Keychain entries. |
|
|
43
45
|
| `LKP_LOG_LEVEL` | | `info` | `trace`/`debug`/`info`/`warn`/`error`/`fatal`/`silent` |
|
|
44
46
|
| `LKP_REQUEST_TIMEOUT_MS` | | `10000` | Per-request HTTP timeout. |
|
|
45
47
|
| `LKP_RETRY_ATTEMPTS` | | `2` | Retries on 5xx/network. 429 is retried once honoring `Retry-After`. |
|
|
@@ -52,17 +54,46 @@ git clone https://github.com/denisvandrade/lkpgestao-mcp.git
|
|
|
52
54
|
cd lkpgestao-mcp
|
|
53
55
|
npm install
|
|
54
56
|
npm run typecheck
|
|
55
|
-
npm test #
|
|
56
|
-
npm run build # dist/index.js (ESM, shebang, ~
|
|
57
|
+
npm test # 54 unit tests (errors, config, keychain, http-client incl. DELETE/204 + Retry-After cap, logger redaction, timesheet detectors)
|
|
58
|
+
npm run build # dist/index.js (ESM, shebang, ~59 KB)
|
|
57
59
|
node dist/index.js # speaks MCP on stdio
|
|
58
60
|
```
|
|
59
61
|
|
|
62
|
+
### Loading the token from macOS Keychain
|
|
63
|
+
|
|
64
|
+
To avoid storing the token in plaintext inside the MCP client config, use Keychain instead:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
# Store once (prompts for the token)
|
|
68
|
+
security add-generic-password -s lkpgestao-mcp-token -a "$USER" -w
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Then point the config at the Keychain entry — no secret touches disk:
|
|
72
|
+
|
|
73
|
+
```jsonc
|
|
74
|
+
{
|
|
75
|
+
"mcpServers": {
|
|
76
|
+
"lkpgestao": {
|
|
77
|
+
"command": "lkpgestao-mcp",
|
|
78
|
+
"env": {
|
|
79
|
+
"LKP_API_BASE_URL": "https://lkpgestaodev.linkupconsultoria.com",
|
|
80
|
+
"LKP_API_TOKEN_KEYCHAIN_SERVICE": "lkpgestao-mcp-token"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The server shells out to `/usr/bin/security` at startup. If the lookup fails (item missing, user cancels the Keychain prompt), startup aborts with a clear error.
|
|
88
|
+
|
|
60
89
|
## Security
|
|
61
90
|
|
|
62
91
|
- Token is loaded once at startup; never written to logs or tool results.
|
|
63
|
-
- `pino` redaction covers `authorization`, `token`, `bearer` fields in any log record.
|
|
92
|
+
- `pino` redaction covers `authorization`, `token`, `bearer` fields in any log record — verified by integration tests that capture stderr and assert the token value never appears (including under `headers.*`, `env.*`, and child loggers).
|
|
93
|
+
- Keychain resolution uses `execFileSync("security", [...])` with args as an array — service/account names are passed verbatim to the `security` binary; no shell interpretation, no injection surface.
|
|
94
|
+
- `Retry-After` values are capped at 60 s — a hostile or misconfigured server returning `Retry-After: 99999` cannot hang the process for hours.
|
|
64
95
|
- Every request sends `X-Request-ID` (UUID v4) for cross-correlating stderr lines with API-side traces.
|
|
65
|
-
- Write tools (`lkp_opportunity_activity_add
|
|
96
|
+
- Write tools (opportunity create/update/archive, activity add/update/delete, contact attach/update/detach, plus the pre-existing `lkp_opportunity_activity_add` and `lkp_opportunity_update`) require explicit user approval in the prompt contract — the server does not gate; the slash prompts and tool descriptions instruct the LLM to summarize and wait for confirmation before every destructive or state-changing call.
|
|
66
97
|
|
|
67
98
|
## License
|
|
68
99
|
|
package/dist/index.js
CHANGED
|
@@ -5,6 +5,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
|
5
5
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
6
6
|
|
|
7
7
|
// src/config.ts
|
|
8
|
+
import { execFileSync } from "child_process";
|
|
8
9
|
import { z } from "zod";
|
|
9
10
|
var SERVER_NAME = "lkpgestao-mcp";
|
|
10
11
|
var SERVER_VERSION = "0.1.0";
|
|
@@ -18,15 +19,54 @@ var ConfigSchema = z.object({
|
|
|
18
19
|
LKP_RETRY_ATTEMPTS: z.coerce.number().int().min(0).max(5).default(2),
|
|
19
20
|
LKP_CACHE_TTL_SECONDS: z.coerce.number().int().min(0).default(30)
|
|
20
21
|
});
|
|
21
|
-
|
|
22
|
-
const
|
|
22
|
+
var defaultKeychainLookup = (service, account) => {
|
|
23
|
+
const args = ["find-generic-password", "-s", service, "-w"];
|
|
24
|
+
if (account) args.push("-a", account);
|
|
25
|
+
try {
|
|
26
|
+
const out = execFileSync("security", args, {
|
|
27
|
+
encoding: "utf8",
|
|
28
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
29
|
+
});
|
|
30
|
+
return out.replace(/\r?\n$/, "");
|
|
31
|
+
} catch (err) {
|
|
32
|
+
const e = err;
|
|
33
|
+
if (e.code === "ENOENT") {
|
|
34
|
+
throw new Error(
|
|
35
|
+
"Keychain lookup requires the macOS `security` binary (not found on PATH)"
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
const stderr = typeof e.stderr === "string" ? e.stderr : e.stderr?.toString("utf8") ?? "";
|
|
39
|
+
const hint = /could not be found|SecKeychainSearchCopyNext/.test(stderr) ? `item "${service}" not found in Keychain` : stderr.trim() || `security exited with status ${e.status}`;
|
|
40
|
+
throw new Error(`Keychain lookup failed: ${hint}`);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
function loadConfig(env = process.env, options = {}) {
|
|
44
|
+
const lookup = options.keychainLookup ?? defaultKeychainLookup;
|
|
45
|
+
const resolved = { ...env };
|
|
46
|
+
if (!resolved.LKP_API_TOKEN && resolved.LKP_API_TOKEN_KEYCHAIN_SERVICE) {
|
|
47
|
+
try {
|
|
48
|
+
resolved.LKP_API_TOKEN = lookup(
|
|
49
|
+
resolved.LKP_API_TOKEN_KEYCHAIN_SERVICE,
|
|
50
|
+
resolved.LKP_API_TOKEN_KEYCHAIN_ACCOUNT
|
|
51
|
+
);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
process.stderr.write(
|
|
54
|
+
`[${SERVER_NAME}] configuration error:
|
|
55
|
+
- ${err.message}
|
|
56
|
+
|
|
57
|
+
`
|
|
58
|
+
);
|
|
59
|
+
process.exit(1);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const parsed = ConfigSchema.safeParse(resolved);
|
|
23
63
|
if (!parsed.success) {
|
|
24
64
|
const issues = parsed.error.issues.map((i) => ` - ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
|
|
25
65
|
process.stderr.write(
|
|
26
66
|
`[${SERVER_NAME}] configuration error:
|
|
27
67
|
${issues}
|
|
28
68
|
|
|
29
|
-
Required env vars: LKP_API_BASE_URL, LKP_API_TOKEN.
|
|
69
|
+
Required env vars: LKP_API_BASE_URL, LKP_API_TOKEN (or LKP_API_TOKEN_KEYCHAIN_SERVICE on macOS).
|
|
30
70
|
See README for the full reference.
|
|
31
71
|
`
|
|
32
72
|
);
|
|
@@ -37,7 +77,21 @@ See README for the full reference.
|
|
|
37
77
|
|
|
38
78
|
// src/logger.ts
|
|
39
79
|
import pino from "pino";
|
|
40
|
-
|
|
80
|
+
var REDACT_PATHS = [
|
|
81
|
+
"authorization",
|
|
82
|
+
"Authorization",
|
|
83
|
+
"headers.authorization",
|
|
84
|
+
"headers.Authorization",
|
|
85
|
+
"token",
|
|
86
|
+
"api_token",
|
|
87
|
+
"bearer",
|
|
88
|
+
"LKP_API_TOKEN",
|
|
89
|
+
"env.LKP_API_TOKEN",
|
|
90
|
+
"*.token",
|
|
91
|
+
"*.api_token",
|
|
92
|
+
"*.authorization"
|
|
93
|
+
];
|
|
94
|
+
function createLogger(config, destination) {
|
|
41
95
|
return pino(
|
|
42
96
|
{
|
|
43
97
|
name: SERVER_NAME,
|
|
@@ -48,26 +102,13 @@ function createLogger(config) {
|
|
|
48
102
|
pid: process.pid
|
|
49
103
|
},
|
|
50
104
|
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
|
-
],
|
|
105
|
+
paths: REDACT_PATHS,
|
|
65
106
|
censor: "[REDACTED]",
|
|
66
107
|
remove: false
|
|
67
108
|
},
|
|
68
109
|
timestamp: pino.stdTimeFunctions.isoTime
|
|
69
110
|
},
|
|
70
|
-
pino.destination({ dest: 2, sync: false })
|
|
111
|
+
destination ?? pino.destination({ dest: 2, sync: false })
|
|
71
112
|
);
|
|
72
113
|
}
|
|
73
114
|
|
|
@@ -116,6 +157,7 @@ function mapHttpStatus(status) {
|
|
|
116
157
|
}
|
|
117
158
|
|
|
118
159
|
// src/http-client.ts
|
|
160
|
+
var MAX_RETRY_AFTER_SECONDS = 60;
|
|
119
161
|
var LkpClient = class {
|
|
120
162
|
baseUrl;
|
|
121
163
|
token;
|
|
@@ -140,6 +182,9 @@ var LkpClient = class {
|
|
|
140
182
|
patch(path, body) {
|
|
141
183
|
return this.request("PATCH", path, { body });
|
|
142
184
|
}
|
|
185
|
+
delete(path) {
|
|
186
|
+
return this.request("DELETE", path, {});
|
|
187
|
+
}
|
|
143
188
|
async request(method, path, opts) {
|
|
144
189
|
const url = this.buildUrl(path, opts.query);
|
|
145
190
|
const requestId = randomUUID();
|
|
@@ -171,7 +216,8 @@ var LkpClient = class {
|
|
|
171
216
|
const duration_ms = Date.now() - started;
|
|
172
217
|
const remaining = res.headers.get("x-ratelimit-remaining");
|
|
173
218
|
if (res.ok) {
|
|
174
|
-
const
|
|
219
|
+
const isEmpty = res.status === 204 || res.headers.get("content-length") === "0";
|
|
220
|
+
const data = isEmpty ? null : await res.json();
|
|
175
221
|
log.info(
|
|
176
222
|
{ http_status: res.status, duration_ms, remaining, attempt },
|
|
177
223
|
"http_ok"
|
|
@@ -189,9 +235,15 @@ var LkpClient = class {
|
|
|
189
235
|
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
190
236
|
if (res.status === 429 && !retriedOn429 && attempt < maxAttempts) {
|
|
191
237
|
retriedOn429 = true;
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
238
|
+
const effective = Math.min(
|
|
239
|
+
retryAfter ?? 1,
|
|
240
|
+
MAX_RETRY_AFTER_SECONDS
|
|
241
|
+
);
|
|
242
|
+
log.warn(
|
|
243
|
+
{ retry_after: retryAfter, effective_wait: effective },
|
|
244
|
+
"rate_limited_retry"
|
|
245
|
+
);
|
|
246
|
+
await sleep(effective * 1e3);
|
|
195
247
|
continue;
|
|
196
248
|
}
|
|
197
249
|
const retryable = res.status >= 500;
|
|
@@ -566,6 +618,19 @@ var ActivityType = z5.enum([
|
|
|
566
618
|
"DOCUMENT_RECEIVED",
|
|
567
619
|
"OTHER"
|
|
568
620
|
]);
|
|
621
|
+
var ContactRole = z5.enum([
|
|
622
|
+
"DECISION_MAKER",
|
|
623
|
+
"INFLUENCER",
|
|
624
|
+
"TECHNICAL",
|
|
625
|
+
"FINANCIAL",
|
|
626
|
+
"USER",
|
|
627
|
+
"SPONSOR",
|
|
628
|
+
"GATEKEEPER",
|
|
629
|
+
"CHAMPION",
|
|
630
|
+
"OTHER"
|
|
631
|
+
]);
|
|
632
|
+
var EngagementLevel = z5.enum(["LOW", "MEDIUM", "HIGH"]);
|
|
633
|
+
var Sentiment = z5.enum(["NEGATIVE", "NEUTRAL", "POSITIVE", "CHAMPION"]);
|
|
569
634
|
function registerOpportunities(server, client, logger) {
|
|
570
635
|
server.registerTool(
|
|
571
636
|
"lkp_opportunities_list",
|
|
@@ -600,6 +665,89 @@ function registerOpportunities(server, client, logger) {
|
|
|
600
665
|
() => client.get("/api/v1/opportunities/summary")
|
|
601
666
|
)
|
|
602
667
|
);
|
|
668
|
+
server.registerTool(
|
|
669
|
+
"lkp_opportunity_detail",
|
|
670
|
+
{
|
|
671
|
+
title: "Opportunity detail",
|
|
672
|
+
description: "Full opportunity detail: parent fields (with weighted_value, status_label, last_activity_at) plus embedded activities (latest 20) and contacts. Children default to active-only; pass include_inactive=true for audit/restore flows. Returns 404 when id is unknown or (without include_inactive) when the opportunity itself is archived.",
|
|
673
|
+
inputSchema: {
|
|
674
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
675
|
+
include_inactive: z5.coerce.boolean().optional()
|
|
676
|
+
}
|
|
677
|
+
},
|
|
678
|
+
async ({ opportunity_id, include_inactive }) => runTool(
|
|
679
|
+
logger,
|
|
680
|
+
"lkp_opportunity_detail",
|
|
681
|
+
() => client.get(`/api/v1/opportunities/${opportunity_id}`, {
|
|
682
|
+
include_inactive
|
|
683
|
+
})
|
|
684
|
+
)
|
|
685
|
+
);
|
|
686
|
+
server.registerTool(
|
|
687
|
+
"lkp_opportunity_create",
|
|
688
|
+
{
|
|
689
|
+
title: "Create opportunity (write)",
|
|
690
|
+
description: "Create a new opportunity. Requires client_id, name and project_b1_code_id (a B1 code bound to the client). Since the B1 code choice is rarely obvious, call lkp_client_detail first so the user can pick from the returned b1_codes list. Status defaults to NEW; terminal statuses (WON/LOST/CANCELLED) are rejected on create \u2014 use lkp_opportunity_update afterwards. account_manager_id defaults to the token user. Summarize the draft and wait for user approval before calling.",
|
|
691
|
+
inputSchema: {
|
|
692
|
+
client_id: z5.coerce.number().int().positive(),
|
|
693
|
+
name: z5.string().min(1),
|
|
694
|
+
project_b1_code_id: z5.coerce.number().int().positive(),
|
|
695
|
+
description: z5.string().optional(),
|
|
696
|
+
status: OpportunityStatus.optional(),
|
|
697
|
+
probability: z5.coerce.number().min(0).max(100).optional(),
|
|
698
|
+
expected_value: z5.coerce.number().nonnegative().optional(),
|
|
699
|
+
expected_close_date: z5.string().optional(),
|
|
700
|
+
account_manager_id: z5.coerce.number().int().positive().optional(),
|
|
701
|
+
price_list_id: z5.coerce.number().int().positive().optional(),
|
|
702
|
+
source: z5.string().optional()
|
|
703
|
+
}
|
|
704
|
+
},
|
|
705
|
+
async (args) => runTool(
|
|
706
|
+
logger,
|
|
707
|
+
"lkp_opportunity_create",
|
|
708
|
+
() => client.post("/api/v1/opportunities", args)
|
|
709
|
+
)
|
|
710
|
+
);
|
|
711
|
+
server.registerTool(
|
|
712
|
+
"lkp_opportunity_update",
|
|
713
|
+
{
|
|
714
|
+
title: "Update opportunity (write)",
|
|
715
|
+
description: "Update whitelisted fields on an opportunity. For status changes, business rules apply (e.g., LOST requires lost_reason). Setting is_active toggles archive/restore (true = restore, false = archive \u2014 equivalent to lkp_opportunity_archive). Works on archived opportunities too so they can be restored. Returns the updated opportunity. Confirm any state transition with the user before calling.",
|
|
716
|
+
inputSchema: {
|
|
717
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
718
|
+
name: z5.string().optional(),
|
|
719
|
+
description: z5.string().optional(),
|
|
720
|
+
status: OpportunityStatus.optional(),
|
|
721
|
+
probability: z5.coerce.number().min(0).max(100).optional(),
|
|
722
|
+
expected_value: z5.coerce.number().nonnegative().optional(),
|
|
723
|
+
expected_close_date: z5.string().optional(),
|
|
724
|
+
account_manager_id: z5.coerce.number().int().positive().optional(),
|
|
725
|
+
is_active: z5.coerce.boolean().optional(),
|
|
726
|
+
lost_reason: z5.string().optional(),
|
|
727
|
+
lost_reason_detail: z5.string().optional(),
|
|
728
|
+
lost_notes: z5.string().optional()
|
|
729
|
+
}
|
|
730
|
+
},
|
|
731
|
+
async ({ opportunity_id, ...body }) => runTool(
|
|
732
|
+
logger,
|
|
733
|
+
"lkp_opportunity_update",
|
|
734
|
+
() => client.patch(`/api/v1/opportunities/${opportunity_id}`, body)
|
|
735
|
+
)
|
|
736
|
+
);
|
|
737
|
+
server.registerTool(
|
|
738
|
+
"lkp_opportunity_archive",
|
|
739
|
+
{
|
|
740
|
+
title: "Archive opportunity (write)",
|
|
741
|
+
description: "Soft-archive (soft-delete) an opportunity by setting is_active=0. The opportunity and its children remain in the DB and can be restored with lkp_opportunity_update passing is_active: true. After archiving, lkp_opportunity_detail without include_inactive returns 404. Always ask user approval before calling \u2014 destructive intent.",
|
|
742
|
+
inputSchema: {
|
|
743
|
+
opportunity_id: z5.coerce.number().int().positive()
|
|
744
|
+
}
|
|
745
|
+
},
|
|
746
|
+
async ({ opportunity_id }) => runTool(logger, "lkp_opportunity_archive", async () => {
|
|
747
|
+
await client.delete(`/api/v1/opportunities/${opportunity_id}`);
|
|
748
|
+
return { ok: true, archived: true, opportunity_id };
|
|
749
|
+
})
|
|
750
|
+
);
|
|
603
751
|
server.registerTool(
|
|
604
752
|
"lkp_opportunity_activity_add",
|
|
605
753
|
{
|
|
@@ -626,30 +774,138 @@ function registerOpportunities(server, client, logger) {
|
|
|
626
774
|
)
|
|
627
775
|
);
|
|
628
776
|
server.registerTool(
|
|
629
|
-
"
|
|
777
|
+
"lkp_opportunity_activity_update",
|
|
630
778
|
{
|
|
631
|
-
title: "Update opportunity (write)",
|
|
632
|
-
description: "
|
|
779
|
+
title: "Update opportunity activity (write)",
|
|
780
|
+
description: "Edit a manual activity on an opportunity. System-generated activities (STATUS_CHANGE, QUOTE_*, CONVERSION, TASK_*, CONTACT_ADDED) are immutable and return 403. activity_type is also immutable. Setting is_active=false archives the activity (same as delete). Confirm with the user before calling.",
|
|
633
781
|
inputSchema: {
|
|
634
782
|
opportunity_id: z5.coerce.number().int().positive(),
|
|
635
|
-
|
|
783
|
+
activity_id: z5.coerce.number().int().positive(),
|
|
784
|
+
subject: z5.string().optional(),
|
|
636
785
|
description: z5.string().optional(),
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
786
|
+
activity_date: z5.string().optional(),
|
|
787
|
+
duration_minutes: z5.coerce.number().int().nonnegative().optional(),
|
|
788
|
+
follow_up_date: z5.string().optional(),
|
|
789
|
+
follow_up_notes: z5.string().optional(),
|
|
790
|
+
is_follow_up_done: z5.coerce.boolean().optional(),
|
|
791
|
+
outcome: z5.string().optional(),
|
|
792
|
+
is_internal: z5.coerce.boolean().optional(),
|
|
793
|
+
is_active: z5.coerce.boolean().optional()
|
|
794
|
+
}
|
|
795
|
+
},
|
|
796
|
+
async ({ opportunity_id, activity_id, ...body }) => runTool(
|
|
797
|
+
logger,
|
|
798
|
+
"lkp_opportunity_activity_update",
|
|
799
|
+
() => client.patch(
|
|
800
|
+
`/api/v1/opportunities/${opportunity_id}/activities/${activity_id}`,
|
|
801
|
+
body
|
|
802
|
+
)
|
|
803
|
+
)
|
|
804
|
+
);
|
|
805
|
+
server.registerTool(
|
|
806
|
+
"lkp_opportunity_activity_delete",
|
|
807
|
+
{
|
|
808
|
+
title: "Delete opportunity activity (write)",
|
|
809
|
+
description: "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.",
|
|
810
|
+
inputSchema: {
|
|
811
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
812
|
+
activity_id: z5.coerce.number().int().positive()
|
|
813
|
+
}
|
|
814
|
+
},
|
|
815
|
+
async ({ opportunity_id, activity_id }) => runTool(logger, "lkp_opportunity_activity_delete", async () => {
|
|
816
|
+
await client.delete(
|
|
817
|
+
`/api/v1/opportunities/${opportunity_id}/activities/${activity_id}`
|
|
818
|
+
);
|
|
819
|
+
return { ok: true, archived: true, opportunity_id, activity_id };
|
|
820
|
+
})
|
|
821
|
+
);
|
|
822
|
+
server.registerTool(
|
|
823
|
+
"lkp_opportunity_contacts_list",
|
|
824
|
+
{
|
|
825
|
+
title: "List opportunity contacts",
|
|
826
|
+
description: "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.",
|
|
827
|
+
inputSchema: {
|
|
828
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
829
|
+
include_inactive: z5.coerce.boolean().optional()
|
|
830
|
+
}
|
|
831
|
+
},
|
|
832
|
+
async ({ opportunity_id, include_inactive }) => runTool(
|
|
833
|
+
logger,
|
|
834
|
+
"lkp_opportunity_contacts_list",
|
|
835
|
+
() => client.get(
|
|
836
|
+
`/api/v1/opportunities/${opportunity_id}/contacts`,
|
|
837
|
+
{ include_inactive }
|
|
838
|
+
)
|
|
839
|
+
)
|
|
840
|
+
);
|
|
841
|
+
server.registerTool(
|
|
842
|
+
"lkp_opportunity_contact_attach",
|
|
843
|
+
{
|
|
844
|
+
title: "Attach contact to opportunity (write)",
|
|
845
|
+
description: "Link an existing client_contact_persons record to an opportunity. The contact must belong to the same client as the opportunity. If a previously-archived link for the same (opportunity, contact) pair exists, it is reactivated with the new field values (200 OK) instead of creating a duplicate. Setting is_primary: true clears the prior primary on the same opportunity. Roles: DECISION_MAKER | INFLUENCER | TECHNICAL | FINANCIAL | USER | SPONSOR | GATEKEEPER | CHAMPION | OTHER. Engagement: LOW | MEDIUM | HIGH. Sentiment: NEGATIVE | NEUTRAL | POSITIVE | CHAMPION.",
|
|
846
|
+
inputSchema: {
|
|
847
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
848
|
+
contact_person_id: z5.coerce.number().int().positive(),
|
|
849
|
+
role: ContactRole.optional(),
|
|
850
|
+
role_description: z5.string().optional(),
|
|
851
|
+
is_primary: z5.coerce.boolean().optional(),
|
|
852
|
+
notes: z5.string().optional(),
|
|
853
|
+
engagement_level: EngagementLevel.optional(),
|
|
854
|
+
sentiment: Sentiment.optional()
|
|
645
855
|
}
|
|
646
856
|
},
|
|
647
857
|
async ({ opportunity_id, ...body }) => runTool(
|
|
648
858
|
logger,
|
|
649
|
-
"
|
|
650
|
-
() => client.
|
|
859
|
+
"lkp_opportunity_contact_attach",
|
|
860
|
+
() => client.post(
|
|
861
|
+
`/api/v1/opportunities/${opportunity_id}/contacts`,
|
|
862
|
+
body
|
|
863
|
+
)
|
|
864
|
+
)
|
|
865
|
+
);
|
|
866
|
+
server.registerTool(
|
|
867
|
+
"lkp_opportunity_contact_update",
|
|
868
|
+
{
|
|
869
|
+
title: "Update opportunity contact link (write)",
|
|
870
|
+
description: "Update attributes of a contact link on an opportunity. contact_person_id and opportunity_id are immutable on an existing link \u2014 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).",
|
|
871
|
+
inputSchema: {
|
|
872
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
873
|
+
link_id: z5.coerce.number().int().positive(),
|
|
874
|
+
role: ContactRole.optional(),
|
|
875
|
+
role_description: z5.string().optional(),
|
|
876
|
+
is_primary: z5.coerce.boolean().optional(),
|
|
877
|
+
notes: z5.string().optional(),
|
|
878
|
+
engagement_level: EngagementLevel.optional(),
|
|
879
|
+
sentiment: Sentiment.optional(),
|
|
880
|
+
is_active: z5.coerce.boolean().optional()
|
|
881
|
+
}
|
|
882
|
+
},
|
|
883
|
+
async ({ opportunity_id, link_id, ...body }) => runTool(
|
|
884
|
+
logger,
|
|
885
|
+
"lkp_opportunity_contact_update",
|
|
886
|
+
() => client.patch(
|
|
887
|
+
`/api/v1/opportunities/${opportunity_id}/contacts/${link_id}`,
|
|
888
|
+
body
|
|
889
|
+
)
|
|
651
890
|
)
|
|
652
891
|
);
|
|
892
|
+
server.registerTool(
|
|
893
|
+
"lkp_opportunity_contact_detach",
|
|
894
|
+
{
|
|
895
|
+
title: "Detach contact from opportunity (write)",
|
|
896
|
+
description: "Soft-archive a contact link on an opportunity (is_active=0). The underlying client_contact_persons record is never touched \u2014 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.",
|
|
897
|
+
inputSchema: {
|
|
898
|
+
opportunity_id: z5.coerce.number().int().positive(),
|
|
899
|
+
link_id: z5.coerce.number().int().positive()
|
|
900
|
+
}
|
|
901
|
+
},
|
|
902
|
+
async ({ opportunity_id, link_id }) => runTool(logger, "lkp_opportunity_contact_detach", async () => {
|
|
903
|
+
await client.delete(
|
|
904
|
+
`/api/v1/opportunities/${opportunity_id}/contacts/${link_id}`
|
|
905
|
+
);
|
|
906
|
+
return { ok: true, detached: true, opportunity_id, link_id };
|
|
907
|
+
})
|
|
908
|
+
);
|
|
653
909
|
}
|
|
654
910
|
|
|
655
911
|
// src/tools/clients.ts
|
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 { 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 function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {\n const parsed = ConfigSchema.safeParse(env);\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` +\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 } from \"pino\";\nimport { SERVER_NAME, SERVER_VERSION, type Config } from \"./config.js\";\n\nexport type Logger = PinoLogger;\n\nexport function createLogger(config: Config): 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: [\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 censor: \"[REDACTED]\",\n remove: false,\n },\n timestamp: pino.stdTimeFunctions.isoTime,\n },\n 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\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 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 data = (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 wait = (retryAfter ?? 1) * 1000;\n log.warn({ retry_after: retryAfter }, \"rate_limited_retry\");\n await sleep(wait);\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\nfunction 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\nexport function registerOpportunities(\n server: McpServer,\n client: LkpClient,\n logger: Logger,\n): void {\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\n .number()\n .int()\n .positive()\n .max(200)\n .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_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_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). 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 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","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,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;AAIM,SAAS,WAAW,MAAyB,QAAQ,KAAa;AACvE,QAAM,SAAS,aAAa,UAAU,GAAG;AACzC,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,SAAS,OAAO,MAAM,OACzB,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,KAAK,GAAG,KAAK,QAAQ,KAAK,EAAE,OAAO,EAAE,EAC9D,KAAK,IAAI;AACZ,YAAQ,OAAO;AAAA,MACb,IAAI,WAAW;AAAA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PT","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/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;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,MAAM;AAAA,MACzC,UAAU;AAAA,MACV,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,IACl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