1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
//! Cross-instance fan-out for subscription notifications (MCP 2026-07-28).
//!
//! A `subscriptions/listen` stream is a socket held open by exactly one
//! process. Under the stateless 2026-07-28 HTTP transport nothing pins a client
//! to an instance, so the stream and the request that mutates the server
//! routinely land on different ones:
//!
//! ```text
//! client --- subscriptions/listen ------------> instance A (stream held here)
//! client --- tools/call (mutates the tools) --> instance B (ctx.add_tool)
//! instance B has no subscribers
//! instance A's subscriber hears nothing
//! ```
//!
//! The subscriber is told its filter was accepted, so the loss reads as "the
//! server never changes" rather than as a delivery failure.
//!
//! ## Why the registry is not the seam
//!
//! The registry behind those streams is a table of *live connections*, not
//! application state: each entry pairs a serializable id and filter with an
//! `mpsc::Sender` writing into one held-open response body and an in-process
//! cancellation token. A shared store could persist the first half and still
//! deliver nothing -- instance B cannot write into instance A's socket. So the
//! registry stays node-local by construction, and what is made pluggable is the
//! *distribution*: every instance keeps its own subscribers, a
//! [`NotificationBus`] carries notifications between instances, and each one
//! delivers to the subscribers it actually holds.
//!
//! This is the same split the crate already draws elsewhere:
//! [`RequestStateStore`](crate::app::mrtr_store::RequestStateStore) is a trait
//! with an in-memory default because it stores a plain `Response` under a
//! string key; the SSE session registry is a concrete in-process type because
//! it holds channel senders.
//!
//! ## The default
//!
//! No bus is configured by default, and a notification goes straight to this
//! instance's own subscribers -- no channel, no allocation, no task. A
//! single-instance server behaves exactly as it did before this trait existed,
//! and pays nothing for its presence.
//!
//! Shared implementations (Redis pub/sub, NATS, Postgres `LISTEN`/`NOTIFY`)
//! live outside this crate; neva ships the trait and the local default, the
//! same way it does for the MRTR state store.
//!
//! # Examples
//! ```no_run
//! # #[cfg(not(feature = "legacy-spec"))] {
//! use neva::App;
//! use neva::app::notification_bus::{BusNotification, NotificationBus};
//! use neva::shared::Stream;
//! use tokio::sync::broadcast::{Sender, channel, error::RecvError};
//!
//! /// Stands in for a real bus: one process-wide channel every instance
//! /// publishes to and reads back from, echo included.
//! struct BroadcastBus(Sender<BusNotification>);
//!
//! impl NotificationBus for BroadcastBus {
//! async fn publish(&self, notification: BusNotification) {
//! // Nobody draining yet is not an error worth failing a request over.
//! let _ = self.0.send(notification);
//! }
//!
//! fn subscribe(&self) -> impl Stream<Item = BusNotification> + Send + 'static {
//! let rx = self.0.subscribe();
//! futures_util::stream::unfold(rx, |mut rx| async move {
//! loop {
//! match rx.recv().await {
//! Ok(notification) => return Some((notification, rx)),
//! // At-most-once: skip what was missed rather than end
//! // delivery for good.
//! Err(RecvError::Lagged(_)) => continue,
//! Err(RecvError::Closed) => return None,
//! }
//! }
//! })
//! }
//! }
//!
//! let (tx, _) = channel(64);
//! let app = App::new().with_notification_bus(BroadcastBus(tx));
//! # }
//! ```
use crate;
use ;
/// One subscribable notification in flight between instances
/// (MCP 2026-07-28).
///
/// Carries the JSON-RPC method and params of a `tools`/`prompts`/`resources`
/// list-changed or `resources/updated` notification -- and nothing about the
/// instance that produced it or the subscription it will end up on. Both are
/// decided on arrival: the receiving instance matches it against the filters of
/// the streams *it* holds and stamps each copy with that stream's own
/// subscription id.
///
/// It serializes as the notification body it describes (`{"method": ...,
/// "params": ...}`), so a bus that ships JSON can hand it straight to
/// `serde_json` in both directions rather than inventing an envelope.
///
/// # Examples
/// ```
/// # #[cfg(not(feature = "legacy-spec"))] {
/// use neva::app::notification_bus::BusNotification;
///
/// let notification = BusNotification::new(
/// "notifications/resources/updated",
/// Some(serde_json::json!({ "uri": "res://config" })),
/// );
///
/// let wire = serde_json::to_string(¬ification).unwrap();
/// let back: BusNotification = serde_json::from_str(&wire).unwrap();
///
/// assert_eq!(back.method(), "notifications/resources/updated");
/// assert_eq!(back.params().unwrap()["uri"], "res://config");
/// # }
/// ```
/// Carries subscribable notifications between the instances of one logical
/// server (MCP 2026-07-28).
///
/// Implement this to fan `tools`/`prompts`/`resources` list-changed and
/// `resources/updated` notifications out across a horizontally scaled
/// deployment, and install it with
/// [`App::with_notification_bus`](crate::App::with_notification_bus). Only
/// notification types a client can subscribe to reach the bus; progress, task
/// status and elicitation stay request-scoped and never travel on one.
///
/// See the [module docs](self) for why the subscriber table itself stays
/// node-local, and for a complete implementation.
///
/// ## Contract
///
/// * **No echo suppression.** [`subscribe`](Self::subscribe) must yield the
/// notifications this instance published as well as everybody else's. Local
/// delivery happens through that stream and only through it, so a bus that
/// hides an instance's own messages from it silences that instance's own
/// subscribers. (Redis pub/sub, NATS and a `tokio::sync::broadcast` channel
/// all echo by default; suppressing it takes deliberate work.)
/// * **At-most-once.** A subscription whose buffer is full drops the
/// notification with a warning rather than blocking the request that produced
/// it, so a bus must not promise more than the sink it feeds. Redelivery
/// after an instance dies buys nothing either: subscriptions are not
/// resumable by spec, and a client whose stream drops re-sends
/// `subscriptions/listen`.
/// * **Ordering.** The "acknowledgment MUST be first" rule is per-subscription
/// and stays entirely local -- the acknowledgment is queued before the
/// registry entry goes live, so no notification can overtake it however it
/// arrives. Cross-instance ordering between *different* notifications is not
/// something the spec requires.
/// * **Cost.** [`publish`](Self::publish) is awaited inside the request that
/// produced the notification, so a slow bus slows that request down. Prefer
/// an implementation that hands off to a background connection over one that
/// waits for a round trip.
///
/// # Examples
/// See the [module docs](self) for a complete implementation.
/// The `dyn`-compatible shape of [`NotificationBus`], which the server stores
/// and calls.
///
/// [`NotificationBus`] returns `impl Future` / `impl Stream` so that
/// implementing it is plain `async fn` and needs no `Pin<Box<..>>` anywhere.
/// Those are not `dyn`-compatible, and the server holds exactly one bus behind
/// an `Arc<dyn ..>`, so the boxing has to happen somewhere: it happens here,
/// once, in a blanket impl nobody outside this module ever names.
pub