netget-tool 0.3.4

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
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
//! XML-RPC protocol actions implementation
//!
//! This module implements the action system for XML-RPC.
//! The LLM controls all XML-RPC responses through these actions, including:
//! - Method execution responses (success values, faults)
//! - Introspection (system.listMethods, system.methodHelp, system.methodSignature)
//! - Extensions (nil values, i8/64-bit integers, system.multicall)

use crate::llm::actions::{
    protocol_trait::{ActionResult, Protocol, Server},
    ActionDefinition, Parameter,
};
use crate::protocol::log_template::LogTemplate;
use crate::protocol::{Event, EventType};
use crate::state::app_state::AppState;
use anyhow::{Context, Result};
use serde_json::json;
use std::sync::LazyLock;
use tracing::debug;

use super::{generate_fault, generate_success_response, MethodCall, XmlRpcValue};

/// XML-RPC protocol action handler
pub struct XmlRpcProtocol;

impl XmlRpcProtocol {
    pub fn new() -> Self {
        Self
    }

    /// Read an integer the model may have written as a JSON string.
    ///
    /// Models routinely quote numbers (`"8"` for `8`), and refusing that turns
    /// an otherwise correct answer into an XML-RPC fault the caller cannot act
    /// on. The rest of the tree already coerces this way (usb-fido2's
    /// `approval_id` takes a number or a numeric string), so accept it here
    /// too. Anything that is not a whole number is still refused.
    fn as_integer(value: &serde_json::Value, what: &str) -> Result<i64> {
        value
            .as_i64()
            .or_else(|| value.as_str().and_then(|s| s.trim().parse::<i64>().ok()))
            .with_context(|| {
                format!(
                    "value must be an integer for value_type '{}', got {}",
                    what, value
                )
            })
    }

    /// Same for doubles: `"19.99"` is a number a model plausibly quotes.
    fn as_double(value: &serde_json::Value) -> Result<f64> {
        value
            .as_f64()
            .or_else(|| value.as_str().and_then(|s| s.trim().parse::<f64>().ok()))
            .with_context(|| {
                format!(
                    "value must be a number for value_type 'double', got {}",
                    value
                )
            })
    }

    /// Same for booleans: XML-RPC itself writes them as 0/1, and models mirror
    /// that or quote `"true"`.
    fn as_boolean(value: &serde_json::Value) -> Result<bool> {
        if let Some(b) = value.as_bool() {
            return Ok(b);
        }
        if let Some(i) = value.as_i64() {
            return Ok(i != 0);
        }
        match value.as_str().map(|s| s.trim().to_ascii_lowercase()) {
            Some(ref s) if s == "true" || s == "1" => Ok(true),
            Some(ref s) if s == "false" || s == "0" => Ok(false),
            _ => Err(anyhow::anyhow!(
                "value must be a boolean for value_type 'boolean', got {}",
                value
            )),
        }
    }

    fn execute_success_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let value_type = action
            .get("value_type")
            .and_then(|v| v.as_str())
            .context("Missing 'value_type' parameter")?;

        let value = action.get("value").context("Missing 'value' parameter")?;

        // Convert JSON value to XmlRpcValue
        let xmlrpc_value = match value_type {
            "int" | "i4" => {
                // Range-checked, not cast: `as i32` silently wrapped, so 5000000000
                // went on the wire as 705032704.
                let i = Self::as_integer(value, value_type)?;
                let i = i32::try_from(i).map_err(|_| {
                    anyhow::anyhow!(
                        "{} does not fit in an XML-RPC <int> (-2147483648..2147483647); use value_type 'i8'",
                        i
                    )
                })?;
                XmlRpcValue::Int(i)
            }
            "i8" => {
                let i = Self::as_integer(value, "i8")?;
                XmlRpcValue::I8(i)
            }
            "boolean" | "bool" => {
                let b = Self::as_boolean(value)?;
                XmlRpcValue::Boolean(b)
            }
            "string" => {
                let s = value.as_str().context("Invalid string value")?;
                XmlRpcValue::String(s.to_string())
            }
            "double" => {
                let d = Self::as_double(value)?;
                if !d.is_finite() {
                    // NaN/inf render as "NaN"/"inf", which is not valid <double>.
                    return Err(anyhow::anyhow!("double value must be finite"));
                }
                XmlRpcValue::Double(d)
            }
            "array" => {
                let arr = value.as_array().context("Invalid array value")?;
                let items: Vec<XmlRpcValue> = arr
                    .iter()
                    .map(|v| self.json_to_xmlrpc_value(v))
                    .collect::<Result<Vec<_>>>()?;
                XmlRpcValue::Array(items)
            }
            "struct" => {
                let obj = value.as_object().context("Invalid struct value")?;
                let members: Vec<(String, XmlRpcValue)> = obj
                    .iter()
                    .map(|(k, v)| Ok((k.clone(), self.json_to_xmlrpc_value(v)?)))
                    .collect::<Result<Vec<_>>>()?;
                XmlRpcValue::Struct(members)
            }
            "nil" | "null" => XmlRpcValue::Nil,
            _ => return Err(anyhow::anyhow!("Unknown value_type: {}", value_type)),
        };

        let xml = generate_success_response(&xmlrpc_value);

        debug!("XML-RPC success response generated ({} bytes)", xml.len());
        Ok(ActionResult::Output(xml.as_bytes().to_vec()))
    }

    fn execute_fault_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        // `fault_code` is declared `required: true`, and a value that is present but not a
        // whole number is an error rather than a silent -32603. It used to be
        // `.and_then(|v| v.as_i64()).unwrap_or(-32603)`, so the quoted form models routinely
        // produce — `"fault_code": "-32601"` — became "internal error" on the wire: the model
        // said "no such method" and the caller was told netget had broken. `as_integer`
        // accepts the quoted form for the same reason every other field here does.
        // Absent stays -32603, which is the honest default for "the handler did not say".
        let code_i64 = match action.get("fault_code") {
            Some(value) => Self::as_integer(value, "fault_code")?,
            None => -32603,
        };
        let code = i32::try_from(code_i64).map_err(|_| {
            anyhow::anyhow!("fault_code {} does not fit in an XML-RPC <int>", code_i64)
        })?;

        let message = action
            .get("fault_string")
            .and_then(|v| v.as_str())
            .context("Missing 'fault_string' parameter")?;

        let xml = generate_fault(code, message);

        debug!("XML-RPC fault response: {} - {}", code, message);
        Ok(ActionResult::Output(xml.as_bytes().to_vec()))
    }

    fn execute_list_methods_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let methods = action
            .get("methods")
            .and_then(|v| v.as_array())
            .context("Missing 'methods' parameter")?;

        // Non-string entries used to be dropped silently while the log still
        // reported methods.len(), so the log disagreed with the wire.
        let method_list: Vec<XmlRpcValue> = methods
            .iter()
            .map(|v| {
                v.as_str()
                    .map(|s| XmlRpcValue::String(s.to_string()))
                    .context("every entry of 'methods' must be a method-name string")
            })
            .collect::<Result<Vec<_>>>()?;

        let method_count = method_list.len();
        let response_value = XmlRpcValue::Array(method_list);
        let xml = generate_success_response(&response_value);

        debug!(
            "XML-RPC system.listMethods response ({} methods)",
            method_count
        );
        Ok(ActionResult::Output(xml.as_bytes().to_vec()))
    }

    fn execute_method_help_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let help_text = action
            .get("help_text")
            .and_then(|v| v.as_str())
            .context("Missing 'help_text' parameter")?;

        let response_value = XmlRpcValue::String(help_text.to_string());
        let xml = generate_success_response(&response_value);

        debug!("XML-RPC system.methodHelp response");
        Ok(ActionResult::Output(xml.as_bytes().to_vec()))
    }

    fn execute_method_signature_response(&self, action: serde_json::Value) -> Result<ActionResult> {
        let signatures = action
            .get("signatures")
            .and_then(|v| v.as_array())
            .context("Missing 'signatures' parameter")?;

        // Convert signatures array to XML-RPC array of arrays
        // A flat list like ["int","int"] used to produce an empty result with no
        // error, because every non-array entry was filtered out.
        let sig_list: Vec<XmlRpcValue> = signatures
            .iter()
            .map(|v| {
                let arr = v.as_array().context(
                    "each entry of 'signatures' must itself be an array of type names, \
                     starting with the return type",
                )?;
                let types: Vec<XmlRpcValue> = arr
                    .iter()
                    .map(|t| {
                        t.as_str()
                            .map(|s| XmlRpcValue::String(s.to_string()))
                            .context("signature type names must be strings")
                    })
                    .collect::<Result<Vec<_>>>()?;
                Ok(XmlRpcValue::Array(types))
            })
            .collect::<Result<Vec<_>>>()?;

        let response_value = XmlRpcValue::Array(sig_list);
        let xml = generate_success_response(&response_value);

        debug!("XML-RPC system.methodSignature response");
        Ok(ActionResult::Output(xml.as_bytes().to_vec()))
    }

    /// Helper: Convert JSON value to XmlRpcValue (auto-detect type)
    fn json_to_xmlrpc_value(&self, value: &serde_json::Value) -> Result<XmlRpcValue> {
        match value {
            serde_json::Value::Null => Ok(XmlRpcValue::Nil),
            serde_json::Value::Bool(b) => Ok(XmlRpcValue::Boolean(*b)),
            serde_json::Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    if i >= i32::MIN as i64 && i <= i32::MAX as i64 {
                        Ok(XmlRpcValue::Int(i as i32))
                    } else {
                        Ok(XmlRpcValue::I8(i))
                    }
                } else if let Some(f) = n.as_f64() {
                    Ok(XmlRpcValue::Double(f))
                } else {
                    Err(anyhow::anyhow!("Invalid number"))
                }
            }
            serde_json::Value::String(s) => Ok(XmlRpcValue::String(s.clone())),
            serde_json::Value::Array(arr) => {
                let items: Vec<XmlRpcValue> = arr
                    .iter()
                    .map(|v| self.json_to_xmlrpc_value(v))
                    .collect::<Result<Vec<_>>>()?;
                Ok(XmlRpcValue::Array(items))
            }
            serde_json::Value::Object(obj) => {
                let members: Vec<(String, XmlRpcValue)> = obj
                    .iter()
                    .map(|(k, v)| Ok((k.clone(), self.json_to_xmlrpc_value(v)?)))
                    .collect::<Result<Vec<_>>>()?;
                Ok(XmlRpcValue::Struct(members))
            }
        }
    }
}

// Implement Protocol trait (common functionality)
impl Protocol for XmlRpcProtocol {
    fn get_async_actions(&self, _state: &AppState) -> Vec<ActionDefinition> {
        // XML-RPC is purely request-response, no async actions needed
        Vec::new()
    }
    fn get_sync_actions(&self) -> Vec<ActionDefinition> {
        vec![
            success_response_action(),
            fault_response_action(),
            list_methods_response_action(),
            method_help_response_action(),
            method_signature_response_action(),
        ]
    }
    fn protocol_name(&self) -> &'static str {
        "XML-RPC"
    }
    fn get_event_types(&self) -> Vec<EventType> {
        vec![XMLRPC_METHOD_CALL_EVENT.clone()]
    }
    fn stack_name(&self) -> &'static str {
        "ETH>IP>TCP>HTTP>XML-RPC"
    }
    fn keywords(&self) -> Vec<&'static str> {
        vec!["xmlrpc", "xml-rpc", "xml rpc"]
    }
    fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
        use crate::protocol::metadata::{DevelopmentState, ProtocolMetadataV2};

        ProtocolMetadataV2::builder()
            .state(DevelopmentState::Experimental)
            .implementation("Hand-written XML-RPC codec over HTTP POST (quick-xml, hyper 1)")
            .llm_control("Every method call: a typed return value or a fault code/string")
            .e2e_testing("curl and mocked in-process HTTP")
            .notes(
                "Parameters reach the model with their XML-RPC types: <int>5</int> is the \
                 number 5, not \"5\". <base64> is reported as a structural description, not \
                 an encoded blob. Faults are XML-escaped, so a fault_string containing < or \
                 & is still valid XML. system.multicall is not implemented. Any path is \
                 accepted; there is no auth, no rate limiting, and non-POST returns a fault \
                 body with HTTP 200 rather than 405. Request bodies are capped at 4 MiB and \
                 value nesting at 64 levels.",
            )
            .max_inbound_bytes(crate::server::xmlrpc::MAX_REQUEST_BODY_BYTES)
            .request_only(
                "XML-RPC is HTTP request/response; a server cannot send a peer anything unprompted",
            )
            .build()
    }
    fn description(&self) -> &'static str {
        "XML-RPC server"
    }
    fn example_prompt(&self) -> &'static str {
        "Start an XML-RPC server on port 8080 with methods add(a,b) and greet(name)"
    }
    fn group_name(&self) -> &'static str {
        "AI & API"
    }
    fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
        use crate::llm::actions::StartupExamples;

        StartupExamples::new(
            // LLM mode: instruction-based
            json!({
                "type": "open_server",
                "port": 8080,
                "base_stack": "xmlrpc",
                "instruction": "XML-RPC server with add(a,b), subtract(a,b), and system.listMethods. Return proper fault codes for errors"
            }),
            // Script mode: event_handlers with script handler
            json!({
                "type": "open_server",
                "port": 8080,
                "base_stack": "xmlrpc",
                "event_handlers": [{
                    "event_pattern": "xmlrpc_method_call",
                    "handler": {
                        "type": "script",
                        "language": "python",
                        "code": "method = event.get('method_name', '')\nparams = event.get('params', [])\nif method == 'add' and len(params) >= 2:\n    action('xmlrpc_success_response', value_type='int', value=params[0] + params[1])\nelse:\n    action('xmlrpc_fault_response', fault_code=-32601, fault_string='Method not found')"
                    }
                }]
            }),
            // Static mode: event_handlers with static actions
            json!({
                "type": "open_server",
                "port": 8080,
                "base_stack": "xmlrpc",
                "event_handlers": [{
                    "event_pattern": "xmlrpc_method_call",
                    "handler": {
                        "type": "static",
                        "actions": [{
                            "type": "xmlrpc_success_response",
                            "value_type": "string",
                            "value": "Hello from XML-RPC server"
                        }]
                    }
                }]
            }),
        )
    }
}

// Implement Server trait (server-specific functionality)
impl Server for XmlRpcProtocol {
    fn spawn(
        &self,
        ctx: crate::protocol::SpawnContext,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = anyhow::Result<std::net::SocketAddr>> + Send>,
    > {
        Box::pin(async move {
            use crate::server::xmlrpc::XmlRpcServer;
            XmlRpcServer::spawn_with_llm_actions(
                ctx.legacy_listen_addr(),
                ctx.llm_client,
                ctx.state,
                ctx.status_tx,
                ctx.server_id,
            )
            .await
        })
    }
    fn execute_action(&self, action: serde_json::Value) -> Result<ActionResult> {
        let action_type = action
            .get("type")
            .and_then(|v| v.as_str())
            .context("Missing 'type' field")?;

        match action_type {
            "xmlrpc_success_response" => self.execute_success_response(action),
            "xmlrpc_fault_response" => self.execute_fault_response(action),
            "xmlrpc_list_methods_response" => self.execute_list_methods_response(action),
            "xmlrpc_method_help_response" => self.execute_method_help_response(action),
            "xmlrpc_method_signature_response" => self.execute_method_signature_response(action),
            _ => Err(anyhow::anyhow!("Unknown action type: {}", action_type)),
        }
    }
}

// Action definitions

fn success_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "xmlrpc_success_response".to_string(),
        description: "Send XML-RPC success response with a value".to_string(),
        parameters: vec![
            Parameter {
                name: "value_type".to_string(),
                type_hint: "string".to_string(),
                description: "Type of the return value (int, i8, boolean, string, double, array, struct, nil)".to_string(),
                required: true,
            },
            Parameter {
                name: "value".to_string(),
                type_hint: "any".to_string(),
                description: "The actual value to return (type must match value_type)".to_string(),
                required: true,
            },
        ],
        example: json!({
            "type": "xmlrpc_success_response",
            "value_type": "int",
            "value": 42
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> XML-RPC success type={value_type}")
                .with_debug("XML-RPC xmlrpc_success_response: type={value_type}"),
        ),
    }
}

fn fault_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "xmlrpc_fault_response".to_string(),
        description: "Send XML-RPC fault/error response".to_string(),
        parameters: vec![
            Parameter {
                name: "fault_code".to_string(),
                type_hint: "number".to_string(),
                description: "Fault code (standard codes: -32700 parse error, -32600 invalid request, -32601 method not found, -32602 invalid params, -32603 internal error)".to_string(),
                required: true,
            },
            Parameter {
                name: "fault_string".to_string(),
                type_hint: "string".to_string(),
                description: "Human-readable error message".to_string(),
                required: true,
            },
        ],
        example: json!({
            "type": "xmlrpc_fault_response",
            "fault_code": -32601,
            "fault_string": "Method not found"
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> XML-RPC fault {fault_code}: {fault_string}")
                .with_debug("XML-RPC xmlrpc_fault_response: code={fault_code} message={fault_string}"),
        ),
    }
}

fn list_methods_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "xmlrpc_list_methods_response".to_string(),
        description: "Respond to system.listMethods introspection with array of method names"
            .to_string(),
        parameters: vec![Parameter {
            name: "methods".to_string(),
            type_hint: "array".to_string(),
            description: "Array of available method names (strings)".to_string(),
            required: true,
        }],
        example: json!({
            "type": "xmlrpc_list_methods_response",
            "methods": ["add", "subtract", "system.listMethods", "system.methodHelp"]
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> XML-RPC list methods ({methods_len})")
                .with_debug("XML-RPC xmlrpc_list_methods_response: count={methods_len}"),
        ),
    }
}

fn method_help_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "xmlrpc_method_help_response".to_string(),
        description: "Respond to system.methodHelp introspection with documentation string"
            .to_string(),
        parameters: vec![Parameter {
            name: "help_text".to_string(),
            type_hint: "string".to_string(),
            description: "Documentation/help text for the requested method".to_string(),
            required: true,
        }],
        example: json!({
            "type": "xmlrpc_method_help_response",
            "help_text": "add(a, b) - Returns the sum of two numbers"
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> XML-RPC method help")
                .with_debug("XML-RPC xmlrpc_method_help_response"),
        ),
    }
}

fn method_signature_response_action() -> ActionDefinition {
    ActionDefinition {
        name: "xmlrpc_method_signature_response".to_string(),
        description: "Respond to system.methodSignature introspection with array of signatures".to_string(),
        parameters: vec![Parameter {
            name: "signatures".to_string(),
            type_hint: "array".to_string(),
            description: "Array of signature arrays. Each signature is [return_type, param1_type, param2_type, ...]. Multiple signatures indicate overloads.".to_string(),
            required: true,
        }],
        example: json!({
            "type": "xmlrpc_method_signature_response",
            "signatures": [["int", "int", "int"]]
        }),
        log_template: Some(
            LogTemplate::new()
                .with_info("-> XML-RPC method signature")
                .with_debug("XML-RPC xmlrpc_method_signature_response: {signatures_len} sigs"),
        ),
    }
}

// Event type definitions

/// XML-RPC method call event
pub static XMLRPC_METHOD_CALL_EVENT: LazyLock<EventType> = LazyLock::new(|| {
    EventType::new(
        "xmlrpc_method_call",
        "XML-RPC method call received from client",
        json!({
            "type": "xmlrpc_success_response",
            "value_type": "int",
            "value": 42
        }),
    )
    .with_parameters(vec![
        Parameter {
            name: "method_name".to_string(),
            type_hint: "string".to_string(),
            description: "Name of the RPC method being called".to_string(),
            required: true,
        },
        Parameter {
            name: "params".to_string(),
            type_hint: "array".to_string(),
            description: "Array of parameter values (can be integers, strings, booleans, arrays, structs, etc.)".to_string(),
            required: true,
        },
    ])
    .with_actions(vec![
        success_response_action(),
        fault_response_action(),
        list_methods_response_action(),
        method_help_response_action(),
        method_signature_response_action(),
    ])
    .with_log_template(
        LogTemplate::new()
            .with_info("XML-RPC {method_name}")
            .with_debug("XML-RPC method={method_name}")
            .with_trace("XML-RPC: {json_pretty(.)}"),
    )
});

/// Create event from method call
pub fn create_method_call_event(method_call: &MethodCall) -> Event {
    // Convert XmlRpcValue params to JSON
    let params_json: Vec<serde_json::Value> = method_call
        .params
        .iter()
        .map(xmlrpc_value_to_json)
        .collect();

    Event::new(
        &XMLRPC_METHOD_CALL_EVENT,
        json!({
            "method_name": method_call.method_name,
            "params": params_json,
        }),
    )
}

/// Convert XmlRpcValue to JSON for LLM
fn xmlrpc_value_to_json(value: &XmlRpcValue) -> serde_json::Value {
    match value {
        XmlRpcValue::Int(i) => json!(i),
        XmlRpcValue::I8(i) => json!(i),
        XmlRpcValue::Boolean(b) => json!(b),
        XmlRpcValue::String(s) => json!(s),
        XmlRpcValue::Double(d) => json!(d),
        XmlRpcValue::DateTime(dt) => json!(dt),
        // Never hand the model a base64 blob (project rule: no raw bytes or
        // encoded payloads in event data). Report it structurally, with the text
        // only when the bytes happen to be UTF-8. This path is newly reachable:
        // before the parser was fixed, <base64> was decoded as a plain string.
        XmlRpcValue::Base64(bytes) => json!({
            "xmlrpc_type": "base64",
            "byte_length": bytes.len(),
            "text": std::str::from_utf8(bytes).ok(),
        }),
        XmlRpcValue::Array(arr) => {
            let items: Vec<serde_json::Value> = arr.iter().map(xmlrpc_value_to_json).collect();
            json!(items)
        }
        XmlRpcValue::Struct(members) => {
            let obj: serde_json::Map<String, serde_json::Value> = members
                .iter()
                .map(|(k, v)| (k.clone(), xmlrpc_value_to_json(v)))
                .collect();
            json!(obj)
        }
        XmlRpcValue::Nil => json!(null),
    }
}