rustapi-mcp 0.1.550

Native Model Context Protocol (MCP) support for RustAPI - expose your endpoints as tools for LLMs and AI agents
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
//! Tool discovery: converting RustAPI OpenAPI metadata into MCP tools.
//!
//! This module walks the OpenAPI spec produced by RustApi and turns
//! HTTP operations into MCP `McpTool` definitions, applying exposure
//! filters from `McpConfig`.

use crate::config::{McpConfig, ToolPolicy};
use crate::types::McpTool;
use rustapi_openapi::{Components, OpenApiSpec, Operation, Parameter, RequestBody, SchemaRef};
use std::collections::BTreeMap;

/// Main entry point: extract a filtered list of MCP tools from an OpenAPI spec.
pub fn extract_tools_from_spec(spec: &OpenApiSpec, config: &McpConfig) -> Vec<McpTool> {
    if !config.tools_enabled {
        return vec![];
    }

    let mut tools = Vec::new();
    let components = spec.components.as_ref();

    for (path, path_item) in &spec.paths {
        // Apply path prefix filter if configured
        if !path_matches_prefixes(path, &config.allowed_path_prefixes) {
            continue;
        }

        // Check each HTTP method
        if let Some(op) = &path_item.get {
            if let Some(tool) = operation_to_tool("GET", path, op, components, config) {
                tools.push(tool);
            }
        }
        if let Some(op) = &path_item.post {
            if let Some(tool) = operation_to_tool("POST", path, op, components, config) {
                tools.push(tool);
            }
        }
        if let Some(op) = &path_item.put {
            if let Some(tool) = operation_to_tool("PUT", path, op, components, config) {
                tools.push(tool);
            }
        }
        if let Some(op) = &path_item.patch {
            if let Some(tool) = operation_to_tool("PATCH", path, op, components, config) {
                tools.push(tool);
            }
        }
        if let Some(op) = &path_item.delete {
            if let Some(tool) = operation_to_tool("DELETE", path, op, components, config) {
                tools.push(tool);
            }
        }

        // We can add more methods later if needed (HEAD, OPTIONS...)

        if tools.len() >= config.max_tools {
            break;
        }
    }

    // Enforce max_tools
    if tools.len() > config.max_tools {
        tools.truncate(config.max_tools);
    }

    tools
}

fn path_matches_prefixes(path: &str, prefixes: &[String]) -> bool {
    if prefixes.is_empty() {
        return true;
    }
    prefixes.iter().any(|p| path.starts_with(p))
}

/// Classify an HTTP method as read or write for permission scoping.
fn is_read_method(method: &str) -> bool {
    matches!(method.to_uppercase().as_str(), "GET" | "HEAD" | "OPTIONS")
}

/// Returns whether this operation should be exposed given the current policy.
fn operation_allowed_by_policy(method: &str, _op: &Operation, policy: &ToolPolicy) -> bool {
    match policy {
        ToolPolicy::All => true,
        ToolPolicy::ReadOnly => is_read_method(method),
        // Custom can be added later
    }
}

/// Support for route-level skip via special tags (hot-fix until full #[mcp(skip)] proc-macro).
/// Any tag exactly "mcp-skip" or containing ":skip" will drop the operation.
fn is_skipped_by_tag(op: &Operation) -> bool {
    op.tags.iter().any(|t| {
        let t = t.to_lowercase();
        t == "mcp-skip" || t.contains(":skip") || t == "mcp:skip"
    })
}

fn operation_to_tool(
    method: &str,
    path: &str,
    op: &Operation,
    components: Option<&Components>,
    config: &McpConfig,
) -> Option<McpTool> {
    // Rich x-mcp struct takes precedence
    if let Some(mcp_meta) = &op.x_mcp {
        if mcp_meta.skip == Some(true) {
            return None;
        }
    }

    // Legacy tag skip
    if is_skipped_by_tag(op) {
        return None;
    }

    // Policy gating
    if !operation_allowed_by_policy(method, op, &config.tool_policy) {
        return None;
    }

    // Tag filtering
    if !config.allowed_tags.is_empty() {
        let has_match = op.tags.iter().any(|t| config.allowed_tags.contains(t));
        if !has_match {
            return None;
        }
    }

    let name = generate_tool_name(method, path, op);
    let description = op.summary.clone().or_else(|| op.description.clone());

    let input_schema = build_input_schema(op, components);

    // Derive permission + confirmation from x-mcp (rich) or tags / method
    let (permission, requires_confirmation) = if let Some(mcp_meta) = &op.x_mcp {
        let p = if mcp_meta.readonly == Some(true) {
            "read".to_string()
        } else if mcp_meta.write == Some(true) || !is_read_method(method) {
            "write".to_string()
        } else {
            if is_read_method(method) {
                "read"
            } else {
                "write"
            }
            .to_string()
        };
        let needs_confirm =
            mcp_meta.require.is_some() || (p == "write" && mcp_meta.readonly != Some(true));
        (p, needs_confirm)
    } else {
        let has_write = op.tags.iter().any(|t| t.eq_ignore_ascii_case("mcp-write"));
        let has_ro = op
            .tags
            .iter()
            .any(|t| t.eq_ignore_ascii_case("mcp-readonly"));
        let req = op
            .tags
            .iter()
            .any(|t| t.to_lowercase().starts_with("mcp-require"));

        let p = if has_ro {
            "read"
        } else if has_write || !is_read_method(method) {
            "write"
        } else {
            "read"
        }
        .to_string();
        let c = req || (!has_ro && !is_read_method(method));
        (p, c)
    };

    Some(McpTool {
        name,
        description,
        input_schema,
        output_schema: None,
        tags: op.tags.clone(),
        permission: Some(permission),
        requires_confirmation: Some(requires_confirmation),
    })
}

/// Generate a stable, agent-friendly tool name.
fn generate_tool_name(method: &str, path: &str, op: &Operation) -> String {
    if let Some(oid) = &op.operation_id {
        return sanitize_name(oid);
    }

    // Fallback: method + sanitized path
    let mut slug = path
        .trim_start_matches('/')
        .replace(['/', '{', '}', ':'], "_")
        .replace(['-', '.', ' '], "_");

    // Collapse multiple underscores
    while slug.contains("__") {
        slug = slug.replace("__", "_");
    }

    let slug = slug.trim_matches('_').to_string();
    let method_lower = method.to_lowercase();

    if slug.is_empty() {
        method_lower
    } else {
        format!("{}_{}", method_lower, slug)
    }
}

fn sanitize_name(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect::<String>()
        .trim_matches('_')
        .to_string()
        .to_lowercase()
}

/// Build a JSON Schema for the tool input.
///
/// Strategy (MVP):
/// - If there is a JSON request body, use its schema (attempt simple $ref resolution).
/// - Otherwise, synthesize an object schema from the operation's parameters.
fn build_input_schema(op: &Operation, components: Option<&Components>) -> serde_json::Value {
    // 1. Try request body first (most common for "tool call with data")
    if let Some(body) = &op.request_body {
        if let Some(schema_val) = extract_json_schema_from_body(body, components) {
            return schema_val;
        }
    }

    // 2. Fallback: build from parameters (path + query + header)
    build_schema_from_parameters(&op.parameters, components)
}

fn extract_json_schema_from_body(
    body: &RequestBody,
    components: Option<&Components>,
) -> Option<serde_json::Value> {
    // Prefer application/json
    let media = body
        .content
        .get("application/json")
        .or_else(|| body.content.values().next())?;

    if let Some(schema_ref) = &media.schema {
        return Some(schema_ref_to_json(schema_ref, components));
    }
    None
}

fn build_schema_from_parameters(
    params: &[Parameter],
    components: Option<&Components>,
) -> serde_json::Value {
    if params.is_empty() {
        return serde_json::json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        });
    }

    let mut properties = BTreeMap::new();
    let mut required = Vec::new();

    for param in params {
        let name = param.name.clone();
        let schema = if let Some(s) = &param.schema {
            schema_ref_to_json(s, components)
        } else {
            // Default to string if no schema
            serde_json::json!({"type": "string"})
        };

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

        properties.insert(name, schema);
    }

    let mut schema = serde_json::json!({
        "type": "object",
        "properties": properties,
    });

    if !required.is_empty() {
        schema["required"] =
            serde_json::to_value(required).expect("required field names must serialize");
    }
    schema["additionalProperties"] = serde_json::json!(false);

    schema
}

/// Convert a SchemaRef into a plain JSON value suitable for MCP tool inputSchema.
/// For $ref we attempt a shallow resolution from components.schemas when available.
fn schema_ref_to_json(
    schema_ref: &SchemaRef,
    components: Option<&Components>,
) -> serde_json::Value {
    match schema_ref {
        SchemaRef::Ref { reference } => {
            // Try to resolve simple "#/components/schemas/Name"
            if let Some(name) = reference.strip_prefix("#/components/schemas/") {
                if let Some(components) = components {
                    if let Some(schema) = components.schemas.get(name) {
                        // Serialize the JsonSchema2020 as value (it will be a valid schema)
                        return serde_json::to_value(schema)
                            .unwrap_or_else(|_| serde_json::json!({ "$ref": reference }));
                    }
                }
            }
            // Can't resolve — emit the ref (MCP clients / LLMs can sometimes handle it, or we improve later)
            serde_json::json!({ "$ref": reference })
        }
        SchemaRef::Schema(boxed) => {
            serde_json::to_value(boxed.as_ref()).unwrap_or(serde_json::json!({}))
        }
        SchemaRef::Inline(val) => val.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustapi_openapi::{OpenApiSpec, Operation};

    fn make_minimal_spec() -> OpenApiSpec {
        let mut spec = OpenApiSpec::new("Test API", "1.0.0");

        let mut get_user = Operation::new();
        get_user.summary = Some("Get user by ID".to_string());
        get_user.tags = vec!["users".to_string(), "public".to_string()];
        get_user.operation_id = Some("getUser".to_string());

        let mut create_user = Operation::new();
        create_user.summary = Some("Create a user".to_string());
        create_user.tags = vec!["users".to_string()];
        create_user.operation_id = Some("createUser".to_string());

        let mut admin = Operation::new();
        admin.summary = Some("Admin only".to_string());
        admin.tags = vec!["admin".to_string()];

        spec = spec
            .path("/users/{id}", "GET", get_user)
            .path("/users", "POST", create_user)
            .path("/admin/users", "GET", admin);

        spec
    }

    #[test]
    fn extracts_tools_with_operation_id_as_name() {
        let spec = make_minimal_spec();
        let config = McpConfig::new().tool_policy(ToolPolicy::All); // test covers write ops too

        let tools = extract_tools_from_spec(&spec, &config);
        assert!(!tools.is_empty());

        let names: Vec<_> = tools.iter().map(|t| t.name.as_str()).collect();
        assert!(names.contains(&"getuser"));
        assert!(names.contains(&"createuser"));
    }

    #[test]
    fn respects_allowed_tags_filter() {
        let spec = make_minimal_spec();

        let config = McpConfig::new().allowed_tags(["public"]);

        let tools = extract_tools_from_spec(&spec, &config);
        let _tags: Vec<Vec<String>> = tools.iter().map(|t| t.tags.clone()).collect();

        assert_eq!(tools.len(), 1);
        assert!(tools[0].name.contains("getuser") || tools[0].tags.contains(&"public".to_string()));
    }

    #[test]
    fn respects_path_prefix_filter() {
        let spec = make_minimal_spec();

        let config = McpConfig::new().allow_path_prefix("/users");

        let tools = extract_tools_from_spec(&spec, &config);
        assert!(tools.iter().all(|t| !t.name.contains("admin")));
    }

    #[test]
    fn max_tools_limit_is_respected() {
        let spec = make_minimal_spec();
        let config = McpConfig::new().max_tools(1);

        let tools = extract_tools_from_spec(&spec, &config);
        assert!(tools.len() <= 1);
    }
}