bevy_brp_mcp 0.22.2

MCP server for Bevy Remote Protocol (BRP) integration
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
//! Background task management for watch connections

use std::path::PathBuf;
use std::time::Instant;

use error_stack::Report;
use futures::StreamExt;
use reqwest::Response;
use serde_json::Value;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing::warn;

use super::constants::BUFFER_CONTENT_FIELD;
use super::constants::BUFFER_SIZE_FIELD;
use super::constants::CHUNK_SIZE_FIELD;
use super::constants::CHUNKS_RECEIVED_BEFORE_ERROR_FIELD;
use super::constants::COMPONENT_UPDATE_EVENT;
use super::constants::CONNECTION_ERROR_EVENT;
use super::constants::CONTAINS_DATA_PREFIX_FIELD;
use super::constants::CONTAINS_NEWLINE_FIELD;
use super::constants::CONTENT_TYPE_FIELD;
use super::constants::CONTENT_TYPE_HEADER;
use super::constants::DATA_LENGTH_FIELD;
use super::constants::DEBUG_CHUNK_RECEIVED_EVENT;
use super::constants::DEBUG_FIRST_CHUNK_EVENT;
use super::constants::DEBUG_HTTP_RESPONSE_EVENT;
use super::constants::DEBUG_INCOMPLETE_LINE_IN_BUFFER_EVENT;
use super::constants::DEBUG_JSON_PARSE_FAILED_EVENT;
use super::constants::DEBUG_JSON_PARSED_EVENT;
use super::constants::DEBUG_LINE_RECEIVED_EVENT;
use super::constants::DEBUG_LINES_PROCESSED_EVENT;
use super::constants::DEBUG_NO_RESULT_EVENT;
use super::constants::DEBUG_STREAM_ENDED_EVENT;
use super::constants::DEBUG_STREAM_ERROR_EVENT;
use super::constants::DEBUG_STREAM_STARTED_EVENT;
use super::constants::ELAPSED_SECONDS_FIELD;
use super::constants::EMPTY_LINES_FIELD;
use super::constants::ENTITY_FIELD;
use super::constants::ERROR_FIELD;
use super::constants::FINAL_BUFFER_SIZE_FIELD;
use super::constants::FULL_DATA_FIELD;
use super::constants::HAD_INCOMPLETE_LINE_FIELD;
use super::constants::HAS_ERROR_FIELD;
use super::constants::HAS_ID_FIELD;
use super::constants::HAS_RESULT_FIELD;
use super::constants::HEADERS_COUNT_FIELD;
use super::constants::IS_SSE_DATA_FIELD;
use super::constants::JSON_KEYS_FIELD;
use super::constants::JSON_RPC_ERROR_FIELD;
use super::constants::JSON_RPC_ID_FIELD;
use super::constants::JSON_RPC_RESULT_FIELD;
use super::constants::LINE_BUFFER_SIZE_BEFORE_FIELD;
use super::constants::LINE_FIELD;
use super::constants::LINE_LENGTH_FIELD;
use super::constants::LINES_PROCESSED_FIELD;
use super::constants::MAX_BUFFER_SIZE;
use super::constants::MAX_CHUNK_SIZE;
use super::constants::MAX_PREVIEW_BYTES;
use super::constants::PREVIEW_FIELD;
use super::constants::RAW_DATA_FIELD;
use super::constants::REMAINING_BUFFER_SIZE_FIELD;
use super::constants::RESPONSE_STATUS_FIELD;
use super::constants::SSE_DATA_PREFIX;
use super::constants::STARTS_WITH_DATA_FIELD;
use super::constants::STATUS_FIELD;
use super::constants::STATUS_TEXT_FIELD;
use super::constants::TIMESTAMP_FIELD;
use super::constants::TOTAL_BUFFER_SIZE_BEFORE_FIELD;
use super::constants::TOTAL_CHUNKS_RECEIVED_FIELD;
use super::constants::UNKNOWN_STATUS_TEXT;
use super::constants::WATCH_ENDED_EVENT;
use super::constants::WATCH_STARTED_EVENT;
use super::constants::WATCH_TYPE_FIELD;
use super::logger::BufferedWatchLogger;
use super::manager::WATCH_MANAGER;
use super::manager::WatchInfo;
use crate::brp_tools::BrpClient;
use crate::brp_tools::Port;
use crate::error::Error;
use crate::error::Result;
use crate::tool::BrpMethod;
use crate::tool::ParameterName;

/// Parameters for a watch connection
struct WatchConnectionParams {
    watch_id:   u32,
    entity_id:  u64,
    kind:       String,
    brp_method: BrpMethod,
    params:     Value,
    port:       Port,
}

/// Process a single SSE line and log the update if valid
async fn parse_sse_line(
    line: &str,
    entity_id: u64,
    watch_type: &str,
    logger: &BufferedWatchLogger,
) -> Result<()> {
    // Log EVERY line received for debugging
    let _ = logger
        .write_debug_update(
            DEBUG_LINE_RECEIVED_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: watch_type,
                ParameterName::Entity: entity_id,
                LINE_FIELD: line,
                LINE_LENGTH_FIELD: line.len(),
                IS_SSE_DATA_FIELD: line.starts_with(SSE_DATA_PREFIX),
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;

    // Handle SSE format: "data: {json}"
    let Some(json_str) = line.strip_prefix(SSE_DATA_PREFIX) else {
        debug!("[{watch_type}] Received non-SSE line: {line}");
        return Ok(());
    };

    let Ok(data) = serde_json::from_str::<Value>(json_str) else {
        debug!("[{watch_type}] Failed to parse SSE data as JSON: {json_str}");

        // Log parse failure
        let _ = logger
            .write_debug_update(
                DEBUG_JSON_PARSE_FAILED_EVENT,
                serde_json::json!({
                    WATCH_TYPE_FIELD: watch_type,
                    ParameterName::Entity: entity_id,
                    RAW_DATA_FIELD: json_str,
                    DATA_LENGTH_FIELD: json_str.len(),
                    TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
                }),
            )
            .await;
        return Ok(());
    };

    debug!("[{watch_type}] Received watch update for entity {entity_id}: {data:?}");

    // Log successful JSON parsing
    let _ = logger.write_debug_update(
        DEBUG_JSON_PARSED_EVENT,
        serde_json::json!({
            WATCH_TYPE_FIELD: watch_type,
            ParameterName::Entity: entity_id,
            HAS_RESULT_FIELD: data.get(JSON_RPC_RESULT_FIELD).is_some(),
            HAS_ERROR_FIELD: data.get(JSON_RPC_ERROR_FIELD).is_some(),
            HAS_ID_FIELD: data.get(JSON_RPC_ID_FIELD).is_some(),
            JSON_KEYS_FIELD: data.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default(),
            TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
        })
    ).await;

    // Extract the result from JSON-RPC response
    if let Some(result) = data.get(JSON_RPC_RESULT_FIELD) {
        log_update(logger, result.clone()).await?;
    } else {
        debug!("[{watch_type}] No result in JSON-RPC response: {data:?}");

        // Log missing result field
        let _ = logger
            .write_debug_update(
                DEBUG_NO_RESULT_EVENT,
                serde_json::json!({
                    WATCH_TYPE_FIELD: watch_type,
                    ParameterName::Entity: entity_id,
                    FULL_DATA_FIELD: data,
                    TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
                }),
            )
            .await;
    }
    Ok(())
}

/// Log a watch update with error handling
async fn log_update(logger: &BufferedWatchLogger, result: Value) -> Result<()> {
    if let Err(e) = logger.write_update(COMPONENT_UPDATE_EVENT, result).await {
        error!("Failed to write watch update to log: {e}");
        return Err(error_stack::Report::new(Error::failed_to(
            "write watch update to log",
            &e,
        )));
    }
    Ok(())
}

/// Process a single chunk from the stream
async fn process_chunk(
    bytes: &[u8],
    line_buffer: &mut String,
    total_buffer_size: &mut usize,
    entity_id: u64,
    watch_type: &str,
    logger: &BufferedWatchLogger,
) -> Result<()> {
    // Log chunk size
    let _ = logger
        .write_debug_update(
            DEBUG_CHUNK_RECEIVED_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: watch_type,
                ParameterName::Entity: entity_id,
                CHUNK_SIZE_FIELD: bytes.len(),
                LINE_BUFFER_SIZE_BEFORE_FIELD: line_buffer.len(),
                TOTAL_BUFFER_SIZE_BEFORE_FIELD: *total_buffer_size,
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;

    // Check chunk size limit
    if bytes.len() > MAX_CHUNK_SIZE {
        return Err(error_stack::Report::new(Error::InvalidState(format!(
            "Stream chunk size {} exceeds maximum {}",
            bytes.len(),
            MAX_CHUNK_SIZE
        ))));
    }

    // Convert bytes to string
    let text = match std::str::from_utf8(bytes) {
        Ok(text) => text,
        Err(e) => {
            debug!("[{watch_type}] Invalid UTF-8 in stream chunk: {e}");
            return Ok(());
        },
    };

    // Add to line buffer and check total buffer size
    line_buffer.push_str(text);
    *total_buffer_size += text.len();

    if *total_buffer_size > MAX_BUFFER_SIZE {
        return Err(error_stack::Report::new(Error::InvalidState(format!(
            "Stream buffer size {} exceeds maximum {}",
            *total_buffer_size, MAX_BUFFER_SIZE
        ))));
    }

    // Process complete lines from the buffer
    let mut lines_processed = 0;
    let mut empty_lines = 0;

    while let Some(newline_pos) = line_buffer.find('\n') {
        let line = line_buffer.drain(..=newline_pos).collect::<String>();
        let line = line.trim_end_matches('\n').trim_end_matches('\r');

        // Update buffer size tracking
        *total_buffer_size = line_buffer.len();

        if line.trim().is_empty() {
            empty_lines += 1;
            continue;
        }

        lines_processed += 1;
        parse_sse_line(line, entity_id, watch_type, logger).await?;
    }

    // Log number of lines processed
    if lines_processed > 0 || empty_lines > 0 {
        let _ = logger
            .write_debug_update(
                DEBUG_LINES_PROCESSED_EVENT,
                serde_json::json!({
                    WATCH_TYPE_FIELD: watch_type,
                    ParameterName::Entity: entity_id,
                    LINES_PROCESSED_FIELD: lines_processed,
                    EMPTY_LINES_FIELD: empty_lines,
                    REMAINING_BUFFER_SIZE_FIELD: line_buffer.len(),
                    TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
                }),
            )
            .await;
    }

    // Log incomplete lines in buffer
    if !line_buffer.is_empty() {
        let _ = logger
            .write_debug_update(
                DEBUG_INCOMPLETE_LINE_IN_BUFFER_EVENT,
                serde_json::json!({
                    WATCH_TYPE_FIELD: watch_type,
                    ParameterName::Entity: entity_id,
                    BUFFER_CONTENT_FIELD: line_buffer,
                    BUFFER_SIZE_FIELD: line_buffer.len(),
                    CONTAINS_DATA_PREFIX_FIELD: line_buffer.contains(SSE_DATA_PREFIX),
                    TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
                }),
            )
            .await;
    }

    Ok(())
}

/// Handle stream error
async fn handle_stream_error(
    error: reqwest::Error,
    entity_id: u64,
    watch_type: &str,
    logger: &BufferedWatchLogger,
    start_time: Instant,
    total_chunks: usize,
) {
    let elapsed = start_time.elapsed();
    let error_string = error.to_string();

    error!("Error reading stream chunk: {error}");

    // Log stream error
    let _ = logger
        .write_debug_update(
            DEBUG_STREAM_ERROR_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: watch_type,
                ParameterName::Entity: entity_id,
                ERROR_FIELD: error_string,
                CHUNKS_RECEIVED_BEFORE_ERROR_FIELD: total_chunks,
                ELAPSED_SECONDS_FIELD: elapsed.as_secs(),
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;
}

/// Log the first chunk of data for debugging
async fn log_first_chunk(
    bytes: &[u8],
    entity_id: u64,
    watch_type: &str,
    logger: &BufferedWatchLogger,
) {
    let preview = if bytes.len() <= MAX_PREVIEW_BYTES {
        String::from_utf8_lossy(bytes).to_string()
    } else {
        format!(
            "{}... (truncated from {} bytes)",
            String::from_utf8_lossy(&bytes[..MAX_PREVIEW_BYTES]),
            bytes.len()
        )
    };

    let _ = logger
        .write_debug_update(
            DEBUG_FIRST_CHUNK_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: watch_type,
                ParameterName::Entity: entity_id,
                CHUNK_SIZE_FIELD: bytes.len(),
                PREVIEW_FIELD: preview,
                STARTS_WITH_DATA_FIELD: String::from_utf8_lossy(bytes).starts_with(SSE_DATA_PREFIX.trim_end()),
                CONTAINS_NEWLINE_FIELD: bytes.contains(&b'\n'),
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;
}

/// Process the watch stream from the BRP server
async fn process_watch_stream(
    response: Response,
    entity_id: u64,
    watch_type: &str,
    logger: &BufferedWatchLogger,
    start_time: Instant,
) -> Result<()> {
    if !response.status().is_success() {
        let error_message = format!(
            "server returned {}: {}",
            response.status(),
            response
                .status()
                .canonical_reason()
                .unwrap_or(UNKNOWN_STATUS_TEXT)
        );
        error!("Failed to process watch stream: {error_message}");
        return Err(error_stack::Report::new(Error::BrpCommunication(format!(
            "Failed to process watch stream: {error_message}"
        ))));
    }

    // Log stream start
    let _ = logger
        .write_debug_update(
            DEBUG_STREAM_STARTED_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: watch_type,
                ParameterName::Entity: entity_id,
                RESPONSE_STATUS_FIELD: response.status().as_u16(),
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;

    let total_chunks =
        consume_stream_chunks(response, entity_id, watch_type, logger, start_time).await?;

    info!("[{watch_type}] Watch stream ended for entity {entity_id} ({total_chunks} chunks)");
    Ok(())
}

/// Read all chunks from the streaming response and process them
async fn consume_stream_chunks(
    response: Response,
    entity_id: u64,
    watch_type: &str,
    logger: &BufferedWatchLogger,
    start_time: Instant,
) -> Result<usize> {
    let mut stream = response.bytes_stream();
    let mut line_buffer = String::new();
    let mut total_buffer_size = 0;
    let mut total_chunks = 0;

    while let Some(chunk) = stream.next().await {
        match chunk {
            Ok(bytes) => {
                total_chunks += 1;

                // Special logging for first chunk
                if total_chunks == 1 {
                    log_first_chunk(&bytes, entity_id, watch_type, logger).await;
                }

                process_chunk(
                    &bytes,
                    &mut line_buffer,
                    &mut total_buffer_size,
                    entity_id,
                    watch_type,
                    logger,
                )
                .await?;
            },
            Err(e) => {
                handle_stream_error(e, entity_id, watch_type, logger, start_time, total_chunks)
                    .await;
                break;
            },
        }
    }

    // Process any remaining incomplete line in the buffer
    if !line_buffer.trim().is_empty() {
        debug!(
            "[{watch_type}] Processing remaining incomplete line: {}",
            line_buffer.trim()
        );
        parse_sse_line(line_buffer.trim(), entity_id, watch_type, logger).await?;
    }

    // Log stream end with details
    let _ = logger
        .write_debug_update(
            DEBUG_STREAM_ENDED_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: watch_type,
                ParameterName::Entity: entity_id,
                TOTAL_CHUNKS_RECEIVED_FIELD: total_chunks,
                FINAL_BUFFER_SIZE_FIELD: line_buffer.len(),
                HAD_INCOMPLETE_LINE_FIELD: !line_buffer.trim().is_empty(),
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;

    Ok(total_chunks)
}

/// Handle connection errors and log appropriately
async fn handle_connection_error(
    error: Report<Error>,
    conn_params: &WatchConnectionParams,
    logger: &BufferedWatchLogger,
    start_time: Instant,
) {
    let elapsed = start_time.elapsed();
    let error_string = error.to_string();

    error!("Failed to connect to BRP server: {error}");

    let _ = logger
        .write_update(
            CONNECTION_ERROR_EVENT,
            serde_json::json!({
                WATCH_TYPE_FIELD: &conn_params.kind,
                ParameterName::Entity: conn_params.entity_id,
                ERROR_FIELD: error_string,
                ELAPSED_SECONDS_FIELD: elapsed.as_secs(),
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;
}

/// Run the watch connection in a spawned task
async fn run_watch_connection(conn_params: WatchConnectionParams, logger: BufferedWatchLogger) {
    info!(
        "Starting {} watch task for entity {} on port {}",
        conn_params.kind, conn_params.entity_id, conn_params.port
    );

    // Track start time for timeout detection
    let start_time = std::time::Instant::now();

    // Create BRP client
    let brp_client = BrpClient::new(
        conn_params.brp_method,
        conn_params.port,
        Some(conn_params.params.clone()),
    );

    match brp_client.execute_streaming().await {
        Ok(response) => {
            // Log initial HTTP response
            let _ = logger
                .write_debug_update(
                    DEBUG_HTTP_RESPONSE_EVENT,
                    serde_json::json!({
                        WATCH_TYPE_FIELD: &conn_params.kind,
                        ParameterName::Entity: conn_params.entity_id,
                        STATUS_FIELD: response.status().as_u16(),
                        STATUS_TEXT_FIELD: response.status().canonical_reason().unwrap_or(UNKNOWN_STATUS_TEXT),
                        HEADERS_COUNT_FIELD: response.headers().len(),
                        CONTENT_TYPE_FIELD: response
                            .headers()
                            .get(CONTENT_TYPE_HEADER)
                            .and_then(|value| value.to_str().ok()),
                        TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
                    }),
                )
                .await;

            if let Err(e) = process_watch_stream(
                response,
                conn_params.entity_id,
                &conn_params.kind,
                &logger,
                start_time,
            )
            .await
            {
                error!("Watch stream processing failed: {e}");
            }
        },
        Err(e) => {
            handle_connection_error(e, &conn_params, &logger, start_time).await;
        },
    }

    // Write final log entry
    let _ = logger
        .write_update(
            WATCH_ENDED_EVENT,
            serde_json::json!({
                ParameterName::Entity: conn_params.entity_id,
                TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
            }),
        )
        .await;

    // Remove this watch from the active watches with defensive checks
    {
        let mut manager = WATCH_MANAGER.lock().await;
        if manager
            .active_watches
            .remove(&conn_params.watch_id)
            .is_some()
        {
            info!(
                "Watch {} for entity {} automatically cleaned up after connection ended",
                conn_params.watch_id, conn_params.entity_id
            );
        } else {
            warn!(
                "Watch {} for entity {} attempted to clean up but was not found in active watches - possible phantom watch removal",
                conn_params.watch_id, conn_params.entity_id
            );
        }
    }
}

/// Generic function to start a watch task
async fn start_watch_task(
    entity_id: u64,
    watch_type: &str,
    brp_method: BrpMethod,
    params: Value,
    port: Port,
) -> Result<(u32, PathBuf)> {
    // Prepare all data that doesn't require the watch_id
    let watch_type_owned = watch_type.to_string();
    let brp_method_owned = brp_method;

    // Perform all operations within a single lock to ensure atomicity
    let mut manager = WATCH_MANAGER.lock().await;

    // Generate ID while holding the lock
    let watch_id = manager.next_id();

    // Create log path and logger
    let log_path = BufferedWatchLogger::get_watch_log_path(watch_id, entity_id, watch_type);
    let buffered_watch_logger = BufferedWatchLogger::new(log_path.clone());

    // Create initial log entry
    let log_data = match params.clone() {
        Value::Object(mut map) => {
            map.insert(String::from(ParameterName::Port), serde_json::json!(port));
            map.insert(
                TIMESTAMP_FIELD.to_string(),
                serde_json::json!(chrono::Local::now().to_rfc3339()),
            );
            Value::Object(map)
        },
        _ => serde_json::json!({
            ParameterName::Entity: entity_id,
            ParameterName::Port: port,
            TIMESTAMP_FIELD: chrono::Local::now().to_rfc3339()
        }),
    };

    // If logging fails, we haven't registered anything yet
    let log_result = buffered_watch_logger
        .write_update(WATCH_STARTED_EVENT, log_data)
        .await;

    if let Err(e) = log_result {
        return Err(error_stack::Report::new(Error::WatchOperation(format!(
            "Failed to log initial entry for entity {entity_id}: {e}"
        ))));
    }

    // Spawn task
    let handle = tokio::spawn(run_watch_connection(
        WatchConnectionParams {
            watch_id,
            entity_id,
            kind: watch_type_owned,
            brp_method: brp_method_owned,
            params,
            port,
        },
        buffered_watch_logger,
    ));

    // Register immediately while still holding the lock
    manager.active_watches.insert(
        watch_id,
        (
            WatchInfo {
                id: watch_id,
                entity_id,
                kind: watch_type.to_string(),
                log_path: log_path.clone(),
                port,
            },
            handle,
        ),
    );

    // Release lock by dropping manager
    drop(manager);

    Ok((watch_id, log_path))
}

/// Start a background task for entity component watching
pub(super) async fn start_entity_watch_task(
    entity_id: u64,
    components: Option<Vec<String>>,
    port: Port,
) -> Result<(u32, PathBuf)> {
    // Validate components parameter
    let components = components.ok_or_else(|| {
        error_stack::Report::new(Error::missing("components parameter is required for entity watch. Specify which components to monitor"))
    })?;

    if components.is_empty() {
        return Err(error_stack::Report::new(Error::invalid(
            "components array",
            "cannot be empty. Specify at least one component to watch",
        )));
    }

    // Build the watch parameters
    let params = serde_json::json!({
        ParameterName::Entity: entity_id,
        ParameterName::Components: components
    });

    start_watch_task(
        entity_id,
        "get",
        BrpMethod::WorldGetComponentsWatch,
        params,
        port,
    )
    .await
}

/// Start a background task for entity list watching
pub(super) async fn start_list_watch_task(entity_id: u64, port: Port) -> Result<(u32, PathBuf)> {
    let params = serde_json::json!({
        ENTITY_FIELD: entity_id
    });

    start_watch_task(
        entity_id,
        "list",
        BrpMethod::WorldListComponentsWatch,
        params,
        port,
    )
    .await
}