findymail-mcp 0.1.15 → 0.1.17

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 CHANGED
@@ -47,7 +47,7 @@ For `exclusion_list_ids`:
47
47
  ## Prerequisites
48
48
 
49
49
  - Node.js 18+
50
- - A Findymail API key ([get one here](https://app.findymail.com/settings/api))
50
+ - A Findymail API key ([get one here](https://app.findymail.com/user/api-tokens))
51
51
 
52
52
  ## Installation
53
53
 
@@ -130,6 +130,12 @@ PORT=3456 node src/http.js
130
130
 
131
131
  Requests to `/mcp` without a valid `Authorization: Bearer <token>` header will be rejected with a 401 error.
132
132
 
133
+ ### Optional settings
134
+
135
+ | Variable | Default | Effect |
136
+ |---|---|---|
137
+ | `FINDYMAIL_API_TIMEOUT_MS` | `100000` | How long a call to the Findymail API may take before the tool gives up. A value that is not a whole number between 1 and 2147483647 is ignored, with a warning in the logs. |
138
+
133
139
  ## Usage Examples
134
140
 
135
141
  Once configured, you can ask your AI assistant:
@@ -146,7 +152,7 @@ Once configured, you can ask your AI assistant:
146
152
 
147
153
  ## API Key
148
154
 
149
- Get your API key from [Findymail Settings](https://app.findymail.com/settings/api).
155
+ Get your API key from [Findymail Settings](https://app.findymail.com/user/api-tokens).
150
156
 
151
157
  Each API call consumes credits from your Findymail account.
152
158
 
@@ -162,6 +168,9 @@ npm install
162
168
 
163
169
  # Run locally
164
170
  FINDYMAIL_API_KEY=your-key npm start
171
+
172
+ # Run the tests (Node 18.2+, no network access or API key needed)
173
+ npm test
165
174
  ```
166
175
 
167
176
  ## Deployment
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "findymail-mcp",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "MCP server for Findymail - Find verified B2B emails, phone numbers, and company data",
5
5
  "type": "module",
6
6
  "main": "src/stdio.js",
@@ -12,7 +12,8 @@
12
12
  ],
13
13
  "scripts": {
14
14
  "start": "node src/stdio.js",
15
- "start:http": "node src/http.js"
15
+ "start:http": "node src/http.js",
16
+ "test": "node --test"
16
17
  },
17
18
  "keywords": [
18
19
  "mcp",
package/src/api.js CHANGED
@@ -1,5 +1,28 @@
1
+ // Fixed on purpose: every call carries the user's API key, so the host it goes
2
+ // to is not something configuration should be able to change.
1
3
  const API_BASE_URL = "https://app.findymail.com/api";
2
4
 
5
+ // Cloudflare gives up on the origin at 100s, so no call can still succeed past
6
+ // that. Without a deadline at all, an upstream that stopped answering held the
7
+ // tool call open forever — and a session with a request in flight is never
8
+ // reclaimed, so each one leaked.
9
+ const DEFAULT_API_TIMEOUT_MS = 100 * 1000;
10
+ // Timers cannot go past a signed 32-bit millisecond count: AbortSignal.timeout
11
+ // throws below 0 and silently fires after 1ms above this.
12
+ const MAX_TIMER_MS = 2 ** 31 - 1;
13
+ const API_TIMEOUT_MS = apiTimeoutFromEnv(process.env.FINDYMAIL_API_TIMEOUT_MS);
14
+
15
+ // A bad value must not break every call, so fall back to the default — loudly.
16
+ function apiTimeoutFromEnv(raw) {
17
+ if (raw === undefined || raw === "") return DEFAULT_API_TIMEOUT_MS;
18
+
19
+ const ms = Number(raw);
20
+ if (Number.isInteger(ms) && ms >= 1 && ms <= MAX_TIMER_MS) return ms;
21
+
22
+ log(`FINDYMAIL_API_TIMEOUT_MS=${raw} is not a whole number of milliseconds between 1 and ${MAX_TIMER_MS} — using ${DEFAULT_API_TIMEOUT_MS}`);
23
+ return DEFAULT_API_TIMEOUT_MS;
24
+ }
25
+
3
26
  /**
4
27
  * Log to stderr (stdout is reserved for MCP protocol in stdio mode)
5
28
  */
@@ -34,18 +57,104 @@ export function resolveApiKey(extra) {
34
57
  // Laravel's abort(403) and abort(404) send an empty `message`, so a failure can
35
58
  // carry no reason at all. Give the agent something actionable per status code.
36
59
  const STATUS_REASONS = {
37
- 401: "Unauthorized — the API key is missing, invalid or expired",
60
+ 400: "Bad request — the API could not process the parameters as sent",
61
+ 401: "Unauthorized — the API key is missing, invalid or expired. Keys are managed at https://app.findymail.com/user/api-tokens",
62
+ 402: "Out of credits — your Findymail account has no credits left for this call",
38
63
  403: "Forbidden — none of the resources you targeted belong to you, or your account may not edit them",
39
64
  404: "Not found — the resource does not exist",
40
- 429: "Too many requests — rate limit reached, retry later",
65
+ 422: "Invalid parameters — the API rejected the request payload",
66
+ 429: "Too many requests — rate limit reached",
67
+ 500: "Findymail server error — the call never completed, retry it",
68
+ 502: "Findymail is unreachable — retry in a few seconds",
69
+ 503: "Findymail is temporarily unavailable — retry in a few seconds",
70
+ 504: "Findymail timed out — retry in a few seconds",
41
71
  };
42
72
 
73
+ // Running out mid-run is the failure an agent is most likely to hit, and the
74
+ // one it can least afford to read as a generic error: say which pool is empty
75
+ // and where to refill it, so the caller stops instead of retrying the loop.
76
+ const CREDIT_GUIDANCE =
77
+ "Finder credits (email, phone, company, employee and lead-list lookups) and verifier credits (`verify_email`) are separate pools, so one being empty leaves the other usable. Top up or change plan at https://app.findymail.com/subscription.";
78
+
79
+ function isCreditFailure(status, reason) {
80
+ return status === 402 || /\bcredits?\b|\bquota\b/i.test(reason ?? "");
81
+ }
82
+
83
+ // The messages under a field are usually an array of strings, but nested rules
84
+ // answer with an object keyed by sub-field — flatten whatever shape arrives
85
+ // rather than letting it stringify to [object Object].
86
+ function flatten(value) {
87
+ if (Array.isArray(value)) return value.flatMap(flatten);
88
+ if (value && typeof value === "object") return Object.values(value).flatMap(flatten);
89
+ return value === undefined || value === null || value === "" ? [] : [String(value)];
90
+ }
91
+
92
+ // Laravel validation answers with {"message": "...", "errors": {field: [...]}},
93
+ // and the field list is the only part that says what to change.
94
+ function validationDetail(payload) {
95
+ const errors = payload.errors;
96
+ if (!errors || typeof errors !== "object") return "";
97
+
98
+ const fields = Object.entries(errors)
99
+ .map(([field, messages]) => `${field}: ${flatten(messages).join(" ")}`)
100
+ .filter(Boolean)
101
+ .join("; ");
102
+
103
+ return fields ? ` Rejected parameters — ${fields}` : "";
104
+ }
105
+
106
+ // RFC 7231 allows Retry-After to be either delay-seconds or an HTTP-date, and
107
+ // pasting the date form straight in produced "Retry after Wed, 21 Oct 2015
108
+ // 07:28:00 GMTs". Normalise both to seconds from now.
109
+ function retryDetail(response) {
110
+ if (response.status !== 429) return "";
111
+
112
+ const retryAfter = response.headers.get("retry-after")?.trim();
113
+ if (!retryAfter) return " Back off before retrying.";
114
+
115
+ if (/^\d+$/.test(retryAfter)) return ` Retry after ${retryAfter}s.`;
116
+
117
+ const at = Date.parse(retryAfter);
118
+ if (Number.isNaN(at)) return ` Retry after ${retryAfter}.`;
119
+
120
+ return ` Retry after ${Math.max(0, Math.round((at - Date.now()) / 1000))}s.`;
121
+ }
122
+
123
+ // A gateway, a WAF or a PHP fatal answers with HTML rather than JSON, and a
124
+ // JSON body can carry its reason under a key we do not know. Either way the
125
+ // body is the only clue left, so pass it through instead of the bare status.
126
+ function bodyDetail(raw) {
127
+ const text = raw.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
128
+ if (!text) return "";
129
+ return ` Response body: ${text.length > 300 ? `${text.slice(0, 300)}…` : text}`;
130
+ }
131
+
43
132
  /**
44
133
  * Turn a failed response into an Error carrying the best reason available.
45
134
  * The status is attached so callers can add their own context.
46
135
  */
136
+ // Echoing the body is only worth it when we could not read a reason out of it:
137
+ // a JSON error that simply carried an empty `message` adds nothing.
138
+ function showBody(reason, parsedAsJson, payload) {
139
+ if (reason) return false;
140
+ if (!parsedAsJson) return true;
141
+ return Object.keys(payload).some(key => !["message", "error", "errors"].includes(key));
142
+ }
143
+
47
144
  async function apiError(response) {
48
- const payload = await response.json().catch(() => ({}));
145
+ const raw = await response.text().catch(() => "");
146
+
147
+ let payload = {};
148
+ let parsedAsJson = false;
149
+ try {
150
+ const parsed = raw ? JSON.parse(raw) : {};
151
+ if (parsed && typeof parsed === "object") {
152
+ payload = parsed;
153
+ parsedAsJson = true;
154
+ }
155
+ } catch {
156
+ // Not JSON — bodyDetail below surfaces it verbatim.
157
+ }
49
158
 
50
159
  // Some endpoints report the reason under `error` rather than `message`, and
51
160
  // an aborted request reports an empty string under both.
@@ -53,78 +162,124 @@ async function apiError(response) {
53
162
  .find(value => typeof value === "string" && value.trim() !== "")
54
163
  ?.trim();
55
164
 
56
- const error = new Error(
57
- reason || `${STATUS_REASONS[response.status] ?? "API error"} (HTTP ${response.status})`
58
- );
165
+ const message = [
166
+ `${reason || STATUS_REASONS[response.status] || "API error"} (HTTP ${response.status})`,
167
+ response.status === 422 ? validationDetail(payload) : "",
168
+ isCreditFailure(response.status, reason) ? ` ${CREDIT_GUIDANCE}` : "",
169
+ retryDetail(response),
170
+ showBody(reason, parsedAsJson, payload) ? bodyDetail(raw) : "",
171
+ ].join("");
172
+
173
+ const error = new Error(message);
59
174
  error.status = response.status;
60
175
  return error;
61
176
  }
62
177
 
63
- /**
64
- * Make authenticated POST request to Findymail API
65
- */
66
- export async function apiPost(endpoint, body = {}, apiKey) {
67
- if (!apiKey) apiKey = getApiKey();
178
+ // A write that failed after it was sent is not a failed write: the API may have
179
+ // finished it after we stopped listening. Say so, or the agent's natural move is
180
+ // to replay a call it cannot see the result of — a paid one, for a POST. Only
181
+ // POSTs spend credits; a DELETE removes exclusion domains, which costs nothing.
182
+ function mayHaveCompleted(method) {
183
+ const cost = method === "POST" ? ", credits included" : "";
184
+ return `The request may still have completed on Findymail's side${cost} — check its effect before sending it again`;
185
+ }
68
186
 
69
- const response = await fetch(`${API_BASE_URL}${endpoint}`, {
70
- method: "POST",
71
- headers: {
72
- "Authorization": `Bearer ${apiKey}`,
73
- "Content-Type": "application/json",
74
- "Accept": "application/json",
75
- },
76
- body: JSON.stringify(body),
77
- });
78
-
79
- if (!response.ok) {
80
- throw await apiError(response);
81
- }
187
+ function timeoutError(method, timeoutMs) {
188
+ const seconds = timeoutMs / 1000;
189
+ const message = method === "GET"
190
+ ? `Findymail did not answer within ${seconds}s — retry in a few seconds`
191
+ : `Findymail did not answer within ${seconds}s. ${mayHaveCompleted(method)}`;
82
192
 
83
- return response.json();
193
+ // get_lead_list_results tells a slow check apart from a real failure by this.
194
+ const error = new Error(message);
195
+ error.code = "timeout";
196
+ return error;
84
197
  }
85
198
 
86
- /**
87
- * Make authenticated GET request to Findymail API
88
- */
89
- export async function apiGet(endpoint, apiKey) {
199
+ // Failures that happen before a connection exists: the request never left, so
200
+ // even a write is safe to send again.
201
+ const NOT_SENT = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"]);
202
+
203
+ // fetch() reports every transport failure as a bare "fetch failed"; the reason
204
+ // (connection refused, reset, DNS) is on `cause`.
205
+ function networkError(method, error) {
206
+ const reason = error.cause?.code || error.cause?.message || error.message;
207
+ const message = method === "GET" || NOT_SENT.has(error.cause?.code)
208
+ ? `Could not reach Findymail (${reason}) — retry in a few seconds`
209
+ : `The connection to Findymail broke (${reason}). ${mayHaveCompleted(method)}`;
210
+
211
+ return new Error(message);
212
+ }
213
+
214
+ async function request(method, endpoint, { apiKey, body, timeoutMs = API_TIMEOUT_MS } = {}) {
90
215
  if (!apiKey) apiKey = getApiKey();
91
216
 
92
- const response = await fetch(`${API_BASE_URL}${endpoint}`, {
93
- method: "GET",
94
- headers: {
95
- "Authorization": `Bearer ${apiKey}`,
96
- "Accept": "application/json",
97
- },
98
- });
217
+ const headers = {
218
+ "Authorization": `Bearer ${apiKey}`,
219
+ "Accept": "application/json",
220
+ };
221
+ if (body !== undefined) headers["Content-Type"] = "application/json";
99
222
 
100
- if (!response.ok) {
101
- throw await apiError(response);
102
- }
223
+ // The query string carries user input (a search filter, a run hash), so only
224
+ // the path reaches the logs — and never the token.
225
+ const path = endpoint.split("?")[0];
226
+ const startedAt = Date.now();
227
+ const elapsed = () => `${Date.now() - startedAt}ms`;
228
+
229
+ // Kept in hand so a timeout is recognised by the signal itself, not by the
230
+ // name of whatever error the runtime rejects with when it fires.
231
+ const signal = AbortSignal.timeout(timeoutMs);
232
+
233
+ try {
234
+ // The signal also bounds reading the body, not just the headers.
235
+ const response = await fetch(`${API_BASE_URL}${endpoint}`, {
236
+ method,
237
+ headers,
238
+ body: body === undefined ? undefined : JSON.stringify(body),
239
+ signal,
240
+ });
241
+
242
+ if (!response.ok) {
243
+ const error = await apiError(response);
244
+ log(`API ${method} ${path} → ${response.status} in ${elapsed()}`);
245
+ throw error;
246
+ }
103
247
 
104
- return response.json();
248
+ const data = await response.json();
249
+ log(`API ${method} ${path} → ${response.status} in ${elapsed()}`);
250
+ return data;
251
+ } catch (error) {
252
+ if (error.status) throw error;
253
+
254
+ if (signal.aborted) {
255
+ log(`API ${method} ${path} → timeout in ${elapsed()}`);
256
+ throw timeoutError(method, timeoutMs);
257
+ }
258
+
259
+ log(`API ${method} ${path} → ${error.cause?.code || error.name} in ${elapsed()}`);
260
+ throw error instanceof SyntaxError ? error : networkError(method, error);
261
+ }
105
262
  }
106
263
 
107
264
  /**
108
- * Make authenticated DELETE request to Findymail API
265
+ * Make authenticated POST request to Findymail API
109
266
  */
110
- export async function apiDelete(endpoint, body = {}, apiKey) {
111
- if (!apiKey) apiKey = getApiKey();
267
+ export function apiPost(endpoint, body = {}, apiKey, options = {}) {
268
+ return request("POST", endpoint, { ...options, apiKey, body });
269
+ }
112
270
 
113
- const response = await fetch(`${API_BASE_URL}${endpoint}`, {
114
- method: "DELETE",
115
- headers: {
116
- "Authorization": `Bearer ${apiKey}`,
117
- "Content-Type": "application/json",
118
- "Accept": "application/json",
119
- },
120
- body: JSON.stringify(body),
121
- });
122
-
123
- if (!response.ok) {
124
- throw await apiError(response);
125
- }
271
+ /**
272
+ * Make authenticated GET request to Findymail API
273
+ */
274
+ export function apiGet(endpoint, apiKey, options = {}) {
275
+ return request("GET", endpoint, { ...options, apiKey });
276
+ }
126
277
 
127
- return response.json();
278
+ /**
279
+ * Make authenticated DELETE request to Findymail API
280
+ */
281
+ export function apiDelete(endpoint, body = {}, apiKey, options = {}) {
282
+ return request("DELETE", endpoint, { ...options, apiKey, body });
128
283
  }
129
284
 
130
285
  /**
package/src/http.js CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import { randomUUID } from "node:crypto";
3
4
  import { createRequire } from "node:module";
4
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
6
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
7
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
6
8
  import { log } from "./api.js";
7
9
  import { registerTools } from "./tools.js";
8
10
 
@@ -25,8 +27,80 @@ const AUTH_SERVER = process.env.AUTH_SERVER || "https://app.findymail.com";
25
27
 
26
28
  const app = express();
27
29
 
28
- // Store active transports by session
29
- const transports = {};
30
+ // Store active transports by session. A session pins a transport *and* a full
31
+ // MCP server, so it must be reclaimed on all three paths: the client closes it,
32
+ // it goes idle, or we hit the ceiling.
33
+ const SESSION_TTL_MS = Number(process.env.MCP_SESSION_TTL_MS) || 30 * 60 * 1000;
34
+ const MAX_SESSIONS = Number(process.env.MCP_MAX_SESSIONS) || 300;
35
+ const SWEEP_INTERVAL_MS = Number(process.env.MCP_SESSION_SWEEP_MS) || 60 * 1000;
36
+ const MAX_BODY_BYTES = Number(process.env.MCP_MAX_BODY_BYTES) || 4 * 1024 * 1024;
37
+
38
+ // A Map, not an object: iteration order is insertion order and touchSession
39
+ // re-inserts on every hit, so the first entry is always least recently used.
40
+ const sessions = new Map();
41
+
42
+ function touchSession(sessionId) {
43
+ const session = sessions.get(sessionId);
44
+ if (!session) return undefined;
45
+ session.lastSeen = Date.now();
46
+ sessions.delete(sessionId);
47
+ sessions.set(sessionId, session);
48
+ return session;
49
+ }
50
+
51
+ // Only a request that is being answered protects a session from reclaim, and
52
+ // the standalone GET stream is not one: a well-behaved Streamable HTTP client
53
+ // holds it open for the life of the session, so counting it would exempt every
54
+ // normal client from the sweep and turn MAX_SESSIONS into a wall with no
55
+ // reclaim path. A quiet stream is cut once the session passes its TTL — clients
56
+ // recover through the 404 path below by re-initializing.
57
+ function trackRequest(session, req, res) {
58
+ if (req.method === "GET") return;
59
+ session.pending += 1;
60
+ res.once("close", () => {
61
+ session.pending -= 1;
62
+ session.lastSeen = Date.now();
63
+ });
64
+ }
65
+
66
+ function dropSession(sessionId, reason) {
67
+ const session = sessions.get(sessionId);
68
+ if (!session) return;
69
+ sessions.delete(sessionId);
70
+ log(`Session closed (${reason}): ${sessionId} — ${sessions.size} live`);
71
+ session.server.close().catch(error => log(`Close error: ${error.message}`));
72
+ }
73
+
74
+ // Is there room, or at least one session we could reclaim to make room? Asked
75
+ // before the handshake so a full server refuses early, and answered without
76
+ // evicting anyone: a handshake the SDK goes on to reject must not cost a live
77
+ // client its session.
78
+ function canMakeRoom() {
79
+ if (sessions.size < MAX_SESSIONS) return true;
80
+ for (const session of sessions.values()) {
81
+ if (session.pending === 0) return true;
82
+ }
83
+ return false;
84
+ }
85
+
86
+ // Evict least-recently-used idle sessions. Called only once a handshake has
87
+ // actually succeeded. Never cuts a client mid-request.
88
+ function makeRoom() {
89
+ for (const [sessionId, session] of sessions) {
90
+ if (sessions.size < MAX_SESSIONS) return;
91
+ if (session.pending === 0) dropSession(sessionId, "capacity");
92
+ }
93
+ }
94
+
95
+ const sweeper = setInterval(() => {
96
+ const cutoff = Date.now() - SESSION_TTL_MS;
97
+ for (const [sessionId, session] of sessions) {
98
+ if (session.pending === 0 && session.lastSeen < cutoff) {
99
+ dropSession(sessionId, "idle");
100
+ }
101
+ }
102
+ }, SWEEP_INTERVAL_MS);
103
+ sweeper.unref();
30
104
 
31
105
  // JSON parsing only for non-MCP routes (MCP transport handles its own parsing)
32
106
  app.use((req, res, next) => {
@@ -105,25 +179,160 @@ app.use("/mcp", (req, res, next) => {
105
179
  app.all("/mcp", async (req, res) => {
106
180
  log(`MCP request: ${req.method}`);
107
181
 
108
- const sessionId = req.headers["mcp-session-id"] || `session_${Date.now()}`;
109
- log(`Session: ${sessionId}`);
182
+ const sessionId = req.headers["mcp-session-id"];
183
+
184
+ if (sessionId) {
185
+ const session = touchSession(sessionId);
186
+ if (!session) {
187
+ // 404 is the one answer MCP clients know how to recover from: they drop
188
+ // the session and re-initialize. Minting a blank transport under an id we
189
+ // never issued got a permanent 400 "Server not initialized" instead, and
190
+ // the phantom transport stayed in memory for good.
191
+ log(`Unknown session: ${sessionId}`);
192
+ return res.status(404).json({
193
+ jsonrpc: "2.0",
194
+ error: { code: -32001, message: "Session not found" },
195
+ id: null,
196
+ });
197
+ }
198
+ log(`Session: ${sessionId}`);
199
+ trackRequest(session, req, res);
200
+ return handOff(session.transport, req, res);
201
+ }
202
+
203
+ // Everything below builds a session. Only an initialize handshake may do
204
+ // that: any other session-less request used to reach makeRoom() and evict a
205
+ // healthy session per call — an authenticated caller, or a client that simply
206
+ // dropped the header on a retry, could clear out other people's sessions —
207
+ // before spawning a server the SDK then rejected. Read the body here and
208
+ // hand it to the transport, which cannot re-read a consumed stream.
209
+ const body = await readJsonBody(req);
110
210
 
111
- let transport = transports[sessionId];
211
+ if (body === TOO_LARGE) {
212
+ log(`Session-less ${req.method} over ${MAX_BODY_BYTES} bytes — rejected`);
213
+ return res.status(413).json({
214
+ jsonrpc: "2.0",
215
+ error: { code: -32000, message: `Request body exceeds ${MAX_BODY_BYTES} bytes` },
216
+ id: null,
217
+ });
218
+ }
112
219
 
113
- if (!transport) {
114
- log("Creating new transport and server...");
115
- const server = createMcpServer();
116
- transport = new StreamableHTTPServerTransport({
117
- sessionIdGenerator: () => sessionId,
220
+ if (body === UNPARSABLE) {
221
+ log(`Session-less ${req.method} with a body that is not JSON — rejected`);
222
+ return res.status(400).json({
223
+ jsonrpc: "2.0",
224
+ error: { code: -32700, message: "Parse error: request body is not valid JSON" },
225
+ id: null,
118
226
  });
119
- transports[sessionId] = transport;
227
+ }
120
228
 
121
- await server.connect(transport);
122
- log("Server connected");
229
+ if (!isInitializeRequest(body)) {
230
+ log(`Session-less ${req.method} that is not an initialize — rejected`);
231
+ return res.status(400).json({
232
+ jsonrpc: "2.0",
233
+ error: { code: -32000, message: "Bad Request: Mcp-Session-Id header is required" },
234
+ id: null,
235
+ });
123
236
  }
124
237
 
238
+ if (!canMakeRoom()) {
239
+ log(`Refusing new session: ${sessions.size} sessions, all busy`);
240
+ return res.status(503).json({
241
+ jsonrpc: "2.0",
242
+ error: { code: -32000, message: "Server busy: too many active sessions" },
243
+ id: null,
244
+ });
245
+ }
246
+
247
+ log("Creating new transport and server...");
248
+ const server = createMcpServer();
249
+
250
+ const transport = new StreamableHTTPServerTransport({
251
+ // Server-generated and unguessable. The id used to be `session_${Date.now()}`
252
+ // taken from the client header, so it was both predictable and pickable by
253
+ // whoever asked.
254
+ sessionIdGenerator: () => randomUUID(),
255
+
256
+ // Only a handshake the SDK actually accepted gets registered, and only here
257
+ // do we spend another client's session to make room for it.
258
+ onsessioninitialized: (newSessionId) => {
259
+ makeRoom();
260
+ const session = { transport, server, lastSeen: Date.now(), pending: 0 };
261
+ sessions.set(newSessionId, session);
262
+ trackRequest(session, req, res);
263
+ log(`Session opened: ${newSessionId} — ${sessions.size} live`);
264
+ },
265
+ });
266
+
267
+ // Must be assigned before connect(): Protocol.connect() chains onto whatever
268
+ // handler is already in place, so setting it afterwards would replace the
269
+ // SDK's own teardown instead of adding to it.
270
+ transport.onclose = () => {
271
+ const openId = transport.sessionId;
272
+ if (openId && sessions.delete(openId)) {
273
+ log(`Session closed (transport): ${openId} — ${sessions.size} live`);
274
+ }
275
+ };
276
+
277
+ await server.connect(transport);
278
+ log("Server connected");
279
+ await handOff(transport, req, res, body);
280
+
281
+ // connect() already ran, so a handshake the SDK rejected leaves a live server
282
+ // holding a live transport. Leaving those to the garbage collector is the
283
+ // very thing this file set out to stop, so close what never became a session.
284
+ if (!transport.sessionId || !sessions.has(transport.sessionId)) {
285
+ log("Handshake rejected — closing the orphaned server");
286
+ await server.close().catch(error => log(`Close error: ${error.message}`));
287
+ }
288
+ });
289
+
290
+ const TOO_LARGE = Symbol("too large");
291
+ const UNPARSABLE = Symbol("unparsable");
292
+
293
+ // The transport parses the body itself, but it cannot do that once we have read
294
+ // the stream to find out whether this is an initialize — so parse it here and
295
+ // pass it down through handleRequest's parsedBody argument.
296
+ //
297
+ // Going over the limit used to destroy the socket mid-upload, so the client saw
298
+ // a dropped connection — which reads as a network fault and invites sending the
299
+ // same body again — instead of a 413 it could act on. Answering early and
300
+ // closing fails the same way for a client still writing, so do what body-parser
301
+ // does: stop buffering, discard the rest, answer once the upload ends. Node's
302
+ // requestTimeout bounds how long that can take. Bytes are counted, not characters.
303
+ function readJsonBody(req) {
304
+ return new Promise(resolve => {
305
+ const chunks = [];
306
+ let size = 0;
307
+ let tooLarge = Number(req.headers["content-length"]) > MAX_BODY_BYTES;
308
+
309
+ req.on("data", chunk => {
310
+ if (tooLarge) return;
311
+ size += chunk.length;
312
+ if (size > MAX_BODY_BYTES) {
313
+ tooLarge = true;
314
+ chunks.length = 0;
315
+ return;
316
+ }
317
+ chunks.push(chunk);
318
+ });
319
+ req.on("end", () => {
320
+ if (tooLarge) return resolve(TOO_LARGE);
321
+ const raw = Buffer.concat(chunks).toString("utf8");
322
+ if (!raw) return resolve(undefined);
323
+ try {
324
+ resolve(JSON.parse(raw));
325
+ } catch {
326
+ resolve(UNPARSABLE);
327
+ }
328
+ });
329
+ req.on("error", () => resolve(undefined));
330
+ });
331
+ }
332
+
333
+ async function handOff(transport, req, res, parsedBody) {
125
334
  try {
126
- await transport.handleRequest(req, res);
335
+ await transport.handleRequest(req, res, parsedBody);
127
336
  log("Request handled");
128
337
  } catch (error) {
129
338
  log(`Error: ${error.message}`);
@@ -131,7 +340,7 @@ app.all("/mcp", async (req, res) => {
131
340
  res.status(500).json({ error: error.message });
132
341
  }
133
342
  }
134
- });
343
+ }
135
344
 
136
345
  // =============================================================================
137
346
  // Health check
@@ -149,8 +358,19 @@ app.get("/health", (req, res) => {
149
358
  // Start server
150
359
  // =============================================================================
151
360
 
152
- app.listen(PORT, () => {
361
+ const server = app.listen(PORT, () => {
153
362
  log(`MCP Server listening on ${BASE_URL}`);
154
363
  log(`MCP endpoint: ${BASE_URL}/mcp`);
155
364
  log(`Health check: ${BASE_URL}/health`);
156
- });
365
+ });
366
+
367
+ // A client that vanishes without closing its TCP connection — a laptop going to
368
+ // sleep, a NAT dropping the mapping — leaves its SSE stream open forever. No
369
+ // "close" event fires, so a POST answered as a stream keeps `pending` above
370
+ // zero and its session escapes both the idle sweep and the capacity eviction:
371
+ // enough of them and every new session is refused for good. (The standalone GET
372
+ // stream is not counted — see trackRequest.) Node cuts nothing on its own here
373
+ // (`server.timeout` is 0 by default and applies to the request, not the stream),
374
+ // so lean on TCP keepalive to notice the dead peer.
375
+ const KEEPALIVE_MS = Number(process.env.MCP_TCP_KEEPALIVE_MS) || 60 * 1000;
376
+ server.on("connection", socket => socket.setKeepAlive(true, KEEPALIVE_MS));