Skip to main content

velocity_mcp_edge/
lib.rs

1//! VELOCITY-MCP Edge Library - Testable HTTP handler functions.
2//!
3//! This module exposes the core HTTP handling logic for testing purposes,
4//! and provides the `tools` module with pure-Rust tool implementations
5//! suitable for WASM/WASIX edge deployment.
6
7pub mod tools;
8
9// Native-only: HTTP handler functions that depend on hyper.
10// On wasm32 the entry point lives in main.rs: the socket HTTP server for the
11// deployed WASIX build (`target_vendor = "wasmer"`), and the plain-WASI CGI
12// fallback for other wasm32 targets.
13#[cfg(not(target_arch = "wasm32"))]
14use http_body_util::Full;
15#[cfg(not(target_arch = "wasm32"))]
16use hyper::body::Bytes;
17#[cfg(not(target_arch = "wasm32"))]
18use hyper::{Response, StatusCode};
19#[cfg(not(target_arch = "wasm32"))]
20use tools::EdgeToolExecutor;
21#[cfg(not(target_arch = "wasm32"))]
22use velocity_mcp_core::{
23    handle_mcp_request, handle_mcp_request_with_executor, parse_request, serialize_response,
24};
25
26/// Process MCP JSON-RPC request using the edge tool executor for real tool execution.
27///
28/// This is the preferred entry point. It creates an `EdgeToolExecutor` and routes
29/// `tools/list` and `tools/call` through it, returning real tool definitions and
30/// actual execution results.
31#[cfg(not(target_arch = "wasm32"))]
32pub fn process_mcp_request(request_body: &[u8]) -> Vec<u8> {
33    match parse_request(request_body) {
34        Ok(request) => {
35            let executor = EdgeToolExecutor::new();
36            let response = handle_mcp_request_with_executor(&request, &executor);
37            serialize_response(&response)
38        }
39        Err(_) => error_response_bytes("Parse error"),
40    }
41}
42
43/// Process MCP JSON-RPC request in stub mode (no tool execution).
44///
45/// Kept for backwards compatibility and testing the stub path.
46#[cfg(not(target_arch = "wasm32"))]
47pub fn process_mcp_request_stub(request_body: &[u8]) -> Vec<u8> {
48    match parse_request(request_body) {
49        Ok(request) => {
50            let response = handle_mcp_request(&request);
51            serialize_response(&response)
52        }
53        Err(_) => error_response_bytes("Parse error"),
54    }
55}
56
57/// Create error response as raw bytes
58#[cfg(not(target_arch = "wasm32"))]
59pub fn error_response_bytes(message: &str) -> Vec<u8> {
60    let error_json = serde_json::json!({
61        "jsonrpc": "2.0",
62        "error": {
63            "code": -32700,
64            "message": message
65        },
66        "id": null
67    });
68    serde_json::to_vec(&error_json).unwrap_or_default()
69}
70
71/// Create error response as Response object.
72///
73/// Maps HTTP status codes to JSON-RPC 2.0 error codes per spec:
74/// - 400 -> -32600 (Invalid Request)
75/// - 401/403 -> -32600 (Invalid Request - auth failure)
76/// - 404 -> -32601 (Method Not Found)
77/// - 413 -> -32602 (Invalid Params - payload too large)
78/// - 429 -> -32600 (Invalid Request - rate limited)
79/// - 500 -> -32603 (Internal Error)
80#[cfg(not(target_arch = "wasm32"))]
81pub fn error_response(status: StatusCode, message: &str) -> Response<Full<Bytes>> {
82    let jsonrpc_code = match status.as_u16() {
83        400 | 401 | 403 | 429 => -32600,
84        404 | 405 => -32601,
85        413 => -32602,
86        _ => -32603,
87    };
88
89    let error_json = serde_json::json!({
90        "jsonrpc": "2.0",
91        "error": {
92            "code": jsonrpc_code,
93            "message": message
94        },
95        "id": null
96    });
97
98    let body_bytes = serde_json::to_vec(&error_json).unwrap_or_default();
99
100    Response::builder()
101        .status(status)
102        .header("content-type", "application/json")
103        .body(Full::new(Bytes::from(body_bytes)))
104        .unwrap_or_else(|_| {
105            const FALLBACK_JSON: &[u8] = b"{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32603,\"message\":\"Internal server error\"},\"id\":null}";
106            Response::builder()
107                .status(500)
108                .header("content-type", "application/json")
109                .body(Full::new(Bytes::from_static(FALLBACK_JSON)))
110                .expect("fallback 500 response should never fail")
111        })
112}