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
use error_stack::ResultExt;
use serde::Serialize;
use serde_json::Value;

use super::HandlerContext;
use super::ParamStruct;
use super::ParameterName;
use super::ResultStruct;
use super::constants::ENTITY_COUNT_PLACEHOLDER;
use super::constants::OPTIONAL_PARAMETERS_NOT_PROVIDED_FIELD;
use super::constants::RESULT_PLACEHOLDER;
use super::constants::SKIP_NULL_FIELD_SENTINEL;
use super::field_placement::FieldPlacement;
use super::json_response::AnySchemaValue;
use super::json_response::ResponseStatus;
use super::json_response::ToolCallJsonResponse;
use super::name::CallInfo;
use crate::error::Error;
use crate::error::Result;

/// High-level response creation API
///
/// This provides a cleaner, more ergonomic interface for creating responses
/// compared to using `ResponseBuilder` directly.
pub(super) struct Response;

impl Response {
    /// Create a success response from a `ResultStruct`
    pub(super) fn success<R: ResultStruct + ?Sized, P: ParamStruct>(
        result: &R,
        params: Option<P>,
        call_info: CallInfo,
        context: &HandlerContext,
    ) -> Result<ToolCallJsonResponse> {
        ResponseBuilder::success(call_info).build_with_result_struct(result, params, context)
    }

    /// Create an error response from a `ResultStruct`
    pub(super) fn error<R: ResultStruct + ?Sized, P: ParamStruct>(
        error_result: &R,
        params: Option<P>,
        call_info: CallInfo,
        context: &HandlerContext,
    ) -> Result<ToolCallJsonResponse> {
        ResponseBuilder::error(call_info).build_with_result_struct(error_result, params, context)
    }

    /// Create a simple error response with just a message
    pub(super) fn error_message(
        message: impl Into<String>,
        call_info: CallInfo,
    ) -> ToolCallJsonResponse {
        ResponseBuilder::error(call_info).message(message).build()
    }

    /// Create an error response with message and optional details
    pub(super) fn error_with_details(
        message: impl Into<String>,
        details: Option<&Value>,
        call_info: CallInfo,
    ) -> ToolCallJsonResponse {
        ResponseBuilder::error(call_info)
            .message(message)
            .add_optional_details(details)
            .build()
    }
}

/// Builder for constructing JSON responses
#[derive(Clone)]
pub struct ResponseBuilder {
    status:                ResponseStatus,
    message:               String,
    call_info:             CallInfo,
    metadata:              Option<AnySchemaValue>,
    parameters:            Option<AnySchemaValue>,
    result:                Option<AnySchemaValue>,
    error_info:            Option<AnySchemaValue>,
    brp_extras_debug_info: Option<AnySchemaValue>,
}

impl ResponseBuilder {
    /// Create a success response with call info pre-populated
    pub(super) const fn success(call_info: CallInfo) -> Self {
        Self {
            status: ResponseStatus::Success,
            message: String::new(),
            call_info,
            metadata: None,
            parameters: None,
            result: None,
            error_info: None,
            brp_extras_debug_info: None,
        }
    }

    /// Create an error response with call info pre-populated
    pub(super) const fn error(call_info: CallInfo) -> Self {
        Self {
            status: ResponseStatus::Error,
            message: String::new(),
            call_info,
            metadata: None,
            parameters: None,
            result: None,
            error_info: None,
            brp_extras_debug_info: None,
        }
    }

    pub(super) fn message(mut self, message: impl Into<String>) -> Self {
        self.message = message.into();
        self
    }

    /// Add a field to the metadata object. Creates a new object if metadata is None.
    fn add_field(mut self, key: &str, value: impl Serialize) -> Result<Self> {
        let value_json = serde_json::to_value(value)
            .change_context(Error::General(format!("Failed to serialize field '{key}'")))?;

        // Skip fields marked for nullable skipping
        if let Value::String(s) = &value_json
            && s == SKIP_NULL_FIELD_SENTINEL
        {
            return Ok(self);
        }

        if let Some(AnySchemaValue(Value::Object(map))) = &mut self.metadata {
            map.insert(key.to_string(), value_json);
        } else {
            let mut map = serde_json::Map::new();
            map.insert(key.to_string(), value_json);
            self.metadata = Some(AnySchemaValue(Value::Object(map)));
        }

        Ok(self)
    }

    /// Add multiple fields from an optional JSON object to metadata
    /// Useful for adding error details or other optional metadata
    fn add_optional_details(self, details: Option<&Value>) -> Self {
        match details {
            Some(Value::Object(map)) => {
                map.iter()
                    .filter(|(_, v)| !v.is_null())
                    .fold(self, |builder, (key, value)| {
                        builder.clone().add_field(key, value).unwrap_or_else(|_| {
                            tracing::warn!("Failed to add detail field '{key}'");
                            builder // Keep the original builder if add_field fails
                        })
                    })
            },
            _ => self,
        }
    }

    /// Add a field to the specified location (metadata or result object)
    pub fn add_field_to(
        mut self,
        key: &str,
        value: impl Serialize,
        placement: FieldPlacement,
    ) -> Result<Self> {
        let value_json = serde_json::to_value(value)
            .change_context(Error::General(format!("Failed to serialize field '{key}'")))?;

        // Skip fields marked for nullable skipping
        if let Value::String(s) = &value_json
            && s == SKIP_NULL_FIELD_SENTINEL
        {
            return Ok(self);
        }

        match placement {
            FieldPlacement::Metadata => {
                // For metadata, use field name as key in object
                if let Some(AnySchemaValue(Value::Object(map))) = &mut self.metadata {
                    map.insert(key.to_string(), value_json);
                } else {
                    let mut map = serde_json::Map::new();
                    map.insert(key.to_string(), value_json);
                    self.metadata = Some(AnySchemaValue(Value::Object(map)));
                }
            },
            FieldPlacement::Result => {
                // For result, set the entire result field to the value
                // Field name is ignored to match raw BRP behavior
                self.result = Some(AnySchemaValue(value_json));
            },
            FieldPlacement::ErrorInfo => {
                // For error_info, use field name as key in object
                if let Some(AnySchemaValue(Value::Object(map))) = &mut self.error_info {
                    map.insert(key.to_string(), value_json);
                } else {
                    let mut map = serde_json::Map::new();
                    map.insert(key.to_string(), value_json);
                    self.error_info = Some(AnySchemaValue(Value::Object(map)));
                }
            },
        }

        Ok(self)
    }

    pub(super) fn build(self) -> ToolCallJsonResponse {
        ToolCallJsonResponse {
            status:                self.status,
            message:               self.message,
            call_info:             self.call_info,
            metadata:              self.metadata,
            parameters:            self.parameters,
            result:                self.result,
            error_info:            self.error_info,
            brp_extras_debug_info: self.brp_extras_debug_info,
        }
    }

    /// Get metadata for template substitution
    const fn metadata(&self) -> Option<&Value> {
        match &self.metadata {
            Some(any_val) => Some(&any_val.0),
            None => None,
        }
    }

    /// Get result for template substitution
    const fn result(&self) -> Option<&Value> {
        match &self.result {
            Some(any_val) => Some(&any_val.0),
            None => None,
        }
    }

    /// Set parameters with optional parameter tracking
    fn parameters(mut self, params: impl Serialize) -> Result<Self> {
        let mut params_value = serde_json::to_value(params)
            .change_context(Error::General("Failed to serialize parameters".to_string()))?;

        // Extract optional parameters that were not provided
        if let Value::Object(ref mut params_obj) = params_value {
            let mut optional_not_provided = Vec::new();

            // Collect keys that have null values (optional parameters not provided)
            let null_keys: Vec<String> = params_obj
                .iter()
                .filter_map(|(key, value)| {
                    if value.is_null() {
                        Some(key.clone())
                    } else {
                        None
                    }
                })
                .collect();

            // Remove null values from the main parameters object
            for key in &null_keys {
                params_obj.remove(key);
                optional_not_provided.push(key.clone());
            }

            // Add the optional_parameters_not_provided array if there are any
            if !optional_not_provided.is_empty() {
                params_obj.insert(
                    OPTIONAL_PARAMETERS_NOT_PROVIDED_FIELD.to_string(),
                    Value::Array(
                        optional_not_provided
                            .into_iter()
                            .map(Value::String)
                            .collect(),
                    ),
                );
            }
        }

        self.parameters = Some(AnySchemaValue(params_value));
        Ok(self)
    }

    /// Get parameters for template substitution
    const fn parameters_ref(&self) -> Option<&Value> {
        match &self.parameters {
            Some(any_val) => Some(&any_val.0),
            None => None,
        }
    }

    /// Terminal operation: Build complete response from a `ResultStruct`, handling all formatting
    /// and template substitution
    pub(super) fn build_with_result_struct<R: ResultStruct + ?Sized, P: ParamStruct>(
        mut self,
        result: &R,
        params: Option<P>,
        handler_context: &HandlerContext,
    ) -> Result<ToolCallJsonResponse> {
        // Add response fields
        self = result
            .add_response_fields(self)
            .map_err(|e| Error::failed_to("add response fields", e))?;

        // Add parameters if present
        if let Some(params) = params {
            self = self.parameters(params)?;
        }

        // Perform template substitution
        let template_str = result.get_message_template()?;
        tracing::debug!("Template before substitution: '{template_str}'");
        let message = Self::substitute_dynamic_template(template_str, &self, handler_context);
        tracing::debug!("Template after substitution: '{message}'");
        self = self.message(message);

        Ok(self.build())
    }

    /// Substitute template placeholders with values from the builder using dynamic template string
    fn substitute_dynamic_template(
        template_str: &str,
        builder: &Self,
        handler_context: &HandlerContext,
    ) -> String {
        let mut result = template_str.to_string();

        // Extract placeholders from template
        let placeholders = Self::parse_template_placeholders(&result);

        for placeholder in placeholders {
            if let Some(replacement) =
                Self::find_placeholder_value(&placeholder, builder, handler_context)
            {
                let placeholder_str = format!("{{{{{placeholder}}}}}");
                result = result.replace(&placeholder_str, &replacement);
            }
        }

        result
    }

    /// Parse template to find placeholder names
    fn parse_template_placeholders(template: &str) -> Vec<String> {
        let mut placeholders = Vec::new();
        let mut remaining = template;

        while let Some(start) = remaining.find("{{") {
            if let Some(end) = remaining[start + 2..].find("}}") {
                let placeholder = &remaining[start + 2..start + 2 + end];
                if !placeholder.is_empty() && !placeholder.contains('{') {
                    placeholders.push(placeholder.to_string());
                }
                remaining = &remaining[start + 2 + end + 2..];
            } else {
                break;
            }
        }

        placeholders
    }

    /// Find value for a placeholder
    fn find_placeholder_value(
        placeholder: &str,
        builder: &Self,
        handler_context: &HandlerContext,
    ) -> Option<String> {
        tracing::debug!("Looking for placeholder: '{placeholder}'");
        // First check error_info (for error fields)
        if let Some(AnySchemaValue(Value::Object(error_info))) = &builder.error_info {
            tracing::debug!(
                "Error info contains: {:?}",
                error_info.keys().collect::<Vec<_>>()
            );
            if let Some(value) = error_info.get(placeholder) {
                let result = Self::value_to_string(value);
                tracing::debug!("Found '{placeholder}' in error_info: '{result}'");
                return Some(result);
            }
        }

        // Then check metadata
        if let Some(Value::Object(metadata)) = builder.metadata()
            && let Some(value) = metadata.get(placeholder)
        {
            return Some(Self::value_to_string(value));
        }

        // Then check result if placeholder is "result"
        if placeholder == RESULT_PLACEHOLDER
            && let Some(result_value) = builder.result()
        {
            return Some(Self::value_to_string(result_value));
        }

        // Check parameters added to the builder
        if let Some(Value::Object(params_obj)) = builder.parameters_ref() {
            // Special handling for entity_count from entities array
            if placeholder == ENTITY_COUNT_PLACEHOLDER
                && let Some(Value::Array(entities)) =
                    params_obj.get(ParameterName::Entities.as_ref())
            {
                return Some(entities.len().to_string());
            }

            // Regular parameter lookup
            if let Some(value) = params_obj.get(placeholder) {
                return Some(Self::value_to_string(value));
            }
        }

        // Finally check request parameters
        if let Some(value) = handler_context.extract_optional_named_field(placeholder) {
            return Some(Self::value_to_string(value));
        }

        None
    }

    /// Convert value to string for template substitution
    fn value_to_string(value: &Value) -> String {
        match value {
            Value::String(s) => s.clone(),
            Value::Number(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            Value::Array(arr) => format!("{} items", arr.len()),
            _ => value.to_string(),
        }
    }
}