@astratra/mcp 1.0.0 → 1.0.1

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,6 +47,11 @@ http.createServer(handler).listen(3001); // ou app.post('/mcp', handler
47
47
  (protection contre le « DNS rebinding », exigée par la spécification ; le SDK ne la fait pas par défaut).
48
48
  - Le corps fait 4 Mio au plus, un lot 100 messages au plus ; 1 000 sessions au plus, fermées après 30 minutes sans
49
49
  requête (jamais pendant une requête) ; une requête plus longue que 5 minutes répond 504.
50
+ - Un client tient au plus un dixième des sessions (`maxSessionsPerClient`, 100 par défaut) : ouvrir une session de
51
+ plus ferme sa plus ancienne session au repos, pour qu'un seul client ne prenne pas toutes les sessions du serveur.
52
+ Un client est reconnu à son adresse (`req.ip`, sinon celle de la connexion ; en IPv6, son bloc /56 entier) ; derrière un proxy, donne
53
+ `clientKey: (req) => …` (l'adresse transmise par le proxy, ou le compte connecté), sinon tous les clients
54
+ partagent la même part.
50
55
  - Le serveur répond en JSON ; il n'ouvre pas de flux GET (rien n'est poussé au client hors des réponses).
51
56
 
52
57
  ## Un client
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/mcp",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "The Model Context Protocol with no dependency: client and server (initialize, tools/list, tools/call, ping, cancellation), stdio and Streamable HTTP transports, Origin check, size and time limits. Works with transports from the official SDK too.",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -11,10 +11,6 @@
11
11
  "files": [
12
12
  "src"
13
13
  ],
14
- "scripts": {
15
- "test": "jest",
16
- "verify:mutations": "node scripts/verify-mcp-mutations.cjs"
17
- },
18
14
  "jest": {
19
15
  "testMatch": [
20
16
  "**/__tests__/**/*.test.js"
@@ -35,5 +31,9 @@
35
31
  "devDependencies": {
36
32
  "@astratra/testkit": "^2.0.0",
37
33
  "jest": "30.4.2"
34
+ },
35
+ "scripts": {
36
+ "test": "jest",
37
+ "verify:mutations": "node scripts/verify-mcp-mutations.cjs"
38
38
  }
39
- }
39
+ }
package/src/index.d.ts CHANGED
@@ -99,5 +99,5 @@ export interface StreamableHttpHandler {
99
99
  closeAll(): Promise<void>;
100
100
  readonly sessionCount: number;
101
101
  }
102
- export function createStreamableHttpHandler(options: { createServer: () => McpServer; allowedOrigins?: string[]; maxBodyBytes?: number; maxSessions?: number; sessionIdleMs?: number; requestTimeoutMs?: number }): StreamableHttpHandler;
102
+ export function createStreamableHttpHandler(options: { createServer: () => McpServer; allowedOrigins?: string[]; maxBodyBytes?: number; maxSessions?: number; /** Sessions one client may hold (default: a tenth of maxSessions). Opening one more closes its oldest idle session. */ maxSessionsPerClient?: number; /** What tells clients apart (default: req.ip, else the connection address). Give it behind a proxy. */ clientKey?: (req: any) => string | undefined; sessionIdleMs?: number; requestTimeoutMs?: number }): StreamableHttpHandler;
103
103
  export function readServerSentEvents(body: ReadableStream<Uint8Array>, options?: { maxEventBytes?: number; maxStreamBytes?: number }): AsyncGenerator<{ event: string; data: string; id?: string }>;
package/src/transports.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /* global AbortController, TextDecoder, queueMicrotask */
2
2
  const crypto = require('node:crypto');
3
+ const net = require('node:net');
3
4
  const { messageKind, McpError, ErrorCode, SUPPORTED_PROTOCOL_VERSIONS } = require('./jsonrpc');
4
5
 
5
6
  /*
@@ -351,8 +352,50 @@ function readBody(req, limit) {
351
352
  * @param {object} options { createServer, allowedOrigins = [], maxBodyBytes = 4 Mio, maxSessions = 1000,
352
353
  * sessionIdleMs = 30 min, requestTimeoutMs = 5 min }
353
354
  */
354
- function createStreamableHttpHandler({ createServer, allowedOrigins = [], maxBodyBytes = MAX_MESSAGE, maxSessions = 1000, sessionIdleMs = 30 * 60_000, requestTimeoutMs = 5 * 60_000 } = {}) {
355
+ /*
356
+ * Ce qui identifie un client d'après son adresse. Un abonné IPv6 reçoit un bloc entier et change d'adresse à chaque
357
+ * requête : son bloc /56 compte pour un seul client. Une IPv4 écrite en IPv6 (::ffff:a.b.c.d) est cette IPv4.
358
+ */
359
+ function clientBlock(address) {
360
+ let text = String(address).trim().toLowerCase();
361
+ if (text.startsWith('[') && text.endsWith(']')) text = text.slice(1, -1);
362
+ const zone = text.indexOf('%');
363
+ if (zone !== -1) text = text.slice(0, zone);
364
+ if (!net.isIPv6(text)) return text;
365
+ let expanded = text;
366
+ const lastColon = text.lastIndexOf(':');
367
+ const tailV4 = text.slice(lastColon + 1);
368
+ if (net.isIPv4(tailV4)) {
369
+ const bytes = tailV4.split('.').map(Number);
370
+ expanded = `${text.slice(0, lastColon + 1)}${((bytes[0] << 8) | bytes[1]).toString(16)}:${((bytes[2] << 8) | bytes[3]).toString(16)}`;
371
+ }
372
+ const [head, tail] = expanded.split('::');
373
+ const left = head ? head.split(':') : [];
374
+ const right = tail ? tail.split(':') : [];
375
+ const groups = [...left, ...Array(expanded.includes('::') ? Math.max(0, 8 - left.length - right.length) : 0).fill('0'), ...right].map((group) => parseInt(group, 16) || 0);
376
+ if (groups.length !== 8) return text;
377
+ if (groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff) {
378
+ return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`;
379
+ }
380
+ return `${groups[0].toString(16)}:${groups[1].toString(16)}:${groups[2].toString(16)}:${(groups[3] & 0xff00).toString(16)}::/56`;
381
+ }
382
+
383
+ function createStreamableHttpHandler({ createServer, allowedOrigins = [], maxBodyBytes = MAX_MESSAGE, maxSessions = 1000, maxSessionsPerClient, clientKey, sessionIdleMs = 30 * 60_000, requestTimeoutMs = 5 * 60_000 } = {}) {
355
384
  if (typeof createServer !== 'function') throw new TypeError('createStreamableHttpHandler needs createServer()');
385
+ /* Ouvrir une session ne prouve rien et ne coûte qu'une requête : sans part par client, un seul en ouvrait autant
386
+ que la limite du serveur et fermait la porte à tous les autres. Un client est reconnu à son adresse (req.ip
387
+ quand Express la calcule, sinon celle de la connexion) ; derrière un proxy, donner clientKey. */
388
+ const perClient = maxSessionsPerClient === undefined ? Math.max(1, Math.ceil(maxSessions / 10)) : maxSessionsPerClient;
389
+ if (!Number.isInteger(perClient) || perClient < 1) throw new TypeError('maxSessionsPerClient must be a positive integer');
390
+ if (clientKey !== undefined && typeof clientKey !== 'function') throw new TypeError('clientKey must be a function (req) => string');
391
+ const keyOf = (req) => {
392
+ if (clientKey) {
393
+ const key = clientKey(req);
394
+ return key === undefined || key === null || key === '' ? 'unknown' : String(key).slice(0, 256);
395
+ }
396
+ const address = req.ip || req.socket?.remoteAddress;
397
+ return address === undefined || address === null || address === '' ? 'unknown' : clientBlock(address).slice(0, 256);
398
+ };
356
399
  const sessions = new Map();
357
400
 
358
401
  const reply = (res, status, body, headers = {}) => {
@@ -420,12 +463,21 @@ function createStreamableHttpHandler({ createServer, allowedOrigins = [], maxBod
420
463
  if (initialize) {
421
464
  if (messages.length > 1) return reply(res, 400, rpcError(ErrorCode.InvalidRequest, 'Invalid Request: Only one initialization request is allowed'));
422
465
  if (sessionHeader && sessions.has(sessionHeader)) return reply(res, 400, rpcError(ErrorCode.InvalidRequest, 'Invalid Request: Server already initialized'));
466
+ /* Un client à sa part pleine fait place lui-même : sa plus ancienne session sans requête en cours est
467
+ fermée (un client qui oublie de fermer ses sessions n'est pas bloqué, et personne d'autre n'y perd). */
468
+ const client = keyOf(req);
469
+ const own = [...sessions.values()].filter((session) => session.client === client);
470
+ if (own.length >= perClient) {
471
+ const idle = own.find((session) => session.inflight === 0);
472
+ if (!idle) return reply(res, 429, rpcError(ErrorCode.ConnectionClosed, 'Too many sessions for this client'));
473
+ await closeSession(idle.id);
474
+ }
423
475
  if (sessions.size >= maxSessions) return reply(res, 503, rpcError(ErrorCode.ConnectionClosed, 'Too many sessions'));
424
476
  const transport = sessionTransport();
425
477
  transport.sessionId = crypto.randomUUID();
426
478
  const server = createServer();
427
479
  await server.connect(transport);
428
- entry = { id: transport.sessionId, server, transport, inflight: 0 };
480
+ entry = { id: transport.sessionId, server, transport, inflight: 0, client };
429
481
  sessions.set(entry.id, entry);
430
482
  } else {
431
483
  if (!sessionHeader) return reply(res, 400, rpcError(ErrorCode.ConnectionClosed, 'Bad Request: Mcp-Session-Id header is required'));