sqlx-mcp 0.1.0

SQLx MCP Server - Secure multi-database CRUD operations via Model Context Protocol
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! Configuration module for SQLx MCP Server
//!
//! Handles multi-database configuration with support for MySQL, PostgreSQL, and SQLite.
//! Configuration is loaded from .databases.json file (hidden for security).

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// Supported database engines
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DatabaseEngine {
    MySQL,
    Postgres,
    SQLite,
}

impl DatabaseEngine {
    pub fn as_str(&self) -> &'static str {
        match self {
            DatabaseEngine::MySQL => "mysql",
            DatabaseEngine::Postgres => "postgres",
            DatabaseEngine::SQLite => "sqlite",
        }
    }

}

impl std::fmt::Display for DatabaseEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DatabaseEngine::MySQL => write!(f, "MySQL"),
            DatabaseEngine::Postgres => write!(f, "PostgreSQL"),
            DatabaseEngine::SQLite => write!(f, "SQLite"),
        }
    }
}

/// SSL/TLS mode for database connection
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SslMode {
    Disabled,
    #[default]
    Preferred,
    Required,
}

impl SslMode {
    #[allow(dead_code)] // Used in tests
    pub fn from_str(value: &str) -> Self {
        match value.to_lowercase().as_str() {
            "disabled" | "disable" | "false" | "0" => Self::Disabled,
            "required" | "require" | "true" | "1" => Self::Required,
            _ => Self::Preferred,
        }
    }
}

/// Connection configuration for a single database
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "engine", rename_all = "lowercase")]
pub enum ConnectionConfig {
    MySQL(MySqlConnectionConfig),
    Postgres(PostgresConnectionConfig),
    SQLite(SqliteConnectionConfig),
}

impl ConnectionConfig {
    pub fn name(&self) -> &str {
        match self {
            ConnectionConfig::MySQL(c) => &c.name,
            ConnectionConfig::Postgres(c) => &c.name,
            ConnectionConfig::SQLite(c) => &c.name,
        }
    }

    pub fn engine(&self) -> DatabaseEngine {
        match self {
            ConnectionConfig::MySQL(_) => DatabaseEngine::MySQL,
            ConnectionConfig::Postgres(_) => DatabaseEngine::Postgres,
            ConnectionConfig::SQLite(_) => DatabaseEngine::SQLite,
        }
    }

    pub fn max_connections(&self) -> u32 {
        match self {
            ConnectionConfig::MySQL(c) => c.max_connections,
            ConnectionConfig::Postgres(c) => c.max_connections,
            ConnectionConfig::SQLite(c) => c.max_connections,
        }
    }

    pub fn min_connections(&self) -> u32 {
        match self {
            ConnectionConfig::MySQL(c) => c.min_connections,
            ConnectionConfig::Postgres(c) => c.min_connections,
            ConnectionConfig::SQLite(_) => 1,
        }
    }

    pub fn connect_timeout_secs(&self) -> u64 {
        match self {
            ConnectionConfig::MySQL(c) => c.connect_timeout_secs,
            ConnectionConfig::Postgres(c) => c.connect_timeout_secs,
            ConnectionConfig::SQLite(_) => 30,
        }
    }

    /// Build connection URL for SQLx
    pub fn connection_url(&self) -> String {
        match self {
            ConnectionConfig::MySQL(c) => c.connection_url(),
            ConnectionConfig::Postgres(c) => c.connection_url(),
            ConnectionConfig::SQLite(c) => c.connection_url(),
        }
    }
}

/// MySQL-specific connection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MySqlConnectionConfig {
    pub name: String,
    #[serde(default = "default_host")]
    pub host: String,
    #[serde(default = "default_mysql_port")]
    pub port: u16,
    pub username: String,
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub database: Option<String>,
    #[serde(default)]
    pub ssl_mode: SslMode,
    #[serde(default = "default_max_connections")]
    pub max_connections: u32,
    #[serde(default = "default_min_connections")]
    pub min_connections: u32,
    #[serde(default = "default_timeout")]
    pub connect_timeout_secs: u64,
}

impl MySqlConnectionConfig {
    pub fn connection_url(&self) -> String {
        let ssl_param = match self.ssl_mode {
            SslMode::Disabled => "ssl-mode=DISABLED",
            SslMode::Preferred => "ssl-mode=PREFERRED",
            SslMode::Required => "ssl-mode=REQUIRED",
        };

        let db_part = self.database.as_deref().unwrap_or("");
        format!(
            "mysql://{}:{}@{}:{}/{}?{}",
            self.username, self.password, self.host, self.port, db_part, ssl_param
        )
    }
}

/// PostgreSQL-specific connection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PostgresConnectionConfig {
    pub name: String,
    #[serde(default = "default_host")]
    pub host: String,
    #[serde(default = "default_postgres_port")]
    pub port: u16,
    pub username: String,
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub database: Option<String>,
    #[serde(default)]
    pub ssl_mode: SslMode,
    #[serde(default = "default_max_connections")]
    pub max_connections: u32,
    #[serde(default = "default_min_connections")]
    pub min_connections: u32,
    #[serde(default = "default_timeout")]
    pub connect_timeout_secs: u64,
}

impl PostgresConnectionConfig {
    pub fn connection_url(&self) -> String {
        let ssl_param = match self.ssl_mode {
            SslMode::Disabled => "sslmode=disable",
            SslMode::Preferred => "sslmode=prefer",
            SslMode::Required => "sslmode=require",
        };

        let db_part = self.database.as_deref().unwrap_or("postgres");
        format!(
            "postgres://{}:{}@{}:{}/{}?{}",
            self.username, self.password, self.host, self.port, db_part, ssl_param
        )
    }
}

/// SQLite-specific connection configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SqliteConnectionConfig {
    pub name: String,
    pub path: String,
    #[serde(default = "default_sqlite_max_connections")]
    pub max_connections: u32,
}

impl SqliteConnectionConfig {
    pub fn connection_url(&self) -> String {
        if self.path == ":memory:" {
            "sqlite::memory:".to_string()
        } else {
            format!("sqlite:{}", self.path)
        }
    }
}

/// Root configuration structure for databases.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabasesConfig {
    #[serde(default = "default_version")]
    pub version: String,
    pub databases: Vec<ConnectionConfig>,
    #[serde(default)]
    pub default_connection: Option<String>,
}

impl DatabasesConfig {
    /// Load configuration from .databases.json file
    ///
    /// Search order:
    /// 1. ./.databases.json (current directory, hidden for security)
    /// 2. ~/.config/sqlx-mcp/.databases.json (user config)
    pub fn load() -> Result<Self, ConfigError> {
        let paths = Self::config_paths();

        for path in &paths {
            if path.exists() {
                let content = fs::read_to_string(path)
                    .map_err(|e| ConfigError::FileRead(path.clone(), e.to_string()))?;
                let config: Self = serde_json::from_str(&content)
                    .map_err(|e| ConfigError::Parse(path.clone(), e.to_string()))?;

                // Validate configuration
                config.validate()?;

                return Ok(config);
            }
        }

        Err(ConfigError::NotFound)
    }

    /// Get all possible config file paths
    pub fn config_paths() -> Vec<PathBuf> {
        let mut paths = vec![PathBuf::from(".databases.json")];

        if let Some(home) = dirs::home_dir() {
            paths.push(home.join(".config/sqlx-mcp/.databases.json"));
        }

        paths
    }

    /// Validate the configuration
    fn validate(&self) -> Result<(), ConfigError> {
        if self.databases.is_empty() {
            return Err(ConfigError::Validation(
                "At least one database connection is required".to_string(),
            ));
        }

        // Check for duplicate names
        let mut names = std::collections::HashSet::new();
        for conn in &self.databases {
            let name = conn.name();
            if !names.insert(name) {
                return Err(ConfigError::Validation(format!(
                    "Duplicate connection name: {}",
                    name
                )));
            }
        }

        // Validate default connection exists
        if let Some(ref default) = self.default_connection {
            if !names.contains(default.as_str()) {
                return Err(ConfigError::Validation(format!(
                    "Default connection '{}' not found in databases",
                    default
                )));
            }
        }

        Ok(())
    }

    /// Get a connection configuration by name
    #[allow(dead_code)] // Public API helper
    pub fn get_connection(&self, name: &str) -> Option<&ConnectionConfig> {
        self.databases.iter().find(|c| c.name() == name)
    }

    /// Get the default connection configuration
    #[allow(dead_code)] // Public API helper
    pub fn get_default_connection(&self) -> Option<&ConnectionConfig> {
        self.default_connection
            .as_ref()
            .and_then(|name| self.get_connection(name))
            .or_else(|| self.databases.first())
    }

    /// Save configuration to file
    pub fn save(&self, path: &PathBuf) -> Result<(), ConfigError> {
        // Create parent directories if needed
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| ConfigError::FileWrite(path.clone(), e.to_string()))?;
        }

        let content = serde_json::to_string_pretty(self)
            .map_err(|e| ConfigError::Serialize(e.to_string()))?;

        fs::write(path, content)
            .map_err(|e| ConfigError::FileWrite(path.clone(), e.to_string()))?;

        Ok(())
    }
}

impl Default for DatabasesConfig {
    fn default() -> Self {
        Self {
            version: default_version(),
            databases: Vec::new(),
            default_connection: None,
        }
    }
}

// Default value functions
fn default_version() -> String {
    "1.0".to_string()
}

fn default_host() -> String {
    "localhost".to_string()
}

fn default_mysql_port() -> u16 {
    3306
}

fn default_postgres_port() -> u16 {
    5432
}

fn default_max_connections() -> u32 {
    5
}

fn default_min_connections() -> u32 {
    1
}

fn default_timeout() -> u64 {
    30
}

fn default_sqlite_max_connections() -> u32 {
    1
}

/// Configuration errors
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Configuration file not found. Run 'sqlx-mcp --init' to create one.")]
    NotFound,

    #[error("Failed to read config file {0}: {1}")]
    FileRead(PathBuf, String),

    #[error("Failed to parse config file {0}: {1}")]
    Parse(PathBuf, String),

    #[error("Failed to write config file {0}: {1}")]
    FileWrite(PathBuf, String),

    #[error("Failed to serialize config: {0}")]
    Serialize(String),

    #[error("Configuration validation error: {0}")]
    Validation(String),
}

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

    #[test]
    fn test_mysql_connection_url() {
        let config = MySqlConnectionConfig {
            name: "test".to_string(),
            host: "localhost".to_string(),
            port: 3306,
            username: "root".to_string(),
            password: "secret".to_string(),
            database: Some("mydb".to_string()),
            ssl_mode: SslMode::Preferred,
            max_connections: 5,
            min_connections: 1,
            connect_timeout_secs: 30,
        };

        let url = config.connection_url();
        assert!(url.starts_with("mysql://root:secret@localhost:3306/mydb"));
        assert!(url.contains("ssl-mode=PREFERRED"));
    }

    #[test]
    fn test_postgres_connection_url() {
        let config = PostgresConnectionConfig {
            name: "test".to_string(),
            host: "localhost".to_string(),
            port: 5432,
            username: "postgres".to_string(),
            password: "secret".to_string(),
            database: Some("mydb".to_string()),
            ssl_mode: SslMode::Required,
            max_connections: 5,
            min_connections: 1,
            connect_timeout_secs: 30,
        };

        let url = config.connection_url();
        assert!(url.starts_with("postgres://postgres:secret@localhost:5432/mydb"));
        assert!(url.contains("sslmode=require"));
    }

    #[test]
    fn test_sqlite_connection_url() {
        let config = SqliteConnectionConfig {
            name: "test".to_string(),
            path: "/data/test.db".to_string(),
            max_connections: 1,
        };

        assert_eq!(config.connection_url(), "sqlite:/data/test.db");

        let memory_config = SqliteConnectionConfig {
            name: "memory".to_string(),
            path: ":memory:".to_string(),
            max_connections: 1,
        };

        assert_eq!(memory_config.connection_url(), "sqlite::memory:");
    }

    #[test]
    fn test_ssl_mode_parsing() {
        assert_eq!(SslMode::from_str("disabled"), SslMode::Disabled);
        assert_eq!(SslMode::from_str("DISABLED"), SslMode::Disabled);
        assert_eq!(SslMode::from_str("false"), SslMode::Disabled);
        assert_eq!(SslMode::from_str("required"), SslMode::Required);
        assert_eq!(SslMode::from_str("true"), SslMode::Required);
        assert_eq!(SslMode::from_str("preferred"), SslMode::Preferred);
        assert_eq!(SslMode::from_str("unknown"), SslMode::Preferred);
    }

    #[test]
    fn test_config_validation_duplicate_names() {
        let config = DatabasesConfig {
            version: "1.0".to_string(),
            databases: vec![
                ConnectionConfig::SQLite(SqliteConnectionConfig {
                    name: "test".to_string(),
                    path: "/data/a.db".to_string(),
                    max_connections: 1,
                }),
                ConnectionConfig::SQLite(SqliteConnectionConfig {
                    name: "test".to_string(),
                    path: "/data/b.db".to_string(),
                    max_connections: 1,
                }),
            ],
            default_connection: None,
        };

        assert!(config.validate().is_err());
    }
}