turbomcp-proxy 3.0.12

Universal MCP adapter/generator - introspection, proxying, and code generation for any MCP server
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
//! REST API adapter for MCP servers
//!
//! Exposes MCP server capabilities as a `RESTful` HTTP API with `OpenAPI` documentation.
//! Automatically generates REST endpoints from introspected tool and resource definitions.

// Always-available imports (stdlib + core dependencies)
use serde_json::{Value, json};
use std::sync::Arc;
use tracing::{debug, info};

// Core proxy types
use crate::error::{ProxyError, ProxyResult};

// Feature-gated imports (only if rest feature is enabled)
#[cfg(feature = "rest")]
use crate::introspection::ServerSpec;
#[cfg(feature = "rest")]
use crate::proxy::BackendConnector;
#[cfg(feature = "rest")]
use axum::{
    Json, Router,
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    routing::{get, post},
};

/// REST adapter configuration
#[derive(Debug, Clone)]
pub struct RestAdapterConfig {
    /// Bind address (e.g., "127.0.0.1:3001")
    pub bind: String,
    /// Enable `OpenAPI` Swagger UI
    pub openapi_ui: bool,
}

impl RestAdapterConfig {
    /// Create a new REST adapter configuration
    pub fn new(bind: impl Into<String>, openapi_ui: bool) -> Self {
        Self {
            bind: bind.into(),
            openapi_ui,
        }
    }
}

/// REST adapter state
#[cfg(feature = "rest")]
#[derive(Clone)]
struct RestAdapterState {
    backend: BackendConnector, // Used for routing tool calls, resource reads, prompt gets
    spec: Arc<ServerSpec>,
}

/// REST API adapter for MCP servers
#[cfg(feature = "rest")]
pub struct RestAdapter {
    config: RestAdapterConfig,
    backend: BackendConnector,
    spec: ServerSpec,
}

#[cfg(feature = "rest")]
impl RestAdapter {
    /// Create a new REST adapter
    #[must_use]
    pub fn new(config: RestAdapterConfig, backend: BackendConnector, spec: ServerSpec) -> Self {
        Self {
            config,
            backend,
            spec,
        }
    }

    /// Run the REST adapter server
    ///
    /// # Errors
    ///
    /// Returns error if binding fails or server encounters fatal error
    pub async fn run(self) -> ProxyResult<()> {
        info!("Starting REST adapter on {}", self.config.bind);

        let state = RestAdapterState {
            backend: self.backend,
            spec: Arc::new(self.spec),
        };

        // Build router with OpenAPI routes
        let router = Router::new()
            .route("/api/tools", get(list_tools).post(call_tool))
            .route("/api/tools/:name", post(call_tool_by_name))
            .route("/api/resources", get(list_resources))
            .route("/api/resources/:uri", get(read_resource))
            .route("/api/prompts", get(list_prompts))
            .route("/api/prompts/:name", post(get_prompt))
            .route("/openapi.json", get(openapi_spec))
            .route("/health", get(health_check))
            .with_state(state);

        // Note: Full Swagger UI integration requires utoipa-swagger-ui feature
        if self.config.openapi_ui {
            info!("OpenAPI specification available at /openapi.json");
            info!("Full Swagger UI integration requires utoipa-swagger-ui crate");
        }

        // Parse bind address
        let listener = tokio::net::TcpListener::bind(&self.config.bind)
            .await
            .map_err(|e| {
                ProxyError::backend_connection(format!(
                    "Failed to bind REST adapter to {}: {}",
                    self.config.bind, e
                ))
            })?;

        info!("REST adapter listening on {}", self.config.bind);

        // Start server
        axum::serve(listener, router)
            .await
            .map_err(|e| ProxyError::backend(format!("REST adapter server error: {e}")))?;

        Ok(())
    }
}

// ============ REST Endpoint Handlers ============

/// Health check endpoint
#[cfg(feature = "rest")]
async fn health_check() -> impl IntoResponse {
    Json(json!({
        "status": "ok",
        "service": "turbomcp-rest-adapter"
    }))
}

/// List all tools
#[cfg(feature = "rest")]
async fn list_tools(State(state): State<RestAdapterState>) -> impl IntoResponse {
    debug!("GET /api/tools");

    let tools: Vec<Value> = state
        .spec
        .tools
        .iter()
        .map(|tool| {
            json!({
                "name": tool.name,
                "description": tool.description,
                "input_schema": tool.input_schema,
            })
        })
        .collect();

    Json(json!({
        "tools": tools,
        "count": tools.len()
    }))
}

/// Call a tool (generic endpoint with tool name in body)
#[cfg(feature = "rest")]
async fn call_tool(
    State(state): State<RestAdapterState>,
    Json(payload): Json<Value>,
) -> impl IntoResponse {
    debug!("POST /api/tools with payload: {}", payload);

    // Extract tool name and arguments from payload
    let Some(tool_name) = payload.get("name").and_then(|v| v.as_str()) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({
                "error": "Missing required field 'name' in request body",
                "code": -32602
            })),
        );
    };

    let arguments = payload
        .get("arguments")
        .and_then(|v| v.as_object())
        .map(|obj| {
            obj.iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect::<std::collections::HashMap<String, Value>>()
        });

    // Call the backend
    match state.backend.call_tool(tool_name, arguments).await {
        Ok(result) => (StatusCode::OK, Json(json!({ "result": result }))),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": format!("Tool call failed: {e}"),
                "code": -32603
            })),
        ),
    }
}

/// Call a specific tool by name
#[cfg(feature = "rest")]
async fn call_tool_by_name(
    Path(name): Path<String>,
    State(state): State<RestAdapterState>,
    Json(payload): Json<Value>,
) -> impl IntoResponse {
    debug!("POST /api/tools/{} with payload: {}", name, payload);

    let arguments = payload.as_object().map(|obj| {
        obj.iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect::<std::collections::HashMap<String, Value>>()
    });

    // Call the backend
    match state.backend.call_tool(&name, arguments).await {
        Ok(result) => (StatusCode::OK, Json(json!({ "result": result }))),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": format!("Tool call failed: {e}"),
                "tool": name,
                "code": -32603
            })),
        ),
    }
}

/// List all resources
#[cfg(feature = "rest")]
async fn list_resources(State(state): State<RestAdapterState>) -> impl IntoResponse {
    debug!("GET /api/resources");

    let resources: Vec<Value> = state
        .spec
        .resources
        .iter()
        .map(|res| {
            json!({
                "uri": res.uri,
                "name": res.name,
                "description": res.description,
                "mime_type": res.mime_type,
            })
        })
        .collect();

    Json(json!({
        "resources": resources,
        "count": resources.len()
    }))
}

/// Read a specific resource
#[cfg(feature = "rest")]
async fn read_resource(
    Path(uri): Path<String>,
    State(state): State<RestAdapterState>,
) -> impl IntoResponse {
    debug!("GET /api/resources/{}", uri);

    // Call the backend
    match state.backend.read_resource(&uri).await {
        Ok(result) => (StatusCode::OK, Json(json!({ "contents": result.contents }))),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": format!("Resource read failed: {e}"),
                "uri": uri,
                "code": -32603
            })),
        ),
    }
}

/// List all prompts
#[cfg(feature = "rest")]
async fn list_prompts(State(state): State<RestAdapterState>) -> impl IntoResponse {
    debug!("GET /api/prompts");

    let prompts: Vec<Value> = state
        .spec
        .prompts
        .iter()
        .map(|prompt| {
            json!({
                "name": prompt.name,
                "description": prompt.description,
                "arguments": prompt.arguments,
            })
        })
        .collect();

    Json(json!({
        "prompts": prompts,
        "count": prompts.len()
    }))
}

/// Get a specific prompt
#[cfg(feature = "rest")]
async fn get_prompt(
    Path(name): Path<String>,
    State(state): State<RestAdapterState>,
    Json(payload): Json<Value>,
) -> impl IntoResponse {
    debug!("POST /api/prompts/{} with payload: {}", name, payload);

    let arguments = payload
        .get("arguments")
        .and_then(|v| v.as_object())
        .map(|obj| {
            obj.iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect::<std::collections::HashMap<String, Value>>()
        });

    // Call the backend
    match state.backend.get_prompt(&name, arguments).await {
        Ok(result) => (
            StatusCode::OK,
            Json(json!({
                "description": result.description,
                "messages": result.messages
            })),
        ),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": format!("Prompt get failed: {e}"),
                "prompt": name,
                "code": -32603
            })),
        ),
    }
}

/// `OpenAPI` specification endpoint
#[cfg(feature = "rest")]
async fn openapi_spec(State(_state): State<RestAdapterState>) -> impl IntoResponse {
    debug!("GET /openapi.json");

    let openapi = json!({
        "openapi": "3.1.0",
        "info": {
            "title": "MCP REST API",
            "version": "1.0.0",
            "description": "REST API adapter for MCP servers"
        },
        "servers": [
            {
                "url": "http://localhost",
                "description": "Development server"
            }
        ],
        "paths": {
            "/api/tools": {
                "get": {
                    "summary": "List all tools",
                    "responses": {
                        "200": {
                            "description": "List of available tools"
                        }
                    }
                }
            },
            "/api/resources": {
                "get": {
                    "summary": "List all resources",
                    "responses": {
                        "200": {
                            "description": "List of available resources"
                        }
                    }
                }
            },
            "/api/prompts": {
                "get": {
                    "summary": "List all prompts",
                    "responses": {
                        "200": {
                            "description": "List of available prompts"
                        }
                    }
                }
            },
            "/health": {
                "get": {
                    "summary": "Health check",
                    "responses": {
                        "200": {
                            "description": "Service is healthy"
                        }
                    }
                }
            }
        },
        "components": {
            "schemas": {
                "Tool": {
                    "type": "object",
                    "properties": {
                        "name": { "type": "string" },
                        "description": { "type": "string" },
                        "input_schema": { "type": "object" }
                    }
                },
                "Resource": {
                    "type": "object",
                    "properties": {
                        "uri": { "type": "string" },
                        "name": { "type": "string" },
                        "description": { "type": "string" },
                        "mime_type": { "type": "string" }
                    }
                }
            }
        }
    });

    Json(openapi)
}

#[cfg(not(feature = "rest"))]
/// Placeholder when REST feature is disabled
pub struct RestAdapter;

#[cfg(not(feature = "rest"))]
impl RestAdapter {
    /// Create a new REST adapter (stub)
    pub fn new(
        _config: RestAdapterConfig,
        _backend: crate::proxy::BackendConnector,
        _spec: crate::introspection::ServerSpec,
    ) -> Self {
        Self
    }

    /// Run the REST adapter server (stub)
    pub async fn run(self) -> ProxyResult<()> {
        Err(ProxyError::configuration(
            "REST adapter requires 'rest' feature to be enabled",
        ))
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "rest")]
    use super::*;

    #[test]
    #[cfg(feature = "rest")]
    fn test_rest_adapter_config() {
        let config = RestAdapterConfig::new("127.0.0.1:3001", true);
        assert_eq!(config.bind, "127.0.0.1:3001");
        assert!(config.openapi_ui);
    }
}