Skip to content

Commit c48f822

Browse files
committed
SQL: Stronger read-only mode, using sqlparse
1 parent 5727a27 commit c48f822

File tree

8 files changed

+89
-15
lines changed

8 files changed

+89
-15
lines changed

CHANGES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@
1111
- MCP documentation: Add reference to medium-sized llms.txt context file
1212
- Boilerplate: Added software tests and CI configuration
1313
- Documentation: Added development sandbox section
14+
- SQL: Stronger read-only mode, using `sqlparse`

README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,12 @@ LLMs can still hallucinate and give incorrect answers.
4040
* What is the storage consumption of my tables, give it in a graph.
4141
* How can I format a timestamp column to '2019 Jan 21'.
4242

43-
# Data integrity
44-
We do not recommend letting the LLMs insert data or modify columns by itself, as such we tell the
45-
LLMs to only allow 'SELECT' statements in the `cratedb_sql` tool, you can jailbreak this against
46-
our recommendation.
43+
# Read-only access
44+
We do not recommend letting LLM-based agents insert or modify data by itself.
45+
As such, only `SELECT` statements are permitted and forwarded to the database.
46+
All other operations will raise a `ValueError` exception, unless the
47+
`CRATEDB_MCP_PERMIT_ALL_STATEMENTS` environment variable will be set
48+
to a truthy value.
4749

4850
# Install
4951
```shell

cratedb_mcp/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import httpx
22
from mcp.server.fastmcp import FastMCP
33

4-
from .knowledge import DOCUMENTATION_INDEX, Queries
4+
from .knowledge import DOCUMENTATION_INDEX, Queries, sql_expression_permitted
55
from .settings import HTTP_URL
66

77
mcp = FastMCP("cratedb-mcp")
@@ -14,7 +14,7 @@ def query_cratedb(query: str) -> list[dict]:
1414
@mcp.tool(description="Send a SQL query to CrateDB, only 'SELECT' queries are allows, queries that"
1515
" modify data, columns or are otherwise deemed un-safe are rejected.")
1616
def query_sql(query: str):
17-
if 'select' not in query.lower():
17+
if not sql_expression_permitted(query):
1818
raise ValueError('Only queries that have a SELECT statement are allowed.')
1919
return query_cratedb(query)
2020

cratedb_mcp/knowledge.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
# ruff: noqa: E501
2+
import sqlparse
3+
4+
from cratedb_mcp.settings import PERMIT_ALL_STATEMENTS
5+
26

37
class Queries:
48
TABLES_METADATA = """
@@ -100,3 +104,32 @@ class Queries:
100104
"link": "https://raw.githubusercontent.com/crate/cratedb-guide/9ab661997d7704ecbb63af9c3ee33535957e24e6/docs/performance/optimization.rst"
101105
}
102106
]
107+
108+
109+
def sql_expression_permitted(expression: str) -> bool:
110+
"""
111+
Validate the SQL expression, only permit read queries.
112+
113+
FIXME: Revisit implementation, it might be too naive and weak.
114+
Issue: https://github.com/crate/cratedb-mcp/issues/10
115+
Question: Does SQLAlchemy provide a solid read-only mode, or any other library?
116+
"""
117+
118+
if not expression:
119+
return False
120+
121+
if PERMIT_ALL_STATEMENTS:
122+
return True
123+
124+
# Parse the SQL statement.
125+
parsed = sqlparse.parse(expression.strip())
126+
if not parsed:
127+
return False
128+
129+
# Check if the expression is valid and if it's a SELECT statement,
130+
# also trying to consider `SELECT ... INTO ...` statements.
131+
operation = parsed[0].get_type().upper()
132+
tokens = [str(item).upper() for item in parsed[0]]
133+
if operation != 'SELECT' or (operation == 'SELECT' and 'INTO' in tokens):
134+
return False
135+
return True

cratedb_mcp/settings.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
11
import os
22

3+
from attr.converters import to_bool
4+
35
HTTP_URL: str = os.getenv("CRATEDB_MCP_HTTP_URL", "http://localhost:4200")
6+
7+
# Whether to permit all statements. By default, only SELECT operations are permitted.
8+
PERMIT_ALL_STATEMENTS: bool = to_bool(os.getenv("CRATEDB_MCP_PERMIT_ALL_STATEMENTS", "false"))

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ dynamic = [
2020
"version",
2121
]
2222
dependencies = [
23+
"attrs",
2324
"mcp[cli]>=1.5.0",
25+
"sqlparse<0.6",
2426
]
2527
optional-dependencies.develop = [
2628
"mypy<1.16",

tests/test_knowledge.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from cratedb_mcp.knowledge import DOCUMENTATION_INDEX, Queries
1+
import cratedb_mcp
2+
from cratedb_mcp.knowledge import DOCUMENTATION_INDEX, Queries, sql_expression_permitted
23

34

45
def test_documentation_index():
@@ -16,3 +17,32 @@ def test_queries():
1617
assert "sys.health" in Queries.TABLES_METADATA
1718
assert "WITH partitions_health" in Queries.TABLES_METADATA
1819
assert "LEFT JOIN" in Queries.TABLES_METADATA
20+
21+
22+
def test_sql_expression_create_forbidden():
23+
assert sql_expression_permitted("CREATE TABLE foobar AS SELECT 42") is False
24+
25+
26+
def test_sql_expression_insert_forbidden():
27+
assert sql_expression_permitted("INSERT INTO foobar") is False
28+
29+
30+
def test_sql_expression_select_into_forbidden():
31+
assert sql_expression_permitted("SELECT * INTO foobar FROM bazqux") is False
32+
33+
34+
def test_sql_expression_empty():
35+
assert sql_expression_permitted("") is False
36+
37+
38+
def test_sql_expression_almost_empty():
39+
assert sql_expression_permitted(" ") is False
40+
41+
42+
def test_sql_expression_none():
43+
assert sql_expression_permitted(None) is False
44+
45+
46+
def test_sql_expression_insert_allowed(mocker):
47+
mocker.patch.object(cratedb_mcp.knowledge, "PERMIT_ALL_STATEMENTS", True)
48+
assert sql_expression_permitted("INSERT INTO foobar") is True

tests/test_mcp.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,20 @@ def test_fetch_docs_permitted():
2424
assert "initcap" in response
2525

2626

27-
def test_query_sql_forbidden():
27+
def test_query_sql_permitted():
28+
assert query_sql("SELECT 42")["rows"] == [[42]]
29+
30+
31+
def test_query_sql_forbidden_easy():
2832
with pytest.raises(ValueError) as ex:
2933
assert "RelationUnknown" in str(query_sql("INSERT INTO foobar (id) VALUES (42) RETURNING id"))
3034
assert ex.match("Only queries that have a SELECT statement are allowed")
3135

3236

33-
def test_query_sql_permitted():
34-
assert query_sql("SELECT 42")["rows"] == [[42]]
35-
36-
37-
def test_query_sql_permitted_exploit():
38-
# FIXME: Read-only protection must become stronger.
39-
query_sql("INSERT INTO foobar (operation) VALUES ('select')")
37+
def test_query_sql_forbidden_sneak_value():
38+
with pytest.raises(ValueError) as ex:
39+
query_sql("INSERT INTO foobar (operation) VALUES ('select')")
40+
assert ex.match("Only queries that have a SELECT statement are allowed")
4041

4142

4243
def test_get_table_metadata():

0 commit comments

Comments
 (0)