aiohttp-tiny-mcp 0.5.8__tar.gz → 0.5.9__tar.gz

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.
Files changed (62) hide show
  1. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/PKG-INFO +19 -1
  2. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/README.md +18 -0
  3. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/pyproject.toml +5 -2
  4. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/pyproject.toml.orig +2 -2
  5. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/console.js +188 -27
  6. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/index.html +4 -0
  7. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/sqlite.py +62 -33
  8. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/LICENSE +0 -0
  9. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/__init__.py +0 -0
  10. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/auth/__init__.py +0 -0
  11. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/auth/jwt.py +0 -0
  12. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/__init__.py +0 -0
  13. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/base.py +0 -0
  14. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/callback.py +0 -0
  15. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/http.py +0 -0
  16. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/loopback.py +0 -0
  17. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/oauth.py +0 -0
  18. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/oauth_helpers.py +0 -0
  19. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/client/stdio.py +0 -0
  20. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/__init__.py +0 -0
  21. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/console.css +0 -0
  22. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/console/oauth-callback.html +0 -0
  23. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/extensions/__init__.py +0 -0
  24. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/extensions/skills.py +0 -0
  25. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/__init__.py +0 -0
  26. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/github.py +0 -0
  27. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/provider.py +0 -0
  28. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/server.py +0 -0
  29. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/oauth/tokens.py +0 -0
  30. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/__init__.py +0 -0
  31. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/adapter.py +0 -0
  32. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/core.py +0 -0
  33. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/models.py +0 -0
  34. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/schema.py +0 -0
  35. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/selection.py +0 -0
  36. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2024_11_05.py +0 -0
  37. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2025_03_26.py +0 -0
  38. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2025_06_18.py +0 -0
  39. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2025_11_25.py +0 -0
  40. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/protocol/v2026_07_28.py +0 -0
  41. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/py.typed +0 -0
  42. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/__init__.py +0 -0
  43. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/dispatcher.py +0 -0
  44. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/exchange.py +0 -0
  45. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/http.py +0 -0
  46. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/registry.py +0 -0
  47. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/request_state.py +0 -0
  48. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/specs.py +0 -0
  49. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/sse.py +0 -0
  50. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/stdio.py +0 -0
  51. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/subscriptions.py +0 -0
  52. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/server/tasks.py +0 -0
  53. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/__init__.py +0 -0
  54. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/hub.py +0 -0
  55. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/namespaces.py +0 -0
  56. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/postgres.py +0 -0
  57. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/redis.py +0 -0
  58. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/storage/sessions.py +0 -0
  59. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/testing.py +0 -0
  60. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/transport/__init__.py +0 -0
  61. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/transport/metadata.py +0 -0
  62. {aiohttp_tiny_mcp-0.5.8 → aiohttp_tiny_mcp-0.5.9}/src/aiohttp_tiny_mcp/transport/sse.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aiohttp-tiny-mcp
3
- Version: 0.5.8
3
+ Version: 0.5.9
4
4
  Summary: Remote MCP server and client library for aiohttp
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -178,6 +178,12 @@ the five revisions, builds a form from each tool's schema, answers the
178
178
  questions a handler asks, and shows every message either way. Static files from
179
179
  this package need no build step or second process.
180
180
 
181
+ The console receives background MCP notifications by default. Its
182
+ **Notifications** checkbox controls resource updates, list changes, and extension
183
+ broadcasts shown in **Traffic**. See the
184
+ [console guide](https://mosquito.github.io/aiohttp-tiny-mcp/guide/console.html)
185
+ for subscription and reconnection behavior.
186
+
181
187
  An MCP host that supports Streamable HTTP can connect to
182
188
  `http://127.0.0.1:8080/mcp`. In an existing aiohttp service, use
183
189
  `Endpoint(registry).setup(app, "/mcp")`. For a local subprocess transport,
@@ -190,6 +196,18 @@ from the client. Put irreversible work after the final question: some revisions
190
196
  restart the handler when the answer arrives. Python locals are not persisted
191
197
  automatically. See [Asking the user](https://mosquito.github.io/aiohttp-tiny-mcp/guide/asking.html).
192
198
 
199
+ ## Team chat for agents
200
+
201
+ [MCP Chat](examples/mcp-chat/README.md) is a runnable team chat for AI agents
202
+ and people. Agents use MCP tools; people use the web UI. It provides channels,
203
+ direct messages, threads, subscriptions, persistent inboxes, and full-text
204
+ search within each organization. Live MCP notifications deliver updates, with
205
+ polling as a fallback. Optional JWT authentication binds each agent to an
206
+ organization and user, and Observe shows its activity.
207
+
208
+ The example has its own `pyproject.toml`, SQLite database, and setup guide for
209
+ Codex, Claude Code, Pi, Cursor, and VS Code.
210
+
193
211
  ## Call it from Python
194
212
 
195
213
  The bundled `Client` is useful for integration tests or an application that
@@ -134,6 +134,12 @@ the five revisions, builds a form from each tool's schema, answers the
134
134
  questions a handler asks, and shows every message either way. Static files from
135
135
  this package need no build step or second process.
136
136
 
137
+ The console receives background MCP notifications by default. Its
138
+ **Notifications** checkbox controls resource updates, list changes, and extension
139
+ broadcasts shown in **Traffic**. See the
140
+ [console guide](https://mosquito.github.io/aiohttp-tiny-mcp/guide/console.html)
141
+ for subscription and reconnection behavior.
142
+
137
143
  An MCP host that supports Streamable HTTP can connect to
138
144
  `http://127.0.0.1:8080/mcp`. In an existing aiohttp service, use
139
145
  `Endpoint(registry).setup(app, "/mcp")`. For a local subprocess transport,
@@ -146,6 +152,18 @@ from the client. Put irreversible work after the final question: some revisions
146
152
  restart the handler when the answer arrives. Python locals are not persisted
147
153
  automatically. See [Asking the user](https://mosquito.github.io/aiohttp-tiny-mcp/guide/asking.html).
148
154
 
155
+ ## Team chat for agents
156
+
157
+ [MCP Chat](examples/mcp-chat/README.md) is a runnable team chat for AI agents
158
+ and people. Agents use MCP tools; people use the web UI. It provides channels,
159
+ direct messages, threads, subscriptions, persistent inboxes, and full-text
160
+ search within each organization. Live MCP notifications deliver updates, with
161
+ polling as a fallback. Optional JWT authentication binds each agent to an
162
+ organization and user, and Observe shows its activity.
163
+
164
+ The example has its own `pyproject.toml`, SQLite database, and setup guide for
165
+ Codex, Claude Code, Pi, Cursor, and VS Code.
166
+
149
167
  ## Call it from Python
150
168
 
151
169
  The bundled `Client` is useful for integration tests or an application that
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.5.8"
3
+ version = "0.5.9"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -116,7 +116,10 @@ root = [
116
116
  ]
117
117
 
118
118
  [tool.ty.src]
119
- exclude = ["examples/docker-mcp"]
119
+ exclude = [
120
+ "examples/docker-mcp",
121
+ "examples/mcp-chat",
122
+ ]
120
123
 
121
124
  [build-system]
122
125
  requires = ["uv_build>=0.12,<0.13"]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiohttp-tiny-mcp"
3
- version = "0.5.8"
3
+ version = "0.5.9"
4
4
  description = "Remote MCP server and client library for aiohttp"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -116,4 +116,4 @@ root = ["src", "examples"]
116
116
 
117
117
  [tool.ty.src]
118
118
  # Checked separately with its own dependencies.
119
- exclude = ["examples/docker-mcp"]
119
+ exclude = ["examples/docker-mcp", "examples/mcp-chat"]
@@ -239,12 +239,22 @@ class Client {
239
239
  this.onQuestion = options.onQuestion; // returns an ElicitResult
240
240
  this.authHeaders = { ...(options.authHeaders || {}) };
241
241
  this.onAuthError = options.onAuthError;
242
+ this.notifications = Boolean(options.notifications);
243
+ this.onNotificationError = options.onNotificationError;
242
244
  this.abort = new AbortController();
245
+ this.abort.signal.addEventListener("abort", () => this.stopNotifications(), { once: true });
243
246
  // Return the server-issued session id on subsequent requests.
244
247
  this.sessionId = null;
245
248
  this.counter = 0;
246
249
  this.tools = new Map();
247
250
  this.serverCapabilities = {};
251
+ this.resourceUris = new Set();
252
+ this.readUris = new Set();
253
+ this.notificationStarted = false;
254
+ this.notificationAbort = null;
255
+ this.notificationTask = Promise.resolve();
256
+ this.notificationFilter = null;
257
+ this.lastEventId = null;
248
258
  }
249
259
 
250
260
  get capabilities() {
@@ -284,7 +294,7 @@ class Client {
284
294
  return headers;
285
295
  }
286
296
 
287
- async post(envelope, method, name) {
297
+ async post(envelope, method, name, signal = this.abort.signal) {
288
298
  this.onFrame("sent", envelope);
289
299
  const response = await fetch(this.url, {
290
300
  method: "POST",
@@ -292,8 +302,17 @@ class Client {
292
302
  body: JSON.stringify(envelope),
293
303
  credentials: "omit",
294
304
  redirect: "error",
295
- signal: this.abort.signal,
305
+ signal,
296
306
  });
307
+ await this.checkResponse(response, signal);
308
+ return response;
309
+ }
310
+
311
+ async checkResponse(response, signal) {
312
+ if (signal.aborted) {
313
+ await response.body?.cancel();
314
+ throw new DOMException("The request was aborted.", "AbortError");
315
+ }
297
316
  if (!response.ok) {
298
317
  const error = new HttpError(response);
299
318
  const authenticationFailure = error.status === 401 ||
@@ -304,27 +323,29 @@ class Client {
304
323
  if (body?.jsonrpc === "2.0" && body.error) {
305
324
  this.onFrame("received", body);
306
325
  throw Object.assign(new Error(body.error.message), {
307
- code: body.error.code, data: body.error.data,
326
+ code: body.error.code, data: body.error.data, status: response.status,
308
327
  });
309
328
  }
310
329
  }
311
330
  if (!response.bodyUsed) await response.body?.cancel();
312
- if (authenticationFailure) this.onAuthError?.(error);
331
+ if (authenticationFailure && !signal.aborted) this.onAuthError?.(error);
313
332
  throw error;
314
333
  }
315
- return response;
316
334
  }
317
335
 
318
- /* Read frames before EOF so pushed questions can be answered while the stream stays open. */
319
- async *frames(envelope, method, name) {
320
- const response = await this.post(envelope, method, name);
336
+ // Read frames before EOF so pushed questions can be answered while the stream stays open.
337
+ async *frames(envelope, method, name, signal = this.abort.signal) {
338
+ const response = await this.post(envelope, method, name, signal);
321
339
  const issued = response.headers.get("Mcp-Session-Id");
322
340
  if (issued) this.sessionId = issued;
341
+ yield* this.responseFrames(response, signal);
342
+ }
323
343
 
344
+ async *responseFrames(response, signal, onEventId) {
324
345
  const kind = (response.headers.get("Content-Type") || "").split(";")[0].trim();
325
346
  if (kind !== "text/event-stream") {
326
347
  const text = await response.text();
327
- if (!text) return;
348
+ if (!text || signal.aborted) return;
328
349
  const body = JSON.parse(text);
329
350
  this.onFrame("received", body);
330
351
  yield body;
@@ -334,22 +355,38 @@ class Client {
334
355
  const reader = response.body.getReader();
335
356
  const decoder = new TextDecoder();
336
357
  let buffer = "";
337
- while (true) {
338
- const { value, done } = await reader.read();
339
- if (done) break;
340
- buffer += decoder.decode(value, { stream: true });
341
- let cut;
342
- while ((cut = buffer.indexOf("\n")) >= 0) {
343
- const line = buffer.slice(0, cut).trim();
344
- buffer = buffer.slice(cut + 1);
345
- if (!line.startsWith("data:")) continue;
346
- const text = line.slice(5).trim();
347
- // A data line with no payload primes or keeps the stream alive.
348
- if (!text) continue;
349
- const body = JSON.parse(text);
350
- this.onFrame("received", body);
351
- yield body;
358
+ let eventId = null;
359
+ let data = [];
360
+ const cancel = () => { reader.cancel().catch(() => {}); };
361
+ signal.addEventListener("abort", cancel, { once: true });
362
+ try {
363
+ while (!signal.aborted) {
364
+ const { value, done } = await reader.read();
365
+ if (done || signal.aborted) break;
366
+ buffer += decoder.decode(value, { stream: true });
367
+ let cut;
368
+ while ((cut = buffer.indexOf("\n")) >= 0) {
369
+ const line = buffer.slice(0, cut).trim();
370
+ buffer = buffer.slice(cut + 1);
371
+ if (line.startsWith("id:")) eventId = line.slice(3).trim();
372
+ if (line.startsWith("data:")) data.push(line.slice(5).trim());
373
+ if (line !== "") continue;
374
+ const text = data.join("\n");
375
+ const body = text ? JSON.parse(text) : null;
376
+ // Commit the resume cursor only after the complete event is received.
377
+ if (eventId !== null) onEventId?.(eventId);
378
+ eventId = null;
379
+ data = [];
380
+ if (body === null) continue;
381
+ this.onFrame("received", body);
382
+ yield body;
383
+ if (signal.aborted) return;
384
+ }
352
385
  }
386
+ } finally {
387
+ signal.removeEventListener("abort", cancel);
388
+ await reader.cancel().catch(() => {});
389
+ reader.releaseLock();
353
390
  }
354
391
  }
355
392
 
@@ -359,7 +396,7 @@ class Client {
359
396
  return frame.id === id || ("error" in frame && frame.id === null);
360
397
  }
361
398
 
362
- async request(method, params, name) {
399
+ async request(method, params, name, signal = this.abort.signal) {
363
400
  const envelope = {
364
401
  jsonrpc: "2.0",
365
402
  id: this.nextId(),
@@ -367,7 +404,7 @@ class Client {
367
404
  params: this.decorate(params || {}, method),
368
405
  };
369
406
  let body = null;
370
- for await (const frame of this.frames(envelope, method, name)) {
407
+ for await (const frame of this.frames(envelope, method, name, signal)) {
371
408
  if (this.answers(frame, envelope.id)) {
372
409
  body = frame;
373
410
  break;
@@ -423,6 +460,117 @@ class Client {
423
460
  return this.rules.extensions ? this.serverCapabilities.extensions || {} : {};
424
461
  }
425
462
 
463
+ notificationSelection() {
464
+ const caps = this.serverCapabilities;
465
+ const selected = {};
466
+ for (const kind of ["tools", "prompts", "resources"]) {
467
+ if (caps[kind]?.listChanged) selected[`${kind}ListChanged`] = true;
468
+ }
469
+ if (caps.resources?.subscribe) {
470
+ const uris = [...new Set([...this.resourceUris, ...this.readUris])].sort();
471
+ if (uris.length) selected.resourceSubscriptions = uris;
472
+ }
473
+ const methods = [...new Set(Object.values(this.extensions).flatMap((extension) => {
474
+ const declared = extension.notifications || {};
475
+ return Array.isArray(declared) ? declared : Object.keys(declared);
476
+ }))].sort();
477
+ if (methods.length) selected.methods = methods;
478
+ return selected;
479
+ }
480
+
481
+ startNotifications() {
482
+ if (!this.notifications || this.abort.signal.aborted) return;
483
+ this.notificationStarted = true;
484
+ const selected = this.notificationSelection();
485
+ const key = JSON.stringify(selected);
486
+ if (this.notificationFilter === key) return;
487
+ this.notificationAbort?.abort();
488
+ this.notificationFilter = key;
489
+ const controller = new AbortController();
490
+ this.notificationAbort = controller;
491
+ const previous = this.notificationTask;
492
+ this.notificationTask = previous.then(async () => {
493
+ if (controller.signal.aborted) return;
494
+ if (this.rules.meta && !Object.keys(selected).length) return;
495
+ await this.listenNotifications(selected, controller.signal);
496
+ });
497
+ }
498
+
499
+ stopNotifications() {
500
+ this.notificationStarted = false;
501
+ this.notificationFilter = null;
502
+ this.notificationAbort?.abort();
503
+ this.notificationAbort = null;
504
+ }
505
+
506
+ async listenNotifications(selected, signal) {
507
+ let delay = 500;
508
+ while (!signal.aborted) {
509
+ try {
510
+ let response;
511
+ let id;
512
+ if (this.rules.meta) {
513
+ const method = "subscriptions/listen";
514
+ id = this.nextId();
515
+ response = await this.post({
516
+ jsonrpc: "2.0", id, method,
517
+ params: this.decorate({ notifications: selected }, method),
518
+ }, method, undefined, signal);
519
+ } else {
520
+ for (const uri of selected.resourceSubscriptions || []) {
521
+ if (signal.aborted) return;
522
+ await this.request("resources/subscribe", { uri }, uri, signal);
523
+ }
524
+ if (signal.aborted) return;
525
+ const headers = this.headers();
526
+ headers.Accept = "text/event-stream";
527
+ if (this.lastEventId !== null) headers["Last-Event-ID"] = this.lastEventId;
528
+ response = await fetch(this.url, {
529
+ method: "GET", headers, credentials: "omit", redirect: "error", signal,
530
+ });
531
+ await this.checkResponse(response, signal);
532
+ }
533
+ if (signal.aborted) {
534
+ await response.body?.cancel();
535
+ return;
536
+ }
537
+ const kind = (response.headers.get("Content-Type") || "").split(";")[0].trim();
538
+ for await (const frame of this.responseFrames(response, signal, (eventId) => {
539
+ if (!this.rules.meta) this.lastEventId = eventId;
540
+ })) {
541
+ if (signal.aborted) return;
542
+ if (id !== undefined && this.answers(frame, id)) {
543
+ if (frame.error) throw Object.assign(new Error(frame.error.message), frame.error);
544
+ return;
545
+ }
546
+ delay = 500;
547
+ await this.incoming(frame);
548
+ }
549
+ if (signal.aborted) return;
550
+ if (kind !== "text/event-stream") {
551
+ throw Object.assign(new Error("Notifications require an SSE response."), { permanent: true });
552
+ }
553
+ throw new Error("The notification stream closed. Reconnecting.");
554
+ } catch (error) {
555
+ if (signal.aborted) return;
556
+ this.onNotificationError?.(error);
557
+ const rejected = [-32600, -32601, -32602].includes(error.code);
558
+ if (error.permanent || rejected || (error.status >= 400 && error.status < 500)) return;
559
+ await new Promise((resolve) => {
560
+ const finish = () => {
561
+ clearTimeout(timer);
562
+ signal.removeEventListener("abort", finish);
563
+ resolve();
564
+ };
565
+ const timer = setTimeout(finish, delay);
566
+ signal.addEventListener("abort", finish, { once: true });
567
+ if (signal.aborted) finish();
568
+ });
569
+ delay = Math.min(delay * 2, 15000);
570
+ }
571
+ }
572
+ }
573
+
426
574
  async pages(method, key) {
427
575
  const items = [];
428
576
  const seen = new Set();
@@ -456,6 +604,8 @@ class Client {
456
604
  /* A server with no templates may not expose the method. */
457
605
  if (error instanceof HttpError) throw error;
458
606
  }
607
+ this.resourceUris = new Set(resources.map((resource) => resource.uri));
608
+ if (this.notificationStarted) this.startNotifications();
459
609
  return { resources, templates };
460
610
  }
461
611
 
@@ -480,7 +630,10 @@ class Client {
480
630
  }
481
631
 
482
632
  async readResource(uri) {
483
- return this.request("resources/read", { uri }, uri);
633
+ const result = await this.request("resources/read", { uri }, uri);
634
+ this.readUris.add(uri);
635
+ if (this.notificationStarted) this.startNotifications();
636
+ return result;
484
637
  }
485
638
 
486
639
  async getPrompt(name, argumentValues) {
@@ -561,6 +714,7 @@ const page = {
561
714
  endpoint: document.getElementById("endpoint"),
562
715
  revision: document.getElementById("revision"),
563
716
  answerable: document.getElementById("answerable"),
717
+ notifications: document.getElementById("notifications"),
564
718
  connect: document.getElementById("connect"),
565
719
  refresh: document.getElementById("refresh"),
566
720
  status: document.getElementById("status"),
@@ -1896,6 +2050,7 @@ function disconnect() {
1896
2050
  page.refresh.disabled = true;
1897
2051
  page.revision.disabled = false;
1898
2052
  page.answerable.disabled = false;
2053
+ page.notifications.disabled = false;
1899
2054
  page.endpoint.disabled = false;
1900
2055
  page.connect.textContent = "Connect";
1901
2056
  say("not connected", "");
@@ -1906,6 +2061,7 @@ async function connect() {
1906
2061
  page.authenticate.disabled = true;
1907
2062
  page.revision.disabled = true;
1908
2063
  page.answerable.disabled = true;
2064
+ page.notifications.disabled = true;
1909
2065
  page.endpoint.disabled = true;
1910
2066
  say("connecting", "");
1911
2067
  page.outcome.textContent = "";
@@ -1916,6 +2072,8 @@ async function connect() {
1916
2072
  authHeaders: credentials.forEndpoint(endpointUrl.href),
1917
2073
  onAuthError: openAuthentication,
1918
2074
  answerable: page.answerable.checked,
2075
+ notifications: page.notifications.checked,
2076
+ onNotificationError: (error) => report("Notifications interrupted", error.message, true),
1919
2077
  onFrame: record,
1920
2078
  onNotify: noticed,
1921
2079
  onQuestion: askPerson,
@@ -1928,12 +2086,15 @@ async function connect() {
1928
2086
  say(`${name || "connected"} · ${client.version}`, "on");
1929
2087
  page.connect.textContent = "Disconnect";
1930
2088
  if (!chosen) showServerInstructions(false);
2089
+ client.startNotifications();
1931
2090
  } catch (error) {
2091
+ client?.abort.abort();
1932
2092
  setServerInstructions("");
1933
2093
  client = null;
1934
2094
  page.refresh.disabled = true;
1935
2095
  page.revision.disabled = false;
1936
2096
  page.answerable.disabled = false;
2097
+ page.notifications.disabled = false;
1937
2098
  page.endpoint.disabled = false;
1938
2099
  page.connect.textContent = "Connect";
1939
2100
  say(error.message, "off");
@@ -23,6 +23,10 @@
23
23
  <input id="answerable" type="checkbox" checked>
24
24
  <span>Can be asked</span>
25
25
  </label>
26
+ <label class="toggle" title="Receive background notifications in Traffic. Disconnect to change this setting.">
27
+ <input id="notifications" type="checkbox" checked>
28
+ <span>Notifications</span>
29
+ </label>
26
30
  <button id="connect" class="primary">Connect</button>
27
31
  <button id="authenticate" class="quiet" type="button">Authentication</button>
28
32
  <span id="status" class="status">not connected</span>
@@ -6,7 +6,7 @@ import asyncio
6
6
  import json
7
7
  import logging
8
8
  from collections.abc import AsyncIterator, Mapping, Sequence
9
- from contextlib import suppress
9
+ from contextlib import asynccontextmanager, suppress
10
10
  from pathlib import Path
11
11
  from typing import Any
12
12
 
@@ -67,31 +67,67 @@ class SqliteStorage:
67
67
  self.sweep_seconds = sweep_seconds
68
68
  self.connection: aiosqlite.Connection | None = None
69
69
  self.opening = asyncio.Lock()
70
+ self.executing = asyncio.Lock()
70
71
 
71
72
  async def open(self) -> aiosqlite.Connection:
72
73
  async with self.opening:
73
74
  if self.connection is None:
74
75
  connection = await aiosqlite.connect(self.path, isolation_level=None)
75
- await connection.execute("PRAGMA journal_mode=WAL")
76
- await connection.execute(f"PRAGMA busy_timeout={self.busy_timeout_ms}")
77
- await connection.executescript(SCHEMA)
76
+ try:
77
+ async with connection.execute(f"PRAGMA busy_timeout={self.busy_timeout_ms}"):
78
+ pass
79
+ await self.enable_wal(connection)
80
+ async with connection.executescript(SCHEMA):
81
+ pass
82
+ except BaseException:
83
+ await connection.close()
84
+ raise
78
85
  self.connection = connection
79
86
  log.debug("MCP state in %s", self.path)
80
87
  return self.connection
81
88
 
89
+ async def enable_wal(self, connection: aiosqlite.Connection) -> None:
90
+ """Retry competing WAL transitions within the configured busy timeout."""
91
+ loop = asyncio.get_running_loop()
92
+ deadline = loop.time() + self.busy_timeout_ms / 1000
93
+ while True:
94
+ try:
95
+ async with connection.execute("PRAGMA journal_mode=WAL"):
96
+ return
97
+ except aiosqlite.OperationalError as error:
98
+ busy = (
99
+ getattr(error, "sqlite_errorcode", None) == 5
100
+ or str(error) == "database is locked"
101
+ )
102
+ remaining = deadline - loop.time()
103
+ if not busy or remaining <= 0:
104
+ raise
105
+ await asyncio.sleep(min(0.01, remaining))
106
+
82
107
  async def close(self) -> None:
83
- async with self.opening:
108
+ async with self.executing, self.opening:
84
109
  if self.connection is not None:
85
110
  await self.connection.close()
86
111
  self.connection = None
87
112
 
113
+ @asynccontextmanager
114
+ async def execute(
115
+ self, sql: str, parameters: Sequence[Any] = ()
116
+ ) -> AsyncIterator[aiosqlite.Cursor]:
117
+ """Keep concurrent operations out until this statement's cursor is closed."""
118
+ async with self.executing:
119
+ connection = await self.open()
120
+ async with connection.execute(sql, parameters) as cursor:
121
+ yield cursor
122
+
88
123
  async def sweep(self) -> None:
89
124
  """Remove what has expired. Safe to call at any time, from any worker."""
90
- connection = await self.open()
91
- await connection.execute(f"DELETE FROM mcp_sessions WHERE expires_at <= {NOW}")
92
- await connection.execute(
125
+ async with self.execute(f"DELETE FROM mcp_sessions WHERE expires_at <= {NOW}"):
126
+ pass
127
+ async with self.execute(
93
128
  f"DELETE FROM mcp_events WHERE created_at <= {NOW} - ?", (self.event_ttl_seconds,)
94
- )
129
+ ):
130
+ pass
95
131
 
96
132
  async def sweeping(self, *, every: float | None = None) -> None:
97
133
  """Sweep until cancelled. A failed sweep is logged and tried again."""
@@ -123,8 +159,7 @@ class SqliteSessionStore(SessionStore):
123
159
  self.storage = storage
124
160
 
125
161
  async def create(self, session_id: str, data: Mapping[str, Any], *, ttl_seconds: int) -> bool:
126
- connection = await self.storage.open()
127
- cursor = await connection.execute(
162
+ async with self.storage.execute(
128
163
  f"""
129
164
  INSERT INTO mcp_sessions (id, data, version, expires_at)
130
165
  VALUES (?, ?, 1, {NOW} + ?)
@@ -133,12 +168,11 @@ class SqliteSessionStore(SessionStore):
133
168
  WHERE mcp_sessions.expires_at <= {NOW}
134
169
  """,
135
170
  (session_id, json.dumps(data), ttl_seconds),
136
- )
137
- return cursor.rowcount > 0
171
+ ) as cursor:
172
+ return cursor.rowcount > 0
138
173
 
139
174
  async def get(self, session_id: str) -> SessionRecord | None:
140
- connection = await self.storage.open()
141
- async with connection.execute(
175
+ async with self.storage.execute(
142
176
  f"SELECT data, version FROM mcp_sessions WHERE id = ? AND expires_at > {NOW}",
143
177
  (session_id,),
144
178
  ) as cursor:
@@ -155,27 +189,25 @@ class SqliteSessionStore(SessionStore):
155
189
  expected_version: int,
156
190
  ttl_seconds: int,
157
191
  ) -> bool:
158
- connection = await self.storage.open()
159
- cursor = await connection.execute(
192
+ async with self.storage.execute(
160
193
  f"""
161
194
  UPDATE mcp_sessions SET data = ?, version = version + 1, expires_at = {NOW} + ?
162
195
  WHERE id = ? AND version = ? AND expires_at > {NOW}
163
196
  """,
164
197
  (json.dumps(data), ttl_seconds, session_id, expected_version),
165
- )
166
- return cursor.rowcount > 0
198
+ ) as cursor:
199
+ return cursor.rowcount > 0
167
200
 
168
201
  async def touch(self, session_id: str, *, ttl_seconds: int) -> bool:
169
- connection = await self.storage.open()
170
- cursor = await connection.execute(
202
+ async with self.storage.execute(
171
203
  f"UPDATE mcp_sessions SET expires_at = {NOW} + ? WHERE id = ? AND expires_at > {NOW}",
172
204
  (ttl_seconds, session_id),
173
- )
174
- return cursor.rowcount > 0
205
+ ) as cursor:
206
+ return cursor.rowcount > 0
175
207
 
176
208
  async def delete(self, session_id: str) -> None:
177
- connection = await self.storage.open()
178
- await connection.execute("DELETE FROM mcp_sessions WHERE id = ?", (session_id,))
209
+ async with self.storage.execute("DELETE FROM mcp_sessions WHERE id = ?", (session_id,)):
210
+ pass
179
211
 
180
212
 
181
213
  class SqliteHub(Hub):
@@ -190,16 +222,14 @@ class SqliteHub(Hub):
190
222
  self.look_again = look_again
191
223
 
192
224
  async def publish(self, topic: str, message: Mapping[str, Any]) -> Cursor:
193
- connection = await self.storage.open()
194
- async with connection.execute(
225
+ async with self.storage.execute(
195
226
  f"INSERT INTO mcp_events (topic, message, created_at) VALUES (?, ?, {NOW})",
196
227
  (topic, json.dumps(message)),
197
228
  ) as inserted:
198
229
  return str(inserted.lastrowid)
199
230
 
200
231
  async def position(self, topic: str) -> Cursor:
201
- connection = await self.storage.open()
202
- async with connection.execute(
232
+ async with self.storage.execute(
203
233
  "SELECT MAX(id) FROM mcp_events WHERE topic = ?", (topic,)
204
234
  ) as cursor:
205
235
  row = await cursor.fetchone()
@@ -207,8 +237,7 @@ class SqliteHub(Hub):
207
237
 
208
238
  async def after(self, topic: str, cursor: Cursor) -> list[Event]:
209
239
  """Events after `cursor`. The row id is the event id."""
210
- connection = await self.storage.open()
211
- async with connection.execute(
240
+ async with self.storage.execute(
212
241
  "SELECT id, message FROM mcp_events WHERE topic = ? AND id > ? ORDER BY id",
213
242
  (topic, int(cursor) if cursor else 0),
214
243
  ) as rows:
@@ -228,8 +257,8 @@ class SqliteHub(Hub):
228
257
  await asyncio.sleep(min(self.look_again, left))
229
258
 
230
259
  async def delete(self, topic: str) -> None:
231
- connection = await self.storage.open()
232
- await connection.execute("DELETE FROM mcp_events WHERE topic = ?", (topic,))
260
+ async with self.storage.execute("DELETE FROM mcp_events WHERE topic = ?", (topic,)):
261
+ pass
233
262
 
234
263
 
235
264
  __all__ = [