sqlguard-mcp 0.1.0__tar.gz
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.
- sqlguard_mcp-0.1.0/LICENSE +21 -0
- sqlguard_mcp-0.1.0/PKG-INFO +86 -0
- sqlguard_mcp-0.1.0/README.md +71 -0
- sqlguard_mcp-0.1.0/pyproject.toml +45 -0
- sqlguard_mcp-0.1.0/pyproject.toml.orig +38 -0
- sqlguard_mcp-0.1.0/src/sqlguard_mcp/__init__.py +3 -0
- sqlguard_mcp-0.1.0/src/sqlguard_mcp/catalog.py +170 -0
- sqlguard_mcp-0.1.0/src/sqlguard_mcp/guard.py +130 -0
- sqlguard_mcp-0.1.0/src/sqlguard_mcp/py.typed +0 -0
- sqlguard_mcp-0.1.0/src/sqlguard_mcp/server.py +64 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kennywu411-dev
|
|
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.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sqlguard-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read-only SQLite MCP server with layered SQL defenses for AI agents
|
|
5
|
+
Keywords: mcp,sqlite,text-to-sql,llm,agent,security
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Topic :: Database
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Requires-Dist: mcp>=2.3
|
|
12
|
+
Requires-Dist: sqlglot>=30.24.0
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# sqlguard-mcp:只读 SQL 防护 MCP 服务器
|
|
17
|
+
|
|
18
|
+
[](https://github.com/kennywu411-dev/sqlguard-mcp/actions/workflows/ci.yml)
|
|
19
|
+
|
|
20
|
+
A read-only SQLite MCP server for AI agents. It lets Claude Code, Claude Desktop or any MCP client explore and query SQLite databases, and it is built so that a model cannot change your data even when it tries to.
|
|
21
|
+
|
|
22
|
+
It was extracted from [MetricLens](https://github.com/kennywu411-dev/metriclens), a text-to-SQL project evaluated on the BIRD Mini-Dev benchmark, where the same guard ran about 20,000 model-generated queries and a prompt-injection test.
|
|
23
|
+
|
|
24
|
+
## Why another SQLite server
|
|
25
|
+
|
|
26
|
+
The common reference SQLite server exposes write tools. For an agent that only needs to answer questions about data, that is more power than it should have. A read-only file mode alone is not enough either: SQLite still lets a read-only connection run `ATTACH`, most `PRAGMA`s and `CREATE TEMP TABLE`.
|
|
27
|
+
|
|
28
|
+
sqlguard-mcp stacks five layers:
|
|
29
|
+
|
|
30
|
+
1. Static check: sqlglot must parse the input as a single `SELECT` (CTEs and `UNION` included). Multiple statements and write nodes anywhere in the tree, such as `WITH t AS (...) DELETE ...`, are rejected.
|
|
31
|
+
2. Read-only connection: the database is opened with `mode=ro`, and a missing path is an error rather than a new empty file.
|
|
32
|
+
3. Authorizer: `sqlite3.set_authorizer` allows read actions and a few metadata pragmas only, so `ATTACH`, `PRAGMA writable_schema = 1` and temp tables are refused even if layer 1 is bypassed.
|
|
33
|
+
4. Timeout: a progress handler interrupts queries that run too long.
|
|
34
|
+
5. Row cap: results are fetched with a hard limit so a large table cannot flood the model's context.
|
|
35
|
+
|
|
36
|
+
SQL that sqlglot cannot parse is still passed to SQLite, so the agent gets SQLite's own error message and can correct itself; layers 2 and 3 still apply.
|
|
37
|
+
|
|
38
|
+
## Tools
|
|
39
|
+
|
|
40
|
+
| Tool | Purpose |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `list_databases` | db_id of every database (the file name without extension) |
|
|
43
|
+
| `list_tables` | tables and their column counts |
|
|
44
|
+
| `describe_table` | columns, types, primary and foreign keys, 3 sample rows |
|
|
45
|
+
| `search_values` | case-insensitive search of text columns, to find the value actually stored (the user says "female", the column holds `F`) |
|
|
46
|
+
| `run_sql` | runs one `SELECT`; errors come back as `{"error", "message"}` instead of failing the call |
|
|
47
|
+
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
Run it from PyPI with [uv](https://docs.astral.sh/uv/), or install it with `pip install sqlguard-mcp`:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
uvx sqlguard-mcp path/to/shop.db
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Or from a checkout, with more than one database and your own limits:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
uv run sqlguard-mcp path/to/shop.db path/to/folder_of_dbs --timeout 30 --max-rows 1000
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Add it to Claude Code:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
claude mcp add sqlguard -- uvx sqlguard-mcp /path/to/shop.db
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Inspect it with the MCP Inspector:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
npx @modelcontextprotocol/inspector uv run sqlguard-mcp /path/to/shop.db
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
uv sync
|
|
78
|
+
uv run pytest
|
|
79
|
+
uv run ruff check
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The tests include write attempts that bypass the static check, to show the connection layers hold on their own, plus a row of injected instructions stored in the data to show it comes back as plain data.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# sqlguard-mcp:只读 SQL 防护 MCP 服务器
|
|
2
|
+
|
|
3
|
+
[](https://github.com/kennywu411-dev/sqlguard-mcp/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
A read-only SQLite MCP server for AI agents. It lets Claude Code, Claude Desktop or any MCP client explore and query SQLite databases, and it is built so that a model cannot change your data even when it tries to.
|
|
6
|
+
|
|
7
|
+
It was extracted from [MetricLens](https://github.com/kennywu411-dev/metriclens), a text-to-SQL project evaluated on the BIRD Mini-Dev benchmark, where the same guard ran about 20,000 model-generated queries and a prompt-injection test.
|
|
8
|
+
|
|
9
|
+
## Why another SQLite server
|
|
10
|
+
|
|
11
|
+
The common reference SQLite server exposes write tools. For an agent that only needs to answer questions about data, that is more power than it should have. A read-only file mode alone is not enough either: SQLite still lets a read-only connection run `ATTACH`, most `PRAGMA`s and `CREATE TEMP TABLE`.
|
|
12
|
+
|
|
13
|
+
sqlguard-mcp stacks five layers:
|
|
14
|
+
|
|
15
|
+
1. Static check: sqlglot must parse the input as a single `SELECT` (CTEs and `UNION` included). Multiple statements and write nodes anywhere in the tree, such as `WITH t AS (...) DELETE ...`, are rejected.
|
|
16
|
+
2. Read-only connection: the database is opened with `mode=ro`, and a missing path is an error rather than a new empty file.
|
|
17
|
+
3. Authorizer: `sqlite3.set_authorizer` allows read actions and a few metadata pragmas only, so `ATTACH`, `PRAGMA writable_schema = 1` and temp tables are refused even if layer 1 is bypassed.
|
|
18
|
+
4. Timeout: a progress handler interrupts queries that run too long.
|
|
19
|
+
5. Row cap: results are fetched with a hard limit so a large table cannot flood the model's context.
|
|
20
|
+
|
|
21
|
+
SQL that sqlglot cannot parse is still passed to SQLite, so the agent gets SQLite's own error message and can correct itself; layers 2 and 3 still apply.
|
|
22
|
+
|
|
23
|
+
## Tools
|
|
24
|
+
|
|
25
|
+
| Tool | Purpose |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `list_databases` | db_id of every database (the file name without extension) |
|
|
28
|
+
| `list_tables` | tables and their column counts |
|
|
29
|
+
| `describe_table` | columns, types, primary and foreign keys, 3 sample rows |
|
|
30
|
+
| `search_values` | case-insensitive search of text columns, to find the value actually stored (the user says "female", the column holds `F`) |
|
|
31
|
+
| `run_sql` | runs one `SELECT`; errors come back as `{"error", "message"}` instead of failing the call |
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
Run it from PyPI with [uv](https://docs.astral.sh/uv/), or install it with `pip install sqlguard-mcp`:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
uvx sqlguard-mcp path/to/shop.db
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or from a checkout, with more than one database and your own limits:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
uv run sqlguard-mcp path/to/shop.db path/to/folder_of_dbs --timeout 30 --max-rows 1000
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Add it to Claude Code:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
claude mcp add sqlguard -- uvx sqlguard-mcp /path/to/shop.db
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Inspect it with the MCP Inspector:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npx @modelcontextprotocol/inspector uv run sqlguard-mcp /path/to/shop.db
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Development
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
uv sync
|
|
63
|
+
uv run pytest
|
|
64
|
+
uv run ruff check
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The tests include write attempts that bypass the static check, to show the connection layers hold on their own, plus a row of injected instructions stored in the data to show it comes back as plain data.
|
|
68
|
+
|
|
69
|
+
## License
|
|
70
|
+
|
|
71
|
+
MIT
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sqlguard-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Read-only SQLite MCP server with layered SQL defenses for AI agents"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
keywords = [
|
|
9
|
+
"mcp",
|
|
10
|
+
"sqlite",
|
|
11
|
+
"text-to-sql",
|
|
12
|
+
"llm",
|
|
13
|
+
"agent",
|
|
14
|
+
"security",
|
|
15
|
+
]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Database",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
]
|
|
21
|
+
requires-python = ">=3.12"
|
|
22
|
+
dependencies = [
|
|
23
|
+
"mcp>=2.3",
|
|
24
|
+
"sqlglot>=30.24.0",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
sqlguard-mcp = "sqlguard_mcp.server:main"
|
|
29
|
+
|
|
30
|
+
[build-system]
|
|
31
|
+
requires = ["uv_build>=0.13.0,<0.14.0"]
|
|
32
|
+
build-backend = "uv_build"
|
|
33
|
+
|
|
34
|
+
[dependency-groups]
|
|
35
|
+
dev = [
|
|
36
|
+
"pytest>=9.1.1",
|
|
37
|
+
"pytest-asyncio>=1.4.0",
|
|
38
|
+
"ruff>=0.17.2",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.pytest.ini_options]
|
|
42
|
+
asyncio_mode = "auto"
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 110
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sqlguard-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Read-only SQLite MCP server with layered SQL defenses for AI agents"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
keywords = ["mcp", "sqlite", "text-to-sql", "llm", "agent", "security"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Programming Language :: Python :: 3",
|
|
11
|
+
"Topic :: Database",
|
|
12
|
+
"Intended Audience :: Developers",
|
|
13
|
+
]
|
|
14
|
+
requires-python = ">=3.12"
|
|
15
|
+
dependencies = [
|
|
16
|
+
"mcp>=2.3",
|
|
17
|
+
"sqlglot>=30.24.0",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
sqlguard-mcp = "sqlguard_mcp.server:main"
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["uv_build>=0.13.0,<0.14.0"]
|
|
25
|
+
build-backend = "uv_build"
|
|
26
|
+
|
|
27
|
+
[dependency-groups]
|
|
28
|
+
dev = [
|
|
29
|
+
"pytest>=9.1.1",
|
|
30
|
+
"pytest-asyncio>=1.4.0",
|
|
31
|
+
"ruff>=0.17.2",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[tool.pytest.ini_options]
|
|
35
|
+
asyncio_mode = "auto"
|
|
36
|
+
|
|
37
|
+
[tool.ruff]
|
|
38
|
+
line-length = 110
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Database tools: discover tables, inspect schema, find real values, run SQL.
|
|
2
|
+
|
|
3
|
+
A Catalog maps db_id (the file stem) to SQLite files. Every call goes through a
|
|
4
|
+
read-only connection from guard.py.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sqlite3
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from sqlglot import exp
|
|
14
|
+
|
|
15
|
+
from sqlguard_mcp.guard import SQLRejected, connect_readonly, run_readonly
|
|
16
|
+
|
|
17
|
+
SAMPLE_ROWS = 3
|
|
18
|
+
MAX_CELL_CHARS = 200
|
|
19
|
+
SEARCH_TIMEOUT_S = 5.0
|
|
20
|
+
SQLITE_SUFFIXES = {".db", ".sqlite", ".sqlite3"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _q(name: str) -> str:
|
|
24
|
+
return exp.to_identifier(name, quoted=True).sql(dialect="sqlite")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _clip(value):
|
|
28
|
+
if isinstance(value, bytes):
|
|
29
|
+
return f"<{len(value)} bytes>"
|
|
30
|
+
if isinstance(value, str) and len(value) > MAX_CELL_CHARS:
|
|
31
|
+
return value[:MAX_CELL_CHARS] + "..."
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _escape_like(text: str) -> str:
|
|
36
|
+
return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_text(declared_type: str) -> bool:
|
|
40
|
+
t = (declared_type or "").upper()
|
|
41
|
+
return not t or any(k in t for k in ("CHAR", "TEXT", "CLOB"))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Catalog:
|
|
45
|
+
def __init__(self, paths: list[str | Path], timeout_s: float = 30.0, max_rows: int = 1000):
|
|
46
|
+
self.timeout_s = timeout_s
|
|
47
|
+
self.max_rows = max_rows
|
|
48
|
+
self.dbs: dict[str, Path] = {}
|
|
49
|
+
for p in map(Path, paths):
|
|
50
|
+
files = sorted(f for f in p.rglob("*") if f.suffix in SQLITE_SUFFIXES) if p.is_dir() else [p]
|
|
51
|
+
for f in files:
|
|
52
|
+
if not f.is_file():
|
|
53
|
+
raise FileNotFoundError(f)
|
|
54
|
+
if f.stem in self.dbs:
|
|
55
|
+
raise ValueError(f"duplicate db_id {f.stem!r}: {self.dbs[f.stem]} and {f}")
|
|
56
|
+
self.dbs[f.stem] = f.resolve()
|
|
57
|
+
if not self.dbs:
|
|
58
|
+
raise ValueError("no SQLite databases found")
|
|
59
|
+
|
|
60
|
+
def _db(self, db_id: str) -> Path:
|
|
61
|
+
try:
|
|
62
|
+
return self.dbs[db_id]
|
|
63
|
+
except KeyError:
|
|
64
|
+
raise ValueError(f"unknown db_id {db_id!r}; available: {sorted(self.dbs)}") from None
|
|
65
|
+
|
|
66
|
+
def _tables(self, conn: sqlite3.Connection) -> list[str]:
|
|
67
|
+
return [
|
|
68
|
+
r[0]
|
|
69
|
+
for r in conn.execute(
|
|
70
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
71
|
+
)
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
def _table(self, conn: sqlite3.Connection, table: str) -> str:
|
|
75
|
+
"""Resolve the table name case-insensitively; unknown names raise."""
|
|
76
|
+
by_lower = {t.lower(): t for t in self._tables(conn)}
|
|
77
|
+
try:
|
|
78
|
+
return by_lower[table.lower()]
|
|
79
|
+
except KeyError:
|
|
80
|
+
raise ValueError(f"unknown table {table!r}") from None
|
|
81
|
+
|
|
82
|
+
def list_databases(self) -> list[str]:
|
|
83
|
+
return sorted(self.dbs)
|
|
84
|
+
|
|
85
|
+
def list_tables(self, db_id: str) -> list[dict]:
|
|
86
|
+
conn = connect_readonly(self._db(db_id))
|
|
87
|
+
try:
|
|
88
|
+
return [
|
|
89
|
+
{"table": t, "columns": len(conn.execute(f"PRAGMA table_info({_q(t)})").fetchall())}
|
|
90
|
+
for t in self._tables(conn)
|
|
91
|
+
]
|
|
92
|
+
finally:
|
|
93
|
+
conn.close()
|
|
94
|
+
|
|
95
|
+
def describe_table(self, db_id: str, table: str) -> dict:
|
|
96
|
+
conn = connect_readonly(self._db(db_id))
|
|
97
|
+
try:
|
|
98
|
+
table = self._table(conn, table)
|
|
99
|
+
cols = conn.execute(f"PRAGMA table_info({_q(table)})").fetchall()
|
|
100
|
+
fks = conn.execute(f"PRAGMA foreign_key_list({_q(table)})").fetchall()
|
|
101
|
+
sample = conn.execute(f"SELECT * FROM {_q(table)} LIMIT {SAMPLE_ROWS}").fetchall()
|
|
102
|
+
finally:
|
|
103
|
+
conn.close()
|
|
104
|
+
return {
|
|
105
|
+
"table": table,
|
|
106
|
+
"columns": [{"name": c[1], "type": c[2], "primary_key": bool(c[5])} for c in cols],
|
|
107
|
+
"foreign_keys": [{"column": f[3], "ref_table": f[2], "ref_column": f[4]} for f in fks],
|
|
108
|
+
"sample_rows": [[_clip(v) for v in r] for r in sample],
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
def search_values(
|
|
112
|
+
self, db_id: str, keyword: str, table: str | None = None, column: str | None = None, limit: int = 10
|
|
113
|
+
) -> dict:
|
|
114
|
+
"""Case-insensitive LIKE search over text columns, to find the value actually
|
|
115
|
+
stored (the user says "female", the column holds 'F')."""
|
|
116
|
+
if not keyword:
|
|
117
|
+
raise ValueError("keyword must not be empty")
|
|
118
|
+
limit = max(1, min(limit, 100))
|
|
119
|
+
conn = connect_readonly(self._db(db_id))
|
|
120
|
+
try:
|
|
121
|
+
tables = [self._table(conn, table)] if table else self._tables(conn)
|
|
122
|
+
targets = []
|
|
123
|
+
for t in tables:
|
|
124
|
+
cols = conn.execute(f"PRAGMA table_info({_q(t)})").fetchall()
|
|
125
|
+
if column:
|
|
126
|
+
match = [c[1] for c in cols if c[1].lower() == column.lower()]
|
|
127
|
+
if not match:
|
|
128
|
+
raise ValueError(f"unknown column {t}.{column}")
|
|
129
|
+
targets.append((t, match[0]))
|
|
130
|
+
else:
|
|
131
|
+
targets += [(t, c[1]) for c in cols if _is_text(c[2])]
|
|
132
|
+
|
|
133
|
+
matches, skipped = [], []
|
|
134
|
+
deadline = time.monotonic() + SEARCH_TIMEOUT_S
|
|
135
|
+
conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 10_000)
|
|
136
|
+
for t, c in targets:
|
|
137
|
+
if len(matches) >= limit:
|
|
138
|
+
break
|
|
139
|
+
sql = (
|
|
140
|
+
f"SELECT DISTINCT {_q(c)} FROM {_q(t)} WHERE {_q(c)} LIKE ? ESCAPE '\\' "
|
|
141
|
+
f"LIMIT {limit - len(matches)}"
|
|
142
|
+
)
|
|
143
|
+
try:
|
|
144
|
+
rows = conn.execute(sql, (f"%{_escape_like(keyword)}%",)).fetchall()
|
|
145
|
+
except sqlite3.OperationalError: # timed out or a bad column: skip and report
|
|
146
|
+
skipped.append(f"{t}.{c}")
|
|
147
|
+
continue
|
|
148
|
+
matches += [{"table": t, "column": c, "value": _clip(r[0])} for r in rows]
|
|
149
|
+
finally:
|
|
150
|
+
conn.close()
|
|
151
|
+
return {"keyword": keyword, "matches": matches[:limit], "skipped": skipped}
|
|
152
|
+
|
|
153
|
+
def run_sql(self, db_id: str, sql: str, max_rows: int = 50) -> dict:
|
|
154
|
+
"""Errors are returned, not raised, so an agent can read them and fix its SQL."""
|
|
155
|
+
try:
|
|
156
|
+
res = run_readonly(
|
|
157
|
+
self._db(db_id), sql, timeout_s=self.timeout_s, max_rows=min(max(max_rows, 0), self.max_rows)
|
|
158
|
+
)
|
|
159
|
+
except SQLRejected as e:
|
|
160
|
+
return {"error": "rejected", "message": str(e)}
|
|
161
|
+
except TimeoutError as e:
|
|
162
|
+
return {"error": "timeout", "message": str(e)}
|
|
163
|
+
except sqlite3.Error as e:
|
|
164
|
+
return {"error": "sql_error", "message": str(e)}
|
|
165
|
+
return {
|
|
166
|
+
"columns": res.columns,
|
|
167
|
+
"rows": [[_clip(v) for v in r] for r in res.rows],
|
|
168
|
+
"truncated": res.truncated,
|
|
169
|
+
"elapsed_s": round(res.elapsed_s, 4),
|
|
170
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Read-only SQL execution with layered defenses.
|
|
2
|
+
|
|
3
|
+
1. Static check: sqlglot must parse the input as a single SELECT (WITH / UNION
|
|
4
|
+
included). Input sqlglot cannot parse is not rejected outright; it is handed to
|
|
5
|
+
SQLite so the caller gets SQLite's own error message, and layers 2-3 still apply.
|
|
6
|
+
2. Read-only connection: ``file:...?mode=ro``.
|
|
7
|
+
3. Authorizer: ``set_authorizer`` allows read actions only. A read-only connection
|
|
8
|
+
alone does not stop ATTACH, most PRAGMAs or CREATE TEMP TABLE.
|
|
9
|
+
4. Timeout: ``set_progress_handler`` aborts queries that run too long.
|
|
10
|
+
5. Row cap: ``fetchmany`` keeps huge results out of the model's context.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sqlite3
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import sqlglot
|
|
21
|
+
from sqlglot import exp
|
|
22
|
+
from sqlglot.errors import SqlglotError
|
|
23
|
+
|
|
24
|
+
DEFAULT_TIMEOUT_S = 30.0
|
|
25
|
+
DEFAULT_MAX_ROWS = 1000
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SQLRejected(Exception):
|
|
29
|
+
"""The SQL failed a safety check or was refused by the read-only connection."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SQLUnparseable(SQLRejected):
|
|
33
|
+
"""sqlglot could not parse the SQL. run_readonly still passes it to SQLite."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
_ALLOWED_ACTIONS = {
|
|
37
|
+
sqlite3.SQLITE_SELECT,
|
|
38
|
+
sqlite3.SQLITE_READ,
|
|
39
|
+
sqlite3.SQLITE_FUNCTION,
|
|
40
|
+
sqlite3.SQLITE_RECURSIVE,
|
|
41
|
+
}
|
|
42
|
+
# Read-only metadata pragmas used by describe_table.
|
|
43
|
+
_ALLOWED_PRAGMAS = {"table_info", "table_xinfo", "foreign_key_list", "index_list", "index_info"}
|
|
44
|
+
_WRITE_NODES = (exp.Insert, exp.Update, exp.Delete, exp.Drop, exp.Create, exp.Alter, exp.Command)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _authorizer(action: int, arg1, arg2, _db, _source) -> int:
|
|
48
|
+
if action in _ALLOWED_ACTIONS:
|
|
49
|
+
return sqlite3.SQLITE_OK
|
|
50
|
+
# arg2 is the pragma argument, e.g. the table name in table_info(t); every
|
|
51
|
+
# allowed pragma is read-only, so its argument is harmless
|
|
52
|
+
if action == sqlite3.SQLITE_PRAGMA and (arg1 or "").lower() in _ALLOWED_PRAGMAS:
|
|
53
|
+
return sqlite3.SQLITE_OK
|
|
54
|
+
return sqlite3.SQLITE_DENY
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class QueryResult:
|
|
59
|
+
columns: list[str]
|
|
60
|
+
rows: list[tuple]
|
|
61
|
+
truncated: bool
|
|
62
|
+
elapsed_s: float
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def check_sql(sql: str) -> None:
|
|
66
|
+
"""Allow a single query statement only. Raises SQLRejected otherwise."""
|
|
67
|
+
if not sql or not sql.strip():
|
|
68
|
+
raise SQLRejected("empty SQL")
|
|
69
|
+
try:
|
|
70
|
+
statements = [s for s in sqlglot.parse(sql, read="sqlite") if s is not None]
|
|
71
|
+
except SqlglotError as e: # ParseError and TokenError (the latter is not a subclass)
|
|
72
|
+
raise SQLUnparseable(f"cannot parse SQL: {e}") from e
|
|
73
|
+
if len(statements) != 1:
|
|
74
|
+
raise SQLRejected(f"exactly one statement allowed, got {len(statements)}")
|
|
75
|
+
stmt = statements[0]
|
|
76
|
+
if not isinstance(stmt, exp.Query):
|
|
77
|
+
raise SQLRejected(f"only SELECT queries are allowed, got {type(stmt).__name__}")
|
|
78
|
+
# e.g. WITH t AS (...) DELETE ...: no write node may appear anywhere in the tree
|
|
79
|
+
if any(stmt.find_all(*_WRITE_NODES)):
|
|
80
|
+
raise SQLRejected("query contains a write operation")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def connect_readonly(db_path: str | Path) -> sqlite3.Connection:
|
|
84
|
+
"""Read-only connection with the read-only authorizer. Missing files raise
|
|
85
|
+
instead of silently creating an empty database."""
|
|
86
|
+
path = Path(db_path).resolve()
|
|
87
|
+
if not path.is_file():
|
|
88
|
+
raise FileNotFoundError(path)
|
|
89
|
+
conn = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True, check_same_thread=False)
|
|
90
|
+
conn.set_authorizer(_authorizer)
|
|
91
|
+
return conn
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def run_readonly(
|
|
95
|
+
db_path: str | Path,
|
|
96
|
+
sql: str,
|
|
97
|
+
*,
|
|
98
|
+
timeout_s: float = DEFAULT_TIMEOUT_S,
|
|
99
|
+
max_rows: int = DEFAULT_MAX_ROWS,
|
|
100
|
+
) -> QueryResult:
|
|
101
|
+
"""Run SQL on a read-only connection.
|
|
102
|
+
|
|
103
|
+
Timeouts raise TimeoutError. Ordinary SQL errors are re-raised as sqlite3
|
|
104
|
+
exceptions so their message can be fed back to the model for correction.
|
|
105
|
+
"""
|
|
106
|
+
if max_rows < 0:
|
|
107
|
+
raise ValueError(f"max_rows must be >= 0, got {max_rows}")
|
|
108
|
+
try:
|
|
109
|
+
check_sql(sql)
|
|
110
|
+
except SQLUnparseable:
|
|
111
|
+
pass # let SQLite report the syntax error; layers 2-3 still block writes
|
|
112
|
+
|
|
113
|
+
conn = connect_readonly(db_path)
|
|
114
|
+
start = time.monotonic()
|
|
115
|
+
deadline = start + timeout_s
|
|
116
|
+
conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 10_000)
|
|
117
|
+
try:
|
|
118
|
+
cur = conn.execute(sql)
|
|
119
|
+
columns = [d[0] for d in cur.description or []]
|
|
120
|
+
rows = cur.fetchmany(max_rows + 1)
|
|
121
|
+
except sqlite3.DatabaseError as e:
|
|
122
|
+
msg = str(e)
|
|
123
|
+
if msg == "interrupted":
|
|
124
|
+
raise TimeoutError(f"query interrupted after {timeout_s:g}s") from e
|
|
125
|
+
if "readonly" in msg or "not authorized" in msg:
|
|
126
|
+
raise SQLRejected(f"refused by read-only connection: {msg}") from e
|
|
127
|
+
raise
|
|
128
|
+
finally:
|
|
129
|
+
conn.close()
|
|
130
|
+
return QueryResult(columns, rows[:max_rows], len(rows) > max_rows, time.monotonic() - start)
|
|
File without changes
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""MCP server (stdio) exposing read-only tools over one or more SQLite files.
|
|
2
|
+
|
|
3
|
+
sqlguard-mcp path/to/shop.db path/to/dir_of_dbs --timeout 30 --max-rows 1000
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
|
|
10
|
+
from mcp.server.mcpserver import MCPServer
|
|
11
|
+
|
|
12
|
+
from sqlguard_mcp.catalog import Catalog
|
|
13
|
+
|
|
14
|
+
INSTRUCTIONS = (
|
|
15
|
+
"Read-only SQLite tools. Suggested order: list_databases -> list_tables -> describe_table "
|
|
16
|
+
"-> search_values (confirm the value actually stored) -> run_sql. Only single SELECT "
|
|
17
|
+
"statements are executed; writes, ATTACH and PRAGMA changes are refused."
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_server(catalog: Catalog) -> MCPServer:
|
|
22
|
+
server = MCPServer("sqlguard", instructions=INSTRUCTIONS)
|
|
23
|
+
|
|
24
|
+
@server.tool()
|
|
25
|
+
def list_databases() -> list[str]:
|
|
26
|
+
"""List the db_id of every database that can be queried."""
|
|
27
|
+
return catalog.list_databases()
|
|
28
|
+
|
|
29
|
+
@server.tool()
|
|
30
|
+
def list_tables(db_id: str) -> list[dict]:
|
|
31
|
+
"""List the tables in a database and how many columns each has."""
|
|
32
|
+
return catalog.list_tables(db_id)
|
|
33
|
+
|
|
34
|
+
@server.tool()
|
|
35
|
+
def describe_table(db_id: str, table: str) -> dict:
|
|
36
|
+
"""Columns, types, primary and foreign keys, plus 3 sample rows."""
|
|
37
|
+
return catalog.describe_table(db_id, table)
|
|
38
|
+
|
|
39
|
+
@server.tool()
|
|
40
|
+
def search_values(
|
|
41
|
+
db_id: str, keyword: str, table: str | None = None, column: str | None = None, limit: int = 10
|
|
42
|
+
) -> dict:
|
|
43
|
+
"""Fuzzy-search text columns for real stored values, to get WHERE conditions right."""
|
|
44
|
+
return catalog.search_values(db_id, keyword, table, column, limit)
|
|
45
|
+
|
|
46
|
+
@server.tool()
|
|
47
|
+
def run_sql(db_id: str, sql: str, max_rows: int = 50) -> dict:
|
|
48
|
+
"""Run one SELECT read-only. Returns columns and rows, or error and message."""
|
|
49
|
+
return catalog.run_sql(db_id, sql, max_rows)
|
|
50
|
+
|
|
51
|
+
return server
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def main(argv: list[str] | None = None) -> None:
|
|
55
|
+
parser = argparse.ArgumentParser(prog="sqlguard-mcp", description=__doc__.strip().splitlines()[0])
|
|
56
|
+
parser.add_argument("paths", nargs="+", help="SQLite files or directories containing them")
|
|
57
|
+
parser.add_argument("--timeout", type=float, default=30.0, help="per-query timeout in seconds")
|
|
58
|
+
parser.add_argument("--max-rows", type=int, default=1000, help="hard cap on rows returned")
|
|
59
|
+
args = parser.parse_args(argv)
|
|
60
|
+
build_server(Catalog(args.paths, timeout_s=args.timeout, max_rows=args.max_rows)).run("stdio")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
if __name__ == "__main__":
|
|
64
|
+
main()
|