liteforge 0.2.3

Rust SDK for LiteForge - LLM completions via OpenAI-compatible API
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
425
426
427
428
429
//! MCP configuration types.
//!
//! This module provides configuration structures for MCP servers
//! and clients.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;

/// Transport type for MCP server communication.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TransportType {
    /// Standard I/O (subprocess).
    #[default]
    Stdio,
    /// Server-Sent Events.
    Sse,
    /// HTTP/REST.
    Http,
}

impl std::fmt::Display for TransportType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Stdio => write!(f, "stdio"),
            Self::Sse => write!(f, "sse"),
            Self::Http => write!(f, "http"),
        }
    }
}

/// Authentication configuration for MCP servers.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum AuthConfig {
    /// No authentication.
    #[default]
    None,
    /// Bearer token authentication.
    Bearer {
        /// The bearer token.
        token: String,
    },
    /// OAuth2 authentication.
    OAuth {
        /// Client ID.
        client_id: String,
        /// Client secret.
        #[serde(skip_serializing_if = "Option::is_none")]
        client_secret: Option<String>,
        /// Token endpoint URL.
        token_url: String,
        /// OAuth scopes.
        #[serde(skip_serializing_if = "Option::is_none")]
        scopes: Option<Vec<String>>,
    },
    /// API key authentication.
    ApiKey {
        /// Header name for the API key.
        header: String,
        /// The API key value.
        key: String,
    },
}

/// Configuration for an individual MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Server name (unique identifier).
    pub name: String,

    /// Transport type.
    #[serde(default)]
    pub transport: TransportType,

    /// Command to run for stdio transport.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,

    /// Arguments for the command.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub args: Vec<String>,

    /// Environment variables to set.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub env: HashMap<String, String>,

    /// Working directory for stdio transport.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,

    /// URL for SSE/HTTP transport.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Authentication configuration.
    #[serde(default, skip_serializing_if = "is_auth_none")]
    pub auth: AuthConfig,

    /// Connection timeout.
    #[serde(
        default = "default_timeout",
        with = "humantime_serde",
        skip_serializing_if = "is_default_timeout"
    )]
    pub timeout: Duration,

    /// Whether to auto-reconnect on disconnect.
    #[serde(default = "default_true")]
    pub auto_reconnect: bool,

    /// Maximum reconnection attempts.
    #[serde(default = "default_max_reconnects")]
    pub max_reconnects: u32,

    /// Capabilities to request from the server.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<RequestedCapabilities>,

    /// Additional metadata.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, String>,
}

fn default_timeout() -> Duration {
    Duration::from_secs(30)
}

fn default_true() -> bool {
    true
}

fn default_max_reconnects() -> u32 {
    3
}

fn is_default_timeout(d: &Duration) -> bool {
    *d == default_timeout()
}

fn is_auth_none(auth: &AuthConfig) -> bool {
    matches!(auth, AuthConfig::None)
}

impl McpServerConfig {
    /// Create a new stdio server configuration.
    pub fn stdio(name: impl Into<String>, command: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            transport: TransportType::Stdio,
            command: Some(command.into()),
            args: Vec::new(),
            env: HashMap::new(),
            cwd: None,
            url: None,
            auth: AuthConfig::None,
            timeout: default_timeout(),
            auto_reconnect: true,
            max_reconnects: default_max_reconnects(),
            capabilities: None,
            metadata: HashMap::new(),
        }
    }

    /// Create a new SSE server configuration.
    pub fn sse(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            transport: TransportType::Sse,
            command: None,
            args: Vec::new(),
            env: HashMap::new(),
            cwd: None,
            url: Some(url.into()),
            auth: AuthConfig::None,
            timeout: default_timeout(),
            auto_reconnect: true,
            max_reconnects: default_max_reconnects(),
            capabilities: None,
            metadata: HashMap::new(),
        }
    }

    /// Create a new HTTP server configuration.
    pub fn http(name: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            transport: TransportType::Http,
            command: None,
            args: Vec::new(),
            env: HashMap::new(),
            cwd: None,
            url: Some(url.into()),
            auth: AuthConfig::None,
            timeout: default_timeout(),
            auto_reconnect: true,
            max_reconnects: default_max_reconnects(),
            capabilities: None,
            metadata: HashMap::new(),
        }
    }

    /// Add command arguments.
    pub fn with_args(mut self, args: Vec<String>) -> Self {
        self.args = args;
        self
    }

    /// Add a single argument.
    pub fn with_arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    /// Set environment variables.
    pub fn with_env(mut self, env: HashMap<String, String>) -> Self {
        self.env = env;
        self
    }

    /// Add an environment variable.
    pub fn with_env_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    /// Set working directory.
    pub fn with_cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        self.cwd = Some(cwd.into());
        self
    }

    /// Set authentication.
    pub fn with_auth(mut self, auth: AuthConfig) -> Self {
        self.auth = auth;
        self
    }

    /// Set bearer token authentication.
    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
        self.auth = AuthConfig::Bearer {
            token: token.into(),
        };
        self
    }

    /// Set timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set auto-reconnect behavior.
    pub fn with_auto_reconnect(mut self, auto_reconnect: bool) -> Self {
        self.auto_reconnect = auto_reconnect;
        self
    }

    /// Set max reconnection attempts.
    pub fn with_max_reconnects(mut self, max_reconnects: u32) -> Self {
        self.max_reconnects = max_reconnects;
        self
    }
}

/// Capabilities to request from an MCP server.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RequestedCapabilities {
    /// Request tool capabilities.
    #[serde(default)]
    pub tools: bool,
    /// Request resource capabilities.
    #[serde(default)]
    pub resources: bool,
    /// Request prompt capabilities.
    #[serde(default)]
    pub prompts: bool,
}

/// Overall MCP configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpConfig {
    /// Configured MCP servers.
    #[serde(default)]
    pub servers: Vec<McpServerConfig>,

    /// Default timeout for all servers.
    #[serde(
        default = "default_timeout",
        with = "humantime_serde",
        skip_serializing_if = "is_default_timeout"
    )]
    pub default_timeout: Duration,

    /// Whether to enable all servers by default.
    #[serde(default = "default_true")]
    pub enable_all: bool,
}

impl McpConfig {
    /// Create a new empty configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a server configuration.
    pub fn add_server(&mut self, config: McpServerConfig) -> &mut Self {
        self.servers.push(config);
        self
    }

    /// Add a server configuration (builder pattern).
    pub fn with_server(mut self, config: McpServerConfig) -> Self {
        self.servers.push(config);
        self
    }

    /// Get a server configuration by name.
    pub fn get_server(&self, name: &str) -> Option<&McpServerConfig> {
        self.servers.iter().find(|s| s.name == name)
    }

    /// Get all server names.
    pub fn server_names(&self) -> Vec<&str> {
        self.servers.iter().map(|s| s.name.as_str()).collect()
    }

    /// Set default timeout.
    pub fn with_default_timeout(mut self, timeout: Duration) -> Self {
        self.default_timeout = timeout;
        self
    }
}

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

    #[test]
    fn test_transport_type_display() {
        assert_eq!(TransportType::Stdio.to_string(), "stdio");
        assert_eq!(TransportType::Sse.to_string(), "sse");
        assert_eq!(TransportType::Http.to_string(), "http");
    }

    #[test]
    fn test_server_config_stdio() {
        let config = McpServerConfig::stdio("filesystem", "npx")
            .with_arg("-y")
            .with_arg("@modelcontextprotocol/server-filesystem")
            .with_arg("/tmp");

        assert_eq!(config.name, "filesystem");
        assert_eq!(config.transport, TransportType::Stdio);
        assert_eq!(config.command, Some("npx".to_string()));
        assert_eq!(config.args.len(), 3);
    }

    #[test]
    fn test_server_config_sse() {
        let config = McpServerConfig::sse("remote", "https://example.com/mcp")
            .with_bearer_token("secret123");

        assert_eq!(config.transport, TransportType::Sse);
        assert_eq!(config.url, Some("https://example.com/mcp".to_string()));
        assert!(matches!(config.auth, AuthConfig::Bearer { .. }));
    }

    #[test]
    fn test_server_config_http() {
        let config = McpServerConfig::http("api", "https://api.example.com/v1")
            .with_timeout(Duration::from_secs(60));

        assert_eq!(config.transport, TransportType::Http);
        assert_eq!(config.timeout, Duration::from_secs(60));
    }

    #[test]
    fn test_mcp_config() {
        let config = McpConfig::new()
            .with_server(McpServerConfig::stdio("fs", "mcp-server-filesystem"))
            .with_server(McpServerConfig::sse("remote", "https://example.com"));

        assert_eq!(config.servers.len(), 2);
        assert!(config.get_server("fs").is_some());
        assert!(config.get_server("remote").is_some());
        assert!(config.get_server("nonexistent").is_none());
    }

    #[test]
    fn test_server_names() {
        let config = McpConfig::new()
            .with_server(McpServerConfig::stdio("a", "cmd"))
            .with_server(McpServerConfig::stdio("b", "cmd"));

        let names = config.server_names();
        assert!(names.contains(&"a"));
        assert!(names.contains(&"b"));
    }

    #[test]
    fn test_auth_config_serialization() {
        let bearer = AuthConfig::Bearer {
            token: "secret".to_string(),
        };
        let json = serde_json::to_string(&bearer).unwrap();
        assert!(json.contains("bearer"));
        assert!(json.contains("secret"));

        let api_key = AuthConfig::ApiKey {
            header: "X-API-Key".to_string(),
            key: "mykey".to_string(),
        };
        let json = serde_json::to_string(&api_key).unwrap();
        assert!(json.contains("apikey"));
    }

    #[test]
    fn test_server_config_env() {
        let config = McpServerConfig::stdio("test", "cmd")
            .with_env_var("PATH", "/usr/bin")
            .with_env_var("HOME", "/home/user");

        assert_eq!(config.env.len(), 2);
        assert_eq!(config.env.get("PATH"), Some(&"/usr/bin".to_string()));
    }
}