@tmcp/transport-http 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -135,10 +135,16 @@ The HTTP transport supports custom session managers for different deployment sce
135
135
  #### In-Memory Sessions (Default)
136
136
 
137
137
  ```javascript
138
- import { InMemorySessionManager } from '@tmcp/session-manager';
138
+ import {
139
+ InMemoryStreamSessionManager,
140
+ InMemoryInfoSessionManager,
141
+ } from '@tmcp/session-manager';
139
142
 
140
143
  const transport = new HttpTransport(server, {
141
- sessionManager: new InMemorySessionManager(), // Default behavior
144
+ sessionManager: {
145
+ streams: new InMemoryStreamSessionManager(),
146
+ info: new InMemoryInfoSessionManager(),
147
+ },
142
148
  });
143
149
  ```
144
150
 
@@ -147,10 +153,16 @@ const transport = new HttpTransport(server, {
147
153
  For deployments across multiple servers or serverless environments where sessions need to be shared:
148
154
 
149
155
  ```javascript
150
- import { RedisSessionManager } from '@tmcp/session-manager-redis';
156
+ import {
157
+ RedisStreamSessionManager,
158
+ RedisInfoSessionManager,
159
+ } from '@tmcp/session-manager-redis';
151
160
 
152
161
  const transport = new HttpTransport(server, {
153
- sessionManager: new RedisSessionManager('redis://localhost:6379'),
162
+ sessionManager: {
163
+ streams: new RedisStreamSessionManager('redis://localhost:6379'),
164
+ info: new RedisInfoSessionManager('redis://localhost:6379'),
165
+ },
154
166
  });
155
167
  ```
156
168
 
@@ -170,6 +182,7 @@ const transport = new HttpTransport(server, {
170
182
  - **⚡ Real-time Updates**: Server can push notifications and updates to connected clients
171
183
  - **🛡️ Error Handling**: Graceful error handling for malformed requests
172
184
  - **🔀 Multiple HTTP Methods**: Supports GET (notifications), POST (messages), and DELETE (disconnect)
185
+ - **🧠 Session Metadata**: Automatically persists client capabilities, info, and log levels and exposes them via `server.ctx.sessionInfo`
173
186
 
174
187
  ## API
175
188
 
@@ -195,10 +208,15 @@ interface HttpTransportOptions {
195
208
  getSessionId: () => string; // Custom session ID generator
196
209
  path?: string | null; // MCP endpoint path (default: '/mcp', null responds on every path)
197
210
  oauth?: OAuth; // an oauth provider generated from @tmcp/auth
198
- sessionManager?: SessionManager; // Custom session manager (default: InMemorySessionManager)
211
+ sessionManager?: {
212
+ streams?: StreamSessionManager;
213
+ info?: InfoSessionManager;
214
+ }; // Provide custom managers; defaults to in-memory implementations
199
215
  }
200
216
  ```
201
217
 
218
+ If you omit `sessionManager` the transport creates `InMemoryStreamSessionManager` and `InMemoryInfoSessionManager` instances for you. You can override either field independently (for example, Redis streams with in-memory metadata during development).
219
+
202
220
  #### Methods
203
221
 
204
222
  ##### `respond(request: Request, customContext?: T): Promise<Response | null>`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tmcp/transport-http",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Transport for TMCP using HTTP",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -16,7 +16,13 @@
16
16
  "src/**/*"
17
17
  ],
18
18
  "peerDependencies": {
19
- "tmcp": "^1.15.1"
19
+ "tmcp": "^1.16.0",
20
+ "@tmcp/auth": "^0.3.3"
21
+ },
22
+ "peerDependenciesMeta": {
23
+ "@tmcp/auth": {
24
+ "optional": true
25
+ }
20
26
  },
21
27
  "keywords": [
22
28
  "tmcp",
@@ -30,19 +36,19 @@
30
36
  },
31
37
  "dependencies": {
32
38
  "esm-env": "^1.2.2",
33
- "@tmcp/session-manager": "^0.1.2"
39
+ "@tmcp/session-manager": "^0.2.0"
34
40
  },
35
41
  "devDependencies": {
36
42
  "@modelcontextprotocol/sdk": "^1.17.1",
37
- "@remix-run/node-fetch-server": "^0.10.0",
43
+ "@remix-run/node-fetch-server": "^0.11.0",
38
44
  "@types/node": "^24.0.15",
39
45
  "dts-buddy": "^0.6.2",
40
46
  "publint": "^0.3.12",
41
47
  "valibot": "^1.1.0",
42
- "vitest": "^3.2.4",
48
+ "vitest": "^4.0.0",
43
49
  "@tmcp/adapter-valibot": "^0.1.4",
44
50
  "@tmcp/auth": "^0.3.3",
45
- "tmcp": "^1.15.1"
51
+ "tmcp": "^1.16.0"
46
52
  },
47
53
  "publishConfig": {
48
54
  "access": "public"
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @import { AuthInfo, McpServer } from "tmcp";
3
3
  * @import { OAuth } from "@tmcp/auth";
4
- * @import { SessionManager } from "@tmcp/session-manager";
4
+ * @import { StreamSessionManager, InfoSessionManager } from "@tmcp/session-manager";
5
5
  */
6
6
 
7
7
  /**
@@ -21,25 +21,32 @@
21
21
  * path?: string | null
22
22
  * oauth?: OAuth<"built">
23
23
  * cors?: CorsConfig | boolean,
24
- * sessionManager?: SessionManager
24
+ * sessionManager?: { streams?: StreamSessionManager, info?: InfoSessionManager }
25
25
  * }} HttpTransportOptions
26
26
  */
27
27
 
28
28
  import { AsyncLocalStorage } from 'node:async_hooks';
29
- import { InMemorySessionManager } from '@tmcp/session-manager';
29
+ import {
30
+ InMemoryStreamSessionManager,
31
+ InMemoryInfoSessionManager,
32
+ } from '@tmcp/session-manager';
30
33
  import { DEV } from 'esm-env';
31
34
 
32
35
  /**
33
36
  * @template {Record<string, unknown> | undefined} [TCustom=undefined]
34
37
  */
35
38
  export class HttpTransport {
39
+ /**
40
+ * @typedef {NonNullable<Required<Pick<HttpTransportOptions, "sessionManager">["sessionManager"]>>} SessionManager
41
+ */
42
+
36
43
  /**
37
44
  * @type {McpServer<any, TCustom>}
38
45
  */
39
46
  #server;
40
47
 
41
48
  /**
42
- * @type {Required<Omit<HttpTransportOptions, 'oauth' | 'cors'>> & { cors?: CorsConfig | boolean }}
49
+ * @type {Required<Omit<HttpTransportOptions, 'oauth' | 'cors' | 'sessionManager'>> & { cors?: CorsConfig | boolean, sessionManager: SessionManager }}
43
50
  */
44
51
  #options;
45
52
 
@@ -53,6 +60,11 @@ export class HttpTransport {
53
60
  */
54
61
  #controller_storage = new AsyncLocalStorage();
55
62
 
63
+ /**
64
+ * @type {AsyncLocalStorage<string>}
65
+ */
66
+ #session_id_storage = new AsyncLocalStorage();
67
+
56
68
  /**
57
69
  * @type {OAuth<"built"> | undefined}
58
70
  */
@@ -72,11 +84,23 @@ export class HttpTransport {
72
84
  path = '/mcp',
73
85
  oauth,
74
86
  cors,
75
- sessionManager = new InMemorySessionManager(),
87
+ sessionManager: _sessionManager = {
88
+ streams: new InMemoryStreamSessionManager(),
89
+ info: new InMemoryInfoSessionManager(),
90
+ },
76
91
  } = options ?? {
77
92
  getSessionId: () => crypto.randomUUID(),
78
93
  };
79
94
 
95
+ /**
96
+ * @type {SessionManager}
97
+ */
98
+ const sessionManager = {
99
+ streams:
100
+ _sessionManager.streams ?? new InMemoryStreamSessionManager(),
101
+ info: _sessionManager.info ?? new InMemoryInfoSessionManager(),
102
+ };
103
+
80
104
  if (options?.path === undefined && DEV) {
81
105
  // TODO: remove on 1.0.0 release
82
106
  console.warn(
@@ -90,7 +114,47 @@ export class HttpTransport {
90
114
 
91
115
  this.#options = { getSessionId, path, cors, sessionManager };
92
116
  this.#path = path;
93
- this.#server.on('send', async ({ request, context: { sessions } }) => {
117
+
118
+ this.#server.on('initialize', ({ capabilities, clientInfo }) => {
119
+ const sessionId = this.#session_id_storage.getStore();
120
+ if (!sessionId) return;
121
+ this.#options.sessionManager.info.setClientCapabilities(
122
+ sessionId,
123
+ capabilities,
124
+ );
125
+ this.#options.sessionManager.info.setClientInfo(
126
+ sessionId,
127
+ clientInfo,
128
+ );
129
+ });
130
+
131
+ this.#server.on('subscription', async ({ uri }) => {
132
+ const sessionId = this.#session_id_storage.getStore();
133
+ if (!sessionId) return;
134
+ this.#options.sessionManager.info.addSubscription(sessionId, uri);
135
+ });
136
+
137
+ this.#server.on('loglevelchange', ({ level }) => {
138
+ const sessionId = this.#session_id_storage.getStore();
139
+ if (!sessionId) return;
140
+ this.#options.sessionManager.info.setLogLevel(sessionId, level);
141
+ });
142
+
143
+ this.#server.on('broadcast', async ({ request }) => {
144
+ let sessions = undefined;
145
+ if (request.method === 'notifications/resources/updated') {
146
+ sessions =
147
+ await this.#options.sessionManager.info.getSubscriptions(
148
+ request.params.uri,
149
+ );
150
+ }
151
+ await this.#options.sessionManager.streams.send(
152
+ sessions,
153
+ 'data: ' + JSON.stringify(request) + '\n\n',
154
+ );
155
+ });
156
+
157
+ this.#server.on('send', async ({ request }) => {
94
158
  // use the current controller if the request has an id (it means it's a request and not a notification)
95
159
  if (request.id != null) {
96
160
  const controller = this.#controller_storage.getStore();
@@ -103,8 +167,11 @@ export class HttpTransport {
103
167
  );
104
168
  return;
105
169
  }
106
- await this.#options.sessionManager.send(
107
- sessions,
170
+ const session_id = this.#session_id_storage.getStore();
171
+ if (!session_id) return;
172
+
173
+ await this.#options.sessionManager.streams.send(
174
+ [session_id],
108
175
  'data: ' + JSON.stringify(request) + '\n\n',
109
176
  );
110
177
  });
@@ -197,7 +264,8 @@ export class HttpTransport {
197
264
  * @param {string} session_id
198
265
  */
199
266
  async #handle_delete(session_id) {
200
- await this.#options.sessionManager.delete(session_id);
267
+ await this.#options.sessionManager.streams.delete(session_id);
268
+ await this.#options.sessionManager.info.delete(session_id);
201
269
  return new Response(null, {
202
270
  status: 200,
203
271
  headers: {
@@ -213,8 +281,9 @@ export class HttpTransport {
213
281
  */
214
282
  async #handle_get(session_id) {
215
283
  const sessions = this.#options.sessionManager;
284
+ const text_encoder = this.#text_encoder;
216
285
  // If session already exists, return error
217
- const existing_session = await sessions.has(session_id);
286
+ const existing_session = await sessions.streams.has(session_id);
218
287
  if (existing_session) {
219
288
  return new Response(
220
289
  JSON.stringify({
@@ -239,10 +308,12 @@ export class HttpTransport {
239
308
  // Create new long-lived stream for notifications
240
309
  const stream = new ReadableStream({
241
310
  async start(controller) {
242
- await sessions.create(session_id, controller);
311
+ await sessions.streams.create(session_id, controller);
312
+ // send a comment to flush the headers immediately
313
+ controller.enqueue(text_encoder.encode(': connected\n\n'));
243
314
  },
244
315
  async cancel() {
245
- await sessions.delete(session_id);
316
+ await sessions.streams.delete(session_id);
246
317
  },
247
318
  });
248
319
 
@@ -302,15 +373,35 @@ export class HttpTransport {
302
373
  },
303
374
  });
304
375
 
376
+ const session_id_storage = this.#session_id_storage;
377
+
305
378
  const handle = async () => {
379
+ const client_capabilities =
380
+ await this.#options.sessionManager.info
381
+ .getClientCapabilities(session_id)
382
+ .catch(() => undefined);
383
+ const client_info = await this.#options.sessionManager.info
384
+ .getClientInfo(session_id)
385
+ .catch(() => undefined);
386
+ const log_level = await this.#options.sessionManager.info
387
+ .getLogLevel(session_id)
388
+ .catch(() => undefined);
389
+
306
390
  const response = await this.#controller_storage.run(
307
391
  controller,
308
392
  () =>
309
- this.#server.receive(body, {
310
- sessionId: session_id,
311
- auth: auth_info ?? undefined,
312
- custom: ctx,
313
- }),
393
+ session_id_storage.run(session_id, () =>
394
+ this.#server.receive(body, {
395
+ sessionId: session_id,
396
+ auth: auth_info ?? undefined,
397
+ sessionInfo: {
398
+ clientCapabilities: client_capabilities,
399
+ clientInfo: client_info,
400
+ logLevel: log_level,
401
+ },
402
+ custom: ctx,
403
+ }),
404
+ ),
314
405
  );
315
406
 
316
407
  controller?.enqueue(
@@ -325,18 +416,21 @@ export class HttpTransport {
325
416
 
326
417
  const messages = Array.isArray(body) ? body : [body];
327
418
 
419
+ const has_request = messages.some((message) => message.id != null);
420
+
328
421
  // Determine status code based on response type
329
422
  // 202 Accepted for notifications/responses, 200 OK for standard requests
330
- const status = !messages.some((message) => message.id != null)
331
- ? 202
332
- : 200;
333
-
334
- return new Response(stream, {
335
- headers: {
336
- 'Content-Type': 'text/event-stream',
337
- 'Cache-Control': 'no-cache',
338
- 'mcp-session-id': session_id,
339
- },
423
+ const status = !has_request ? 202 : 200;
424
+
425
+ return new Response(has_request ? stream : null, {
426
+ headers: has_request
427
+ ? {
428
+ 'Content-Type': 'text/event-stream',
429
+ 'Cache-Control': 'no-cache',
430
+ connection: 'keep-alive',
431
+ 'mcp-session-id': session_id,
432
+ }
433
+ : undefined,
340
434
  status,
341
435
  });
342
436
  } catch (error) {
@@ -1,7 +1,7 @@
1
1
  declare module '@tmcp/transport-http' {
2
2
  import type { McpServer } from 'tmcp';
3
3
  import type { OAuth } from '@tmcp/auth';
4
- import type { SessionManager } from '@tmcp/session-manager';
4
+ import type { StreamSessionManager, InfoSessionManager } from '@tmcp/session-manager';
5
5
  export class HttpTransport<TCustom extends Record<string, unknown> | undefined = undefined> {
6
6
 
7
7
  constructor(server: McpServer<any, TCustom>, options?: HttpTransportOptions);
@@ -22,7 +22,10 @@ declare module '@tmcp/transport-http' {
22
22
  path?: string | null;
23
23
  oauth?: OAuth<"built">;
24
24
  cors?: CorsConfig | boolean;
25
- sessionManager?: SessionManager;
25
+ sessionManager?: {
26
+ streams?: StreamSessionManager;
27
+ info?: InfoSessionManager;
28
+ };
26
29
  };
27
30
 
28
31
  export {};
@@ -10,6 +10,6 @@
10
10
  "sourcesContent": [
11
11
  null
12
12
  ],
13
- "mappings": ";;;;cAkCaA,aAAaA",
13
+ "mappings": ";;;;cAqCaA,aAAaA",
14
14
  "ignoreList": []
15
15
  }