rmcp-openapi-server 0.29.0

MCP server executable for OpenAPI specifications
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
use crate::cli::Cli;
use crate::spec_loader::SpecLocation;
use bon::Builder;
use reqwest::header::HeaderMap;
use rmcp_openapi::{
    AuthorizationMode, CliError, Error, Server,
    spec::{Filter, Filters},
};
use url::Url;

#[derive(Debug, Clone, Builder)]
pub struct Configuration {
    pub spec_location: SpecLocation,
    pub base_url: Url,
    pub port: u16,
    pub bind_address: String,
    pub default_headers: HeaderMap,
    pub filters: Option<Filters>,
    pub authorization_mode: AuthorizationMode,
    #[builder(default)]
    pub skip_tool_descriptions: bool,
    #[builder(default)]
    pub skip_parameter_descriptions: bool,
    #[builder(default)]
    pub stateful: bool,
    #[builder(default)]
    pub insecure: bool,
}

impl Configuration {
    pub fn from_cli(cli: Cli) -> Result<Self, Error> {
        // Parse base URL - now required by CLI
        let base_url = Url::parse(&cli.base_url)
            .map_err(|e| Error::InvalidUrl(format!("Invalid base URL: {e}")))?;

        // Parse headers from CLI format "name: value"
        let mut default_headers = HeaderMap::new();
        for header_str in cli.headers {
            if let Some((key, value)) = header_str.split_once(':') {
                let key = key.trim();
                let value = value.trim();

                if key.is_empty() {
                    return Err(Error::Cli(CliError::InvalidHeaderFormat {
                        header: header_str,
                    }));
                }

                // Validate header name using reqwest/http
                let header_name =
                    http::header::HeaderName::from_bytes(key.as_bytes()).map_err(|e| {
                        Error::Cli(CliError::InvalidHeaderName {
                            header: header_str.clone(),
                            source: e,
                        })
                    })?;

                // Validate header value using reqwest/http
                let header_value = http::header::HeaderValue::from_str(value).map_err(|e| {
                    Error::Cli(CliError::InvalidHeaderValue {
                        header: header_str.clone(),
                        source: e,
                    })
                })?;

                default_headers.insert(header_name, header_value);
            } else {
                return Err(Error::Cli(CliError::InvalidHeaderFormat {
                    header: header_str,
                }));
            }
        }

        let filters = {
            let mut f = Filters::builder().build();

            if let Some(tags) = cli.tags {
                f.tags = Some(Filter::Include(tags));
            }

            if let Some(methods) = cli.methods {
                f.methods = Some(Filter::Include(methods));
            }

            f.operations_id = match (cli.operationids_include, cli.operationids_exclude) {
                (Some(op), None) => Some(Filter::Include(op)),
                (None, Some(op)) => Some(Filter::Exclude(op)),
                _ => None,
            };

            if f.tags.is_some() || f.methods.is_some() || f.operations_id.is_some() {
                Some(f)
            } else {
                None
            }
        };

        Ok(Configuration {
            spec_location: cli.spec,
            base_url,
            port: cli.port,
            bind_address: cli.bind_address,
            default_headers,
            filters,
            authorization_mode: cli.authorization_mode,
            skip_tool_descriptions: cli.skip_tool_descriptions,
            skip_parameter_descriptions: cli.skip_parameter_descriptions,
            stateful: cli.stateful,
            insecure: cli.insecure,
        })
    }
}

impl Configuration {
    /// Convert Configuration to Server by loading the OpenAPI spec
    pub async fn try_into_server(self) -> Result<Server, Error> {
        // Load OpenAPI specification from the spec location
        let openapi_spec = self.spec_location.load_json(self.insecure).await?;

        let headers = if self.default_headers.is_empty() {
            None
        } else {
            Some(self.default_headers)
        };

        let mut server = Server::new(
            openapi_spec,
            self.base_url,
            headers,
            self.filters,
            self.skip_tool_descriptions,
            self.skip_parameter_descriptions,
            self.insecure,
        );

        // Set the authorization mode
        server.set_authorization_mode(self.authorization_mode);

        // Set binary metadata
        server.name = Some(env!("CARGO_PKG_NAME").to_string());
        server.version = Some(env!("CARGO_PKG_VERSION").to_string());
        server.instructions = Some(env!("CARGO_PKG_DESCRIPTION").to_string());

        Ok(server)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::Cli;
    use crate::spec_loader::SpecLocation;
    use url::Url;

    #[test]
    fn test_header_parsing_valid_formats() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec![
                "Authorization: Bearer token123".to_string(),
                "X-API-Key: key456".to_string(),
                "Content-Type: application/json".to_string(),
                "User-Agent: TestAgent/1.0".to_string(),
            ],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let config = Configuration::from_cli(cli).unwrap();

        assert_eq!(config.default_headers.len(), 4);
        assert_eq!(
            config
                .default_headers
                .get("Authorization")
                .map(|v| v.to_str().unwrap()),
            Some("Bearer token123")
        );
        assert_eq!(
            config
                .default_headers
                .get("X-API-Key")
                .map(|v| v.to_str().unwrap()),
            Some("key456")
        );
        assert_eq!(
            config
                .default_headers
                .get("Content-Type")
                .map(|v| v.to_str().unwrap()),
            Some("application/json")
        );
        assert_eq!(
            config
                .default_headers
                .get("User-Agent")
                .map(|v| v.to_str().unwrap()),
            Some("TestAgent/1.0")
        );
    }

    #[test]
    fn test_header_parsing_with_spaces() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec![
                " Authorization : Bearer token123 ".to_string(),
                "X-Custom  :  value with spaces  ".to_string(),
            ],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let config = Configuration::from_cli(cli).unwrap();

        assert_eq!(config.default_headers.len(), 2);
        assert_eq!(
            config
                .default_headers
                .get("Authorization")
                .map(|v| v.to_str().unwrap()),
            Some("Bearer token123")
        );
        assert_eq!(
            config
                .default_headers
                .get("X-Custom")
                .map(|v| v.to_str().unwrap()),
            Some("value with spaces")
        );
    }

    #[test]
    fn test_header_parsing_invalid_format_no_equals() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec!["InvalidHeaderNoEquals".to_string()],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let result = Configuration::from_cli(cli);
        assert!(result.is_err());

        let error = result.unwrap_err().to_string();
        assert!(error.contains("Invalid header format"));
        assert!(error.contains("expected 'name: value' format"));
    }

    #[test]
    fn test_header_parsing_invalid_format_empty_key() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec![": value".to_string()],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let result = Configuration::from_cli(cli);
        assert!(result.is_err());

        let error = result.unwrap_err().to_string();
        assert!(error.contains("CLI error"));
        assert!(error.contains("Invalid header format"));
    }

    #[test]
    fn test_header_parsing_empty_value_allowed() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec!["X-Empty-Header:".to_string()],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let config = Configuration::from_cli(cli).unwrap();

        assert_eq!(config.default_headers.len(), 1);
        assert_eq!(
            config
                .default_headers
                .get("X-Empty-Header")
                .map(|v| v.to_str().unwrap()),
            Some("")
        );
    }

    #[test]
    fn test_no_headers() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec![],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let config = Configuration::from_cli(cli).unwrap();
        assert!(config.default_headers.is_empty());
    }

    #[test]
    fn test_header_validation_invalid_header_name() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec!["Invalid Header Name: value".to_string()],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let result = Configuration::from_cli(cli);
        assert!(result.is_err());

        let error = result.unwrap_err().to_string();
        assert!(error.contains("CLI error"));
        assert!(error.contains("Invalid header name"));
    }

    #[test]
    fn test_header_validation_invalid_header_value() {
        let cli = Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec!["Valid-Header: invalid\x00value".to_string()],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        };

        let result = Configuration::from_cli(cli);
        assert!(result.is_err());

        let error = result.unwrap_err().to_string();
        assert!(error.contains("CLI error"));
        assert!(error.contains("Invalid header value"));
    }

    fn minimal_cli() -> Cli {
        Cli {
            spec: SpecLocation::Url(Url::parse("https://example.com/spec.json").unwrap()),
            base_url: "https://api.example.com".to_string(),
            port: 8080,
            bind_address: "127.0.0.1".to_string(),
            headers: vec![],
            tags: None,
            methods: None,
            operationids_include: None,
            operationids_exclude: None,
            authorization_mode: AuthorizationMode::default(),
            skip_tool_descriptions: false,
            skip_parameter_descriptions: false,
            stateful: false,
            insecure: false,
        }
    }

    #[test]
    fn insecure_flag_mapped_when_true() {
        let mut cli = minimal_cli();
        cli.insecure = true;
        let config = Configuration::from_cli(cli).unwrap();
        assert!(config.insecure);
    }

    #[test]
    fn insecure_flag_defaults_to_false() {
        let cli = minimal_cli();
        let config = Configuration::from_cli(cli).unwrap();
        assert!(!config.insecure);
    }
}