sqlite-guard-mcp 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlite_guard_mcp/__init__.py +43 -0
- sqlite_guard_mcp/__main__.py +6 -0
- sqlite_guard_mcp/server.py +962 -0
- sqlite_guard_mcp-0.2.0.dist-info/METADATA +168 -0
- sqlite_guard_mcp-0.2.0.dist-info/RECORD +8 -0
- sqlite_guard_mcp-0.2.0.dist-info/WHEEL +4 -0
- sqlite_guard_mcp-0.2.0.dist-info/entry_points.txt +2 -0
- sqlite_guard_mcp-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""SQLite Guard MCP package.
|
|
2
|
+
|
|
3
|
+
A read-only, security-hardened SQLite MCP server for AI agents.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
__version__ = "0.2.0"
|
|
7
|
+
|
|
8
|
+
from .server import (
|
|
9
|
+
DEFAULT_MAX_ROWS,
|
|
10
|
+
DEFAULT_MAX_VM_STEPS,
|
|
11
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
12
|
+
MAX_BLOB_BYTES,
|
|
13
|
+
MAX_CELL_TEXT,
|
|
14
|
+
MAX_COLUMNS,
|
|
15
|
+
MAX_RESULT_BYTES,
|
|
16
|
+
MAX_ROWS_HARD_LIMIT,
|
|
17
|
+
MAX_SQL_LENGTH,
|
|
18
|
+
create_server,
|
|
19
|
+
describe_table,
|
|
20
|
+
execute_guarded_query,
|
|
21
|
+
explain_query,
|
|
22
|
+
list_tables,
|
|
23
|
+
main,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"DEFAULT_MAX_ROWS",
|
|
28
|
+
"DEFAULT_MAX_VM_STEPS",
|
|
29
|
+
"DEFAULT_TIMEOUT_SECONDS",
|
|
30
|
+
"MAX_BLOB_BYTES",
|
|
31
|
+
"MAX_CELL_TEXT",
|
|
32
|
+
"MAX_COLUMNS",
|
|
33
|
+
"MAX_RESULT_BYTES",
|
|
34
|
+
"MAX_ROWS_HARD_LIMIT",
|
|
35
|
+
"MAX_SQL_LENGTH",
|
|
36
|
+
"__version__",
|
|
37
|
+
"create_server",
|
|
38
|
+
"describe_table",
|
|
39
|
+
"execute_guarded_query",
|
|
40
|
+
"explain_query",
|
|
41
|
+
"list_tables",
|
|
42
|
+
"main",
|
|
43
|
+
]
|
|
@@ -0,0 +1,962 @@
|
|
|
1
|
+
"""Read-only SQLite MCP server with bounded execution and credential masking."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import base64
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import sqlite3
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Annotated, Any
|
|
15
|
+
from urllib.parse import quote
|
|
16
|
+
|
|
17
|
+
from pydantic import Field
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
|
|
21
|
+
MAX_SQL_LENGTH = 100_000
|
|
22
|
+
MAX_ROWS_HARD_LIMIT = 1_000
|
|
23
|
+
MAX_COLUMNS = 100
|
|
24
|
+
MAX_CELL_TEXT = 4_096
|
|
25
|
+
MAX_BLOB_BYTES = 4_096
|
|
26
|
+
MAX_RESULT_BYTES = 1_000_000
|
|
27
|
+
|
|
28
|
+
DEFAULT_MAX_ROWS = 250
|
|
29
|
+
DEFAULT_TIMEOUT_SECONDS = 2.0
|
|
30
|
+
DEFAULT_MAX_VM_STEPS = 250_000
|
|
31
|
+
|
|
32
|
+
_LEADING_COMMENTS = re.compile(
|
|
33
|
+
r"\A(?:\s+|--[^\r\n]*(?:\r?\n|\Z)|/\*[\s\S]*?\*/)*",
|
|
34
|
+
re.MULTILINE,
|
|
35
|
+
)
|
|
36
|
+
_FIRST_WORD = re.compile(r"\A([A-Za-z]+)\b")
|
|
37
|
+
_EXPLAIN_QUERY_PLAN = re.compile(
|
|
38
|
+
r"\AEXPLAIN\s+QUERY\s+PLAN\b",
|
|
39
|
+
re.IGNORECASE,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
_BLOCKED_FUNCTIONS = frozenset(
|
|
43
|
+
{
|
|
44
|
+
"load_extension",
|
|
45
|
+
"readfile",
|
|
46
|
+
"writefile",
|
|
47
|
+
"fts3_tokenizer",
|
|
48
|
+
"edit",
|
|
49
|
+
"randomblob",
|
|
50
|
+
"zeroblob",
|
|
51
|
+
"fsdir",
|
|
52
|
+
"fileio_read",
|
|
53
|
+
"fileio_write",
|
|
54
|
+
"zipfile",
|
|
55
|
+
"zipfile_cds",
|
|
56
|
+
"eval",
|
|
57
|
+
"sqlite_eval",
|
|
58
|
+
}
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
_TABLE_PRAGMAS = frozenset(
|
|
62
|
+
{
|
|
63
|
+
"table_info",
|
|
64
|
+
"table_xinfo",
|
|
65
|
+
"index_list",
|
|
66
|
+
"index_info",
|
|
67
|
+
"index_xinfo",
|
|
68
|
+
"foreign_key_list",
|
|
69
|
+
}
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
_NO_ARGUMENT_PRAGMAS = frozenset(
|
|
73
|
+
{
|
|
74
|
+
"database_list",
|
|
75
|
+
"compile_options",
|
|
76
|
+
"encoding",
|
|
77
|
+
"data_version",
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
_SAFE_TOKEN_METRICS = frozenset(
|
|
82
|
+
{
|
|
83
|
+
"prompt_tokens",
|
|
84
|
+
"prompt_token",
|
|
85
|
+
"completion_tokens",
|
|
86
|
+
"completion_token",
|
|
87
|
+
"total_tokens",
|
|
88
|
+
"total_token",
|
|
89
|
+
"input_tokens",
|
|
90
|
+
"input_token",
|
|
91
|
+
"output_tokens",
|
|
92
|
+
"output_token",
|
|
93
|
+
"cached_tokens",
|
|
94
|
+
"cached_token",
|
|
95
|
+
"reasoning_tokens",
|
|
96
|
+
"reasoning_token",
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
_SENSITIVE_WORDS = frozenset(
|
|
101
|
+
{
|
|
102
|
+
"password",
|
|
103
|
+
"passwd",
|
|
104
|
+
"pwd",
|
|
105
|
+
"passphrase",
|
|
106
|
+
"secret",
|
|
107
|
+
"credential",
|
|
108
|
+
"credentials",
|
|
109
|
+
"authorization",
|
|
110
|
+
"cookie",
|
|
111
|
+
"cookies",
|
|
112
|
+
"apikey",
|
|
113
|
+
"ssn",
|
|
114
|
+
"cvv",
|
|
115
|
+
"cvc",
|
|
116
|
+
"pin",
|
|
117
|
+
"salt",
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
_SENSITIVE_PHRASES = frozenset(
|
|
122
|
+
{
|
|
123
|
+
"api_key",
|
|
124
|
+
"access_key",
|
|
125
|
+
"auth_key",
|
|
126
|
+
"private_key",
|
|
127
|
+
"secret_key",
|
|
128
|
+
"signing_key",
|
|
129
|
+
"encryption_key",
|
|
130
|
+
"session_key",
|
|
131
|
+
"client_secret",
|
|
132
|
+
"social_security",
|
|
133
|
+
"credit_card",
|
|
134
|
+
"card_number",
|
|
135
|
+
"tax_id",
|
|
136
|
+
"national_id",
|
|
137
|
+
"bank_account",
|
|
138
|
+
"routing_number",
|
|
139
|
+
}
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _strip_leading_comments(sql: str) -> str:
|
|
144
|
+
"""Remove whitespace and SQL comments before checking the first keyword."""
|
|
145
|
+
return _LEADING_COMMENTS.sub("", sql, count=1).lstrip()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _is_sensitive_column(name: str | None) -> bool:
|
|
149
|
+
"""Detect common credential and sensitive-data column names."""
|
|
150
|
+
if not name:
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
normalized = re.sub(
|
|
154
|
+
r"(?<=[a-z0-9])(?=[A-Z])",
|
|
155
|
+
"_",
|
|
156
|
+
name.strip(),
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
normalized = (
|
|
160
|
+
re.sub(
|
|
161
|
+
r"[^a-zA-Z0-9]+",
|
|
162
|
+
"_",
|
|
163
|
+
normalized,
|
|
164
|
+
)
|
|
165
|
+
.strip("_")
|
|
166
|
+
.casefold()
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
if normalized in _SAFE_TOKEN_METRICS:
|
|
170
|
+
return False
|
|
171
|
+
|
|
172
|
+
parts = set(normalized.split("_"))
|
|
173
|
+
|
|
174
|
+
if "token" in parts:
|
|
175
|
+
return True
|
|
176
|
+
|
|
177
|
+
if parts.intersection(_SENSITIVE_WORDS):
|
|
178
|
+
return True
|
|
179
|
+
|
|
180
|
+
padded = f"_{normalized}_"
|
|
181
|
+
return any(f"_{phrase}_" in padded for phrase in _SENSITIVE_PHRASES)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _authorize(
|
|
185
|
+
action: int,
|
|
186
|
+
arg1: str | None,
|
|
187
|
+
arg2: str | None,
|
|
188
|
+
_database_name: str | None,
|
|
189
|
+
_source: str | None,
|
|
190
|
+
) -> int:
|
|
191
|
+
"""Permit safe reads, mask sensitive columns, and deny other actions."""
|
|
192
|
+
if action in {
|
|
193
|
+
sqlite3.SQLITE_SELECT,
|
|
194
|
+
getattr(sqlite3, "SQLITE_RECURSIVE", 33),
|
|
195
|
+
}:
|
|
196
|
+
return sqlite3.SQLITE_OK
|
|
197
|
+
|
|
198
|
+
if action == sqlite3.SQLITE_READ:
|
|
199
|
+
if _is_sensitive_column(arg2):
|
|
200
|
+
return sqlite3.SQLITE_IGNORE
|
|
201
|
+
return sqlite3.SQLITE_OK
|
|
202
|
+
|
|
203
|
+
if action == sqlite3.SQLITE_FUNCTION:
|
|
204
|
+
function_name = (arg2 or "").casefold()
|
|
205
|
+
if function_name in _BLOCKED_FUNCTIONS:
|
|
206
|
+
return sqlite3.SQLITE_DENY
|
|
207
|
+
return sqlite3.SQLITE_OK
|
|
208
|
+
|
|
209
|
+
if action == sqlite3.SQLITE_PRAGMA:
|
|
210
|
+
pragma = (arg1 or "").casefold()
|
|
211
|
+
|
|
212
|
+
if pragma in _TABLE_PRAGMAS:
|
|
213
|
+
return sqlite3.SQLITE_OK
|
|
214
|
+
|
|
215
|
+
if pragma in _NO_ARGUMENT_PRAGMAS and arg2 is None:
|
|
216
|
+
return sqlite3.SQLITE_OK
|
|
217
|
+
|
|
218
|
+
return sqlite3.SQLITE_DENY
|
|
219
|
+
|
|
220
|
+
return sqlite3.SQLITE_DENY
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _validate_query(
|
|
224
|
+
sql: str,
|
|
225
|
+
*,
|
|
226
|
+
explain: bool = False,
|
|
227
|
+
allow_explain_plan: bool = False,
|
|
228
|
+
) -> str:
|
|
229
|
+
"""Validate the permitted SQL statement shape."""
|
|
230
|
+
if not isinstance(sql, str) or not sql.strip():
|
|
231
|
+
raise ValueError("SQL query must be a non-empty string.")
|
|
232
|
+
|
|
233
|
+
if len(sql) > MAX_SQL_LENGTH:
|
|
234
|
+
raise ValueError(f"SQL query exceeds the {MAX_SQL_LENGTH}-character limit.")
|
|
235
|
+
|
|
236
|
+
cleaned = _strip_leading_comments(sql)
|
|
237
|
+
|
|
238
|
+
if not cleaned:
|
|
239
|
+
raise ValueError("SQL query must be a non-empty string.")
|
|
240
|
+
|
|
241
|
+
if explain:
|
|
242
|
+
if not re.match(r"\A(?:SELECT|WITH|VALUES)\b", cleaned, re.IGNORECASE):
|
|
243
|
+
raise ValueError("Only SELECT, WITH, or VALUES queries can be explained.")
|
|
244
|
+
return f"EXPLAIN QUERY PLAN {cleaned}"
|
|
245
|
+
|
|
246
|
+
match = _FIRST_WORD.match(cleaned)
|
|
247
|
+
|
|
248
|
+
if not match:
|
|
249
|
+
raise ValueError("Only read-only SELECT and WITH queries are allowed.")
|
|
250
|
+
|
|
251
|
+
first = match.group(1).upper()
|
|
252
|
+
|
|
253
|
+
if first in {"SELECT", "WITH", "VALUES"}:
|
|
254
|
+
return sql.strip()
|
|
255
|
+
|
|
256
|
+
if first == "EXPLAIN" and allow_explain_plan:
|
|
257
|
+
explain_match = _EXPLAIN_QUERY_PLAN.match(cleaned)
|
|
258
|
+
|
|
259
|
+
if explain_match is None:
|
|
260
|
+
raise ValueError("Only EXPLAIN QUERY PLAN is permitted.")
|
|
261
|
+
|
|
262
|
+
explained = cleaned[explain_match.end() :].lstrip()
|
|
263
|
+
explained_match = _FIRST_WORD.match(explained)
|
|
264
|
+
|
|
265
|
+
if not explained_match or explained_match.group(1).upper() not in {
|
|
266
|
+
"SELECT",
|
|
267
|
+
"WITH",
|
|
268
|
+
"VALUES",
|
|
269
|
+
}:
|
|
270
|
+
raise ValueError("EXPLAIN QUERY PLAN must contain a SELECT or WITH query.")
|
|
271
|
+
|
|
272
|
+
return sql.strip()
|
|
273
|
+
|
|
274
|
+
raise ValueError("Only read-only SELECT and WITH queries are allowed.")
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _validate_params(
|
|
278
|
+
params: Any,
|
|
279
|
+
) -> dict[str, Any] | list[Any] | tuple[Any, ...]:
|
|
280
|
+
"""Validate SQLite scalar query parameters."""
|
|
281
|
+
if params is None:
|
|
282
|
+
return ()
|
|
283
|
+
|
|
284
|
+
if not isinstance(params, (dict, list, tuple)):
|
|
285
|
+
raise ValueError("Query parameters must be an object, array, or null.")
|
|
286
|
+
|
|
287
|
+
if isinstance(params, dict):
|
|
288
|
+
if not all(isinstance(key, str) for key in params):
|
|
289
|
+
raise ValueError("Named query parameter keys must be strings.")
|
|
290
|
+
values = params.values()
|
|
291
|
+
else:
|
|
292
|
+
values = params
|
|
293
|
+
|
|
294
|
+
for value in values:
|
|
295
|
+
if value is None or isinstance(value, (str, int, float, bytes)):
|
|
296
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
297
|
+
raise ValueError("Floating-point query parameters must be finite.")
|
|
298
|
+
|
|
299
|
+
if isinstance(value, str) and len(value) > MAX_CELL_TEXT:
|
|
300
|
+
raise ValueError("A query parameter exceeds the maximum text length.")
|
|
301
|
+
|
|
302
|
+
if isinstance(value, bytes) and len(value) > MAX_BLOB_BYTES:
|
|
303
|
+
raise ValueError("A BLOB query parameter exceeds the maximum byte length.")
|
|
304
|
+
|
|
305
|
+
continue
|
|
306
|
+
|
|
307
|
+
if isinstance(value, bool):
|
|
308
|
+
continue
|
|
309
|
+
|
|
310
|
+
raise ValueError("Query parameters must contain only SQLite scalar values.")
|
|
311
|
+
|
|
312
|
+
return params
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _open_connection(
|
|
316
|
+
db_path: str | Path,
|
|
317
|
+
*,
|
|
318
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
319
|
+
max_vm_steps: int = DEFAULT_MAX_VM_STEPS,
|
|
320
|
+
) -> sqlite3.Connection:
|
|
321
|
+
"""Open an existing database in read-only mode with execution limits."""
|
|
322
|
+
path = Path(db_path).expanduser().resolve(strict=True)
|
|
323
|
+
|
|
324
|
+
if not path.is_file():
|
|
325
|
+
raise FileNotFoundError("Database path is not a regular file.")
|
|
326
|
+
|
|
327
|
+
encoded_path = quote(path.as_posix(), safe="/:\\")
|
|
328
|
+
|
|
329
|
+
connection = sqlite3.connect(
|
|
330
|
+
f"file:{encoded_path}?mode=ro",
|
|
331
|
+
uri=True,
|
|
332
|
+
timeout=timeout_seconds,
|
|
333
|
+
isolation_level=None,
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
connection.row_factory = sqlite3.Row
|
|
337
|
+
|
|
338
|
+
try:
|
|
339
|
+
connection.execute("PRAGMA query_only = ON")
|
|
340
|
+
connection.execute("PRAGMA trusted_schema = OFF")
|
|
341
|
+
|
|
342
|
+
if hasattr(connection, "setlimit"):
|
|
343
|
+
limits = (
|
|
344
|
+
("SQLITE_LIMIT_LENGTH", 1_000_000),
|
|
345
|
+
("SQLITE_LIMIT_SQL_LENGTH", MAX_SQL_LENGTH),
|
|
346
|
+
("SQLITE_LIMIT_EXPR_DEPTH", 100),
|
|
347
|
+
("SQLITE_LIMIT_COMPOUND_SELECT", 10),
|
|
348
|
+
("SQLITE_LIMIT_ATTACHED", 0),
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
for name, value in limits:
|
|
352
|
+
limit_id = getattr(sqlite3, name, None)
|
|
353
|
+
|
|
354
|
+
if limit_id is not None:
|
|
355
|
+
connection.setlimit(limit_id, value)
|
|
356
|
+
|
|
357
|
+
started = time.monotonic()
|
|
358
|
+
vm_interval = 1_000
|
|
359
|
+
vm_calls = 0
|
|
360
|
+
|
|
361
|
+
def progress() -> int:
|
|
362
|
+
nonlocal vm_calls
|
|
363
|
+
vm_calls += 1
|
|
364
|
+
|
|
365
|
+
time_exceeded = time.monotonic() - started > timeout_seconds
|
|
366
|
+
steps_exceeded = vm_calls * vm_interval >= max_vm_steps
|
|
367
|
+
|
|
368
|
+
return int(time_exceeded or steps_exceeded)
|
|
369
|
+
|
|
370
|
+
connection.set_progress_handler(progress, vm_interval)
|
|
371
|
+
connection.set_authorizer(_authorize)
|
|
372
|
+
|
|
373
|
+
return connection
|
|
374
|
+
|
|
375
|
+
except Exception:
|
|
376
|
+
connection.close()
|
|
377
|
+
raise
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _json_safe(value: Any) -> Any:
|
|
381
|
+
"""Convert SQLite values into bounded JSON-compatible values."""
|
|
382
|
+
if value is None or isinstance(value, (str, int, bool)):
|
|
383
|
+
if isinstance(value, str) and len(value) > MAX_CELL_TEXT:
|
|
384
|
+
return value[:MAX_CELL_TEXT] + "…[truncated]"
|
|
385
|
+
return value
|
|
386
|
+
|
|
387
|
+
if isinstance(value, float):
|
|
388
|
+
return value if math.isfinite(value) else None
|
|
389
|
+
|
|
390
|
+
if isinstance(value, bytes):
|
|
391
|
+
sample = value[:MAX_BLOB_BYTES]
|
|
392
|
+
|
|
393
|
+
return {
|
|
394
|
+
"type": "blob",
|
|
395
|
+
"byte_length": len(value),
|
|
396
|
+
"base64": base64.b64encode(sample).decode("ascii"),
|
|
397
|
+
"truncated": len(value) > MAX_BLOB_BYTES,
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return str(value)[:MAX_CELL_TEXT]
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _error(message: str, code: str) -> dict[str, Any]:
|
|
404
|
+
"""Build a consistent, non-sensitive error response."""
|
|
405
|
+
return {
|
|
406
|
+
"ok": False,
|
|
407
|
+
"error": message,
|
|
408
|
+
"code": code,
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _serialized_size(payload: dict[str, Any]) -> int:
|
|
413
|
+
"""Return the UTF-8 serialized JSON size of a response."""
|
|
414
|
+
return len(
|
|
415
|
+
json.dumps(
|
|
416
|
+
payload,
|
|
417
|
+
ensure_ascii=False,
|
|
418
|
+
separators=(",", ":"),
|
|
419
|
+
).encode("utf-8")
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _bounded_result(
|
|
424
|
+
columns: list[str],
|
|
425
|
+
rows: list[dict[str, Any]],
|
|
426
|
+
truncated: bool,
|
|
427
|
+
elapsed_ms: float,
|
|
428
|
+
) -> dict[str, Any]:
|
|
429
|
+
"""Build a response within the configured column and byte limits."""
|
|
430
|
+
original_columns = columns[:MAX_COLUMNS]
|
|
431
|
+
limited_columns = [name[:256] for name in original_columns]
|
|
432
|
+
column_names = dict(zip(original_columns, limited_columns, strict=False))
|
|
433
|
+
|
|
434
|
+
columns_truncated = len(columns) > MAX_COLUMNS
|
|
435
|
+
|
|
436
|
+
safe_rows = [
|
|
437
|
+
{column_names[key]: _json_safe(value) for key, value in row.items() if key in column_names}
|
|
438
|
+
for row in rows
|
|
439
|
+
]
|
|
440
|
+
|
|
441
|
+
payload: dict[str, Any] = {
|
|
442
|
+
"ok": True,
|
|
443
|
+
"columns": limited_columns,
|
|
444
|
+
"rows": safe_rows,
|
|
445
|
+
"row_count": len(safe_rows),
|
|
446
|
+
"truncated": truncated,
|
|
447
|
+
"columns_truncated": columns_truncated,
|
|
448
|
+
"elapsed_ms": elapsed_ms,
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
while safe_rows and _serialized_size(payload) > MAX_RESULT_BYTES:
|
|
452
|
+
safe_rows.pop()
|
|
453
|
+
payload["row_count"] = len(safe_rows)
|
|
454
|
+
payload["truncated"] = True
|
|
455
|
+
|
|
456
|
+
if _serialized_size(payload) > MAX_RESULT_BYTES:
|
|
457
|
+
payload["rows"] = []
|
|
458
|
+
payload["row_count"] = 0
|
|
459
|
+
payload["truncated"] = True
|
|
460
|
+
payload["columns_truncated"] = True
|
|
461
|
+
payload["warning"] = "The result exceeded the maximum response size and was omitted."
|
|
462
|
+
|
|
463
|
+
return payload
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def execute_guarded_query(
|
|
467
|
+
db_path: str | Path,
|
|
468
|
+
sql: str,
|
|
469
|
+
params: dict[str, Any] | list[Any] | tuple[Any, ...] | None = None,
|
|
470
|
+
*,
|
|
471
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
472
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
473
|
+
max_vm_steps: int = DEFAULT_MAX_VM_STEPS,
|
|
474
|
+
_allow_explain_plan: bool = False,
|
|
475
|
+
) -> dict[str, Any]:
|
|
476
|
+
"""Execute one parameterized, read-only SQL statement."""
|
|
477
|
+
if not 1 <= max_rows <= MAX_ROWS_HARD_LIMIT:
|
|
478
|
+
return _error(
|
|
479
|
+
f"max_rows must be between 1 and {MAX_ROWS_HARD_LIMIT}.",
|
|
480
|
+
"invalid_limit",
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
if not 0.05 <= timeout_seconds <= 60:
|
|
484
|
+
return _error(
|
|
485
|
+
"timeout_seconds must be between 0.05 and 60.",
|
|
486
|
+
"invalid_limit",
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
if not 1_000 <= max_vm_steps <= 100_000_000:
|
|
490
|
+
return _error(
|
|
491
|
+
"max_vm_steps is outside the permitted range.",
|
|
492
|
+
"invalid_limit",
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
try:
|
|
496
|
+
statement = _validate_query(
|
|
497
|
+
sql,
|
|
498
|
+
allow_explain_plan=_allow_explain_plan,
|
|
499
|
+
)
|
|
500
|
+
bindings = _validate_params(params)
|
|
501
|
+
|
|
502
|
+
except ValueError as exc:
|
|
503
|
+
return _error(str(exc), "invalid_input")
|
|
504
|
+
|
|
505
|
+
try:
|
|
506
|
+
connection = _open_connection(
|
|
507
|
+
db_path,
|
|
508
|
+
timeout_seconds=timeout_seconds,
|
|
509
|
+
max_vm_steps=max_vm_steps,
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
except FileNotFoundError:
|
|
513
|
+
return _error(
|
|
514
|
+
"Database file was not found or is not a regular file.",
|
|
515
|
+
"database_not_found",
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
except (sqlite3.Error, OSError, RuntimeError):
|
|
519
|
+
return _error(
|
|
520
|
+
"Could not open the database in read-only mode.",
|
|
521
|
+
"database_open_failed",
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
started = time.perf_counter()
|
|
525
|
+
|
|
526
|
+
try:
|
|
527
|
+
cursor = connection.execute(statement, bindings)
|
|
528
|
+
fetched = cursor.fetchmany(max_rows + 1)
|
|
529
|
+
|
|
530
|
+
was_truncated = len(fetched) > max_rows
|
|
531
|
+
selected = fetched[:max_rows]
|
|
532
|
+
|
|
533
|
+
columns = [item[0] for item in (cursor.description or [])]
|
|
534
|
+
|
|
535
|
+
rows = [dict(row) for row in selected]
|
|
536
|
+
|
|
537
|
+
elapsed = round(
|
|
538
|
+
(time.perf_counter() - started) * 1000,
|
|
539
|
+
3,
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
return _bounded_result(
|
|
543
|
+
columns,
|
|
544
|
+
rows,
|
|
545
|
+
was_truncated,
|
|
546
|
+
elapsed,
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
except sqlite3.OperationalError as exc:
|
|
550
|
+
reason = str(exc).casefold()
|
|
551
|
+
|
|
552
|
+
if "not authorized" in reason or "prohibited" in reason:
|
|
553
|
+
return _error(
|
|
554
|
+
"The SQLite authorizer blocked this operation.",
|
|
555
|
+
"blocked_operation",
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
if "interrupted" in reason:
|
|
559
|
+
return _error(
|
|
560
|
+
"The query exceeded its execution budget.",
|
|
561
|
+
"query_budget_exceeded",
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
return _error(
|
|
565
|
+
f"SQLite could not execute this query: {exc}",
|
|
566
|
+
"query_failed",
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
except sqlite3.ProgrammingError as exc:
|
|
570
|
+
reason = str(exc).casefold()
|
|
571
|
+
if "one statement" in reason:
|
|
572
|
+
return _error(
|
|
573
|
+
"Only a single SQL statement can be executed at a time.",
|
|
574
|
+
"invalid_input",
|
|
575
|
+
)
|
|
576
|
+
return _error(
|
|
577
|
+
f"SQLite parameter error: {exc}",
|
|
578
|
+
"invalid_input",
|
|
579
|
+
)
|
|
580
|
+
|
|
581
|
+
except sqlite3.Error as exc:
|
|
582
|
+
return _error(
|
|
583
|
+
f"SQLite could not execute this query: {exc}",
|
|
584
|
+
"query_failed",
|
|
585
|
+
)
|
|
586
|
+
|
|
587
|
+
finally:
|
|
588
|
+
connection.close()
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def list_tables(
|
|
592
|
+
db_path: str | Path,
|
|
593
|
+
*,
|
|
594
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
595
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
596
|
+
max_vm_steps: int = DEFAULT_MAX_VM_STEPS,
|
|
597
|
+
) -> dict[str, Any]:
|
|
598
|
+
"""List user-created tables and views."""
|
|
599
|
+
return execute_guarded_query(
|
|
600
|
+
db_path,
|
|
601
|
+
(
|
|
602
|
+
"SELECT name, type FROM sqlite_schema "
|
|
603
|
+
"WHERE type IN ('table', 'view') "
|
|
604
|
+
"AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
605
|
+
),
|
|
606
|
+
max_rows=max_rows,
|
|
607
|
+
timeout_seconds=timeout_seconds,
|
|
608
|
+
max_vm_steps=max_vm_steps,
|
|
609
|
+
)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _quote_identifier(identifier: str) -> str:
|
|
613
|
+
"""Safely quote a SQLite identifier."""
|
|
614
|
+
if (
|
|
615
|
+
not isinstance(identifier, str)
|
|
616
|
+
or not identifier
|
|
617
|
+
or len(identifier) > 256
|
|
618
|
+
or "\x00" in identifier
|
|
619
|
+
):
|
|
620
|
+
raise ValueError("Table name must contain 1–256 non-NUL characters.")
|
|
621
|
+
|
|
622
|
+
return '"' + identifier.replace('"', '""') + '"'
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def describe_table(
|
|
626
|
+
db_path: str | Path,
|
|
627
|
+
table_name: str,
|
|
628
|
+
*,
|
|
629
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
630
|
+
max_vm_steps: int = DEFAULT_MAX_VM_STEPS,
|
|
631
|
+
) -> dict[str, Any]:
|
|
632
|
+
"""Return table columns, indexes, foreign keys, and masking metadata."""
|
|
633
|
+
try:
|
|
634
|
+
quoted_table = _quote_identifier(table_name)
|
|
635
|
+
|
|
636
|
+
except ValueError as exc:
|
|
637
|
+
return _error(str(exc), "invalid_table_name")
|
|
638
|
+
|
|
639
|
+
try:
|
|
640
|
+
connection = _open_connection(
|
|
641
|
+
db_path,
|
|
642
|
+
timeout_seconds=timeout_seconds,
|
|
643
|
+
max_vm_steps=max_vm_steps,
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
except FileNotFoundError:
|
|
647
|
+
return _error(
|
|
648
|
+
"Database file was not found or is not a regular file.",
|
|
649
|
+
"database_not_found",
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
except (sqlite3.Error, OSError, RuntimeError):
|
|
653
|
+
return _error(
|
|
654
|
+
"Could not open the database in read-only mode.",
|
|
655
|
+
"database_open_failed",
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
try:
|
|
659
|
+
columns = [dict(row) for row in connection.execute(f"PRAGMA table_xinfo({quoted_table})")][
|
|
660
|
+
:MAX_COLUMNS
|
|
661
|
+
]
|
|
662
|
+
|
|
663
|
+
if not columns:
|
|
664
|
+
return _error(
|
|
665
|
+
"The requested table or view does not exist.",
|
|
666
|
+
"table_not_found",
|
|
667
|
+
)
|
|
668
|
+
|
|
669
|
+
for column in columns:
|
|
670
|
+
column["masked_by_guard"] = _is_sensitive_column(str(column.get("name", "")))
|
|
671
|
+
|
|
672
|
+
indexes = []
|
|
673
|
+
|
|
674
|
+
index_rows = list(connection.execute(f"PRAGMA index_list({quoted_table})"))[:MAX_COLUMNS]
|
|
675
|
+
|
|
676
|
+
for index in index_rows:
|
|
677
|
+
item = dict(index)
|
|
678
|
+
quoted_index = _quote_identifier(str(item["name"]))
|
|
679
|
+
|
|
680
|
+
item["columns"] = [
|
|
681
|
+
dict(row) for row in connection.execute(f"PRAGMA index_xinfo({quoted_index})")
|
|
682
|
+
]
|
|
683
|
+
|
|
684
|
+
indexes.append(item)
|
|
685
|
+
|
|
686
|
+
foreign_keys = [
|
|
687
|
+
dict(row)
|
|
688
|
+
for row in list(connection.execute(f"PRAGMA foreign_key_list({quoted_table})"))[
|
|
689
|
+
:MAX_COLUMNS
|
|
690
|
+
]
|
|
691
|
+
]
|
|
692
|
+
|
|
693
|
+
return {
|
|
694
|
+
"ok": True,
|
|
695
|
+
"table": table_name,
|
|
696
|
+
"columns": columns,
|
|
697
|
+
"indexes": indexes,
|
|
698
|
+
"foreign_keys": foreign_keys,
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
except sqlite3.Error:
|
|
702
|
+
return _error(
|
|
703
|
+
"SQLite could not inspect this table's schema.",
|
|
704
|
+
"schema_inspection_failed",
|
|
705
|
+
)
|
|
706
|
+
|
|
707
|
+
finally:
|
|
708
|
+
connection.close()
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def explain_query(
|
|
712
|
+
db_path: str | Path,
|
|
713
|
+
sql: str,
|
|
714
|
+
params: dict[str, Any] | list[Any] | tuple[Any, ...] | None = None,
|
|
715
|
+
*,
|
|
716
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
717
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
718
|
+
max_vm_steps: int = DEFAULT_MAX_VM_STEPS,
|
|
719
|
+
) -> dict[str, Any]:
|
|
720
|
+
"""Return SQLite's query plan for a SELECT or WITH query."""
|
|
721
|
+
try:
|
|
722
|
+
statement = _validate_query(sql, explain=True)
|
|
723
|
+
|
|
724
|
+
except ValueError as exc:
|
|
725
|
+
return _error(str(exc), "invalid_input")
|
|
726
|
+
|
|
727
|
+
return execute_guarded_query(
|
|
728
|
+
db_path,
|
|
729
|
+
statement,
|
|
730
|
+
params,
|
|
731
|
+
max_rows=max_rows,
|
|
732
|
+
timeout_seconds=timeout_seconds,
|
|
733
|
+
max_vm_steps=max_vm_steps,
|
|
734
|
+
_allow_explain_plan=True,
|
|
735
|
+
)
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def create_server(
|
|
739
|
+
db_path: str | Path,
|
|
740
|
+
*,
|
|
741
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
742
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
|
|
743
|
+
max_vm_steps: int = DEFAULT_MAX_VM_STEPS,
|
|
744
|
+
) -> Any:
|
|
745
|
+
"""Create the official MCP SDK server with SQLite Guard tools and schema resources."""
|
|
746
|
+
from mcp.server.mcpserver import MCPServer
|
|
747
|
+
|
|
748
|
+
database = Path(db_path).expanduser()
|
|
749
|
+
|
|
750
|
+
server = MCPServer(
|
|
751
|
+
"sqlite-guard-mcp",
|
|
752
|
+
version=__version__,
|
|
753
|
+
instructions=(
|
|
754
|
+
"Inspect the configured SQLite database using read-only tools. "
|
|
755
|
+
"Sensitive credential columns are masked as NULL. "
|
|
756
|
+
"Never claim masked values were retrieved. "
|
|
757
|
+
"Use parameterized SQL for user-provided values."
|
|
758
|
+
),
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
@server.tool()
|
|
762
|
+
def read_query(
|
|
763
|
+
sql: Annotated[
|
|
764
|
+
str,
|
|
765
|
+
Field(description="Read-only SELECT, WITH, or VALUES SQL query to execute."),
|
|
766
|
+
],
|
|
767
|
+
params: Annotated[
|
|
768
|
+
dict[str, Any] | list[Any] | None,
|
|
769
|
+
Field(
|
|
770
|
+
default=None,
|
|
771
|
+
description=(
|
|
772
|
+
"Optional query parameters as a list for positional ? placeholders, "
|
|
773
|
+
"or dict for named (:name, $name) placeholders."
|
|
774
|
+
),
|
|
775
|
+
),
|
|
776
|
+
] = None,
|
|
777
|
+
) -> str:
|
|
778
|
+
"""Run a read-only SELECT, WITH, or VALUES query with bound parameters."""
|
|
779
|
+
result = execute_guarded_query(
|
|
780
|
+
database,
|
|
781
|
+
sql,
|
|
782
|
+
params,
|
|
783
|
+
max_rows=max_rows,
|
|
784
|
+
timeout_seconds=timeout_seconds,
|
|
785
|
+
max_vm_steps=max_vm_steps,
|
|
786
|
+
)
|
|
787
|
+
return json.dumps(result, ensure_ascii=False)
|
|
788
|
+
|
|
789
|
+
@server.tool()
|
|
790
|
+
def list_database_tables() -> str:
|
|
791
|
+
"""List user-created tables and views in the database."""
|
|
792
|
+
result = list_tables(
|
|
793
|
+
database,
|
|
794
|
+
max_rows=max_rows,
|
|
795
|
+
timeout_seconds=timeout_seconds,
|
|
796
|
+
max_vm_steps=max_vm_steps,
|
|
797
|
+
)
|
|
798
|
+
return json.dumps(result, ensure_ascii=False)
|
|
799
|
+
|
|
800
|
+
@server.tool()
|
|
801
|
+
def describe_database_table(
|
|
802
|
+
table_name: Annotated[
|
|
803
|
+
str,
|
|
804
|
+
Field(description="The name of the database table or view to inspect."),
|
|
805
|
+
],
|
|
806
|
+
) -> str:
|
|
807
|
+
"""Inspect a table's schema, indexes, foreign keys, and masking metadata."""
|
|
808
|
+
result = describe_table(
|
|
809
|
+
database,
|
|
810
|
+
table_name,
|
|
811
|
+
timeout_seconds=timeout_seconds,
|
|
812
|
+
max_vm_steps=max_vm_steps,
|
|
813
|
+
)
|
|
814
|
+
return json.dumps(result, ensure_ascii=False)
|
|
815
|
+
|
|
816
|
+
@server.tool()
|
|
817
|
+
def explain_read_query(
|
|
818
|
+
sql: Annotated[
|
|
819
|
+
str,
|
|
820
|
+
Field(description="Read-only SELECT, WITH, or VALUES SQL query to explain."),
|
|
821
|
+
],
|
|
822
|
+
params: Annotated[
|
|
823
|
+
dict[str, Any] | list[Any] | None,
|
|
824
|
+
Field(
|
|
825
|
+
default=None,
|
|
826
|
+
description=(
|
|
827
|
+
"Optional query parameters as a list for positional ? placeholders, "
|
|
828
|
+
"or dict for named placeholders."
|
|
829
|
+
),
|
|
830
|
+
),
|
|
831
|
+
] = None,
|
|
832
|
+
) -> str:
|
|
833
|
+
"""Explain the query plan (EXPLAIN QUERY PLAN) for a read-only query."""
|
|
834
|
+
result = explain_query(
|
|
835
|
+
database,
|
|
836
|
+
sql,
|
|
837
|
+
params,
|
|
838
|
+
max_rows=max_rows,
|
|
839
|
+
timeout_seconds=timeout_seconds,
|
|
840
|
+
max_vm_steps=max_vm_steps,
|
|
841
|
+
)
|
|
842
|
+
return json.dumps(result, ensure_ascii=False)
|
|
843
|
+
|
|
844
|
+
@server.resource("schema://summary")
|
|
845
|
+
def database_schema_summary() -> str:
|
|
846
|
+
"""Provide a summary of all user-created tables, views, and column definitions."""
|
|
847
|
+
tables_res = list_tables(
|
|
848
|
+
database,
|
|
849
|
+
max_rows=MAX_ROWS_HARD_LIMIT,
|
|
850
|
+
timeout_seconds=timeout_seconds,
|
|
851
|
+
max_vm_steps=max_vm_steps,
|
|
852
|
+
)
|
|
853
|
+
if not tables_res.get("ok"):
|
|
854
|
+
return json.dumps(tables_res, ensure_ascii=False)
|
|
855
|
+
|
|
856
|
+
summary: dict[str, Any] = {"tables": {}}
|
|
857
|
+
for row in tables_res.get("rows", []):
|
|
858
|
+
name = row.get("name")
|
|
859
|
+
if name:
|
|
860
|
+
table_info = describe_table(
|
|
861
|
+
database,
|
|
862
|
+
name,
|
|
863
|
+
timeout_seconds=timeout_seconds,
|
|
864
|
+
max_vm_steps=max_vm_steps,
|
|
865
|
+
)
|
|
866
|
+
if table_info.get("ok"):
|
|
867
|
+
summary["tables"][name] = {
|
|
868
|
+
"type": row.get("type"),
|
|
869
|
+
"columns": [
|
|
870
|
+
{
|
|
871
|
+
"name": col.get("name"),
|
|
872
|
+
"type": col.get("type"),
|
|
873
|
+
"pk": bool(col.get("pk")),
|
|
874
|
+
"masked": col.get("masked_by_guard", False),
|
|
875
|
+
}
|
|
876
|
+
for col in table_info.get("columns", [])
|
|
877
|
+
],
|
|
878
|
+
}
|
|
879
|
+
return json.dumps(summary, ensure_ascii=False)
|
|
880
|
+
|
|
881
|
+
return server
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def main(argv: list[str] | None = None) -> int:
|
|
885
|
+
"""Run the SQLite Guard MCP server over standard input/output."""
|
|
886
|
+
parser = argparse.ArgumentParser(
|
|
887
|
+
prog="sqlite-guard-mcp",
|
|
888
|
+
description="Read-only, security-hardened SQLite MCP server.",
|
|
889
|
+
)
|
|
890
|
+
parser.add_argument(
|
|
891
|
+
"-v",
|
|
892
|
+
"--version",
|
|
893
|
+
action="version",
|
|
894
|
+
version=f"%(prog)s {__version__}",
|
|
895
|
+
)
|
|
896
|
+
parser.add_argument(
|
|
897
|
+
"--db",
|
|
898
|
+
default=os.environ.get("SQLITE_GUARD_DB"),
|
|
899
|
+
help="Path to an existing SQLite database.",
|
|
900
|
+
)
|
|
901
|
+
parser.add_argument(
|
|
902
|
+
"--max-rows",
|
|
903
|
+
type=int,
|
|
904
|
+
default=DEFAULT_MAX_ROWS,
|
|
905
|
+
help="Maximum rows returned per query.",
|
|
906
|
+
)
|
|
907
|
+
parser.add_argument(
|
|
908
|
+
"--timeout",
|
|
909
|
+
type=float,
|
|
910
|
+
default=DEFAULT_TIMEOUT_SECONDS,
|
|
911
|
+
help="Maximum query execution time in seconds.",
|
|
912
|
+
)
|
|
913
|
+
parser.add_argument(
|
|
914
|
+
"--max-vm-steps",
|
|
915
|
+
type=int,
|
|
916
|
+
default=DEFAULT_MAX_VM_STEPS,
|
|
917
|
+
help="Maximum SQLite virtual-machine steps.",
|
|
918
|
+
)
|
|
919
|
+
parser.add_argument(
|
|
920
|
+
"--transport",
|
|
921
|
+
choices=["stdio", "sse", "streamable-http"],
|
|
922
|
+
default="stdio",
|
|
923
|
+
help="MCP transport to run (default: stdio).",
|
|
924
|
+
)
|
|
925
|
+
|
|
926
|
+
args = parser.parse_args(argv)
|
|
927
|
+
|
|
928
|
+
if not args.db:
|
|
929
|
+
parser.error("Provide --db or set the SQLITE_GUARD_DB environment variable.")
|
|
930
|
+
|
|
931
|
+
if not 1 <= args.max_rows <= MAX_ROWS_HARD_LIMIT:
|
|
932
|
+
parser.error(f"--max-rows must be between 1 and {MAX_ROWS_HARD_LIMIT}.")
|
|
933
|
+
|
|
934
|
+
if not 0.05 <= args.timeout <= 60:
|
|
935
|
+
parser.error("--timeout must be between 0.05 and 60 seconds.")
|
|
936
|
+
|
|
937
|
+
if not 1_000 <= args.max_vm_steps <= 100_000_000:
|
|
938
|
+
parser.error("--max-vm-steps is outside the permitted range.")
|
|
939
|
+
|
|
940
|
+
try:
|
|
941
|
+
database = Path(args.db).expanduser().resolve(strict=True)
|
|
942
|
+
except (OSError, RuntimeError):
|
|
943
|
+
parser.error("The configured database path does not exist.")
|
|
944
|
+
|
|
945
|
+
if not database.is_file():
|
|
946
|
+
parser.error("The configured database path is not a regular file.")
|
|
947
|
+
|
|
948
|
+
server = create_server(
|
|
949
|
+
database,
|
|
950
|
+
max_rows=args.max_rows,
|
|
951
|
+
timeout_seconds=args.timeout,
|
|
952
|
+
max_vm_steps=args.max_vm_steps,
|
|
953
|
+
)
|
|
954
|
+
try:
|
|
955
|
+
server.run(transport=args.transport)
|
|
956
|
+
except (KeyboardInterrupt, EOFError):
|
|
957
|
+
pass
|
|
958
|
+
return 0
|
|
959
|
+
|
|
960
|
+
|
|
961
|
+
if __name__ == "__main__":
|
|
962
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sqlite-guard-mcp
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A read-only, security-hardened SQLite MCP server for local AI agents.
|
|
5
|
+
Project-URL: Homepage, https://github.com/AtharvaSiddhawar/sqlite-guard-mcp
|
|
6
|
+
Project-URL: Repository, https://github.com/AtharvaSiddhawar/sqlite-guard-mcp
|
|
7
|
+
Project-URL: Issues, https://github.com/AtharvaSiddhawar/sqlite-guard-mcp/issues
|
|
8
|
+
Author: Atharva Siddhawar
|
|
9
|
+
License: MIT License
|
|
10
|
+
|
|
11
|
+
Copyright (c) 2026 Atharva Siddhawar
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
14
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
15
|
+
in the Software without restriction, including without limitation the rights
|
|
16
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
17
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
18
|
+
furnished to do so, subject to the following conditions:
|
|
19
|
+
|
|
20
|
+
The above copyright notice and this permission notice shall be included in all
|
|
21
|
+
copies or substantial portions of the Software.
|
|
22
|
+
|
|
23
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
24
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
26
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
27
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
|
+
SOFTWARE.
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Keywords: ai-agents,mcp,model-context-protocol,read-only,security,sqlite
|
|
32
|
+
Classifier: Development Status :: 4 - Beta
|
|
33
|
+
Classifier: Intended Audience :: Developers
|
|
34
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
35
|
+
Classifier: Operating System :: OS Independent
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
40
|
+
Classifier: Topic :: Database
|
|
41
|
+
Classifier: Topic :: Security
|
|
42
|
+
Requires-Python: >=3.11
|
|
43
|
+
Requires-Dist: mcp<3,>=2.3
|
|
44
|
+
Provides-Extra: dev
|
|
45
|
+
Requires-Dist: anyio>=4.0; extra == 'dev'
|
|
46
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
47
|
+
Requires-Dist: pytest-cov>=6.0; extra == 'dev'
|
|
48
|
+
Requires-Dist: pytest>=8.3; extra == 'dev'
|
|
49
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
50
|
+
Description-Content-Type: text/markdown
|
|
51
|
+
|
|
52
|
+
# SQLite Guard MCP
|
|
53
|
+
|
|
54
|
+
[](https://github.com/AtharvaSiddhawar/sqlite-guard-mcp/actions/workflows/ci.yml)
|
|
55
|
+
[](https://www.python.org/)
|
|
56
|
+
[](LICENSE)
|
|
57
|
+
|
|
58
|
+
A read-only, security-hardened [Model Context Protocol](https://modelcontextprotocol.io/) server for inspecting local SQLite databases. It leverages the official MCP Python SDK, SQLite's read-only URI mode, native SQLite authorizer enforcement, bounded query execution, and heuristic masking for sensitive columns and credentials.
|
|
59
|
+
|
|
60
|
+
> **Security note:** This is defense in depth, not an operating-system sandbox. The process can read any database file its operating-system account can access and that the operator configures. Column-name masking is heuristic and is not a substitute for database-level access controls. See [SECURITY.md](SECURITY.md).
|
|
61
|
+
|
|
62
|
+
## Features
|
|
63
|
+
|
|
64
|
+
- Standard MCP transports (`stdio`, `sse`, and `streamable-http`) through the official MCP Python SDK.
|
|
65
|
+
- Read-only `SELECT`, `WITH`, and `VALUES` queries with bound parameters.
|
|
66
|
+
- Built-in schema inspection: separate tools for listing tables, describing schemas, and explaining query plans.
|
|
67
|
+
- MCP Resource support: `schema://summary` provides zero-turn inspection of tables and schemas.
|
|
68
|
+
- Rich parameter schemas with docstrings and descriptions for LLM agents.
|
|
69
|
+
- SQLite authorizer strictly denies write operations, database attachments, dangerous functions (`load_extension`, `readfile`, `writefile`, `fsdir`, `eval`, etc.), and unapproved PRAGMAs.
|
|
70
|
+
- Sensitive credential columns (`password`, `api_key`, `access_key`, `secret`, `private_key`, `credit_card`, etc.) are masked as `NULL` at SQLite's authorizer boundary.
|
|
71
|
+
- Usage token metrics (`prompt_tokens`, `completion_tokens`, `total_tokens`, etc.) are explicitly preserved.
|
|
72
|
+
- Hard resource bounds: query timeout, SQLite VM-step budget, row cap, column cap, text cell length cap, and total response byte size cap.
|
|
73
|
+
- BLOB values are returned as bounded Base64 previews rather than raw byte dumps.
|
|
74
|
+
|
|
75
|
+
## Requirements
|
|
76
|
+
|
|
77
|
+
- Python 3.11 or newer.
|
|
78
|
+
- The package installs the official `mcp` SDK 2.x and `pydantic` automatically.
|
|
79
|
+
- An existing SQLite database file readable by the current operating-system account.
|
|
80
|
+
|
|
81
|
+
## Install from source
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
git clone https://github.com/AtharvaSiddhawar/sqlite-guard-mcp.git
|
|
85
|
+
cd sqlite-guard-mcp
|
|
86
|
+
python -m pip install .
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
For development:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
python -m pip install -e ".[dev]"
|
|
93
|
+
ruff check .
|
|
94
|
+
ruff format --check .
|
|
95
|
+
pytest --cov --cov-report=term-missing
|
|
96
|
+
python -m build
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Run
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
sqlite-guard-mcp --db "/absolute/path/to/database.sqlite"
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Optional limits and transport flags:
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
sqlite-guard-mcp --db "/path/to/database.sqlite" --max-rows 250 --timeout 2.0 --max-vm-steps 250000 --transport stdio
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
You can also set `SQLITE_GUARD_DB` and omit `--db`. Check version with `sqlite-guard-mcp --version`.
|
|
112
|
+
|
|
113
|
+
## MCP client configuration
|
|
114
|
+
|
|
115
|
+
Example Claude Desktop-style configuration (adjust the Python executable and database path for your computer):
|
|
116
|
+
|
|
117
|
+
```json
|
|
118
|
+
{
|
|
119
|
+
"mcpServers": {
|
|
120
|
+
"sqlite-guard": {
|
|
121
|
+
"command": "sqlite-guard-mcp",
|
|
122
|
+
"args": ["--db", "/absolute/path/to/database.sqlite"]
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
If the executable is not on the client's PATH, use the full path to the virtual environment's `sqlite-guard-mcp` executable.
|
|
129
|
+
|
|
130
|
+
## Tools
|
|
131
|
+
|
|
132
|
+
| Tool | Purpose |
|
|
133
|
+
|---|---|
|
|
134
|
+
| `read_query(sql, params?)` | Run one read-only `SELECT`, `WITH`, or `VALUES` query with bound parameters. |
|
|
135
|
+
| `list_database_tables()` | List user-defined tables and views. |
|
|
136
|
+
| `describe_database_table(table_name)` | Inspect columns, types, primary keys, indexes, foreign keys, and masking metadata. |
|
|
137
|
+
| `explain_read_query(sql, params?)` | Run `EXPLAIN QUERY PLAN` for a read-only query. |
|
|
138
|
+
|
|
139
|
+
`params` accepts a JSON object for named parameters or an array for positional parameters. Example: `{"sql":"SELECT name FROM people WHERE id = ?","params":[7]}`.
|
|
140
|
+
|
|
141
|
+
## Resources
|
|
142
|
+
|
|
143
|
+
| Resource URI | Purpose |
|
|
144
|
+
|---|---|
|
|
145
|
+
| `schema://summary` | Provides a complete JSON summary of all tables, views, and columns without requiring multiple tool calls. |
|
|
146
|
+
|
|
147
|
+
## Masking behavior
|
|
148
|
+
|
|
149
|
+
The authorizer masks common credential and secret columns such as `password`, `passwd`, `pwd`, `secret`, `api_key`, `access_key`, `auth_key`, `private_key`, `client_secret`, `ssn`, `social_security`, `credit_card`, `card_number`, `cvv`, `bank_account`, and session tokens.
|
|
150
|
+
|
|
151
|
+
Common usage metrics such as `prompt_tokens`, `completion_tokens`, `input_tokens`, `output_tokens`, and `total_tokens` are intentionally not masked. These rules are name-based heuristics: review your schema and do not rely on them as an absolute data-loss-prevention system.
|
|
152
|
+
|
|
153
|
+
## Limits and behavior
|
|
154
|
+
|
|
155
|
+
- `SELECT`, `WITH`, and `VALUES` queries are accepted; mutations and write CTEs are rejected.
|
|
156
|
+
- `explain_read_query` accepts read-only queries and prepends `EXPLAIN QUERY PLAN` safely.
|
|
157
|
+
- The default row limit is 250, with a hard limit of 1,000.
|
|
158
|
+
- Query execution is strictly bounded by wall-clock timeout and SQLite VM-step budget.
|
|
159
|
+
- Text cells (4 KB max), BLOB previews (4 KB max), columns (100 max), and total serialized response size (1 MB max) are capped.
|
|
160
|
+
- Multiple SQL statements in one call are rejected by SQLite's single-statement execution boundary.
|
|
161
|
+
|
|
162
|
+
## Skill instructions
|
|
163
|
+
|
|
164
|
+
The agent-facing usage guide is in [`SKILL.md`](SKILL.md).
|
|
165
|
+
|
|
166
|
+
## License
|
|
167
|
+
|
|
168
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
sqlite_guard_mcp/__init__.py,sha256=AmXWfJNP2m8jMMUZX0P3b43kobZhg-BJ_ZoOqFNHxZg,834
|
|
2
|
+
sqlite_guard_mcp/__main__.py,sha256=rzwAHPQnezq2NkOwachv6uEyFZcxE086g2R50_rU8tg,147
|
|
3
|
+
sqlite_guard_mcp/server.py,sha256=J3x-YrD2dYghXvO1qMYmWeHmaM9fCRqJpk9MKCuRuSg,27031
|
|
4
|
+
sqlite_guard_mcp-0.2.0.dist-info/METADATA,sha256=uOEQpz35QbqgPeVQ61v4FD77azvHFh6rijedzDgV61w,8036
|
|
5
|
+
sqlite_guard_mcp-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
sqlite_guard_mcp-0.2.0.dist-info/entry_points.txt,sha256=WNn12jrRLYrIaKKIk9U3ot6jKEYiHP0zk8kjuF7PI8U,66
|
|
7
|
+
sqlite_guard_mcp-0.2.0.dist-info/licenses/LICENSE,sha256=4tOuAYr737vK09B8fcjxxXOCR_dFjxtSFkatRTvCnEE,1074
|
|
8
|
+
sqlite_guard_mcp-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Atharva Siddhawar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|