eggsact 1.2.4

Deterministic MCP and in-process utility tools for coding agents
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
use crate::agent::ToolAudience;
use crate::mcp::registry;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, RwLock};
use tokio::sync::Mutex;
use tokio::time::Instant;

/// RAII guard for an active request entry.
///
/// The awaited `complete_request()` is the primary cleanup path. As a
/// panic-proof fallback, this guard's `Drop` also removes its own entry
/// (generation-checked) if it is somehow still registered — so a task that
/// panics before reaching `complete_request()` cannot leak the in-flight
/// slot. In the normal flow the entry is already gone and the drop is a
/// no-op.
#[doc(hidden)]
pub struct RequestGuard {
    active: ActiveRequests,
    request_id: Value,
    generation: u64,
}

impl RequestGuard {
    #[doc(hidden)]
    pub fn new(
        active: ActiveRequests,
        _cancel_flag: &Arc<AtomicBool>,
        request_id: Value,
        generation: u64,
    ) -> Self {
        Self {
            active,
            request_id,
            generation,
        }
    }
}

impl Drop for RequestGuard {
    fn drop(&mut self) {
        // Primary cleanup is `complete_request()`; this Drop is a panic-proof
        // fallback so a task that panics before reaching `complete_request`
        // cannot leak its in-flight slot.
        if let Ok(mut map) = self.active.try_lock() {
            if let Some(entry) = map.get(&self.request_id) {
                if entry.generation == self.generation {
                    map.remove(&self.request_id);
                }
            }
            return;
        }
        // `try_lock` failed (contended). Fall back to a blocking lock so the
        // slot is still freed even under contention. This blocks the current
        // thread briefly, but the Drop path only runs on panic/unwind where
        // leaking the slot (MAX_IN_FLIGHT_REQUESTS=32) is worse than blocking.
        let mut map = self.active.blocking_lock();
        if let Some(entry) = map.get(&self.request_id) {
            if entry.generation == self.generation {
                map.remove(&self.request_id);
            }
        }
    }
}

#[doc(hidden)]
pub const MAX_IN_FLIGHT_REQUESTS: usize = 32;

#[doc(hidden)]
pub const MAX_TOOL_WORKERS: usize = 16;
#[doc(hidden)]
pub const MAX_REQUEST_ID_LENGTH: usize = 1024;

// Items below are exposed for tests in `tests/`. They are not part of the
// stable API surface; downstream crates should not depend on them. They
// are `pub` (rather than `pub(crate)`) so integration tests can reach them
// through `eggsact::mcp::runtime::*` and `eggsact::mcp::runtime::test_support::*`.
#[doc(hidden)]
pub const MAX_REQUEST_BYTES: usize = 1_000_000;
#[doc(hidden)]
pub const MAX_OUTPUT_BYTES: usize = 1_000_000;

pub(crate) const SCHEMA_DETAIL_FULL: &str = "full";

pub const MCP_SERVER_NAME: &str = "eggsact";

// ═══════════════════════════════════════════════════════════════════════════════
// Protocol version table and negotiation (Workstream 2)
// ═══════════════════════════════════════════════════════════════════════════════

/// Ordered list of supported MCP protocol revisions. The first entry is the
/// preferred (current) revision. Only revisions that eggsact actually implements
/// are listed here.
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2024-11-05"];

/// The preferred (current) protocol revision. Eggsact negotiates to this
/// when the client's requested revision is not in `SUPPORTED_PROTOCOL_VERSIONS`.
pub const PREFERRED_PROTOCOL_VERSION: &str = SUPPORTED_PROTOCOL_VERSIONS[0];

/// Legacy single-version constant for backward compatibility with tests and
/// code that references `MCP_PROTOCOL_VERSION` directly. Prefer
/// `PREFERRED_PROTOCOL_VERSION` in new code.
pub const MCP_PROTOCOL_VERSION: &str = PREFERRED_PROTOCOL_VERSION;

/// Check whether a protocol version string is in the supported list.
pub fn is_supported_protocol_version(version: &str) -> bool {
    SUPPORTED_PROTOCOL_VERSIONS.contains(&version)
}

/// Negotiate a protocol version: return the requested version if supported,
/// otherwise return eggsact's preferred version.
pub fn negotiate_protocol_version(requested: &str) -> String {
    if is_supported_protocol_version(requested) {
        requested.to_string()
    } else {
        PREFERRED_PROTOCOL_VERSION.to_string()
    }
}

/// Negotiated protocol data stored per-connection.
#[derive(Debug, Clone)]
pub struct NegotiatedProtocol {
    /// The protocol version negotiated for this connection.
    pub version: String,
    /// Client implementation name.
    pub client_name: String,
    /// Client implementation version (optional).
    pub client_version: Option<String>,
    /// Client's declared capabilities.
    pub client_capabilities: crate::mcp::protocol::ClientCapabilities,
}

impl NegotiatedProtocol {
    /// Whether this revision supports the `notifications/initialized` handshake.
    pub fn supports_initialized_notification(&self) -> bool {
        // All supported revisions support this.
        true
    }

    /// Whether this revision allows eggsact extension capabilities.
    pub fn allows_extension_capabilities(&self) -> bool {
        // Both 2024-11-05 and 2025-11-25 allow extensions via experimental.
        true
    }

    /// Get a reference to the client's declared capabilities.
    pub fn client_capabilities(&self) -> &crate::mcp::protocol::ClientCapabilities {
        &self.client_capabilities
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Connection lifecycle state machine (Workstream 3)
// ═══════════════════════════════════════════════════════════════════════════════

/// Per-connection lifecycle state for the MCP server.
///
/// Each stdio session has its own `SessionState` that tracks initialization
/// progress. Methods are rejected until the session reaches `Ready`.
#[derive(Debug, Clone)]
pub enum SessionState {
    /// No `initialize` request has been received yet.
    ///
    /// Allowed: `initialize`, `ping`.
    /// Rejected: `tools/list`, `tools/call`, `profiles/list`, extensions.
    Uninitialized,
    /// `initialize` has been processed; waiting for `notifications/initialized`.
    ///
    /// Allowed: `notifications/initialized`, `ping`.
    /// Rejected: `tools/list`, `tools/call`, `profiles/list`, extensions.
    /// Rejected: duplicate `initialize`.
    AwaitingInitialized { negotiated: NegotiatedProtocol },
    /// Session is fully initialized and ready for normal operations.
    ///
    /// Allowed: all negotiated methods.
    /// Rejected: duplicate `initialize`.
    Ready { negotiated: NegotiatedProtocol },
}

impl SessionState {
    /// Whether this state allows a given method.
    pub fn allows_method(&self, method: &str) -> bool {
        match (self, method) {
            // Uninitialized: only initialize and ping
            (SessionState::Uninitialized, "initialize") => true,
            (SessionState::Uninitialized, "ping") => true,
            (SessionState::Uninitialized, _) => false,
            // AwaitingInitialized: only initialized notification and ping
            (SessionState::AwaitingInitialized { .. }, "notifications/initialized") => true,
            (SessionState::AwaitingInitialized { .. }, "ping") => true,
            (SessionState::AwaitingInitialized { .. }, _) => false,
            // Ready: everything except initialize (rejected as duplicate)
            (SessionState::Ready { .. }, "initialize") => false,
            (SessionState::Ready { .. }, _) => true,
        }
    }

    /// Attempt to transition from Uninitialized to AwaitingInitialized.
    /// Returns the negotiated protocol on success.
    pub fn transition_to_awaiting(
        &mut self,
        negotiated: NegotiatedProtocol,
    ) -> Result<(), &'static str> {
        match self {
            SessionState::Uninitialized => {
                *self = SessionState::AwaitingInitialized { negotiated };
                Ok(())
            }
            _ => Err("already_initialized"),
        }
    }

    /// Attempt to transition from AwaitingInitialized to Ready.
    pub fn transition_to_ready(&mut self) -> Result<(), &'static str> {
        match self {
            SessionState::AwaitingInitialized { negotiated } => {
                let negotiated = negotiated.clone();
                *self = SessionState::Ready { negotiated };
                Ok(())
            }
            _ => Err("not_awaiting_initialized"),
        }
    }

    /// Get a reference to the negotiated protocol if available.
    pub fn negotiated(&self) -> Option<&NegotiatedProtocol> {
        match self {
            SessionState::Uninitialized => None,
            SessionState::AwaitingInitialized { negotiated } => Some(negotiated),
            SessionState::Ready { negotiated } => Some(negotiated),
        }
    }
}

#[cfg(test)]
mod lifecycle_tests {
    use super::*;

    #[test]
    fn uninitialized_allows_only_initialize_and_ping() {
        let state = SessionState::Uninitialized;
        assert!(state.allows_method("initialize"));
        assert!(state.allows_method("ping"));
        assert!(!state.allows_method("tools/list"));
        assert!(!state.allows_method("tools/call"));
        assert!(!state.allows_method("profiles/list"));
        assert!(!state.allows_method("notifications/initialized"));
    }

    #[test]
    fn awaiting_initialized_allows_only_notification_and_ping() {
        let negotiated = NegotiatedProtocol {
            version: "2024-11-05".to_string(),
            client_name: "test".to_string(),
            client_version: None,
            client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
        };
        let state = SessionState::AwaitingInitialized {
            negotiated: negotiated.clone(),
        };
        assert!(state.allows_method("notifications/initialized"));
        assert!(state.allows_method("ping"));
        assert!(!state.allows_method("initialize"));
        assert!(!state.allows_method("tools/list"));
        assert!(!state.allows_method("tools/call"));
    }

    #[test]
    fn ready_allows_all_except_initialize() {
        let negotiated = NegotiatedProtocol {
            version: "2024-11-05".to_string(),
            client_name: "test".to_string(),
            client_version: None,
            client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
        };
        let state = SessionState::Ready { negotiated };
        assert!(!state.allows_method("initialize"));
        assert!(state.allows_method("tools/list"));
        assert!(state.allows_method("tools/call"));
        assert!(state.allows_method("profiles/list"));
        assert!(state.allows_method("ping"));
        assert!(state.allows_method("some_extension"));
    }

    #[test]
    fn transition_to_awaiting_from_uninitialized() {
        let negotiated = NegotiatedProtocol {
            version: "2024-11-05".to_string(),
            client_name: "test".to_string(),
            client_version: None,
            client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
        };
        let mut state = SessionState::Uninitialized;
        assert!(state.transition_to_awaiting(negotiated).is_ok());
        assert!(matches!(state, SessionState::AwaitingInitialized { .. }));
    }

    #[test]
    fn transition_to_awaiting_from_non_uninitialized_fails() {
        let negotiated = NegotiatedProtocol {
            version: "2024-11-05".to_string(),
            client_name: "test".to_string(),
            client_version: None,
            client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
        };
        let mut state = SessionState::AwaitingInitialized {
            negotiated: negotiated.clone(),
        };
        assert_eq!(
            state.transition_to_awaiting(negotiated).unwrap_err(),
            "already_initialized"
        );
    }

    #[test]
    fn transition_to_ready_from_awaiting() {
        let negotiated = NegotiatedProtocol {
            version: "2024-11-05".to_string(),
            client_name: "test".to_string(),
            client_version: None,
            client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
        };
        let mut state = SessionState::AwaitingInitialized { negotiated };
        assert!(state.transition_to_ready().is_ok());
        assert!(matches!(state, SessionState::Ready { .. }));
    }

    #[test]
    fn transition_to_ready_from_wrong_state_fails() {
        let mut state = SessionState::Uninitialized;
        assert_eq!(
            state.transition_to_ready().unwrap_err(),
            "not_awaiting_initialized"
        );
    }

    #[test]
    fn negotiated_version_persists_through_transitions() {
        let negotiated = NegotiatedProtocol {
            version: "2025-11-25".to_string(),
            client_name: "my-client".to_string(),
            client_version: Some("2.0".to_string()),
            client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
        };
        let mut state = SessionState::Uninitialized;
        state.transition_to_awaiting(negotiated).unwrap();
        assert_eq!(
            state.negotiated().map(|n| n.version.as_str()),
            Some("2025-11-25")
        );
        state.transition_to_ready().unwrap();
        assert_eq!(
            state.negotiated().map(|n| n.version.as_str()),
            Some("2025-11-25")
        );
        assert_eq!(
            state.negotiated().and_then(|n| n.client_version.as_deref()),
            Some("2.0")
        );
    }
}

static ACTIVE_PROFILE: LazyLock<RwLock<String>> = LazyLock::new(|| {
    let profile = std::env::var("EGGCALC_MCP_PROFILE").unwrap_or_else(|_| "full".to_string());
    RwLock::new(if registry::PROFILE_NAMES.contains(&profile.as_str()) {
        profile
    } else {
        eprintln!(
            "Warning: Invalid EGGCALC_MCP_PROFILE: {:?}. Available profiles: {}. Defaulting to full.",
            profile,
            registry::PROFILE_NAMES.join(", ")
        );
        "full".to_string()
    })
});

/// Validate and initialize the profile selected by the environment.
///
/// Profile validation is explicit so library callers can handle bad
/// configuration without a process-wide exit from a lazy initializer.
pub fn init_active_profile() -> Result<(), String> {
    let profile = std::env::var("EGGCALC_MCP_PROFILE").unwrap_or_else(|_| "full".to_string());
    if !registry::PROFILE_NAMES.contains(&profile.as_str()) {
        let available: Vec<&str> = registry::PROFILE_NAMES.to_vec();
        return Err(format!(
            "Invalid EGGCALC_MCP_PROFILE: {:?}. Available profiles: {}",
            profile,
            available.join(", ")
        ));
    }
    set_active_profile(&profile)
}

/// Parse a schema detail string, returning the validated value or `None` for
/// invalid input. Valid values are `"compact"`, `"normal"`, and `"full"`.
/// Empty strings and unknown values return `None`.
#[doc(hidden)]
pub fn parse_schema_detail(s: &str) -> Option<&'static str> {
    match s {
        "compact" => Some("compact"),
        "normal" => Some("normal"),
        "full" => Some("full"),
        _ => None,
    }
}

static ACTIVE_SCHEMA_DETAIL: LazyLock<RwLock<String>> = LazyLock::new(|| {
    let raw = std::env::var("EGGCALC_MCP_SCHEMA_DETAIL")
        .unwrap_or_else(|_| SCHEMA_DETAIL_FULL.to_string());
    match parse_schema_detail(&raw) {
        Some(valid) => RwLock::new(valid.to_string()),
        None => {
            eprintln!(
                "Warning: Invalid EGGCALC_MCP_SCHEMA_DETAIL: {:?}. \
                 Accepted values: compact, normal, full. Defaulting to full.",
                raw
            );
            RwLock::new(SCHEMA_DETAIL_FULL.to_string())
        }
    }
});

/// Parse an audience string into a `ToolAudience` variant.
///
/// Matching is case-insensitive. Invalid values default to `Model` with a
/// diagnostic warning on stderr. This function is exposed as `pub` (not
/// `pub(crate)`) so integration tests can reach it.
#[doc(hidden)]
pub fn parse_audience(s: &str) -> ToolAudience {
    match s.to_lowercase().as_str() {
        "model" => ToolAudience::Model,
        "harness" => ToolAudience::Harness,
        "debug" => ToolAudience::Debug,
        other => {
            eprintln!(
                "Warning: Invalid EGGCALC_MCP_AUDIENCE: {:?}. Defaulting to Model. Use Model, Harness, or Debug.",
                other
            );
            ToolAudience::Model
        }
    }
}

static ACTIVE_AUDIENCE: LazyLock<RwLock<ToolAudience>> = LazyLock::new(|| {
    let audience_str =
        std::env::var("EGGCALC_MCP_AUDIENCE").unwrap_or_else(|_| "Model".to_string());
    RwLock::new(parse_audience(&audience_str))
});

pub fn set_active_profile(name: &str) -> Result<(), String> {
    if !registry::PROFILE_NAMES.contains(&name) {
        let available: Vec<&str> = registry::PROFILE_NAMES.to_vec();
        return Err(format!(
            "Unknown profile: {:?}. Available profiles: {}",
            name,
            available.join(", ")
        ));
    }
    let mut profile = ACTIVE_PROFILE.write().map_err(|e| e.to_string())?;
    *profile = name.to_string();
    Ok(())
}

pub fn get_active_profile() -> String {
    let profile = ACTIVE_PROFILE.read().unwrap_or_else(|e| e.into_inner());
    profile.clone()
}

pub fn set_schema_detail(level: &str) -> Result<(), String> {
    if parse_schema_detail(level).is_none() {
        return Err(format!(
            "Invalid schema detail: {:?}. Use compact, normal, or full.",
            level
        ));
    }
    let mut detail = ACTIVE_SCHEMA_DETAIL.write().map_err(|e| e.to_string())?;
    *detail = level.to_string();
    Ok(())
}

pub fn get_schema_detail() -> String {
    let detail = ACTIVE_SCHEMA_DETAIL
        .read()
        .unwrap_or_else(|e| e.into_inner());
    detail.clone()
}

pub fn get_active_audience() -> ToolAudience {
    let audience = ACTIVE_AUDIENCE.read().unwrap_or_else(|e| e.into_inner());
    *audience
}

pub fn truncate_2000(s: &str) -> String {
    s.chars().take(2000).collect()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Active request tracking
// ═══════════════════════════════════════════════════════════════════════════════

/// Monotonically increasing generation counter for active-request entries.
/// Each `register_request` call allocates a new generation, and
/// `complete_request` only removes an entry when its stored generation
/// matches the caller's generation — preventing stale cleanup of a
/// recycled request ID.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);

/// State for an in-flight MCP request, used for concurrent request handling.
#[doc(hidden)]
pub struct ActiveRequest {
    pub cancel_flag: Arc<AtomicBool>,
    #[allow(dead_code)]
    pub started_at: Instant,
    #[allow(dead_code)]
    pub method: String,
    pub generation: u64,
}

/// Opaque token returned by `register_request` that identifies a specific
/// registration. Used by `complete_request` to remove the active-request
/// entry with generation-safe cleanup.
#[derive(Debug, Clone)]
#[doc(hidden)]
pub struct RequestRegistration {
    pub id: Value,
    pub generation: u64,
}

#[doc(hidden)]
pub type ActiveRequests = Arc<Mutex<HashMap<Value, ActiveRequest>>>;

/// Create a new shared active requests map.
#[doc(hidden)]
pub fn new_active_requests() -> ActiveRequests {
    Arc::new(Mutex::new(HashMap::new()))
}

// ═══════════════════════════════════════════════════════════════════════════════
// Runtime metrics
// ═══════════════════════════════════════════════════════════════════════════════

/// Global runtime metrics for the MCP server. All counters are atomic and
/// RAII-guarded so they decrement correctly on panic/unwind.
pub struct RuntimeMetrics {
    /// Number of currently active request tasks (registered in the active map).
    pub active_requests: AtomicUsize,
    /// Number of currently running blocking handler closures (inside spawn_blocking).
    pub active_blocking_handlers: AtomicUsize,
    /// Number of handlers that have timed out but whose blocking closure is still running.
    pub timed_out_handlers: AtomicUsize,
    /// Total number of timeout responses returned to clients.
    pub total_timeouts: AtomicUsize,
    /// Peak number of concurrent blocking handlers observed.
    pub peak_blocking_concurrency: AtomicUsize,
}

impl RuntimeMetrics {
    const fn new() -> Self {
        Self {
            active_requests: AtomicUsize::new(0),
            active_blocking_handlers: AtomicUsize::new(0),
            timed_out_handlers: AtomicUsize::new(0),
            total_timeouts: AtomicUsize::new(0),
            peak_blocking_concurrency: AtomicUsize::new(0),
        }
    }

    /// Create a fresh `RuntimeMetrics` instance for tests, independent
    /// of the global `RUNTIME_METRICS`.
    #[cfg(test)]
    pub fn new_for_test() -> Self {
        Self::new()
    }
}

/// Global runtime metrics instance.
#[doc(hidden)]
pub static RUNTIME_METRICS: LazyLock<RuntimeMetrics> = LazyLock::new(RuntimeMetrics::new);

/// RAII guard that increments a metric on creation and decrements on drop.
/// Used for active_requests and active_blocking_handlers counters.
#[doc(hidden)]
pub struct MetricGuard {
    counter: &'static AtomicUsize,
}

impl MetricGuard {
    /// Create a new guard that increments the given counter immediately.
    pub fn new(counter: &'static AtomicUsize) -> Self {
        counter.fetch_add(1, Ordering::Relaxed);
        Self { counter }
    }
}

impl Drop for MetricGuard {
    fn drop(&mut self) {
        self.counter.fetch_sub(1, Ordering::Relaxed);
    }
}

/// Snapshot of runtime metrics for diagnostics.
#[doc(hidden)]
pub struct MetricsSnapshot {
    pub active_requests: usize,
    pub active_blocking_handlers: usize,
    pub timed_out_handlers: usize,
    pub total_timeouts: usize,
    pub peak_blocking_concurrency: usize,
}

/// Take a snapshot of current runtime metrics.
#[doc(hidden)]
pub fn snapshot_metrics() -> MetricsSnapshot {
    MetricsSnapshot {
        active_requests: RUNTIME_METRICS.active_requests.load(Ordering::Relaxed),
        active_blocking_handlers: RUNTIME_METRICS
            .active_blocking_handlers
            .load(Ordering::Relaxed),
        timed_out_handlers: RUNTIME_METRICS.timed_out_handlers.load(Ordering::Relaxed),
        total_timeouts: RUNTIME_METRICS.total_timeouts.load(Ordering::Relaxed),
        peak_blocking_concurrency: RUNTIME_METRICS
            .peak_blocking_concurrency
            .load(Ordering::Relaxed),
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Request registration
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors that can occur when registering a new active request.
#[derive(Debug)]
#[doc(hidden)]
pub enum RegisterRequestError {
    /// A request with this non-null ID is already active.
    DuplicateId,
    /// The in-flight request limit has been reached.
    CapacityExceeded,
}

/// Register a new active request under a single lock acquisition.
///
/// Checks in-flight limits and duplicate IDs atomically, then inserts the
/// request into the active map. Returns a `RequestGuard` (debug-only
/// assertion in drop) and a `RequestRegistration` whose generation token
/// is used by `complete_request` for safe cleanup.
#[doc(hidden)]
pub async fn register_request(
    active: &ActiveRequests,
    cancel_flag: &Arc<AtomicBool>,
    request_id: Value,
    method: String,
) -> Result<(RequestGuard, RequestRegistration), RegisterRequestError> {
    let mut map = active.lock().await;
    if map.len() >= MAX_IN_FLIGHT_REQUESTS {
        return Err(RegisterRequestError::CapacityExceeded);
    }
    if map.contains_key(&request_id) {
        return Err(RegisterRequestError::DuplicateId);
    }
    let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
    map.insert(
        request_id.clone(),
        ActiveRequest {
            cancel_flag: cancel_flag.clone(),
            started_at: Instant::now(),
            method,
            generation,
        },
    );
    Ok((
        RequestGuard::new(active.clone(), cancel_flag, request_id.clone(), generation),
        RequestRegistration {
            id: request_id,
            generation,
        },
    ))
}

/// Awaited cleanup for an active request entry. Removes the entry from the
/// active-request map only if the stored generation matches the caller's
/// generation token. This prevents stale cleanup of a recycled request ID.
///
/// Returns `true` if the entry was removed, `false` if it was already gone
/// or the generation did not match.
#[doc(hidden)]
pub async fn complete_request(active: &ActiveRequests, registration: &RequestRegistration) -> bool {
    let mut map = active.lock().await;
    if let Some(entry) = map.get(&registration.id) {
        if entry.generation == registration.generation {
            map.remove(&registration.id);
            return true;
        }
    }
    false
}

/// Test-only helpers for constructing runtime state from integration tests.
///
/// This module is `#[doc(hidden)]` and not part of the public API; it is
/// exposed only so `tests/` integration tests can construct runtime
/// primitives without relying on `pub(crate)` items.
#[doc(hidden)]
pub mod test_support {
    use super::{ActiveRequest, Instant};
    use std::sync::{atomic::AtomicBool, Arc};

    pub fn make_active_request(cancel_flag: Arc<AtomicBool>) -> ActiveRequest {
        ActiveRequest {
            cancel_flag,
            started_at: Instant::now(),
            method: "test".to_string(),
            generation: 0,
        }
    }
}

/// Apply a cancellation notification to a single active request ID.
///
/// Validates the request ID type (string or integer within size limits),
/// looks up the corresponding active request, clones its cancel flag Arc,
/// releases the lock, then sets the flag outside the critical section.
/// Returns `true` if a cancel flag was actually set.
///
/// This is an async function that properly awaits the active-map lock
/// rather than using `try_lock()`, which can lose cancellations when
/// the map is briefly contended.
///
/// This function is extracted from the server's notification handler so
/// it can be unit-tested in isolation without spawning the stdio loop.
#[doc(hidden)]
pub async fn apply_cancellation(active: &ActiveRequests, request_id: &Value) -> bool {
    // Validate ID type and size BEFORE acquiring the lock — avoids holding
    // the lock for obviously-invalid IDs (bools, oversized strings/numbers).
    let valid = match request_id {
        Value::Bool(_) => return false,
        Value::String(s) => s.len() <= MAX_REQUEST_ID_LENGTH,
        Value::Number(n) => {
            (n.is_i64() || n.is_u64()) && request_id.to_string().len() <= MAX_REQUEST_ID_LENGTH
        }
        _ => return false,
    };
    if !valid {
        return false;
    }
    // Clone the cancel flag Arc while holding the lock.
    let maybe_flag: Option<Arc<AtomicBool>> = {
        let map = active.lock().await;
        map.get(request_id).map(|req| req.cancel_flag.clone())
    };
    // Set the flag outside the critical section — no lock held.
    if let Some(flag) = maybe_flag {
        flag.store(true, Ordering::Release);
        true
    } else {
        false
    }
}