turbomcp-openapi 3.2.0

OpenAPI to MCP conversion - expose REST APIs as MCP tools and resources
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
//! MCP handler implementation for OpenAPI operations.

use std::collections::HashMap;
use std::sync::Arc;

use serde_json::{Value, json};
use turbomcp_core::context::RequestContext;
use turbomcp_core::error::{McpError, McpResult};
use turbomcp_core::handler::McpHandler;
use turbomcp_types::{
    Prompt, PromptResult, Resource, ResourceResult, ServerInfo, Tool, ToolInputSchema,
    ToolOutputSchema, ToolResult,
};

use crate::provider::{ExtractedOperation, OpenApiProvider};
use crate::security::validate_url_for_ssrf;

/// MCP handler that exposes OpenAPI operations as tools and resources.
#[derive(Clone)]
pub struct OpenApiHandler {
    provider: Arc<OpenApiProvider>,
}

impl std::fmt::Debug for OpenApiHandler {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenApiHandler")
            .field("title", &self.provider.title())
            .field("version", &self.provider.version())
            .field("operations", &self.provider.operations().len())
            .finish()
    }
}

impl OpenApiHandler {
    /// Create a new handler from a provider.
    pub fn new(provider: Arc<OpenApiProvider>) -> Self {
        Self { provider }
    }

    /// Get the underlying provider.
    pub fn provider(&self) -> &OpenApiProvider {
        &self.provider
    }

    /// Generate tool name from operation.
    fn tool_name(op: &ExtractedOperation) -> String {
        op.operation_id.clone().unwrap_or_else(|| {
            // Generate name from method and path
            let path_part = op
                .path
                .trim_start_matches('/')
                .replace('/', "_")
                .replace(['{', '}'], "");
            format!("{}_{}", op.method.to_lowercase(), path_part)
        })
    }

    /// Generate resource URI from operation.
    fn resource_uri(op: &ExtractedOperation) -> String {
        format!("openapi://{}{}", op.method.to_lowercase(), op.path)
    }

    /// Build JSON Schema for tool input.
    fn build_input_schema(op: &ExtractedOperation) -> ToolInputSchema {
        let mut properties = serde_json::Map::new();
        let mut required = Vec::new();

        // Add parameters
        for param in &op.parameters {
            let mut param_schema = param.schema.clone().unwrap_or(json!({"type": "string"}));

            // Add description if available
            if let Some(desc) = &param.description
                && let Value::Object(ref mut map) = param_schema
            {
                map.insert("description".to_string(), json!(desc));
            }

            properties.insert(param.name.clone(), param_schema);

            if param.required {
                required.push(param.name.clone());
            }
        }

        // Add request body if present
        if let Some(body_schema) = &op.request_body_schema {
            properties.insert("body".to_string(), body_schema.clone());
            required.push("body".to_string());
        }

        // Carry the SEP-1613 default dialect by deferring to `Default::default`
        // for `extra_keywords`, which now contains `$schema = 2020-12`.
        ToolInputSchema {
            schema_type: Some("object".into()),
            properties: Some(Value::Object(properties)),
            required: if required.is_empty() {
                None
            } else {
                Some(required)
            },
            additional_properties: None,
            ..ToolInputSchema::default()
        }
    }

    /// Find operation by tool name.
    fn find_tool_operation(&self, name: &str) -> Option<&ExtractedOperation> {
        self.provider.tools().find(|op| Self::tool_name(op) == name)
    }

    /// Build the `meta` map shared by both tool and resource exposure paths.
    /// Surfaces the operation's effective `security` requirements so MCP
    /// clients can detect that auth is needed even when no `auth_provider` is
    /// installed yet.
    fn build_operation_meta(&self, op: &ExtractedOperation) -> HashMap<String, Value> {
        let mut meta = HashMap::new();
        meta.insert("method".to_string(), json!(op.method));
        meta.insert("path".to_string(), json!(op.path));
        if let Some(ref id) = op.operation_id {
            meta.insert("operationId".to_string(), json!(id));
        }
        if !op.security.is_empty() {
            meta.insert("security".to_string(), json!(&op.security));
            // Surface the matching scheme definitions so a downstream client
            // can render auth requirements without re-fetching the spec.
            let referenced: HashMap<&String, &openapiv3::SecurityScheme> = op
                .security
                .iter()
                .flat_map(|req| req.keys())
                .filter_map(|name| {
                    self.provider
                        .security_schemes()
                        .get(name)
                        .map(|scheme| (name, scheme))
                })
                .collect();
            if !referenced.is_empty()
                && let Ok(value) = serde_json::to_value(&referenced)
            {
                meta.insert("securitySchemes".to_string(), value);
            }
        }
        meta
    }

    /// Find operation by resource URI.
    fn find_resource_operation(&self, uri: &str) -> Option<&ExtractedOperation> {
        self.provider
            .resources()
            .find(|op| Self::resource_uri(op) == uri)
    }

    /// Execute an operation via HTTP.
    ///
    /// # Security
    ///
    /// This method validates URLs against SSRF attacks before making requests.
    /// Requests to private IP ranges, localhost, and cloud metadata endpoints
    /// are blocked.
    async fn execute_operation(
        &self,
        op: &ExtractedOperation,
        args: HashMap<String, Value>,
    ) -> McpResult<Value> {
        let url = self
            .provider
            .build_url(op, &args)
            .map_err(|e| McpError::internal(e.to_string()))?;

        // SSRF protection: validate URL before making request
        validate_url_for_ssrf(&url).map_err(|e| McpError::internal(e.to_string()))?;

        let client = self.provider.client();

        let mut request = match op.method.as_str() {
            "GET" => client.get(url),
            "POST" => client.post(url),
            "PUT" => client.put(url),
            "DELETE" => client.delete(url),
            "PATCH" => client.patch(url),
            _ => {
                return Err(McpError::internal(format!(
                    "Unsupported method: {}",
                    op.method
                )));
            }
        };

        // Add request body if present
        if let Some(body) = args.get("body") {
            request = request.json(body);
        }

        // Add header parameters
        for param in &op.parameters {
            if param.location == "header"
                && let Some(value) = args.get(&param.name)
            {
                let value_str = match value {
                    Value::String(s) => s.clone(),
                    _ => value.to_string(),
                };
                request = request.header(&param.name, value_str);
            }
        }

        // Inject auth credentials before sending. If the operation has security
        // requirements but no provider is installed, the request still goes
        // out — the upstream will return 401 and surface the misconfiguration.
        if !op.security.is_empty()
            && let Some(auth) = self.provider.auth_provider()
        {
            request = auth.apply(request, &op.security, self.provider.security_schemes());
        }

        let response = request
            .send()
            .await
            .map_err(|e| McpError::internal(format!("HTTP request failed: {}", e)))?;

        let status = response.status();
        let body = response
            .text()
            .await
            .map_err(|e| McpError::internal(format!("Failed to read response: {}", e)))?;

        if !status.is_success() {
            return Err(McpError::internal(format!(
                "API returned {}: {}",
                status, body
            )));
        }

        // Try to parse as JSON, fallback to string
        match serde_json::from_str(&body) {
            Ok(json) => Ok(json),
            Err(_) => Ok(json!(body)),
        }
    }
}

#[allow(clippy::manual_async_fn)]
impl McpHandler for OpenApiHandler {
    fn server_info(&self) -> ServerInfo {
        ServerInfo::new(self.provider.title(), self.provider.version())
    }

    fn list_tools(&self) -> Vec<Tool> {
        self.provider
            .tools()
            .map(|op| Tool {
                name: Self::tool_name(op),
                description: op.summary.clone().or_else(|| op.description.clone()),
                input_schema: Self::build_input_schema(op),
                title: op.summary.clone(),
                icons: None,
                annotations: None,
                execution: None,
                // MCP 2025-11-25 outputSchema: pulled from the operation's
                // first 2xx `application/json` response with `$ref`s
                // inlined. `None` for operations with no JSON response.
                output_schema: op
                    .response_schema
                    .as_ref()
                    .map(|v| ToolOutputSchema::from_value(v.clone())),
                meta: Some(self.build_operation_meta(op)),
            })
            .collect()
    }

    fn list_resources(&self) -> Vec<Resource> {
        self.provider
            .resources()
            .map(|op| Resource {
                uri: Self::resource_uri(op),
                name: op.operation_id.clone().unwrap_or_else(|| op.path.clone()),
                description: op.summary.clone().or_else(|| op.description.clone()),
                title: op.summary.clone(),
                icons: None,
                mime_type: Some("application/json".to_string()),
                annotations: None,
                size: None,
                meta: Some(self.build_operation_meta(op)),
            })
            .collect()
    }

    fn list_prompts(&self) -> Vec<Prompt> {
        // OpenAPI doesn't map to prompts
        Vec::new()
    }

    fn call_tool<'a>(
        &'a self,
        name: &'a str,
        args: Value,
        _ctx: &'a RequestContext,
    ) -> impl std::future::Future<Output = McpResult<ToolResult>> + turbomcp_core::marker::MaybeSend + 'a
    {
        async move {
            let op = self
                .find_tool_operation(name)
                .ok_or_else(|| McpError::tool_not_found(name))?;

            let args_map: HashMap<String, Value> = match args {
                Value::Object(map) => map.into_iter().collect(),
                Value::Null => HashMap::new(),
                _ => {
                    return Err(McpError::invalid_params(
                        "Arguments must be an object or null",
                    ));
                }
            };

            let result = self.execute_operation(op, args_map).await?;

            Ok(ToolResult::text(
                serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()),
            ))
        }
    }

    fn read_resource<'a>(
        &'a self,
        uri: &'a str,
        _ctx: &'a RequestContext,
    ) -> impl std::future::Future<Output = McpResult<ResourceResult>>
    + turbomcp_core::marker::MaybeSend
    + 'a {
        async move {
            let op = self
                .find_resource_operation(uri)
                .ok_or_else(|| McpError::resource_not_found(uri))?;

            // Resources are GET operations with no body
            let result = self.execute_operation(op, HashMap::new()).await?;

            let content =
                serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string());

            Ok(ResourceResult::text(uri, content))
        }
    }

    fn get_prompt<'a>(
        &'a self,
        name: &'a str,
        _args: Option<Value>,
        _ctx: &'a RequestContext,
    ) -> impl std::future::Future<Output = McpResult<PromptResult>> + turbomcp_core::marker::MaybeSend + 'a
    {
        async move { Err(McpError::prompt_not_found(name)) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::McpType;

    const TEST_SPEC: &str = r#"{
        "openapi": "3.0.0",
        "info": { "title": "Test", "version": "1.0" },
        "paths": {
            "/users": {
                "get": { "operationId": "listUsers", "summary": "List users", "responses": { "200": { "description": "Success" } } },
                "post": { "operationId": "createUser", "summary": "Create user", "responses": { "201": { "description": "Created" } } }
            }
        }
    }"#;

    #[test]
    fn test_list_tools() {
        let provider = OpenApiProvider::from_string(TEST_SPEC).unwrap();
        let handler = provider.into_handler();

        let tools = handler.list_tools();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "createUser");
    }

    #[test]
    fn test_list_resources() {
        let provider = OpenApiProvider::from_string(TEST_SPEC).unwrap();
        let handler = provider.into_handler();

        let resources = handler.list_resources();
        assert_eq!(resources.len(), 1);
        assert_eq!(resources[0].name, "listUsers");
    }

    #[test]
    fn test_tool_name_generation() {
        let op_with_id = ExtractedOperation {
            method: "POST".to_string(),
            path: "/users".to_string(),
            operation_id: Some("createUser".to_string()),
            summary: None,
            description: None,
            parameters: vec![],
            request_body_schema: None,
            mcp_type: McpType::Tool,
            security: Vec::new(),
            response_schema: None,
        };

        let op_without_id = ExtractedOperation {
            method: "DELETE".to_string(),
            path: "/users/{id}".to_string(),
            operation_id: None,
            summary: None,
            description: None,
            parameters: vec![],
            request_body_schema: None,
            mcp_type: McpType::Tool,
            security: Vec::new(),
            response_schema: None,
        };

        assert_eq!(OpenApiHandler::tool_name(&op_with_id), "createUser");
        assert_eq!(OpenApiHandler::tool_name(&op_without_id), "delete_users_id");
    }
}