@productbrain/mcp 0.0.1-beta.14272 → 0.0.1-beta.14280

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // src/cli/index.ts
4
4
  var subcommand = process.argv[2];
5
5
  if (subcommand === "setup") {
6
- const { runSetup } = await import("../setup-23QCEKGB.js");
6
+ const { runSetup } = await import("../setup-3QVGCBO3.js");
7
7
  await runSetup();
8
8
  } else {
9
9
  await import("../index.js");
package/dist/http.js CHANGED
@@ -1,80 +1,26 @@
1
1
  import {
2
2
  SERVER_VERSION,
3
3
  createProductBrainServer
4
- } from "./chunk-JEMDFT7G.js";
4
+ } from "./chunk-TPOWHC6M.js";
5
5
  import {
6
6
  DEFAULT_CLOUD_URL,
7
7
  appUrl,
8
8
  bootstrapHttp,
9
9
  checkKeyAgainstCandidates,
10
- forgetStreamLifecycle,
11
10
  getKeyState,
12
11
  hashKey,
13
12
  isApiKeyShaped,
14
13
  parseFallbackUrls,
15
14
  runWithAuth
16
- } from "./chunk-F4FYLPGO.js";
15
+ } from "./chunk-RHPRF4OG.js";
17
16
 
18
17
  // src/http.ts
19
18
  import { randomUUID } from "crypto";
20
19
  import express from "express";
21
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
22
- import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
20
+ import { createMcpHandler } from "@modelcontextprotocol/server";
21
+ import { toNodeHandler } from "@modelcontextprotocol/node";
23
22
  import rateLimit2 from "express-rate-limit";
24
23
 
25
- // src/sessionCap.ts
26
- function planKeyAdmission(sessions2, keyHash, cap, now, opts) {
27
- if (cap < 1) {
28
- throw new RangeError(`cap must be >= 1, got ${cap}`);
29
- }
30
- const { ttlMs, graceMs } = opts;
31
- const isProtected = (s) => s.inFlight > 0 || now - s.lastAccess < graceMs;
32
- const keyEntries = [];
33
- for (const [id, session] of sessions2) {
34
- if (session.keyHash === keyHash) {
35
- keyEntries.push([id, session]);
36
- }
37
- }
38
- const evictSet = /* @__PURE__ */ new Set();
39
- for (const [id, session] of keyEntries) {
40
- if (!isProtected(session) && now - session.lastAccess >= ttlMs) {
41
- evictSet.add(id);
42
- }
43
- }
44
- let survivors = keyEntries.filter(([id]) => !evictSet.has(id));
45
- if (survivors.length >= cap) {
46
- const idleSurvivors = survivors.filter(([, s]) => !isProtected(s)).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
47
- for (const [id] of idleSurvivors) {
48
- if (survivors.length < cap) break;
49
- evictSet.add(id);
50
- survivors = survivors.filter(([sid]) => sid !== id);
51
- }
52
- }
53
- const evict = Array.from(evictSet);
54
- const admit = survivors.length < cap;
55
- let retryAfterSeconds = 0;
56
- let retryIsPoll = false;
57
- if (!admit) {
58
- const graceBlockers = survivors.filter(([, s]) => s.inFlight === 0);
59
- if (graceBlockers.length > 0) {
60
- const minLastAccess = Math.min(...graceBlockers.map(([, s]) => s.lastAccess));
61
- const msRemaining = graceMs - (now - minLastAccess);
62
- retryAfterSeconds = Math.max(1, Math.ceil(msRemaining / 1e3));
63
- } else {
64
- retryAfterSeconds = 5;
65
- retryIsPoll = true;
66
- }
67
- }
68
- return { evict, admit, retryAfterSeconds, retryIsPoll };
69
- }
70
- function countKeySessions(sessions2, keyHash) {
71
- let count = 0;
72
- for (const session of sessions2.values()) {
73
- if (session.keyHash === keyHash) count++;
74
- }
75
- return count;
76
- }
77
-
78
24
  // src/httpErrors.ts
79
25
  function clampSeconds(s) {
80
26
  return Math.max(0, Math.round(s));
@@ -116,11 +62,6 @@ function buildAuthLockoutError(p) {
116
62
  p
117
63
  );
118
64
  }
119
- function buildSessionCapError(p) {
120
- const seconds = clampSeconds(p.retryAfterSeconds);
121
- const message = p.poll ? "Server busy \u2014 all sessions active; retry shortly." : `Too many active sessions for this key \u2014 retry after ${seconds} s.`;
122
- return build("session_cap", message, p);
123
- }
124
65
  function send429(res, built) {
125
66
  if (res.headersSent) return;
126
67
  for (const [k, v] of Object.entries(built.headers)) {
@@ -520,9 +461,9 @@ app.use((_req, res, next) => {
520
461
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
521
462
  res.setHeader(
522
463
  "Access-Control-Allow-Headers",
523
- "Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id"
464
+ "Content-Type, Authorization, Mcp-Protocol-Version, Mcp-Method, Mcp-Name"
524
465
  );
525
- res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, Retry-After");
466
+ res.setHeader("Access-Control-Expose-Headers", "Retry-After");
526
467
  if (_req.method === "OPTIONS") {
527
468
  res.status(204).end();
528
469
  return;
@@ -611,47 +552,9 @@ var authFailures = /* @__PURE__ */ new Map();
611
552
  app.get("/health", (_req, res) => {
612
553
  res.json({ status: "ok", version: SERVER_VERSION, transport: "http" });
613
554
  });
614
- var sessions = /* @__PURE__ */ new Map();
615
- var SESSION_TTL_MS = 30 * 60 * 1e3;
616
- var MAX_SESSIONS = 200;
617
- var EVICT_GRACE_MS = 6e4;
618
- var MAX_SESSIONS_PER_KEY = Math.max(
619
- 1,
620
- Math.min(MAX_SESSIONS - 1, Number(process.env.MCP_MAX_SESSIONS_PER_KEY) || 25)
621
- );
622
- function evictStaleSessions() {
623
- const now = Date.now();
624
- for (const [id, entry] of sessions) {
625
- if (now - entry.lastAccess > SESSION_TTL_MS) {
626
- logSessionLifecycle(
627
- "session_deleted",
628
- id,
629
- entry.inFlight > 0 ? "inflight_leak" : "ttl"
630
- );
631
- entry.transport.close().catch(() => {
632
- });
633
- sessions.delete(id);
634
- }
635
- }
636
- if (sessions.size > MAX_SESSIONS) {
637
- const sorted = [...sessions.entries()].filter(([, e]) => e.inFlight === 0).sort((a, b) => a[1].lastAccess - b[1].lastAccess);
638
- const overflow = sessions.size - MAX_SESSIONS;
639
- for (let i = 0; i < Math.min(overflow, sorted.length); i++) {
640
- logSessionLifecycle("session_deleted", sorted[i][0], "eviction");
641
- sorted[i][1].transport.close().catch(() => {
642
- });
643
- sessions.delete(sorted[i][0]);
644
- }
645
- if (sessions.size > MAX_SESSIONS) {
646
- const ts = (/* @__PURE__ */ new Date()).toISOString();
647
- process.stderr.write(
648
- `[HTTP] ${ts} session_cap_breach size=${sessions.size} max=${MAX_SESSIONS} reason=all_inflight (no idle sessions to evict; TTL backstop will reclaim)
649
- `
650
- );
651
- }
652
- }
653
- }
654
- setInterval(evictStaleSessions, 6e4);
555
+ var mcpHandler = createMcpHandler(createProductBrainServer, { onerror: (err) => process.stderr.write(`[HTTP] handler_error ${err.message}
556
+ `) });
557
+ var serveNode = toNodeHandler(mcpHandler);
655
558
  function send401(req, res) {
656
559
  const base = baseUrl(req);
657
560
  res.status(401).set(
@@ -659,265 +562,62 @@ function send401(req, res) {
659
562
  `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`
660
563
  ).json({ error: "unauthorized" });
661
564
  }
662
- function logRequest(method, outcome, sessionId, durationMs) {
565
+ function logRequest(method, outcome, durationMs, status) {
663
566
  const ts = (/* @__PURE__ */ new Date()).toISOString();
664
- const sid = sessionId ? ` session=${sessionId}` : "";
567
+ const st = status != null ? ` status=${status}` : "";
665
568
  const dur = durationMs != null ? ` duration=${durationMs}ms` : "";
666
- process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${sid}${dur}
667
- `);
668
- }
669
- function logSessionLifecycle(event, sessionId, reason) {
670
- const ts = (/* @__PURE__ */ new Date()).toISOString();
671
- const r = reason ? ` reason=${reason}` : "";
672
- process.stderr.write(`[HTTP] ${ts} ${event} session=${sessionId}${r}
569
+ process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${st}${dur}
673
570
  `);
674
571
  }
675
- app.post("/mcp", ...mcpLimit, async (req, res) => {
572
+ function admit(req, res, auth) {
676
573
  const nowTs = Date.now();
677
- const auth = resolveBearerAuth(req.headers?.authorization);
678
574
  const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
679
575
  if (lockout) {
680
576
  send429(res, lockout);
681
577
  return;
682
578
  }
683
- if (auth.status !== "ok") {
684
- logRequest("POST", "auth_fail");
685
- if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
579
+ if (auth.status === "ok") return auth;
580
+ logRequest(req.method, "auth_fail");
581
+ if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
582
+ send401(req, res);
583
+ }
584
+ function keyPasses(req, res, auth, check) {
585
+ const gate = keyVerdictGate(check.verdict, authFailures, auth.credentialId, Date.now());
586
+ if (gate === "unauthorized") {
587
+ logRequest(req.method, "auth_fail");
686
588
  send401(req, res);
687
- return;
589
+ return false;
688
590
  }
689
- const apiKey = auth.apiKey;
690
- const sessionId = req.headers["mcp-session-id"];
591
+ if (gate === "unavailable") {
592
+ res.status(503).json({ jsonrpc: "2.0", error: { code: -32e3, message: "Product Brain could not verify this API key right now. Retry shortly." }, id: req.body?.id ?? null });
593
+ return false;
594
+ }
595
+ if (check.verdict === "ok" || check.verdict === "rate_limited") getKeyState(auth.apiKey).deploymentUrl = check.deploymentUrl;
596
+ return true;
597
+ }
598
+ async function serve(req, res, apiKey, handle) {
691
599
  const reqStart = Date.now();
692
600
  try {
693
- await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
694
- if (sessionId && sessions.has(sessionId)) {
695
- const entry = sessions.get(sessionId);
696
- if (entry.keyHash !== hashKey(apiKey)) {
697
- res.status(403).json({
698
- jsonrpc: "2.0",
699
- error: { code: -32e3, message: "Session key mismatch" },
700
- id: null
701
- });
702
- return;
703
- }
704
- try {
705
- entry.inFlight++;
706
- entry.lastAccess = Date.now();
707
- await entry.transport.handleRequest(req, res, req.body);
708
- logRequest("POST", "ok", sessionId, Date.now() - reqStart);
709
- } finally {
710
- entry.inFlight--;
711
- entry.lastAccess = Date.now();
712
- }
713
- } else if (!sessionId && isInitializeRequest(req.body)) {
714
- const check = await checkKeyAgainstCandidates(keyCheckCandidates(), apiKey, 5e3);
715
- const gate = keyVerdictGate(check.verdict, authFailures, auth.credentialId, Date.now());
716
- if (gate === "unauthorized") {
717
- logRequest("POST", "auth_fail");
718
- send401(req, res);
719
- return;
720
- }
721
- if (gate === "unavailable") {
722
- res.status(503).json({
723
- jsonrpc: "2.0",
724
- error: { code: -32e3, message: "Product Brain could not verify this API key right now. Retry shortly." },
725
- id: req.body?.id ?? null
726
- });
727
- return;
728
- }
729
- if (check.verdict === "ok" || check.verdict === "rate_limited") getKeyState(apiKey).deploymentUrl = check.deploymentUrl;
730
- const keyH = hashKey(apiKey);
731
- const plan = planKeyAdmission(
732
- sessions,
733
- keyH,
734
- MAX_SESSIONS_PER_KEY,
735
- Date.now(),
736
- { ttlMs: SESSION_TTL_MS, graceMs: EVICT_GRACE_MS }
737
- );
738
- for (const sid2 of plan.evict) {
739
- const victim = sessions.get(sid2);
740
- sessions.delete(sid2);
741
- victim?.transport.close().catch(() => {
742
- });
743
- logSessionLifecycle("session_deleted", sid2, "lru_evict");
744
- }
745
- if (!plan.admit) {
746
- send429(res, buildSessionCapError({
747
- retryAfterSeconds: plan.retryAfterSeconds,
748
- limit: MAX_SESSIONS_PER_KEY,
749
- current: countKeySessions(sessions, keyH),
750
- poll: plan.retryIsPoll,
751
- id: req.body?.id ?? null
752
- }));
753
- return;
754
- }
755
- const sid = randomUUID();
756
- let initialized = false;
757
- const transport = new StreamableHTTPServerTransport({
758
- sessionIdGenerator: () => sid,
759
- onsessioninitialized: (s) => {
760
- initialized = true;
761
- logSessionLifecycle("session_created", s);
762
- }
763
- // log only — no map write
764
- });
765
- const reserved = { transport, lastAccess: Date.now(), keyHash: keyH, inFlight: 1 };
766
- sessions.set(sid, reserved);
767
- transport.onclose = () => {
768
- const s = transport.sessionId ?? sid;
769
- forgetStreamLifecycle(keyH, s);
770
- if (sessions.has(s)) {
771
- sessions.delete(s);
772
- logSessionLifecycle("session_deleted", s, "onclose");
773
- }
774
- };
775
- try {
776
- const server = createProductBrainServer();
777
- await server.connect(transport);
778
- await transport.handleRequest(req, res, req.body);
779
- logRequest("POST", "ok", transport.sessionId ?? void 0, Date.now() - reqStart);
780
- } catch (e) {
781
- transport.onclose = void 0;
782
- sessions.delete(sid);
783
- throw e;
784
- } finally {
785
- if (!initialized) {
786
- transport.onclose = void 0;
787
- if (sessions.delete(sid)) logSessionLifecycle("session_deleted", sid, "init_rejected");
788
- } else {
789
- const e = sessions.get(sid);
790
- if (e) {
791
- e.inFlight--;
792
- e.lastAccess = Date.now();
793
- }
794
- }
795
- }
796
- } else if (sessionId) {
797
- process.stderr.write(
798
- `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale sessionId=${sessionId} (likely server restart \u2014 instructing client to re-initialise)
799
- `
800
- );
801
- res.status(404).json({
802
- jsonrpc: "2.0",
803
- error: { code: -32001, message: "Session not found \u2014 re-initialise" },
804
- id: null
805
- });
806
- } else {
807
- process.stderr.write(
808
- `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_invalid no valid session ID (client may have omitted Mcp-Session-Id)
809
- `
810
- );
811
- res.status(400).json({
812
- jsonrpc: "2.0",
813
- error: { code: -32e3, message: "Bad Request: no valid session ID provided" },
814
- id: null
815
- });
816
- }
817
- });
818
- } catch (err) {
819
- logRequest("POST", "error", sessionId, Date.now() - reqStart);
820
- if (!res.headersSent) {
821
- res.status(500).json({
822
- jsonrpc: "2.0",
823
- error: { code: -32603, message: "Internal server error" },
824
- id: null
825
- });
826
- }
601
+ await runWithAuth({ apiKey, requestId: randomUUID() }, handle);
602
+ logRequest(req.method, "ok", Date.now() - reqStart, res.statusCode);
603
+ } catch {
604
+ logRequest(req.method, "error", Date.now() - reqStart);
605
+ if (!res.headersSent) res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null });
827
606
  }
607
+ }
608
+ app.post("/mcp", ...mcpLimit, async (req, res) => {
609
+ const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));
610
+ if (!auth) return;
611
+ if (!keyPasses(req, res, auth, await checkKeyAgainstCandidates(keyCheckCandidates(), auth.apiKey, 5e3))) return;
612
+ await serve(req, res, auth.apiKey, () => serveNode(req, res, req.body));
828
613
  });
829
614
  app.get("/mcp", ...mcpLimit, async (req, res) => {
830
- const nowTs = Date.now();
831
- const auth = resolveBearerAuth(req.headers?.authorization);
832
- const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
833
- if (lockout) {
834
- send429(res, lockout);
835
- return;
836
- }
837
- if (auth.status !== "ok") {
838
- logRequest("GET", "auth_fail");
839
- if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
840
- send401(req, res);
841
- return;
842
- }
843
- const apiKey = auth.apiKey;
844
- const sessionId = req.headers["mcp-session-id"];
845
- if (!sessionId) {
846
- res.status(400).send("Missing Mcp-Session-Id header");
847
- return;
848
- }
849
- if (!sessions.has(sessionId)) {
850
- process.stderr.write(
851
- `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale GET sessionId=${sessionId}
852
- `
853
- );
854
- res.status(404).send("Session not found \u2014 re-initialise");
855
- return;
856
- }
857
- try {
858
- await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
859
- const entry = sessions.get(sessionId);
860
- if (entry.keyHash !== hashKey(apiKey)) {
861
- res.status(403).json({
862
- jsonrpc: "2.0",
863
- error: { code: -32e3, message: "Session key mismatch" },
864
- id: null
865
- });
866
- return;
867
- }
868
- entry.lastAccess = Date.now();
869
- await entry.transport.handleRequest(req, res);
870
- logRequest("GET", "ok", sessionId);
871
- });
872
- } catch {
873
- logRequest("GET", "error", sessionId);
874
- }
615
+ const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));
616
+ if (auth) await serve(req, res, auth.apiKey, () => serveNode(req, res));
875
617
  });
876
618
  app.delete("/mcp", ...mcpLimit, async (req, res) => {
877
- const nowTs = Date.now();
878
- const auth = resolveBearerAuth(req.headers?.authorization);
879
- const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
880
- if (lockout) {
881
- send429(res, lockout);
882
- return;
883
- }
884
- if (auth.status !== "ok") {
885
- logRequest("DELETE", "auth_fail");
886
- if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
887
- send401(req, res);
888
- return;
889
- }
890
- const apiKey = auth.apiKey;
891
- const sessionId = req.headers["mcp-session-id"];
892
- if (!sessionId) {
893
- res.status(400).send("Missing Mcp-Session-Id header");
894
- return;
895
- }
896
- if (!sessions.has(sessionId)) {
897
- process.stderr.write(
898
- `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale DELETE sessionId=${sessionId}
899
- `
900
- );
901
- res.status(404).send("Session not found \u2014 re-initialise");
902
- return;
903
- }
904
- try {
905
- await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
906
- const entry = sessions.get(sessionId);
907
- if (entry.keyHash !== hashKey(apiKey)) {
908
- res.status(403).json({
909
- jsonrpc: "2.0",
910
- error: { code: -32e3, message: "Session key mismatch" },
911
- id: null
912
- });
913
- return;
914
- }
915
- await entry.transport.handleRequest(req, res);
916
- logRequest("DELETE", "ok", sessionId);
917
- });
918
- } catch {
919
- logRequest("DELETE", "error", sessionId);
920
- }
619
+ const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));
620
+ if (auth) await serve(req, res, auth.apiKey, () => serveNode(req, res));
921
621
  });
922
622
  process.on("unhandledRejection", (reason) => {
923
623
  const msg = reason instanceof Error ? reason.message : String(reason);
@@ -933,10 +633,8 @@ async function gracefulShutdown() {
933
633
  shuttingDown = true;
934
634
  setTimeout(() => process.exit(1), 3e3).unref();
935
635
  console.log("Shutting down...");
936
- for (const [, entry] of sessions) {
937
- await entry.transport.close().catch(() => {
938
- });
939
- }
636
+ await mcpHandler.close().catch(() => {
637
+ });
940
638
  process.exit(0);
941
639
  }
942
640
  var LISTEN_HOST = "0.0.0.0";