-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
2753 lines (2528 loc) Β· 132 KB
/
server.mjs
File metadata and controls
2753 lines (2528 loc) Β· 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* @pickle/mcp-remote v3.0.0
*
* Hosted MCP server for Pickle β stateless, privacy-first.
* Tokens arrive per-request in headers. Nothing is stored. Nothing is logged.
*
* Port: 3055 (override with PORT env var)
*
* Endpoints:
* POST /mcp β MCP StreamableHTTP (primary)
* GET /mcp β SSE fallback (legacy clients)
* GET /health β { status: "ok", version: "3.0.0" }
* GET / β Landing page (static from ./public/)
*
* Request headers expected:
* x-pickle-key β Pickle license key (any non-empty = valid; Polar.sh gating added later)
* x-clickup-token β ClickUp personal API token (pk_...)
*
* Zero telemetry. Only talks to https://api.clickup.com.
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ErrorCode,
McpError,
} from "@modelcontextprotocol/sdk/types.js";
import express from "express";
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
import { fileURLToPath } from "node:url";
import path from "node:path";
import fs from "node:fs";
import https from "node:https";
import { z } from "zod";
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const PORT = Number(process.env.PORT ?? 3055);
const API_BASE = "https://api.clickup.com";
const REQUEST_TIMEOUT_MS = 30_000;
const MAX_RETRIES = 5;
const USER_AGENT = "pickle-mcp-remote/3.0 (+https://pickle.adityaarsharma.com)";
const CACHE_TTL_MS = 3_600_000; // 1 hour β workspace/team data per user token
const VERSION = "3.0.0";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_DIR = path.join(__dirname, "public");
const DATA_DIR = path.join(__dirname, "data");
const SIGNUPS_FILE = path.join(DATA_DIR, "signups.json");
const USAGE_FILE = path.join(DATA_DIR, "usage.json");
// Ensure data dir exists
try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch {}
// Marketing/admin config β set via env vars on the server
const BREVO_API_KEY = process.env.BREVO_API_KEY || "";
const BREVO_LIST_ID = process.env.BREVO_LIST_ID || ""; // free / beta β CRM list
const BREVO_LIST_PRO_ID = process.env.BREVO_LIST_PRO_ID || ""; // pro waitlist β CRM list
const ZEPTO_API_KEY = process.env.ZEPTO_API_KEY || ""; // transactional sends
const ZEPTO_FROM = process.env.ZEPTO_FROM || "noreply@adityaarsharma.com";
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || "pickle-admin-change-me";
// ---------------------------------------------------------------------------
// SSRF protection β whitelist of allowed outbound hosts
// ---------------------------------------------------------------------------
const ALLOWED_HOSTS = new Set([
"api.clickup.com",
"slack.com", // Slack Web API base
"graph.microsoft.com", // Microsoft Graph (Teams + Planner)
"login.microsoftonline.com", // Microsoft OAuth (if needed for refresh)
]);
function assertSafeHost(urlStr) {
let hostname;
try { hostname = new URL(urlStr).hostname; } catch {
throw new McpError(ErrorCode.InvalidRequest, "Invalid API URL");
}
if (!ALLOWED_HOSTS.has(hostname)) {
throw new McpError(ErrorCode.InvalidRequest, `Blocked request to disallowed host: ${hostname}`);
}
}
// ---------------------------------------------------------------------------
// License gate
// Free key format: pickle_free_<uuid>
// Pro key format: anything Polar.sh issues (validated server-side later)
// For now: any non-empty key >= 8 chars is accepted.
// ---------------------------------------------------------------------------
function validateLicenseKey(key) {
return typeof key === "string" && key.trim().length >= 8;
}
// ---------------------------------------------------------------------------
// Free-tier audit window cap (Pro tier in Phase 3 will lift this to 30 days)
// ---------------------------------------------------------------------------
const FREE_TIER_MAX_WINDOW_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
const PRO_COMING_SOON_NOTE =
"Deeper history (beyond 7 days) is part of Pickle Pro, which I'm designing with the Beta cohort. " +
"Beta users are grandfathered into the lowest Pro rate. " +
"If you want this feature or have feedback, email pickle@adityaarsharma.com β I respond personally.";
// Parse a window string like "1h", "6h", "1d", "3d", "7d" into milliseconds.
// Returns { ms, clamped, original } so callers can surface a note when clamped.
function parseTimeWindow(input) {
if (input === undefined || input === null || input === "") {
return { ms: FREE_TIER_MAX_WINDOW_MS, clamped: false, original: "7d" };
}
const m = String(input).trim().toLowerCase().match(/^(\d+)\s*([hd])$/);
if (!m) {
return { ms: FREE_TIER_MAX_WINDOW_MS, clamped: true, original: String(input) };
}
const n = Number(m[1]);
const unit = m[2];
const ms = unit === "h" ? n * 60 * 60 * 1000 : n * 24 * 60 * 60 * 1000;
if (ms > FREE_TIER_MAX_WINDOW_MS) {
return { ms: FREE_TIER_MAX_WINDOW_MS, clamped: true, original: String(input) };
}
return { ms, clamped: false, original: String(input) };
}
// Apply window to ClickUp date filter args: clamps date_updated_gt /
// date_created_gt to "now - window" if they're absent OR set further back.
// Returns the adjusted args and a note if clamped.
function applyWindowCap(args, kind = "updated") {
const tw = parseTimeWindow(args.time_window);
const floor = Date.now() - tw.ms;
const key = kind === "created" ? "date_created_gt" : "date_updated_gt";
const existing = typeof args[key] === "number" ? args[key] : 0;
const finalFloor = Math.max(existing, floor);
return {
args: { ...args, [key]: finalFloor },
clamped: tw.clamped,
window_used: tw.original === "7d" && !args.time_window ? "7d (default)" : tw.original,
pro_note: tw.clamped ? PRO_COMING_SOON_NOTE : null,
};
}
// ---------------------------------------------------------------------------
// Multi-tenant in-memory cache (process-level, keyed by SHA-256 of token)
// Stores workspace/team resolution so we don't re-fetch on every tool call
// within the same server request.
// ---------------------------------------------------------------------------
const _userCache = new Map();
function hashToken(token) {
return createHash("sha256").update(token).digest("hex").slice(0, 16);
}
function getCached(tokenHash, field) {
const entry = _userCache.get(tokenHash);
if (!entry) return undefined;
if (Date.now() - entry.ts > CACHE_TTL_MS) { _userCache.delete(tokenHash); return undefined; }
return entry[field];
}
function setCached(tokenHash, field, value) {
const existing = _userCache.get(tokenHash) ?? { ts: Date.now() };
existing[field] = value;
existing.ts = Date.now();
_userCache.set(tokenHash, existing);
}
// Prune stale cache entries every 5 minutes to avoid unbounded growth
setInterval(() => {
const cutoff = Date.now() - CACHE_TTL_MS;
for (const [k, v] of _userCache) if (v.ts < cutoff) _userCache.delete(k);
}, 300_000).unref();
// ---------------------------------------------------------------------------
// Signups storage (JSON file) + Brevo push
// IMPORTANT: This is OPT-IN marketing data only β emails users explicitly
// submit to get a free key. Task data and tokens are NEVER stored.
// ---------------------------------------------------------------------------
function loadSignups() {
try {
const raw = fs.readFileSync(SIGNUPS_FILE, "utf-8");
const parsed = JSON.parse(raw);
return Array.isArray(parsed?.signups) ? parsed.signups : [];
} catch { return []; }
}
function saveSignups(signups) {
const tmp = SIGNUPS_FILE + ".tmp";
fs.writeFileSync(tmp, JSON.stringify({ signups }, null, 2));
fs.renameSync(tmp, SIGNUPS_FILE);
}
function addSignup(email, ip, userAgent, intent) {
const signups = loadSignups();
const existing = signups.find((s) => s.email.toLowerCase() === email.toLowerCase());
if (existing) {
// Upgrade intent if user came back wanting Pro
if (intent === "pro" && existing.intent !== "pro") {
existing.intent = "pro";
existing.pro_waitlist_at = new Date().toISOString();
saveSignups(signups);
}
return existing;
}
const entry = {
email: email.trim(),
key: `pickle_free_${randomUUID().replace(/-/g, "")}`,
ip: (ip || "").slice(0, 64),
user_agent: (userAgent || "").slice(0, 256),
intent: intent === "pro" ? "pro" : "free",
created_at: new Date().toISOString(),
...(intent === "pro" ? { pro_waitlist_at: new Date().toISOString() } : {}),
};
signups.push(entry);
saveSignups(signups);
return entry;
}
// ββ Simple in-memory IP rate limiter for /api/signup ββββββββββββββββββββββ
// 5 signups per IP per hour. Map<ip, [timestamps]>
const _rl = new Map();
function rateLimitOk(ip) {
const now = Date.now();
const hour = 3_600_000;
const arr = (_rl.get(ip) || []).filter((t) => now - t < hour);
if (arr.length >= 5) { _rl.set(ip, arr); return false; }
arr.push(now);
_rl.set(ip, arr);
return true;
}
// Prune empty buckets every 10min
setInterval(() => {
const now = Date.now();
const hour = 3_600_000;
for (const [k, arr] of _rl) {
const fresh = arr.filter((t) => now - t < hour);
if (fresh.length === 0) _rl.delete(k);
else _rl.set(k, fresh);
}
}, 600_000).unref();
// Brevo HTTPS request via node:https β forces IPv4 (family:4) because
// Hetzner's default IPv6 outbound is blocked by Brevo's IP allowlist.
function brevoRequest(method, path, body) {
return new Promise((resolve) => {
const data = body ? JSON.stringify(body) : null;
const req = https.request({
hostname: "api.brevo.com",
port: 443,
path,
method,
family: 4,
timeout: 8000,
headers: {
"api-key": BREVO_API_KEY,
"Content-Type": "application/json",
accept: "application/json",
...(data ? { "Content-Length": Buffer.byteLength(data) } : {}),
},
}, (res) => {
let chunks = "";
res.on("data", (c) => { chunks += c; });
res.on("end", () => resolve({ ok: res.statusCode >= 200 && res.statusCode < 300, status: res.statusCode, body: chunks }));
});
req.on("error", (err) => resolve({ ok: false, status: 0, error: String(err?.message ?? err) }));
req.on("timeout", () => { req.destroy(); resolve({ ok: false, status: 0, error: "brevo_timeout" }); });
if (data) req.write(data);
req.end();
});
}
async function pushToBrevo(email, intent) {
if (!BREVO_API_KEY) return { skipped: true, reason: "no_brevo_key" };
// Pick which list: pro waitlist signups β Pro list; everyone else β Beta list
const targetList = intent === "pro" && BREVO_LIST_PRO_ID
? Number(BREVO_LIST_PRO_ID)
: (BREVO_LIST_ID ? Number(BREVO_LIST_ID) : null);
if (!targetList) return { skipped: true, reason: "no_list_id" };
const res = await brevoRequest("POST", "/v3/contacts", {
email,
listIds: [targetList],
updateEnabled: true,
attributes: {
SOURCE: "pickle-landing",
SIGNUP_DATE: new Date().toISOString(),
PICKLE_INTENT: intent || "free",
},
});
if (!res.ok && res.status !== 400) {
process.stderr.write(`[brevo] push failed ${res.status}: ${String(res.body || res.error).slice(0, 200)}\n`);
}
return res;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ZeptoMail (Zoho) β transactional sends
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function zeptoRequest(payload) {
return new Promise((resolve) => {
const data = JSON.stringify(payload);
const req = https.request({
hostname: "api.zeptomail.com",
port: 443,
path: "/v1.1/email",
method: "POST",
family: 4,
timeout: 8000,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Zoho-enczapikey ${ZEPTO_API_KEY}`,
"Content-Length": Buffer.byteLength(data),
},
}, (res) => {
let chunks = "";
res.on("data", (c) => { chunks += c; });
res.on("end", () => resolve({ ok: res.statusCode >= 200 && res.statusCode < 300, status: res.statusCode, body: chunks }));
});
req.on("error", (err) => resolve({ ok: false, status: 0, error: String(err?.message ?? err) }));
req.on("timeout", () => { req.destroy(); resolve({ ok: false, status: 0, error: "zepto_timeout" }); });
req.write(data);
req.end();
});
}
function welcomeEmailHTML(pickleKey) {
// v3 β Pickle-branded, MCP-config copy-paste box, chat-guided onboarding.
// Architecture: hosted MCP, tokens via HTTPS header per request, never stored.
if (process.env.USE_LEGACY_WELCOME_EMAIL === "1") {
return welcomeEmailHTMLLegacy(pickleKey);
}
const installPrompt = `Install the Pickle MCP server in my AI assistant. Be careful and do NOT modify or remove any existing MCP servers I already have β Pickle goes alongside them.
Steps:
1. Detect which AI assistant config applies to me (Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json on macOS, %APPDATA%/Claude/claude_desktop_config.json on Windows; Claude Code: ~/.claude.json; Cursor: ~/.cursor/mcp.json; Codex: ~/.codex/config.toml; Cline: VS Code settings).
2. Read my existing config file. Preserve every existing mcpServers entry exactly as-is.
3. Add this Pickle entry to the mcpServers object alongside anything that's already there:
{
"pickle": {
"type": "http",
"url": "https://pickle.adityaarsharma.com/mcp",
"headers": {
"x-pickle-key": "${pickleKey}"
}
}
}
4. Write the file back with that single addition.
5. Print exactly: "β MCP Installed. Please restart your AI assistant now, then type 'Pickle Start' in any chat to begin."
If you don't have file-edit tools (regular ChatGPT, Claude.ai web), don't pretend to install β instead, tell me my assistant's config file path and show me the JSON block above to paste manually.
Never touch any MCP server other than Pickle. Safe-harbour mode.`;
const fallbackJson = `{
"mcpServers": {
"pickle": {
"type": "http",
"url": "https://pickle.adityaarsharma.com/mcp",
"headers": {
"x-pickle-key": "${pickleKey}"
}
}
}
}`;
return `<!doctype html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background:#080a0d;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;color:#e2e8f0;line-height:1.6">
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#080a0d;padding:36px 16px">
<tr><td align="center">
<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;background:#0f1218;border:1px solid #1f2630;border-radius:16px;overflow:hidden">
<!-- ββ HEADER βββββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:32px 32px 0 32px">
<table role="presentation" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="vertical-align:middle">
<span style="display:inline-block;width:36px;height:36px;background:linear-gradient(135deg,#4ade80,#22c55e);border-radius:50%;text-align:center;line-height:36px;font-size:20px">π₯</span>
<span style="font-size:19px;font-weight:700;color:#e2e8f0;letter-spacing:-0.01em;margin-left:6px;vertical-align:middle">Pickle</span>
</td>
<td align="right" style="vertical-align:middle">
<span style="display:inline-block;padding:5px 12px;background:rgba(74,222,128,0.1);border:1px solid rgba(74,222,128,0.35);border-radius:999px;color:#4ade80;font-size:11px;font-family:'JetBrains Mono','SF Mono',Menlo,monospace;letter-spacing:0.08em;text-transform:uppercase;font-weight:600">Beta Β· Welcome</span>
</td>
</tr>
</table>
</td></tr>
<!-- ββ HEADLINE βββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:28px 32px 0 32px">
<h1 style="margin:0 0 16px 0;color:#e2e8f0;font-size:26px;font-weight:700;letter-spacing:-0.025em;line-height:1.2">You're in. Let's wire up Pickle.</h1>
<p style="margin:0 0 14px 0;color:#94a3b8;font-size:15.5px;line-height:1.7">I'm Aditya. I built Pickle because every Monday I'd open ClickUp and find a task with 47 hours logged and an empty description. Every Friday someone's "shipping today" from 3 days ago was still open. So I built the audit tool I wished I had.</p>
<p style="margin:0 0 6px 0;color:#94a3b8;font-size:14.5px;line-height:1.7">Free during Beta, forever for the features you have today. Three minutes to wire it up — here's how.</p>
</td></tr>
<!-- ββ SPACER ββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:14px 32px 0 32px"> </td></tr>
<!-- ββ STEP 1 β INSTALL VIA PROMPT ββββββββββββββββββββββββ -->
<tr><td style="padding:6px 32px 0 32px">
<h2 style="margin:24px 0 10px 0;color:#e2e8f0;font-size:17px;font-weight:600;letter-spacing:-0.01em">Step 1 — Let your AI install Pickle for you</h2>
<p style="margin:0 0 14px 0;color:#94a3b8;font-size:14.5px;line-height:1.7">Open <strong style="color:#cbd5e1">Claude Code, Cursor, Cline, or Codex</strong> (anything with file-edit tools) and paste this prompt as your very first message. The AI installs Pickle into your existing MCP config without touching anything else.</p>
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#080a0d;border:1px solid #2a3340;border-radius:10px;border-left:3px solid #4ade80">
<tr><td style="padding:16px 18px">
<div style="font-size:10px;font-family:'JetBrains Mono','SF Mono',Menlo,monospace;color:#64748b;text-transform:uppercase;letter-spacing:0.1em;margin-bottom:10px">copy → paste as your first message</div>
<pre style="margin:0;font-family:'JetBrains Mono','SF Mono',Menlo,Consolas,monospace;font-size:12.5px;color:#4ade80;line-height:1.6;white-space:pre-wrap;word-break:break-word;user-select:all">${installPrompt}</pre>
</td></tr>
</table>
<p style="margin:14px 0 0 0;color:#94a3b8;font-size:13.5px;line-height:1.65">When the AI is done it prints <strong style="color:#4ade80">"✓ MCP Installed. Please restart your AI assistant now, then type 'Pickle Start' in any chat to begin."</strong> — that's your signal to move to Step 2.</p>
<p style="margin:16px 0 8px 0;color:#64748b;font-size:12.5px;line-height:1.6"><strong style="color:#94a3b8">On Claude Desktop (no file-edit tools)?</strong> Add this block manually instead, in the file noted below:</p>
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:rgba(255,255,255,0.02);border:1px solid #1f2630;border-radius:8px">
<tr><td style="padding:12px 16px">
<pre style="margin:0;font-family:'JetBrains Mono','SF Mono',Menlo,Consolas,monospace;font-size:11.5px;color:#94a3b8;line-height:1.55;white-space:pre-wrap;word-break:break-all;user-select:all">${fallbackJson}</pre>
</td></tr>
</table>
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="margin-top:10px;background:rgba(255,255,255,0.02);border:1px solid #1f2630;border-radius:8px">
<tr><td style="padding:11px 16px;font-size:12px;color:#94a3b8;line-height:1.6">
<strong style="color:#cbd5e1">Config file location by assistant:</strong><br>
• Claude Desktop (macOS): <code style="color:#4ade80;font-size:11px">~/Library/Application Support/Claude/claude_desktop_config.json</code><br>
• Claude Desktop (Windows): <code style="color:#4ade80;font-size:11px">%APPDATA%/Claude/claude_desktop_config.json</code><br>
• Claude Code: <code style="color:#4ade80;font-size:11px">~/.claude.json</code><br>
• Cursor: <code style="color:#4ade80;font-size:11px">~/.cursor/mcp.json</code><br>
• Cline: VS Code → MCP Servers settings UI<br>
• Codex: <code style="color:#4ade80;font-size:11px">~/.codex/config.toml</code>
</td></tr>
</table>
</td></tr>
<!-- ββ SPACER ββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:18px 32px 0 32px"> </td></tr>
<!-- ββ STEP 2 β RESTART ββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:0 32px 0 32px">
<h2 style="margin:0 0 10px 0;color:#e2e8f0;font-size:17px;font-weight:600;letter-spacing:-0.01em">Step 2 — Restart your assistant when it says so</h2>
<p style="margin:0 0 4px 0;color:#94a3b8;font-size:14.5px;line-height:1.7">Once the AI confirms <em>"MCP Installed"</em>, close and reopen your assistant (Claude / Cursor / Cline / Codex) so the new MCP entry is picked up. Pickle's tools appear automatically on next launch.</p>
</td></tr>
<!-- ββ SPACER ββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:18px 32px 0 32px"> </td></tr>
<!-- ββ STEP 3 β TALK TO PICKLE βββββββββββββββββββββββββββββ -->
<tr><td style="padding:0 32px 0 32px">
<h2 style="margin:0 0 10px 0;color:#e2e8f0;font-size:17px;font-weight:600;letter-spacing:-0.01em">Step 3 — In any chat, type "Pickle Start"</h2>
<p style="margin:0 0 14px 0;color:#94a3b8;font-size:14.5px;line-height:1.7">That's the trigger. The guided setup begins right there in chat:</p>
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:rgba(74,222,128,0.04);border:1px solid rgba(74,222,128,0.25);border-radius:8px">
<tr><td style="padding:14px 18px">
<code style="font-family:'JetBrains Mono','SF Mono',Menlo,monospace;font-size:13.5px;color:#4ade80;font-weight:600;user-select:all">Pickle Start</code>
</td></tr>
</table>
<p style="margin:16px 0 0 0;color:#cbd5e1;font-size:14px;line-height:1.7">Pickle asks which platform you want first (ClickUp, Slack, or Microsoft Teams), walks you through getting the right token (~30 seconds per platform), and tells you exactly which header line to add to your MCP config. After that, the morning brief is one prompt away: <em>"Pickle, audit my ClickUp from last 24 hours."</em></p>
<p style="margin:14px 0 0 0;color:#64748b;font-size:13px;line-height:1.6"><strong style="color:#94a3b8">Your tokens never leave your machine.</strong> They travel only in the HTTPS request header. Pickle's server uses them in memory to call ClickUp / Slack / Teams APIs, then drops them. Nothing persisted. Code is MIT open source at <a href="https://github.com/adityaarsharma/pickle" style="color:#94a3b8;text-decoration:none;border-bottom:1px dotted #2a3340">github.com/adityaarsharma/pickle</a>.</p>
</td></tr>
<!-- ββ SPACER ββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:14px 32px 0 32px"> </td></tr>
<!-- ββ MORE COMING (no Pro upsell β just honest 'more soon') ββ -->
<tr><td style="padding:6px 32px 0 32px">
<div style="margin:14px 0 0 0;padding:20px 22px;background:rgba(74,222,128,0.04);border:1px solid rgba(74,222,128,0.18);border-radius:10px">
<div style="font-family:'JetBrains Mono','SF Mono',Menlo,monospace;font-size:11px;color:#4ade80;text-transform:uppercase;letter-spacing:0.1em;font-weight:600;margin-bottom:8px">More features ahead</div>
<p style="margin:0;color:#cbd5e1;font-size:14.5px;line-height:1.7">Today, Pickle audits ClickUp deeply (9 patterns out of the box) and previews Slack & Microsoft Teams setup via chat. New patterns, smarter automation, and per-platform improvements keep landing every couple of weeks.</p>
<p style="margin:10px 0 0 0;color:#cbd5e1;font-size:14.5px;line-height:1.7">I'll email when something material ships. Until then, run your morning audit and tell me what feels off — that's how Pickle gets better.</p>
</div>
</td></tr>
<!-- ββ SPACER ββββββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:14px 32px 0 32px"> </td></tr>
<!-- ββ WEBSITE + REPLY CTA βββββββββββββββββββββββββββββββ -->
<tr><td style="padding:6px 32px 0 32px">
<p style="margin:0 0 12px 0;color:#cbd5e1;font-size:14.5px;line-height:1.7">More about Pickle: <a href="https://pickle.adityaarsharma.com" style="color:#4ade80;text-decoration:none;border-bottom:1px dotted rgba(74,222,128,0.4)">pickle.adityaarsharma.com</a></p>
<p style="margin:14px 0 4px 0;color:#cbd5e1;font-size:14.5px;line-height:1.7">Stuck on any step, or just have feedback? <strong>Hit reply</strong> — or email <a href="mailto:pickle@adityaarsharma.com" style="color:#4ade80;text-decoration:none;border-bottom:1px dotted rgba(74,222,128,0.4)">pickle@adityaarsharma.com</a>. I read every email personally and respond same-day.</p>
</td></tr>
<!-- ββ FOUNDER SIG ββββββββββββββββββββββββββββββββββββββββ -->
<tr><td style="padding:24px 32px 32px 32px">
<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="border-top:1px solid #1f2630;padding-top:20px">
<tr><td style="padding-top:18px">
<span style="color:#e2e8f0;font-size:14px;font-weight:600">β Aditya Sharma</span>
<div style="color:#64748b;font-size:12.5px;margin-top:3px">Founder, Pickle Β· <a href="https://adityaarsharma.com" style="color:#94a3b8;text-decoration:none;border-bottom:1px dotted #2a3340">adityaarsharma.com</a></div>
</td></tr>
</table>
</td></tr>
</table>
<!-- ββ FOOTER (outside the card) ββββββββββββββββββββββββββββ -->
<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="max-width:600px;margin-top:16px">
<tr><td align="center" style="padding:8px 24px 24px 24px;color:#475569;font-size:11px;line-height:1.5">
You're receiving this because you signed up at <a href="https://pickle.adityaarsharma.com" style="color:#64748b;text-decoration:none">pickle.adityaarsharma.com</a>. Reply with "unsubscribe" if you'd like off the list.<br>
Pickle is MIT open source Β· <a href="https://github.com/adityaarsharma/pickle" style="color:#64748b;text-decoration:none">github.com/adityaarsharma/pickle</a> Β· <a href="https://pickle.adityaarsharma.com/legal/privacy" style="color:#64748b;text-decoration:none">Privacy</a> Β· <a href="https://pickle.adityaarsharma.com/legal/terms" style="color:#64748b;text-decoration:none">Terms</a>
</td></tr>
</table>
</td></tr>
</table>
</body></html>`;
}
// Legacy template (pre-npm-installer flow). Kept as fallback during the
// transition. Activate by setting USE_LEGACY_WELCOME_EMAIL=1 in env.
function welcomeEmailHTMLLegacy(pickleKey) {
return `<!doctype html>
<html><body style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#080a0d;color:#e2e8f0;margin:0;padding:32px 16px;line-height:1.6">
<div style="max-width:560px;margin:0 auto;background:#0f1218;border:1px solid #1f2630;border-radius:14px;padding:32px 28px">
<div style="display:inline-block;padding:5px 12px;background:rgba(74,222,128,0.1);border:1px solid rgba(74,222,128,0.3);border-radius:999px;color:#4ade80;font-size:12px;font-family:monospace;letter-spacing:0.05em;margin-bottom:18px">BETA Β· WELCOME</div>
<h1 style="margin:0 0 14px;color:#e2e8f0;font-size:24px;letter-spacing:-0.01em">You're in the Pickle Beta.</h1>
<p style="color:#94a3b8;font-size:15px;margin:0 0 22px">I'm Aditya. Pickle audits your ClickUp / Slack / Microsoft Teams workspaces for the things a good ops manager would catch. Free during Beta. Locked into the lowest price I'll ever charge, forever.</p>
<div style="background:#080a0d;border:1px solid #1f2630;border-radius:10px;padding:16px 18px;margin-bottom:22px">
<div style="font-size:11px;font-family:monospace;color:#94a3b8;text-transform:uppercase;letter-spacing:0.08em;margin-bottom:6px">Your Pickle key</div>
<div style="font-family:monospace;font-size:14px;color:#4ade80;word-break:break-all">${pickleKey}</div>
</div>
<p style="color:#94a3b8;font-size:14px;margin:0 0 14px">Setup instructions are at <a href="https://pickle.adityaarsharma.com/#start" style="color:#4ade80">pickle.adityaarsharma.com/#start</a>. Reply if you get stuck.</p>
<p style="color:#64748b;font-size:13px;margin:22px 0 0;border-top:1px solid #1f2630;padding-top:18px">β Aditya<br/><span style="font-size:12px">Founder, Pickle Β· <a href="https://adityaarsharma.com" style="color:#94a3b8">adityaarsharma.com</a></span></p>
</div>
<div style="max-width:560px;margin:14px auto 0;text-align:center;color:#64748b;font-size:11px">You're receiving this because you signed up at pickle.adityaarsharma.com. Reply with "unsubscribe" if you'd like off the list.</div>
</body></html>`;
}
async function sendZeptoWelcome(email, pickleKey) {
if (!ZEPTO_API_KEY) return { skipped: true, reason: "no_zepto_key" };
const res = await zeptoRequest({
from: { address: ZEPTO_FROM, name: "Pickle (Aditya)" },
to: [{ email_address: { address: email } }],
subject: "You're in the Pickle Beta β your config inside",
htmlbody: welcomeEmailHTML(pickleKey),
});
if (!res.ok) {
process.stderr.write(`[zepto] welcome send failed ${res.status}: ${String(res.body || res.error).slice(0, 200)}\n`);
}
return res;
}
// ββ Per-key usage tracker (in-memory + periodic flush) βββββββββββββββββββ
// Maps key β { count, last_used, first_used, requests_today, today_date }
const _usage = new Map();
function loadUsage() {
try {
const raw = fs.readFileSync(USAGE_FILE, "utf-8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") {
for (const [k, v] of Object.entries(parsed)) _usage.set(k, v);
}
} catch {}
}
loadUsage();
function flushUsage() {
try {
const obj = Object.fromEntries(_usage);
const tmp = USAGE_FILE + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(obj));
fs.renameSync(tmp, USAGE_FILE);
} catch (err) {
process.stderr.write(`[usage] flush failed: ${err?.message ?? err}\n`);
}
}
setInterval(flushUsage, 60_000).unref();
process.on("SIGTERM", () => { try { flushUsage(); } catch {} });
function trackUse(key) {
if (!key) return;
const today = new Date().toISOString().slice(0, 10);
const now = new Date().toISOString();
const entry = _usage.get(key) || {
count: 0,
first_used: now,
last_used: now,
requests_today: 0,
today_date: today,
audits: 0,
audit_windows: {},
};
entry.count++;
entry.last_used = now;
if (entry.today_date !== today) { entry.today_date = today; entry.requests_today = 1; }
else entry.requests_today++;
_usage.set(key, entry);
}
// Install fingerprint tracker β 1 pickle_key should equal 1 install. We hash
// (IP + User-Agent) into a short fingerprint per request and remember the
// first one we saw per key. Subsequent requests from a different fingerprint
// are logged (currently soft warning, not blocking) so abuse can be reviewed
// in the admin dashboard. No PII stored β only the hash.
function fingerprintRequest(req) {
const ip = req.headers["cf-connecting-ip"]
|| req.headers["x-forwarded-for"]?.split(",")[0]?.trim()
|| req.socket?.remoteAddress
|| "";
const ua = String(req.headers["user-agent"] || "").slice(0, 200);
const raw = `${ip}|${ua}`;
// Cheap non-crypto hash β no node:crypto dep needed for fingerprinting.
let h = 0xdeadbeef;
for (let i = 0; i < raw.length; i++) h = Math.imul(h ^ raw.charCodeAt(i), 16777619);
return (h >>> 0).toString(16).padStart(8, "0");
}
function trackInstallFingerprint(key, req) {
if (!key) return;
const fp = fingerprintRequest(req);
const now = new Date().toISOString();
const entry = _usage.get(key) || {
count: 0, first_used: now, last_used: now, requests_today: 0,
today_date: now.slice(0, 10), audits: 0, audit_windows: {},
};
entry.installs = entry.installs || [];
const existing = entry.installs.find((i) => i.fp === fp);
if (existing) {
existing.last_seen = now;
existing.count = (existing.count || 0) + 1;
} else {
entry.installs.push({ fp, first_seen: now, last_seen: now, count: 1 });
// Beyond 1st install for this key β log a sharing warning (soft).
if (entry.installs.length > 1) {
process.stderr.write(
`[pickle-share-watch] key=${key.slice(0, 18)}... now has ${entry.installs.length} distinct fingerprints; latest fp=${fp}\n`
);
}
}
_usage.set(key, entry);
}
// Platform-seen tracker β records WHICH platform tokens have been seen for a
// pickle_key (never the tokens themselves, just first/last-seen timestamps).
// Used for: smart error messages ("you have Slack but not Teams") + admin
// dashboard install-state view.
function trackPlatformsSeen(key, ctx) {
if (!key || !ctx) return;
const now = new Date().toISOString();
const entry = _usage.get(key) || {
count: 0, first_used: now, last_used: now, requests_today: 0,
today_date: now.slice(0, 10), audits: 0, audit_windows: {},
};
entry.platforms_seen = entry.platforms_seen || {};
for (const plat of ["clickup", "slack", "teams"]) {
const tokenKey = `${plat}Token`;
if (ctx[tokenKey]) {
const cur = entry.platforms_seen[plat] || {};
entry.platforms_seen[plat] = {
first: cur.first || now,
last: now,
request_count: (cur.request_count || 0) + 1,
};
}
}
_usage.set(key, entry);
}
// Anonymous audit-specific counter. Tracks how often each pickle key triggers
// an audit-style tool and the time-window distribution. No workspace data is
// stored; only counters + a string label of the window used.
function trackAudit(key, toolName, windowLabel) {
if (!key) return;
const now = new Date().toISOString();
const entry = _usage.get(key) || {
count: 0, first_used: now, last_used: now, requests_today: 0,
today_date: now.slice(0, 10), audits: 0, audit_windows: {},
};
entry.audits = (entry.audits || 0) + 1;
entry.last_audit = now;
entry.audit_windows = entry.audit_windows || {};
const label = windowLabel || "default";
entry.audit_windows[label] = (entry.audit_windows[label] || 0) + 1;
_usage.set(key, entry);
}
function getSignupStats() {
const signups = loadSignups();
const now = Date.now();
const day = 86400000;
const last30 = [];
for (let i = 29; i >= 0; i--) {
const start = now - (i + 1) * day;
const end = now - i * day;
const date = new Date(end - day).toISOString().slice(0, 10);
const count = signups.filter((s) => {
const t = new Date(s.created_at).getTime();
return t >= start && t < end;
}).length;
last30.push({ date, count });
}
const today = signups.filter((s) => now - new Date(s.created_at).getTime() < day).length;
const week = signups.filter((s) => now - new Date(s.created_at).getTime() < 7 * day).length;
const month = signups.filter((s) => now - new Date(s.created_at).getTime() < 30 * day).length;
// Usage metrics
const todayStr = new Date().toISOString().slice(0, 10);
let requests_today = 0;
let requests_total = 0;
let active_installs = 0;
let active_24h = 0;
for (const [, v] of _usage) {
requests_total += v.count || 0;
if (v.today_date === todayStr) requests_today += v.requests_today || 0;
if ((v.count || 0) > 0) active_installs++;
if (v.last_used && (now - new Date(v.last_used).getTime() < day)) active_24h++;
}
// Pro waitlist
const pro_waitlist = signups.filter((s) => s.intent === "pro").length;
const pro_today = signups.filter((s) => s.intent === "pro" && (now - new Date(s.pro_waitlist_at || s.created_at).getTime() < day)).length;
return {
total: signups.length,
today, week, month,
daily: last30,
usage: { requests_today, requests_total, active_installs, active_24h },
pro: { waitlist: pro_waitlist, today: pro_today },
brevo_configured: !!(BREVO_API_KEY && BREVO_LIST_ID),
revenue: { mrr_usd: 0, paid_users: 0, status: "polar_pending" },
};
}
function getUsageForKey(key) {
return _usage.get(key) || null;
}
// ---------------------------------------------------------------------------
// HTTP helpers
// ---------------------------------------------------------------------------
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
function backoffMs(n) { return 500 * Math.pow(2, n) + Math.floor(Math.random() * 250); }
async function safeReadText(res) { try { return await res.text(); } catch { return ""; } }
function buildUrl(base, pathStr, query) {
const url = new URL(pathStr, base);
if (query && typeof query === "object") {
for (const [key, value] of Object.entries(query)) {
if (value === undefined || value === null) continue;
if (Array.isArray(value)) {
for (const v of value) { if (v != null) url.searchParams.append(key, String(v)); }
} else if (typeof value === "boolean") {
url.searchParams.append(key, value ? "true" : "false");
} else {
url.searchParams.append(key, String(value));
}
}
}
return url.toString();
}
// ---------------------------------------------------------------------------
// Zod β JSON Schema (compact, no extra dep β identical to server.mjs)
// ---------------------------------------------------------------------------
function zodToJsonSchema(schema) {
const def = schema?._def;
if (!def) return { type: "object" };
switch (def.typeName) {
case "ZodObject": {
const shape = typeof def.shape === "function" ? def.shape() : def.shape;
const properties = {}, required = [];
for (const [key, child] of Object.entries(shape)) {
properties[key] = zodToJsonSchema(child);
if (!isOptional(child)) required.push(key);
}
const out = { type: "object", properties };
if (required.length) out.required = required;
if (def.unknownKeys === "strict") out.additionalProperties = false;
return out;
}
case "ZodString": {
const out = { type: "string" };
if (Array.isArray(def.checks)) {
for (const c of def.checks) {
if (c.kind === "min") out.minLength = c.value;
if (c.kind === "max") out.maxLength = c.value;
if (c.kind === "url") out.format = "uri";
}
}
if (schema.description) out.description = schema.description;
return out;
}
case "ZodNumber": {
const out = { type: "number" };
if (Array.isArray(def.checks)) {
for (const c of def.checks) {
if (c.kind === "int") out.type = "integer";
if (c.kind === "min") out.minimum = c.value;
if (c.kind === "max") out.maximum = c.value;
}
}
if (schema.description) out.description = schema.description;
return out;
}
case "ZodBoolean": return { type: "boolean", ...(schema.description ? { description: schema.description } : {}) };
case "ZodArray": { const out = { type: "array", items: zodToJsonSchema(def.type) }; if (schema.description) out.description = schema.description; return out; }
case "ZodEnum": return { type: "string", enum: def.values, ...(schema.description ? { description: schema.description } : {}) };
case "ZodLiteral": return { const: def.value };
case "ZodUnion": return { anyOf: def.options.map((o) => zodToJsonSchema(o)) };
case "ZodRecord": return { type: "object", additionalProperties: zodToJsonSchema(def.valueType) };
case "ZodOptional": return zodToJsonSchema(def.innerType);
case "ZodNullable": { const inner = zodToJsonSchema(def.innerType); return inner.type ? { ...inner, type: [inner.type, "null"] } : { anyOf: [inner, { type: "null" }] }; }
case "ZodDefault": return { ...zodToJsonSchema(def.innerType), default: def.defaultValue() };
case "ZodEffects": return zodToJsonSchema(def.schema);
case "ZodAny": case "ZodUnknown": return {};
default: return {};
}
}
function isOptional(schema) {
const def = schema?._def;
if (!def) return false;
if (def.typeName === "ZodOptional" || def.typeName === "ZodDefault") return true;
if (def.typeName === "ZodEffects") return isOptional(def.schema);
return false;
}
// ---------------------------------------------------------------------------
// MCP server factory β creates a new server instance per request
// Captures the ClickUp token via closure; uses per-user cache for team data.
// ---------------------------------------------------------------------------
const TOOL_COUNT = 40; // Updated at runtime in startupLog
function createPickleServer(ctxOrLegacyToken, legacyPickleKey = "") {
// Backwards-compat: old call sites passed (clickupToken, pickleKey).
// New call sites pass a ctx object: { pickleKey, clickupToken, slackToken, teamsToken }.
const ctx = (typeof ctxOrLegacyToken === "object" && ctxOrLegacyToken !== null)
? ctxOrLegacyToken
: { clickupToken: String(ctxOrLegacyToken || ""), pickleKey: legacyPickleKey, slackToken: "", teamsToken: "" };
const { clickupToken = "", slackToken = "", teamsToken = "", pickleKey = "" } = ctx;
// clickupToken may be empty when user is setting up β that's allowed for setup-only flow.
const tokenHash = clickupToken ? hashToken(clickupToken) : null;
// ββ Per-user ClickUp HTTP client βββββββββββββββββββββββββββββββββββββββββ
async function clickupFetch(method, pathStr, { query, body } = {}) {
if (!clickupToken) {
throw new McpError(
ErrorCode.InvalidRequest,
`ClickUp isn't connected for this Pickle key yet. ${(() => {
const connected = [];
if (slackToken) connected.push("Slack");
if (teamsToken) connected.push("Microsoft Teams");
if (!connected.length) return "Run `pickle_setup` with platform=\"clickup\" to connect.";
return `You currently have ${connected.join(" and ")} connected. Either audit there instead, or run \`pickle_setup\` with platform="clickup" to connect ClickUp.`;
})()}`
);
}
const url = buildUrl(API_BASE, pathStr, query);
assertSafeHost(url);
const headers = {
Authorization: clickupToken,
Accept: "application/json",
"User-Agent": USER_AGENT,
};
if (body !== undefined) headers["Content-Type"] = "application/json";
let lastErr = null;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const controller = new AbortController();
const th = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let res;
try {
res = await fetch(url, {
method, headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: controller.signal,
});
} catch (err) {
clearTimeout(th);
lastErr = err;
if (attempt < MAX_RETRIES) { await sleep(backoffMs(attempt)); continue; }
throw new McpError(ErrorCode.InternalError,
`ClickUp request failed after ${MAX_RETRIES + 1} attempts: ${err?.message ?? err}`);
}
clearTimeout(th);
if (res.ok) {
if (res.status === 204) return { ok: true, status: 204 };
const text = await res.text();
if (!text) return { ok: true, status: res.status };
try { return JSON.parse(text); } catch { return { ok: true, status: res.status, raw: text }; }
}
if (res.status === 429 && attempt < MAX_RETRIES) {
const ra = res.headers.get("retry-after");
let wait = ra ? (Number.isFinite(+ra) ? +ra * 1000 : Math.max(0, new Date(ra) - Date.now())) : backoffMs(attempt);
if (!Number.isFinite(wait) || wait < 0) wait = backoffMs(attempt);
await sleep(Math.min(wait, 60_000));
continue;
}
const isIdempotent = method === "GET" || method === "HEAD";
if (res.status >= 500 && isIdempotent && attempt < MAX_RETRIES) {
await sleep(backoffMs(attempt)); continue;
}
const errorBody = await safeReadText(res);
throw new McpError(ErrorCode.InternalError,
`ClickUp API ${method} ${pathStr} β HTTP ${res.status} ${res.statusText}: ${errorBody || "(no body)"}`);
}
throw new McpError(ErrorCode.InternalError,
`ClickUp request exhausted retries: ${lastErr?.message ?? "unknown"}`);
}
// ββ Per-user team resolution (cached) βββββββββββββββββββββββββββββββββββ
async function listTeams() {
const cached = getCached(tokenHash, "teams");
if (cached) return cached;
const data = await clickupFetch("GET", "/api/v2/team");
const teams = Array.isArray(data?.teams) ? data.teams : [];
setCached(tokenHash, "teams", teams);
return teams;
}
async function resolveTeamId(override) {
if (override) return String(override);
const cached = getCached(tokenHash, "teamId");
if (cached) return cached;
const teams = await listTeams();
if (!teams.length) throw new McpError(ErrorCode.InternalError, "No ClickUp workspaces found for this token.");
const teamId = String(teams[0].id);
setCached(tokenHash, "teamId", teamId);
return teamId;
}
// ββ Hierarchy helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function getSpaces(teamId) {
const d = await clickupFetch("GET", `/api/v2/team/${teamId}/space`, { query: { archived: false } });
return Array.isArray(d?.spaces) ? d.spaces : [];
}
async function getFoldersForSpace(spaceId) {
const d = await clickupFetch("GET", `/api/v2/space/${spaceId}/folder`, { query: { archived: false } });
return Array.isArray(d?.folders) ? d.folders : [];
}
async function getFolderlessLists(spaceId) {
const d = await clickupFetch("GET", `/api/v2/space/${spaceId}/list`, { query: { archived: false } });
return Array.isArray(d?.lists) ? d.lists : [];
}
async function getListsInFolder(folderId) {
const d = await clickupFetch("GET", `/api/v2/folder/${folderId}/list`, { query: { archived: false } });
return Array.isArray(d?.lists) ? d.lists : [];
}
// Helper: tell the user what they DO have connected when they ask for
// something they don't. Surfaces a smart "I see you have X β want X instead?"
function connectedPlatformsHint(missing) {
const connected = [];
if (clickupToken && missing !== "clickup") connected.push("ClickUp");
if (slackToken && missing !== "slack") connected.push("Slack");
if (teamsToken && missing !== "teams") connected.push("Microsoft Teams");
if (!connected.length) {
return `Run \`pickle_setup\` with platform="${missing}" to connect.`;
}
return `You currently have ${connected.join(" and ")} connected. Either audit there instead, or run \`pickle_setup\` with platform="${missing}" to connect ${missing}.`;
}
// ββ Per-user Slack HTTP client ββββββββββββββββββββββββββββββββββββββββββββ
// Generic, used by every Slack tool below. SSRF-guarded to slack.com only.
async function slackFetch(method, pathStr, { query, body } = {}) {
if (!slackToken) {
throw new McpError(
ErrorCode.InvalidRequest,
`Slack isn't connected for this Pickle key yet. ${connectedPlatformsHint("slack")}`
);
}
const url = buildUrl("https://slack.com", pathStr, query);
assertSafeHost(url);
const headers = {
Authorization: `Bearer ${slackToken.replace(/^Bearer\s+/i, "")}`,
Accept: "application/json",
"User-Agent": USER_AGENT,
};
if (body !== undefined) headers["Content-Type"] = "application/json; charset=utf-8";
let lastErr = null;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
const controller = new AbortController();
const th = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
let res;
try {
res = await fetch(url, {
method, headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: controller.signal,
});
} catch (err) {
clearTimeout(th);
lastErr = err;
if (attempt < MAX_RETRIES) { await sleep(backoffMs(attempt)); continue; }
throw new McpError(ErrorCode.InternalError,
`Slack request failed after ${MAX_RETRIES + 1} attempts: ${err?.message ?? err}`);
}
clearTimeout(th);