lc-tools 0.25.0

Built-in tools for langchainrust — Calculator, DateTime, URLFetch, etc.
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
//! SQL tool (read-only, SQLite, supports bind parameters)

use std::collections::HashMap;
use std::sync::Mutex;

use async_trait::async_trait;
use regex::Regex;

use lc_core::tools::ToolError;
use lc_core::BaseTool;

/// Lazy-compiled regex for extracting table names from SQL.
static TABLE_NAME_RE: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
    Regex::new(r"(?i)\b(?:FROM|JOIN)\s+([a-zA-Z_][a-zA-Z0-9_]*(?:\s*,\s*[a-zA-Z_][a-zA-Z0-9_]*)*)")
        .expect("static regex literal must compile")
});

/// SQL query tool (read-only SELECT, table whitelist)
pub struct SQLTool {
    conn: Mutex<rusqlite::Connection>,
    allowed_tables: Vec<String>,
}

impl SQLTool {
    /// Creates a new SQL tool over the SQLite database at `path`.
    pub fn new(path: &str) -> Result<Self, ToolError> {
        let conn = rusqlite::Connection::open(path)
            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
        Ok(Self {
            conn: Mutex::new(conn),
            allowed_tables: Vec::new(),
        })
    }

    /// Restricts queries to the given whitelist of table names.
    pub fn with_allowed_tables(mut self, tables: Vec<String>) -> Self {
        self.allowed_tables = tables;
        self
    }

    /// Extract table names from a SELECT SQL statement.
    fn extract_table_names(sql: &str) -> Vec<String> {
        let mut tables = Vec::new();
        for cap in TABLE_NAME_RE.captures_iter(sql) {
            for name in cap[1].split(',') {
                let trimmed = name.trim().to_lowercase();
                if !trimmed.is_empty() {
                    tables.push(trimmed);
                }
            }
        }
        tables
    }

    /// Execute a SELECT query (read-only, without bind parameters).
    pub fn execute(&self, sql: &str) -> Result<Vec<HashMap<String, String>>, ToolError> {
        self.execute_parameterized(sql, &[])
    }

    /// Execute a SELECT query with bind parameters (read-only, single statement).
    ///
    /// Placeholders `?1` / `?2` ... in the SQL text are bound by position from `params` (Q5) —
    /// values are no longer spliced into the SQL as literals, so injected content only matches
    /// as a literal value and cannot become a new statement.
    /// Validation rules match `execute`: only a single SELECT is allowed; multi-statements,
    /// comments, and dangerous functions are rejected; an optional table whitelist applies.
    pub fn execute_parameterized(
        &self,
        sql: &str,
        params: &[rusqlite::types::Value],
    ) -> Result<Vec<HashMap<String, String>>, ToolError> {
        let trimmed = sql.trim();

        if !trimmed.to_lowercase().starts_with("select") {
            return Err(ToolError::InvalidInput(
                "Only SELECT queries are allowed (read-only)".to_string(),
            ));
        }

        if trimmed.contains(';') {
            return Err(ToolError::InvalidInput(
                "Semicolons are not allowed in queries (single SELECT only)".to_string(),
            ));
        }

        if trimmed.contains("--") || trimmed.contains("/*") || trimmed.contains("*/") {
            return Err(ToolError::InvalidInput(
                "SQL comments are not allowed in queries".to_string(),
            ));
        }

        let lower = trimmed.to_lowercase();
        let dangerous_patterns = [
            // MySQL-flavored patterns (kept for defense-in-depth / cross-dialect hints).
            "into outfile",
            "into dumpfile",
            "load_file",
            "benchmark",
            "sleep",
            "waitfor",
            "exec",
            "execute",
            "xp_",
            "sp_",
            // SQLite-specific file-access / code-loading (this tool is SQLite, and
            // these were the dangerous ones the old MySQL-flavored list missed):
            // ```load_extension``` reads arbitrary local files / loads local code (RCE),
            // readfile()/writefile() read & write arbitrary paths, pragma can alter
            // schema. rusqlite disables load_extension by default (so base risk is low),
            // but the blacklist must not give false assurance. sqlite_master/sqlite_schema
            // introspection is also blocked to avoid leaking schema.
            "load_extension",
            "readfile(",
            "writefile(",
            "pragma",
            "sqlite_master",
            "sqlite_schema",
        ];
        for pattern in dangerous_patterns {
            if lower.contains(pattern) {
                return Err(ToolError::InvalidInput(format!(
                    "Potentially dangerous SQL pattern detected: '{}'",
                    pattern
                )));
            }
        }

        if !self.allowed_tables.is_empty() {
            let tables_in_sql = Self::extract_table_names(sql);
            let allowed_lower: Vec<String> = self
                .allowed_tables
                .iter()
                .map(|t| t.to_lowercase())
                .collect();
            for table in &tables_in_sql {
                if !allowed_lower.contains(table) {
                    return Err(ToolError::InvalidInput(format!(
                        "Table '{}' is not in the allowed list. Allowed: {:?}, found: {:?}",
                        table, self.allowed_tables, tables_in_sql
                    )));
                }
            }
            if tables_in_sql.is_empty() {
                return Err(ToolError::InvalidInput(
                    "SQL does not reference any table. At least one table must be specified."
                        .to_string(),
                ));
            }
        }

        let conn = self
            .conn
            .lock()
            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
        let mut stmt = conn
            .prepare(sql)
            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
        let col_names: Vec<String> = stmt.column_names().iter().map(|s| s.to_string()).collect();
        let rows = stmt
            .query_map(rusqlite::params_from_iter(params.iter()), |row| {
                let mut m = HashMap::new();
                for (i, col) in col_names.iter().enumerate() {
                    let val: String = row
                        .get::<_, Option<String>>(i)
                        .unwrap_or(None)
                        .unwrap_or_default();
                    m.insert(col.clone(), val);
                }
                Ok(m)
            })
            .map_err(|e| ToolError::ExecutionFailed(e.to_string()))?;
        let mut result = Vec::new();
        for r in rows {
            result.push(r.map_err(|e| ToolError::ExecutionFailed(e.to_string()))?);
        }
        Ok(result)
    }
}

#[async_trait]
impl BaseTool for SQLTool {
    fn name(&self) -> &str {
        "sql_query"
    }

    fn description(&self) -> &str {
        "Execute SQL SELECT queries (read-only). Input: SQL string."
    }

    async fn run(&self, input: String) -> Result<String, ToolError> {
        let (sql, params) = parse_sql_input(&input)?;
        let rows = self.execute_parameterized(&sql, &params)?;
        serde_json::to_string(&rows).map_err(|e| ToolError::ExecutionFailed(e.to_string()))
    }
}

/// Parses the tool input: prefers `{"sql": "...", "params": [...]}` (parameterized, Q5),
/// otherwise treats the whole input as plain SQL text (compatible with the old interface).
fn parse_sql_input(input: &str) -> Result<(String, Vec<rusqlite::types::Value>), ToolError> {
    if input.trim_start().starts_with('{') {
        let json: serde_json::Value = serde_json::from_str(input)
            .map_err(|e| ToolError::InvalidInput(format!("JSON parse error: {}", e)))?;
        let sql = json
            .get("sql")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                ToolError::InvalidInput("JSON input must have a 'sql' string field".to_string())
            })?
            .to_string();
        let params = json
            .get("params")
            .and_then(|v| v.as_array())
            .map(|arr| arr.iter().map(json_to_sql_value).collect())
            .unwrap_or_default();
        Ok((sql, params))
    } else {
        Ok((input.to_string(), Vec::new()))
    }
}

/// Converts a JSON value into an SQL bind parameter: null → NULL, bool → 0/1,
/// number → Integer/Real, string → Text, any other compound value → NULL.
fn json_to_sql_value(v: &serde_json::Value) -> rusqlite::types::Value {
    use rusqlite::types::Value as SqlValue;
    match v {
        serde_json::Value::Null => SqlValue::Null,
        serde_json::Value::Bool(b) => SqlValue::Integer(*b as i64),
        serde_json::Value::Number(n) => n
            .as_i64()
            .map(SqlValue::Integer)
            .or_else(|| n.as_f64().map(SqlValue::Real))
            .unwrap_or(SqlValue::Null),
        serde_json::Value::String(s) => SqlValue::Text(s.clone()),
        _ => SqlValue::Null,
    }
}

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

    fn tool_with_data() -> SQLTool {
        let tool = SQLTool::new(":memory:").unwrap();
        {
            let conn = tool.conn.lock().unwrap_or_else(|e| e.into_inner());
            conn.execute("CREATE TABLE users (id INTEGER, name TEXT)", [])
                .unwrap();
            conn.execute("INSERT INTO users VALUES (1, 'Alice')", [])
                .unwrap();
            conn.execute("INSERT INTO users VALUES (2, 'Bob')", [])
                .unwrap();
            // The orders table is used by the multi-table JOIN whitelist tests (its earlier
            // absence made prepare fail with "no such table", but the SQL tests were gated
            // behind a feature so they never ran by default and stayed dormant).
            conn.execute("CREATE TABLE orders (id INTEGER, user_id INTEGER)", [])
                .unwrap();
            conn.execute("INSERT INTO orders VALUES (1, 1)", [])
                .unwrap();
        }
        tool
    }

    #[test]
    fn test_select() {
        let tool = tool_with_data();
        let rows = tool.execute("SELECT * FROM users").unwrap();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].get("name"), Some(&"Alice".to_string()));
    }

    #[test]
    fn test_non_select_rejected() {
        let tool = tool_with_data();
        assert!(tool.execute("DROP TABLE users").is_err());
        assert!(tool.execute("INSERT INTO users VALUES (3, 'Eve')").is_err());
    }

    #[test]
    fn test_allowed_tables_exact_match() {
        let tool = tool_with_data().with_allowed_tables(vec!["users".to_string()]);
        assert!(tool.execute("SELECT * FROM users").is_ok());
        assert!(tool.execute("SELECT * FROM users2").is_err());
    }

    #[test]
    fn test_allowed_tables_blocks_unknown() {
        let tool = tool_with_data().with_allowed_tables(vec!["orders".to_string()]);
        assert!(tool.execute("SELECT * FROM users").is_err());
    }

    #[test]
    fn test_extract_table_names() {
        let tables = SQLTool::extract_table_names("SELECT * FROM users WHERE id = 1");
        assert_eq!(tables, vec!["users"]);

        let tables = SQLTool::extract_table_names(
            "SELECT * FROM users JOIN orders ON users.id = orders.user_id",
        );
        assert_eq!(tables, vec!["users", "orders"]);

        let tables = SQLTool::extract_table_names("SELECT * FROM users, orders");
        assert_eq!(tables, vec!["users", "orders"]);
    }

    #[test]
    fn test_allowed_tables_with_join() {
        let tool =
            tool_with_data().with_allowed_tables(vec!["users".to_string(), "orders".to_string()]);
        assert!(tool
            .execute("SELECT * FROM users JOIN orders ON users.id = orders.user_id")
            .is_ok());
    }

    #[test]
    fn test_allowed_tables_blocks_partial_join() {
        let tool = tool_with_data().with_allowed_tables(vec!["users".to_string()]);
        assert!(tool
            .execute("SELECT * FROM users JOIN orders ON users.id = orders.user_id")
            .is_err());
    }

    #[test]
    fn test_semicolon_rejected() {
        let tool = tool_with_data();
        assert!(tool
            .execute("SELECT * FROM users; DROP TABLE users")
            .is_err());
    }

    #[test]
    fn test_sql_comments_rejected() {
        let tool = tool_with_data();
        assert!(tool.execute("SELECT * FROM users -- comment").is_err());
        assert!(tool
            .execute("SELECT * FROM users /* block comment */")
            .is_err());
    }

    #[test]
    fn test_dangerous_patterns_rejected() {
        let tool = tool_with_data();
        assert!(tool.execute("SELECT sleep(1) FROM users").is_err());
        assert!(tool.execute("SELECT benchmark(1, 1) FROM users").is_err());
    }

    /// S2: SQLite-specific file-access / code-loading functions must be rejected,
    /// not just the old MySQL-flavored list.
    #[test]
    fn test_sqlite_dangerous_functions_rejected() {
        let tool = tool_with_data();
        assert!(tool.execute("SELECT load_extension('evil.so')").is_err());
        assert!(tool
            .execute("SELECT load_extension('/etc/passwd')")
            .is_err());
        assert!(tool.execute("SELECT readfile('/etc/passwd')").is_err());
        assert!(tool.execute("SELECT writefile('/tmp/owned', 'x')").is_err());
        assert!(tool.execute("PRAGMA writable_schema").is_err());
        assert!(tool.execute("SELECT * FROM sqlite_master").is_err());
        assert!(tool.execute("SELECT * FROM sqlite_schema").is_err());
    }

    /// Q5: bind parameters take effect by position.
    #[test]
    fn test_parameterized_query() {
        let tool = tool_with_data();
        let rows = tool
            .execute_parameterized(
                "SELECT * FROM users WHERE name = ?1",
                &[rusqlite::types::Value::Text("Alice".to_string())],
            )
            .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].get("name"), Some(&"Alice".to_string()));
    }

    /// Q5: even if a parameter value contains an injection snippet, it only matches
    /// as a literal value and cannot form a new statement.
    #[test]
    fn test_parameterized_prevents_injection() {
        let tool = tool_with_data();
        let rows = tool
            .execute_parameterized(
                "SELECT * FROM users WHERE name = ?1",
                &[rusqlite::types::Value::Text(
                    "Alice'; DROP TABLE users;--".to_string(),
                )],
            )
            .unwrap();
        assert!(rows.is_empty(), "注入片段只应作为字面值匹配不到任何行");

        // The table still exists; subsequent queries are unaffected
        let rows = tool.execute("SELECT COUNT(*) FROM users").unwrap();
        assert_eq!(rows.len(), 1);
    }

    #[tokio::test]
    async fn test_run_accepts_parameterized_json() {
        let tool = tool_with_data();
        let result = tool
            .run(r#"{"sql": "SELECT * FROM users WHERE id = ?1", "params": [1]}"#.to_string())
            .await;
        assert!(result.is_ok(), "got error: {:?}", result.err());
        let rows: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(rows.as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn test_run_accepts_raw_sql() {
        let tool = tool_with_data();
        let result = tool.run("SELECT * FROM users".to_string()).await;
        assert!(result.is_ok());
        let rows: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(rows.as_array().unwrap().len(), 2);
    }
}