bote 0.90.0

MCP core service — JSON-RPC 2.0 protocol, tool registry, audit integration, and TypeScript bridge
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
//! TypeScript bridge — SY-compatible HTTP endpoint with CORS and MCP result formatting.
//!
//! The bridge wraps bote's JSON-RPC dispatch in an HTTP server that:
//! - Adds CORS headers for cross-origin TypeScript clients
//! - Reformats `tools/call` results into SY's MCP envelope (`{ content: [{ type, text }] }`)
//! - Exposes a `/health` endpoint for liveness checks
//!
//! Enable the `bridge` feature to use this module.

use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;

use axum::extract::State;
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::{Router, routing};

use crate::BoteError;
use crate::dispatch::Dispatcher;
use crate::protocol::JsonRpcResponse;
use crate::transport::codec;

/// Configuration for the TypeScript bridge server.
#[non_exhaustive]
pub struct BridgeConfig {
    /// Address to bind the bridge server.
    pub addr: SocketAddr,
    /// Allowed CORS origins. Use `["*"]` during development.
    pub allowed_origins: Vec<String>,
}

impl BridgeConfig {
    #[must_use]
    pub fn new(addr: SocketAddr, allowed_origins: Vec<String>) -> Self {
        Self {
            addr,
            allowed_origins,
        }
    }
}

/// Wrap a raw tool result into SY's MCP envelope format.
///
/// If the result already has a `content` array, it is returned as-is.
/// Otherwise the value is serialized to a text content block.
#[must_use]
#[inline]
pub fn wrap_tool_result(result: &serde_json::Value) -> serde_json::Value {
    // Already in MCP envelope shape — pass through.
    if result.get("content").and_then(|v| v.as_array()).is_some() {
        return result.clone();
    }

    // Wrap raw value into the expected envelope.
    serde_json::json!({
        "content": [{
            "type": "text",
            "text": result.to_string()
        }]
    })
}

/// Wrap an error result into SY's MCP envelope with the `isError` flag.
#[must_use]
#[inline]
fn wrap_error_result(message: &str) -> serde_json::Value {
    serde_json::json!({
        "content": [{
            "type": "text",
            "text": message
        }],
        "isError": true
    })
}

#[derive(Clone)]
struct BridgeState {
    dispatcher: Arc<Dispatcher>,
    allowed_origins: Arc<Vec<String>>,
}

/// Build the bridge axum router.
///
/// Composes JSON-RPC dispatch with CORS headers and MCP result formatting.
#[must_use = "build the axum router for the bridge"]
pub fn router(dispatcher: Arc<Dispatcher>, allowed_origins: Vec<String>) -> Router {
    let state = BridgeState {
        dispatcher,
        allowed_origins: Arc::new(allowed_origins),
    };
    Router::new()
        .route("/", routing::post(handle_rpc).options(handle_preflight))
        .route("/health", routing::get(handle_health))
        .with_state(state)
}

/// Start the bridge HTTP server.
///
/// Runs until the `shutdown` future resolves, then drains in-flight
/// requests and returns `Ok(())`.
pub async fn serve(
    dispatcher: Arc<Dispatcher>,
    config: BridgeConfig,
    shutdown: impl Future<Output = ()> + Send + 'static,
) -> crate::Result<()> {
    let app = router(dispatcher, config.allowed_origins);

    let listener = tokio::net::TcpListener::bind(config.addr)
        .await
        .map_err(|e| BoteError::BindFailed(e.to_string()))?;

    tracing::info!(addr = %config.addr, "bridge transport listening");

    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown)
        .await
        .map_err(BoteError::Io)?;

    tracing::info!("bridge transport shut down");
    Ok(())
}

async fn handle_rpc(State(state): State<BridgeState>, body: String) -> Response {
    let dispatcher = Arc::clone(&state.dispatcher);
    let result = tokio::task::spawn_blocking(move || process_bridge_message(&body, &dispatcher))
        .await
        .expect("BUG: dispatch task panicked");

    let mut response = match result {
        Some(json) => {
            (StatusCode::OK, [("content-type", "application/json")], json).into_response()
        }
        None => StatusCode::NO_CONTENT.into_response(),
    };

    apply_cors_headers(response.headers_mut(), &state.allowed_origins);
    response
}

async fn handle_preflight(State(state): State<BridgeState>) -> Response {
    let mut response = StatusCode::NO_CONTENT.into_response();
    apply_cors_headers(response.headers_mut(), &state.allowed_origins);
    response
}

async fn handle_health(State(state): State<BridgeState>) -> Response {
    let mut response = (StatusCode::OK, "ok").into_response();
    apply_cors_headers(response.headers_mut(), &state.allowed_origins);
    response
}

fn apply_cors_headers(headers: &mut axum::http::HeaderMap, allowed_origins: &[String]) {
    let origin = if allowed_origins.iter().any(|o| o == "*") {
        HeaderValue::from_static("*")
    } else {
        // Join multiple origins — browsers only support one, but we list the first.
        // In production, callers should match the request Origin against allowed_origins.
        match allowed_origins.first() {
            Some(o) => HeaderValue::from_str(o).unwrap_or(HeaderValue::from_static("*")),
            None => HeaderValue::from_static("*"),
        }
    };

    headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    headers.insert(
        header::ACCESS_CONTROL_ALLOW_METHODS,
        HeaderValue::from_static("POST, GET, OPTIONS"),
    );
    headers.insert(
        header::ACCESS_CONTROL_ALLOW_HEADERS,
        HeaderValue::from_static("content-type"),
    );
}

/// Process a JSON-RPC message through the bridge, wrapping tool call results.
fn process_bridge_message(input: &str, dispatcher: &Dispatcher) -> Option<String> {
    // Parse as a single request to check if it's a tools/call.
    let value: serde_json::Value = match serde_json::from_str(input) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(error = %e, "bridge: JSON-RPC parse error");
            let resp = JsonRpcResponse::error(
                serde_json::json!(null),
                -32700,
                format!("parse error: {e}"),
            );
            return Some(serde_json::to_string(&resp).expect("BUG: response serialization"));
        }
    };

    // For non-object values (batch arrays, primitives), fall through to codec.
    if !value.is_object() {
        return codec::process_message(input, dispatcher);
    }

    let request: crate::protocol::JsonRpcRequest = match serde_json::from_value(value) {
        Ok(req) => req,
        Err(e) => {
            let resp = JsonRpcResponse::error(
                serde_json::json!(null),
                -32600,
                format!("invalid request: {e}"),
            );
            return Some(serde_json::to_string(&resp).expect("BUG: response serialization"));
        }
    };

    if request.jsonrpc != "2.0" {
        let resp = JsonRpcResponse::error(
            request.id.clone().unwrap_or(serde_json::Value::Null),
            -32600,
            format!(
                "invalid request: unsupported jsonrpc version '{}'",
                request.jsonrpc
            ),
        );
        return Some(serde_json::to_string(&resp).expect("BUG: response serialization"));
    }

    // Dispatch and wrap tools/call results.
    let resp = dispatcher.dispatch(&request)?;

    let wrapped = if request.method == "tools/call" {
        if let Some(result) = &resp.result {
            JsonRpcResponse::success(resp.id.clone(), wrap_tool_result(result))
        } else if let Some(err) = &resp.error {
            // Tool call failed — return the error in MCP envelope as the result.
            // JSON-RPC 2.0 spec forbids setting both result and error.
            JsonRpcResponse::success(resp.id.clone(), wrap_error_result(&err.message))
        } else {
            resp
        }
    } else {
        resp
    };

    Some(serde_json::to_string(&wrapped).expect("BUG: response serialization"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dispatch::Dispatcher;
    use crate::registry::{ToolDef, ToolRegistry, ToolSchema};
    use axum::body::Body;
    use axum::http::Request;
    use std::collections::HashMap;
    use tower::util::ServiceExt;

    fn make_bridge_app() -> Router {
        let mut reg = ToolRegistry::new();
        reg.register(ToolDef {
            name: "echo".into(),
            description: "Echo".into(),
            input_schema: ToolSchema {
                schema_type: "object".into(),
                properties: HashMap::new(),
                required: vec![],
            },
            version: None,
            deprecated: None,
        });
        let mut d = Dispatcher::new(reg);
        d.handle(
            "echo",
            Arc::new(|params| serde_json::json!({"raw": params})),
        );
        // Also register a tool that returns MCP-formatted results.
        let mut reg2 = ToolRegistry::new();
        reg2.register(ToolDef {
            name: "echo".into(),
            description: "Echo".into(),
            input_schema: ToolSchema {
                schema_type: "object".into(),
                properties: HashMap::new(),
                required: vec![],
            },
            version: None,
            deprecated: None,
        });
        reg2.register(ToolDef {
            name: "mcp_tool".into(),
            description: "MCP formatted".into(),
            input_schema: ToolSchema {
                schema_type: "object".into(),
                properties: HashMap::new(),
                required: vec![],
            },
            version: None,
            deprecated: None,
        });
        let mut d = Dispatcher::new(reg2);
        d.handle(
            "echo",
            Arc::new(|params| serde_json::json!({"raw": params})),
        );
        d.handle(
            "mcp_tool",
            Arc::new(|_| {
                serde_json::json!({
                    "content": [{"type": "text", "text": "already formatted"}]
                })
            }),
        );
        router(Arc::new(d), vec!["*".into()])
    }

    // --- wrap_tool_result tests ---

    #[test]
    fn wrap_raw_value() {
        let raw = serde_json::json!({"answer": 42});
        let wrapped = wrap_tool_result(&raw);
        let content = wrapped["content"].as_array().unwrap();
        assert_eq!(content.len(), 1);
        assert_eq!(content[0]["type"], "text");
        assert!(content[0]["text"].as_str().unwrap().contains("42"));
    }

    #[test]
    fn wrap_already_formatted() {
        let formatted = serde_json::json!({
            "content": [{"type": "text", "text": "hello"}]
        });
        let wrapped = wrap_tool_result(&formatted);
        assert_eq!(wrapped, formatted);
    }

    #[test]
    fn wrap_null_value() {
        let wrapped = wrap_tool_result(&serde_json::Value::Null);
        assert!(wrapped["content"].is_array());
        assert_eq!(wrapped["content"][0]["type"], "text");
    }

    #[test]
    fn wrap_string_value() {
        let wrapped = wrap_tool_result(&serde_json::json!("just a string"));
        let text = wrapped["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("just a string"));
    }

    #[test]
    fn wrap_error_has_is_error_flag() {
        let wrapped = wrap_error_result("something failed");
        assert_eq!(wrapped["isError"], true);
        assert_eq!(wrapped["content"][0]["text"], "something failed");
    }

    // --- Router tests ---

    #[tokio::test]
    async fn bridge_health() {
        let app = make_bridge_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(
            resp.headers().get("access-control-allow-origin").unwrap(),
            "*"
        );
    }

    #[tokio::test]
    async fn bridge_cors_on_options() {
        let app = make_bridge_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("OPTIONS")
                    .uri("/")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert!(resp.headers().contains_key("access-control-allow-origin"));
        assert!(resp.headers().contains_key("access-control-allow-methods"));
        assert!(resp.headers().contains_key("access-control-allow-headers"));
    }

    #[tokio::test]
    async fn bridge_initialize() {
        let app = make_bridge_app();
        let body = serde_json::json!({"jsonrpc": "2.0", "id": 1, "method": "initialize"});
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        assert!(resp.headers().contains_key("access-control-allow-origin"));

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let rpc_resp: JsonRpcResponse = serde_json::from_slice(&bytes).unwrap();
        assert!(rpc_resp.result.is_some());
    }

    #[tokio::test]
    async fn bridge_tool_call_wraps_result() {
        let app = make_bridge_app();
        let body = serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "echo", "arguments": {"msg": "hi"}}
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let rpc_resp: JsonRpcResponse = serde_json::from_slice(&bytes).unwrap();
        let result = rpc_resp.result.unwrap();

        // Should be wrapped in MCP envelope.
        assert!(result["content"].is_array());
        assert_eq!(result["content"][0]["type"], "text");
    }

    #[tokio::test]
    async fn bridge_mcp_tool_passthrough() {
        let app = make_bridge_app();
        let body = serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": "mcp_tool", "arguments": {}}
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let rpc_resp: JsonRpcResponse = serde_json::from_slice(&bytes).unwrap();
        let result = rpc_resp.result.unwrap();

        // Already formatted — should pass through.
        assert_eq!(result["content"][0]["text"], "already formatted");
    }

    #[tokio::test]
    async fn bridge_notification_returns_204() {
        let app = make_bridge_app();
        let body = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
    }

    #[tokio::test]
    async fn bridge_malformed_json() {
        let app = make_bridge_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/")
                    .header("content-type", "application/json")
                    .body(Body::from("not json"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let rpc_resp: JsonRpcResponse = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(rpc_resp.error.unwrap().code, -32700);
    }

    #[tokio::test]
    async fn bridge_graceful_shutdown() {
        let dispatcher = Arc::new(Dispatcher::new(ToolRegistry::new()));
        let (tx, rx) = tokio::sync::oneshot::channel::<()>();

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);

        let handle = tokio::spawn(serve(
            dispatcher,
            BridgeConfig::new(addr, vec!["*".into()]),
            async {
                rx.await.ok();
            },
        ));

        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        tx.send(()).unwrap();

        let result = handle.await.unwrap();
        assert!(result.is_ok());
    }
}