sql-safe-mcp 1.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.
- sql_safe_mcp/__init__.py +3 -0
- sql_safe_mcp/__main__.py +43 -0
- sql_safe_mcp/config.py +201 -0
- sql_safe_mcp/db/__init__.py +1 -0
- sql_safe_mcp/db/extras.py +35 -0
- sql_safe_mcp/db/mysql.py +63 -0
- sql_safe_mcp/db/reflection.py +132 -0
- sql_safe_mcp/db/registry.py +123 -0
- sql_safe_mcp/db/sqlserver.py +65 -0
- sql_safe_mcp/errors.py +49 -0
- sql_safe_mcp/mcp_server.py +140 -0
- sql_safe_mcp/models.py +124 -0
- sql_safe_mcp/security/__init__.py +1 -0
- sql_safe_mcp/security/dialect.py +29 -0
- sql_safe_mcp/security/executor.py +129 -0
- sql_safe_mcp/security/lineage.py +224 -0
- sql_safe_mcp/security/parser.py +183 -0
- sql_safe_mcp/security/pipeline.py +43 -0
- sql_safe_mcp/security/policy.py +101 -0
- sql_safe_mcp/security/reasons.py +43 -0
- sql_safe_mcp/security/schema.py +139 -0
- sql_safe_mcp/security/tokens.py +207 -0
- sql_safe_mcp/security/validated_query.py +209 -0
- sql_safe_mcp/service.py +325 -0
- sql_safe_mcp-1.2.0.dist-info/METADATA +259 -0
- sql_safe_mcp-1.2.0.dist-info/RECORD +29 -0
- sql_safe_mcp-1.2.0.dist-info/WHEEL +4 -0
- sql_safe_mcp-1.2.0.dist-info/entry_points.txt +2 -0
- sql_safe_mcp-1.2.0.dist-info/licenses/LICENSE +21 -0
sql_safe_mcp/service.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import TypeVar
|
|
6
|
+
|
|
7
|
+
from sqlalchemy import Connection, Engine
|
|
8
|
+
from sqlalchemy.exc import DBAPIError, OperationalError, SQLAlchemyError
|
|
9
|
+
from sqlalchemy.exc import TimeoutError as SQLAlchemyTimeoutError
|
|
10
|
+
|
|
11
|
+
from sql_safe_mcp.config import AppConfig, ServerConfig
|
|
12
|
+
from sql_safe_mcp.db.extras import extras_for
|
|
13
|
+
from sql_safe_mcp.db.reflection import get_table_definition as reflect_table_definition
|
|
14
|
+
from sql_safe_mcp.db.reflection import list_tables as reflect_tables
|
|
15
|
+
from sql_safe_mcp.db.registry import EngineRegistry
|
|
16
|
+
from sql_safe_mcp.errors import DomainError, ErrorCode
|
|
17
|
+
from sql_safe_mcp.models import (
|
|
18
|
+
ColumnSource,
|
|
19
|
+
DatabaseList,
|
|
20
|
+
DatabaseSummary,
|
|
21
|
+
ServerList,
|
|
22
|
+
ServerSummary,
|
|
23
|
+
SqlColumn,
|
|
24
|
+
SqlResult,
|
|
25
|
+
StoredProcedureDefinition,
|
|
26
|
+
StoredProcedureList,
|
|
27
|
+
StoredProcedureSummary,
|
|
28
|
+
TableDefinition,
|
|
29
|
+
TableList,
|
|
30
|
+
TableSummary,
|
|
31
|
+
)
|
|
32
|
+
from sql_safe_mcp.security.dialect import dialect_for
|
|
33
|
+
from sql_safe_mcp.security.executor import execute_validated
|
|
34
|
+
from sql_safe_mcp.security.pipeline import validate_sql
|
|
35
|
+
from sql_safe_mcp.security.schema import ReflectedCatalog, SchemaCache, TableCatalog
|
|
36
|
+
from sql_safe_mcp.security.tokens import TokenKeyRegistry
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
CatalogFactory = Callable[[Connection, str, str], TableCatalog]
|
|
40
|
+
_SCHEMA_CACHE_ENTRIES = 1024
|
|
41
|
+
_SCHEMA_CACHE_TTL_SECONDS = 300.0
|
|
42
|
+
T = TypeVar("T")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _contains(value: str, needle: str | None) -> bool:
|
|
46
|
+
return needle is None or needle.casefold() in value.casefold()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _qualified_name(schema: str | None, name: str) -> str:
|
|
50
|
+
return name if schema is None else f"{schema}.{name}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DatabaseService:
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
config: AppConfig,
|
|
57
|
+
registry: EngineRegistry,
|
|
58
|
+
catalog_factory: CatalogFactory | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
self.config = config
|
|
61
|
+
self.registry = registry
|
|
62
|
+
self._tokens = TokenKeyRegistry.from_config(config)
|
|
63
|
+
self._schema_cache = SchemaCache(_SCHEMA_CACHE_ENTRIES, _SCHEMA_CACHE_TTL_SECONDS)
|
|
64
|
+
self._catalog_factory = catalog_factory or self._reflected_catalog
|
|
65
|
+
|
|
66
|
+
def _reflected_catalog(self, connection: Connection, alias: str, database: str) -> TableCatalog:
|
|
67
|
+
return ReflectedCatalog(connection, self._schema_cache, alias, database)
|
|
68
|
+
|
|
69
|
+
def _server(self, alias: str) -> ServerConfig:
|
|
70
|
+
try:
|
|
71
|
+
return self.config.servers[alias]
|
|
72
|
+
except KeyError as exc:
|
|
73
|
+
raise DomainError(
|
|
74
|
+
ErrorCode.UNKNOWN_SERVER,
|
|
75
|
+
f"Unknown configured server {alias!r}.",
|
|
76
|
+
"Call list_servers to discover configured aliases.",
|
|
77
|
+
) from exc
|
|
78
|
+
|
|
79
|
+
async def _run(self, alias: str, database: str | None, operation: Callable[[Engine], T]) -> T:
|
|
80
|
+
self._server(alias)
|
|
81
|
+
try:
|
|
82
|
+
return await self.registry.run(alias, database, operation)
|
|
83
|
+
except DomainError:
|
|
84
|
+
raise
|
|
85
|
+
except SQLAlchemyTimeoutError as exc:
|
|
86
|
+
raise DomainError(
|
|
87
|
+
ErrorCode.TIMEOUT,
|
|
88
|
+
"The database operation timed out.",
|
|
89
|
+
retryable=True,
|
|
90
|
+
) from exc
|
|
91
|
+
except DBAPIError as exc:
|
|
92
|
+
message = str(exc.orig).casefold()
|
|
93
|
+
if any(value in message for value in ("timeout", "timed out", "hyt00", "hyt01")):
|
|
94
|
+
raise DomainError(
|
|
95
|
+
ErrorCode.TIMEOUT, "The database operation timed out.", retryable=True
|
|
96
|
+
) from exc
|
|
97
|
+
if any(value in message for value in ("permission", "denied", "not authorized")):
|
|
98
|
+
raise DomainError(
|
|
99
|
+
ErrorCode.ACCESS_DENIED, "The database denied this operation."
|
|
100
|
+
) from exc
|
|
101
|
+
if any(
|
|
102
|
+
value in message for value in ("cannot open database", "(4060)", "08001", "08004")
|
|
103
|
+
):
|
|
104
|
+
raise DomainError(
|
|
105
|
+
ErrorCode.CONNECTION_FAILED,
|
|
106
|
+
"Could not connect to the configured database server.",
|
|
107
|
+
retryable=True,
|
|
108
|
+
) from exc
|
|
109
|
+
if isinstance(exc, OperationalError):
|
|
110
|
+
raise DomainError(
|
|
111
|
+
ErrorCode.CONNECTION_FAILED,
|
|
112
|
+
"Could not connect to the configured database server.",
|
|
113
|
+
retryable=True,
|
|
114
|
+
) from exc
|
|
115
|
+
error = DomainError.unexpected()
|
|
116
|
+
logger.error("Database operation failed; reference=%s", error.correlation_id)
|
|
117
|
+
raise error from exc
|
|
118
|
+
except SQLAlchemyError as exc:
|
|
119
|
+
error = DomainError.unexpected()
|
|
120
|
+
logger.error("SQLAlchemy operation failed; reference=%s", error.correlation_id)
|
|
121
|
+
raise error from exc
|
|
122
|
+
except Exception as exc:
|
|
123
|
+
error = DomainError.unexpected()
|
|
124
|
+
logger.error(
|
|
125
|
+
"Unexpected database operation failure; reference=%s", error.correlation_id
|
|
126
|
+
)
|
|
127
|
+
raise error from exc
|
|
128
|
+
|
|
129
|
+
def list_servers(self) -> ServerList:
|
|
130
|
+
return ServerList(
|
|
131
|
+
servers=[
|
|
132
|
+
ServerSummary(name=alias, engine=server.engine, access_level=server.access_level)
|
|
133
|
+
for alias, server in sorted(
|
|
134
|
+
self.config.servers.items(), key=lambda item: item[0].casefold()
|
|
135
|
+
)
|
|
136
|
+
]
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
async def list_databases(self, server: str, name_contains: str | None = None) -> DatabaseList:
|
|
140
|
+
configured = self._server(server)
|
|
141
|
+
|
|
142
|
+
def operation(engine: Engine) -> list[str]:
|
|
143
|
+
with engine.connect() as connection:
|
|
144
|
+
return extras_for(configured.engine).list_databases(connection)
|
|
145
|
+
|
|
146
|
+
names = await self._run(server, None, operation)
|
|
147
|
+
return DatabaseList(
|
|
148
|
+
databases=[
|
|
149
|
+
DatabaseSummary(name=name)
|
|
150
|
+
for name in sorted(names, key=str.casefold)
|
|
151
|
+
if _contains(name, name_contains)
|
|
152
|
+
]
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
async def list_tables(
|
|
156
|
+
self,
|
|
157
|
+
server: str,
|
|
158
|
+
database: str,
|
|
159
|
+
schema: str | None = None,
|
|
160
|
+
name_contains: str | None = None,
|
|
161
|
+
) -> TableList:
|
|
162
|
+
self._server(server)
|
|
163
|
+
|
|
164
|
+
def operation(engine: Engine) -> list[TableSummary]:
|
|
165
|
+
with engine.connect() as connection:
|
|
166
|
+
return reflect_tables(connection)
|
|
167
|
+
|
|
168
|
+
tables = await self._run(server, database, operation)
|
|
169
|
+
selected = [
|
|
170
|
+
table
|
|
171
|
+
for table in tables
|
|
172
|
+
if (schema is None or (table.schema_ or "").casefold() == schema.casefold())
|
|
173
|
+
and _contains(table.name, name_contains)
|
|
174
|
+
]
|
|
175
|
+
selected.sort(key=lambda table: ((table.schema_ or "").casefold(), table.name.casefold()))
|
|
176
|
+
return TableList(tables=selected)
|
|
177
|
+
|
|
178
|
+
@staticmethod
|
|
179
|
+
def _resolve_table(tables: list[TableSummary], table: str, schema: str | None) -> TableSummary:
|
|
180
|
+
matches = [
|
|
181
|
+
item
|
|
182
|
+
for item in tables
|
|
183
|
+
if item.name.casefold() == table.casefold()
|
|
184
|
+
and (schema is None or (item.schema_ or "").casefold() == schema.casefold())
|
|
185
|
+
]
|
|
186
|
+
if not matches:
|
|
187
|
+
raise DomainError(ErrorCode.NOT_FOUND, f"Table {table!r} was not found.")
|
|
188
|
+
if len(matches) > 1:
|
|
189
|
+
candidates = ", ".join(_qualified_name(item.schema_, item.name) for item in matches)
|
|
190
|
+
raise DomainError(
|
|
191
|
+
ErrorCode.AMBIGUOUS_OBJECT,
|
|
192
|
+
f"Table {table!r} is ambiguous.",
|
|
193
|
+
f"Specify schema; candidates: {candidates}.",
|
|
194
|
+
)
|
|
195
|
+
return matches[0]
|
|
196
|
+
|
|
197
|
+
async def get_table_definition(
|
|
198
|
+
self, server: str, database: str, table: str, schema: str | None = None
|
|
199
|
+
) -> TableDefinition:
|
|
200
|
+
self._server(server)
|
|
201
|
+
|
|
202
|
+
def operation(engine: Engine) -> TableDefinition:
|
|
203
|
+
with engine.connect() as connection:
|
|
204
|
+
selected = self._resolve_table(reflect_tables(connection), table, schema)
|
|
205
|
+
return reflect_table_definition(connection, selected.schema_, selected.name)
|
|
206
|
+
|
|
207
|
+
return await self._run(server, database, operation)
|
|
208
|
+
|
|
209
|
+
async def list_stored_procedures(
|
|
210
|
+
self,
|
|
211
|
+
server: str,
|
|
212
|
+
database: str,
|
|
213
|
+
schema: str | None = None,
|
|
214
|
+
name_contains: str | None = None,
|
|
215
|
+
) -> StoredProcedureList:
|
|
216
|
+
configured = self._server(server)
|
|
217
|
+
|
|
218
|
+
def operation(engine: Engine) -> list[StoredProcedureSummary]:
|
|
219
|
+
with engine.connect() as connection:
|
|
220
|
+
return extras_for(configured.engine).list_stored_procedures(connection, database)
|
|
221
|
+
|
|
222
|
+
procedures = await self._run(server, database, operation)
|
|
223
|
+
selected = [
|
|
224
|
+
item
|
|
225
|
+
for item in procedures
|
|
226
|
+
if (schema is None or (item.schema_ or "").casefold() == schema.casefold())
|
|
227
|
+
and _contains(item.name, name_contains)
|
|
228
|
+
]
|
|
229
|
+
selected.sort(key=lambda item: ((item.schema_ or "").casefold(), item.name.casefold()))
|
|
230
|
+
return StoredProcedureList(stored_procedures=selected)
|
|
231
|
+
|
|
232
|
+
async def get_stored_procedure(
|
|
233
|
+
self,
|
|
234
|
+
server: str,
|
|
235
|
+
database: str,
|
|
236
|
+
name: str,
|
|
237
|
+
schema: str | None = None,
|
|
238
|
+
) -> StoredProcedureDefinition:
|
|
239
|
+
configured = self._server(server)
|
|
240
|
+
listing = await self.list_stored_procedures(server, database, schema)
|
|
241
|
+
matches = [
|
|
242
|
+
item for item in listing.stored_procedures if item.name.casefold() == name.casefold()
|
|
243
|
+
]
|
|
244
|
+
if not matches:
|
|
245
|
+
raise DomainError(ErrorCode.NOT_FOUND, f"Stored procedure {name!r} was not found.")
|
|
246
|
+
if len(matches) > 1:
|
|
247
|
+
candidates = ", ".join(_qualified_name(item.schema_, item.name) for item in matches)
|
|
248
|
+
raise DomainError(
|
|
249
|
+
ErrorCode.AMBIGUOUS_OBJECT,
|
|
250
|
+
f"Stored procedure {name!r} is ambiguous.",
|
|
251
|
+
f"Specify schema; candidates: {candidates}.",
|
|
252
|
+
)
|
|
253
|
+
selected = matches[0]
|
|
254
|
+
|
|
255
|
+
def operation(engine: Engine) -> StoredProcedureDefinition | None:
|
|
256
|
+
with engine.connect() as connection:
|
|
257
|
+
return extras_for(configured.engine).get_stored_procedure(
|
|
258
|
+
connection, database, selected.schema_, selected.name
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
result = await self._run(server, database, operation)
|
|
262
|
+
if result is None:
|
|
263
|
+
raise DomainError(ErrorCode.NOT_FOUND, f"Stored procedure {name!r} was not found.")
|
|
264
|
+
if (
|
|
265
|
+
result.definition is not None
|
|
266
|
+
and len(result.definition) > self.config.runtime.max_definition_chars
|
|
267
|
+
):
|
|
268
|
+
raise DomainError(
|
|
269
|
+
ErrorCode.DEFINITION_TOO_LARGE,
|
|
270
|
+
"Stored procedure definition exceeds the configured response limit.",
|
|
271
|
+
)
|
|
272
|
+
return result
|
|
273
|
+
|
|
274
|
+
async def execute_sql(
|
|
275
|
+
self, server: str, database: str, sql: str, max_rows: int | None = None
|
|
276
|
+
) -> SqlResult:
|
|
277
|
+
configured = self._server(server)
|
|
278
|
+
if configured.access_level != "pii_safe" or configured.pii is None:
|
|
279
|
+
raise DomainError(
|
|
280
|
+
ErrorCode.ACCESS_LEVEL_DENIED,
|
|
281
|
+
"execute_sql is available only for pii_safe servers.",
|
|
282
|
+
"Use a server configured with access_level pii_safe.",
|
|
283
|
+
)
|
|
284
|
+
runtime = self.config.runtime
|
|
285
|
+
rows_limit = runtime.default_max_rows if max_rows is None else max_rows
|
|
286
|
+
codec = self._tokens.codec_for(server)
|
|
287
|
+
pii = configured.pii
|
|
288
|
+
dialect = dialect_for(configured.engine)
|
|
289
|
+
|
|
290
|
+
def operation(engine: Engine) -> SqlResult:
|
|
291
|
+
with engine.connect() as connection:
|
|
292
|
+
validated = validate_sql(
|
|
293
|
+
sql,
|
|
294
|
+
alias=server,
|
|
295
|
+
database=database,
|
|
296
|
+
catalog=self._catalog_factory(connection, server, database),
|
|
297
|
+
pii_config=pii,
|
|
298
|
+
codec=codec,
|
|
299
|
+
runtime=runtime,
|
|
300
|
+
max_rows=rows_limit,
|
|
301
|
+
dialect=dialect,
|
|
302
|
+
)
|
|
303
|
+
executed = execute_validated(connection, validated, codec)
|
|
304
|
+
return SqlResult(
|
|
305
|
+
columns=[
|
|
306
|
+
SqlColumn(
|
|
307
|
+
name=column.name,
|
|
308
|
+
source=None
|
|
309
|
+
if column.source is None
|
|
310
|
+
else ColumnSource(
|
|
311
|
+
schema=column.source.schema or None,
|
|
312
|
+
table=column.source.table,
|
|
313
|
+
column=column.source.column,
|
|
314
|
+
),
|
|
315
|
+
protected=column.protected,
|
|
316
|
+
encoding=column.encoding,
|
|
317
|
+
)
|
|
318
|
+
for column in executed.columns
|
|
319
|
+
],
|
|
320
|
+
rows=[list(row) for row in executed.rows],
|
|
321
|
+
row_count=len(executed.rows),
|
|
322
|
+
truncated=executed.truncated,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
return await self._run(server, database, operation)
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sql-safe-mcp
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Minimal, read-only, PII-safe MCP server for SQL databases.
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 Anton Padapryhara
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Python: <3.15,>=3.12
|
|
28
|
+
Requires-Dist: anyio<5,>=4.8
|
|
29
|
+
Requires-Dist: cryptography<47,>=46.0.7
|
|
30
|
+
Requires-Dist: mcp<3,>=2
|
|
31
|
+
Requires-Dist: pydantic<3,>=2.10
|
|
32
|
+
Requires-Dist: pymysql>=1.2.3
|
|
33
|
+
Requires-Dist: pyodbc<6,>=5.2
|
|
34
|
+
Requires-Dist: pyyaml<7,>=6
|
|
35
|
+
Requires-Dist: sqlalchemy<3,>=2.0
|
|
36
|
+
Requires-Dist: sqlglot<31,>=30.18
|
|
37
|
+
Description-Content-Type: text/markdown
|
|
38
|
+
|
|
39
|
+
<div align="center">
|
|
40
|
+
|
|
41
|
+
# sql-safe-mcp
|
|
42
|
+
|
|
43
|
+
A read-only, PII-safe SQL Server, MySQL and MariaDB MCP server for coding agents: schema knowledge and safe queries, with no way to change or leak data.
|
|
44
|
+
|
|
45
|
+
[](https://github.com/proprock/sql-safe-mcp/actions/workflows/ci.yml)
|
|
46
|
+
[](https://github.com/proprock/sql-safe-mcp/releases)
|
|
47
|
+
[](https://pypi.org/project/sql-safe-mcp/)
|
|
48
|
+
[](https://www.python.org/downloads/)
|
|
49
|
+
[](LICENSE)
|
|
50
|
+
|
|
51
|
+
[](https://modelcontextprotocol.io)
|
|
52
|
+
[](server.json)
|
|
53
|
+
|
|
54
|
+
<img src="https://raw.githubusercontent.com/proprock/sql-safe-mcp/master/images/luna-guard.jpg" alt="Read the data. Protect the identity." width="760">
|
|
55
|
+
|
|
56
|
+
<i>Read the data. Protect the identity.</i>
|
|
57
|
+
|
|
58
|
+
</div>
|
|
59
|
+
|
|
60
|
+
<!-- mcp-name: io.github.proprock/sql-safe-mcp -->
|
|
61
|
+
|
|
62
|
+
General-purpose database MCP servers hand the agent a raw SQL prompt and dozens of tools. This
|
|
63
|
+
server gives a coding agent the schema knowledge it needs to write correct code - servers,
|
|
64
|
+
databases, tables, columns, keys, indexes, stored procedures - and, on servers you mark
|
|
65
|
+
`pii_safe`, a way to look at real rows without ever seeing the personal data in them.
|
|
66
|
+
|
|
67
|
+
## Read-only by design. PII-safe by default
|
|
68
|
+
|
|
69
|
+
- **Read-only by construction** - seven tools, all annotated read-only. No tool writes data, and
|
|
70
|
+
the server never executes SQL an agent wrote: metadata comes from SQLAlchemy Inspector and fixed
|
|
71
|
+
catalog queries, and `execute_sql` runs only a validated, regenerated `SELECT`.
|
|
72
|
+
- **PII-safe by default** - on a `pii_safe` server, the columns you configure come back as
|
|
73
|
+
alias-bound, authenticated tokens (`pii:v1:...`), never as plaintext. An agent can still
|
|
74
|
+
project, count, and filter on them with `=` and `IN` using tokens it was given, so it can follow
|
|
75
|
+
a record without reading it. Tokens do not work on another server alias or with another key.
|
|
76
|
+
- **Fails closed** - SQL validation is an allowlist. Unknown syntax, unresolved lineage, and
|
|
77
|
+
unsupported protected-value types are refused, not guessed at. The verification evidence is in
|
|
78
|
+
the [security model](SECURITY-MODEL.md).
|
|
79
|
+
- **Least access first** - `access_level: metadata` (the default) exposes schema only;
|
|
80
|
+
`execute_sql` needs an explicit `pii_safe` alias with its own key. Database permissions stay the
|
|
81
|
+
primary control, so use a least-privilege login.
|
|
82
|
+
|
|
83
|
+
## Also
|
|
84
|
+
|
|
85
|
+
- **Your aliases, not your network** - the agent sees only the server aliases you configure. There
|
|
86
|
+
is no network discovery, and the catalog is not published as MCP resources.
|
|
87
|
+
- **Secrets stay out of sight** - connection URLs live in YAML with `${NAME}` placeholders resolved
|
|
88
|
+
from the environment. They never appear in logs or model-visible errors.
|
|
89
|
+
- **Compact, predictable output** - object-rooted results with stable sorting, literal
|
|
90
|
+
case-insensitive name filters, and stored procedure lists that do not expand definitions.
|
|
91
|
+
- **Errors an agent can act on** - an ambiguous name lists the candidate schemas. Errors never
|
|
92
|
+
contain connection details, credentials, keys, tokens, or rows.
|
|
93
|
+
- **On PyPI** - `uvx sql-safe-mcp`, no repo clone required.
|
|
94
|
+
|
|
95
|
+
| Tool | Access | Purpose |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `list_servers` | 🟢 read | Configured server aliases |
|
|
98
|
+
| `list_databases` | 🟢 read | Databases visible to the credentials |
|
|
99
|
+
| `list_tables` | 🟢 read | Base tables, filtered by schema or name |
|
|
100
|
+
| `get_table_definition` | 🟢 read | Columns, keys, constraints, and indexes of one table |
|
|
101
|
+
| `list_stored_procedures` | 🟢 read | Stored procedures, without definitions |
|
|
102
|
+
| `get_stored_procedure` | 🟢 read | The definition of one stored procedure |
|
|
103
|
+
| `execute_sql` | 🟢 read | One restricted `SELECT` on a `pii_safe` server; protected columns return tokens |
|
|
104
|
+
|
|
105
|
+
> [!NOTE]
|
|
106
|
+
> **Status:** SQL Server supports every tool. MySQL and MariaDB (`engine: mysql` or `mariadb`,
|
|
107
|
+
> `mysql+pymysql` URLs) support every tool too. `schema` is always `null` there because the
|
|
108
|
+
> database is the catalog, and `execute_sql` uses `LIMIT` instead of `TOP`. See
|
|
109
|
+
> [ARCHITECTURE.md](ARCHITECTURE.md).
|
|
110
|
+
|
|
111
|
+
- [Install](#install)
|
|
112
|
+
- [Configure](#configure)
|
|
113
|
+
- [PII-safe queries](#pii-safe-queries)
|
|
114
|
+
- [Security](#security)
|
|
115
|
+
- [Contributing](#contributing)
|
|
116
|
+
|
|
117
|
+
More detail lives in [`docs/`](docs): the [configuration reference](docs/configuration.md),
|
|
118
|
+
[what the tools return](docs/tools.md), and the [security model](SECURITY-MODEL.md).
|
|
119
|
+
|
|
120
|
+
## Install
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
uvx sql-safe-mcp
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
or
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
pip install sql-safe-mcp
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Pin a version when you want a fixed surface: `uvx sql-safe-mcp==1.2.0`.
|
|
133
|
+
|
|
134
|
+
Requires Python 3.12+, [uv](https://docs.astral.sh/uv/) (or `pip`), and
|
|
135
|
+
[Microsoft ODBC Driver 18 for SQL Server](https://learn.microsoft.com/sql/connect/odbc/download-odbc-driver-for-sql-server)
|
|
136
|
+
when you connect to SQL Server. MySQL and MariaDB use the bundled PyMySQL driver and need nothing
|
|
137
|
+
else.
|
|
138
|
+
|
|
139
|
+
Verified against SQL Server 2022, MySQL 8.4, and MariaDB 11.4 (see [CHECKS.md](CHECKS.md)).
|
|
140
|
+
|
|
141
|
+
## Configure
|
|
142
|
+
|
|
143
|
+
Copy [sql-safe-mcp.example.yaml](sql-safe-mcp.example.yaml) to `sql-safe-mcp.yaml`, list your
|
|
144
|
+
servers, and keep credentials in environment variables:
|
|
145
|
+
|
|
146
|
+
```yaml
|
|
147
|
+
version: 1
|
|
148
|
+
servers:
|
|
149
|
+
reporting:
|
|
150
|
+
engine: sqlserver
|
|
151
|
+
access_level: metadata
|
|
152
|
+
connection_url: "${REPORTING_SQL_URL}"
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Point the server at the file with `SQL_SAFE_MCP_CONFIG` (or `--config`), and check it without
|
|
156
|
+
connecting to any database:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
SQL_SAFE_MCP_CONFIG=sql-safe-mcp.yaml uvx sql-safe-mcp --check-config
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Configuration is validated at startup, and an error names the problem without printing a URL or
|
|
163
|
+
secret. Keep credentials in the host's own configuration and never commit them. The server acts
|
|
164
|
+
with the database account's permissions, so use a dedicated login with the least access the job
|
|
165
|
+
needs. Every setting, including the runtime limits, is in
|
|
166
|
+
[configuration.md](docs/configuration.md).
|
|
167
|
+
|
|
168
|
+
<details>
|
|
169
|
+
<summary><b>Claude Code</b></summary>
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
claude mcp add --env SQL_SAFE_MCP_CONFIG=/path/to/sql-safe-mcp.yaml --env REPORTING_SQL_URL=mssql+pyodbc://... --transport stdio sql-safe -- uvx sql-safe-mcp
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Put at least one other option between the last `--env` and the server name, as above - the CLI
|
|
176
|
+
otherwise reads the name as another `KEY=value` pair.
|
|
177
|
+
|
|
178
|
+
</details>
|
|
179
|
+
|
|
180
|
+
<details>
|
|
181
|
+
<summary><b>Claude Desktop</b></summary>
|
|
182
|
+
|
|
183
|
+
In `claude_desktop_config.json`:
|
|
184
|
+
|
|
185
|
+
```json
|
|
186
|
+
{
|
|
187
|
+
"mcpServers": {
|
|
188
|
+
"sql-safe": {
|
|
189
|
+
"command": "uvx",
|
|
190
|
+
"args": ["sql-safe-mcp"],
|
|
191
|
+
"env": {
|
|
192
|
+
"SQL_SAFE_MCP_CONFIG": "/path/to/sql-safe-mcp.yaml",
|
|
193
|
+
"REPORTING_SQL_URL": "mssql+pyodbc://..."
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
</details>
|
|
201
|
+
|
|
202
|
+
<details>
|
|
203
|
+
<summary><b>Codex CLI</b></summary>
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
codex mcp add sql-safe --env SQL_SAFE_MCP_CONFIG=/path/to/sql-safe-mcp.yaml --env REPORTING_SQL_URL=mssql+pyodbc://... -- uvx sql-safe-mcp
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
</details>
|
|
210
|
+
|
|
211
|
+
<details>
|
|
212
|
+
<summary><b>Any other stdio host</b></summary>
|
|
213
|
+
|
|
214
|
+
Command `uvx`, argument `sql-safe-mcp`, and the environment variables your configuration
|
|
215
|
+
references, plus `SQL_SAFE_MCP_CONFIG`. The server speaks MCP over stdio and logs only to stderr.
|
|
216
|
+
|
|
217
|
+
</details>
|
|
218
|
+
|
|
219
|
+
## PII-safe queries
|
|
220
|
+
|
|
221
|
+
Mark an alias `access_level: pii_safe`, give it its own key, and list the protected columns:
|
|
222
|
+
|
|
223
|
+
```yaml
|
|
224
|
+
servers:
|
|
225
|
+
legacy_prod:
|
|
226
|
+
engine: sqlserver
|
|
227
|
+
access_level: pii_safe
|
|
228
|
+
connection_url: "${LEGACY_PROD_SQL_URL}"
|
|
229
|
+
pii_key_env: LEGACY_PROD_PII_KEY
|
|
230
|
+
pii:
|
|
231
|
+
rules:
|
|
232
|
+
- database: "*"
|
|
233
|
+
schema: dbo
|
|
234
|
+
table: Users
|
|
235
|
+
columns: [Email, FirstName, LastName]
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
`execute_sql` then accepts one restricted `SELECT`. Protected cells come back as tokens, and a
|
|
239
|
+
token is accepted only in `=` and `IN` predicates on the same alias. Protection covers the columns
|
|
240
|
+
you list, so list every column that holds personal data. The rule format, key generation, and the
|
|
241
|
+
accepted SQL are in [configuration.md](docs/configuration.md) and [tools.md](docs/tools.md).
|
|
242
|
+
|
|
243
|
+
## Security
|
|
244
|
+
|
|
245
|
+
The MCP caller, SQL input, database metadata, rows, and tokens are untrusted; the operator, the
|
|
246
|
+
process environment, and the database credentials are the trusted boundary. Database permissions
|
|
247
|
+
remain the primary authorization control - this server never widens them. The full model and its
|
|
248
|
+
verification are in [SECURITY-MODEL.md](SECURITY-MODEL.md). To report a vulnerability,
|
|
249
|
+
use the private channel in [SECURITY.md](SECURITY.md).
|
|
250
|
+
|
|
251
|
+
## Contributing
|
|
252
|
+
|
|
253
|
+
Setup, checks, the test commands, the branch and commit conventions, and the release model are in
|
|
254
|
+
[CONTRIBUTING.md](CONTRIBUTING.md). Changes that affect someone running the server are recorded in
|
|
255
|
+
[CHANGELOG.md](CHANGELOG.md).
|
|
256
|
+
|
|
257
|
+
## License
|
|
258
|
+
|
|
259
|
+
[MIT](LICENSE).
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
sql_safe_mcp/__init__.py,sha256=ZtYU3y1sIeDCTNPFFv0DQJiXDUg7P4FXl55MCPNrrY8,84
|
|
2
|
+
sql_safe_mcp/__main__.py,sha256=0zI8w4Tg1orvlHngyNiVxrjhpQxhGIpKCcQGvPdLJS0,1210
|
|
3
|
+
sql_safe_mcp/config.py,sha256=3J1cUwI6ygmjrEh2ODZGdOw-uttfoZWEkPo4miUjRXI,8324
|
|
4
|
+
sql_safe_mcp/errors.py,sha256=2V-gXe9j3zdlQQ0ryGEaHk9ET1BxMbWrc7DXkdqOd2w,1483
|
|
5
|
+
sql_safe_mcp/mcp_server.py,sha256=8rW5DR33e8oWI7bUGVinFx-hy4SVrAzaELaCOXUGzkI,4848
|
|
6
|
+
sql_safe_mcp/models.py,sha256=iVXYpjllUEAHYMr0IqLLa567FRuFrVal4qd76fmau9Q,2836
|
|
7
|
+
sql_safe_mcp/service.py,sha256=lP4Ji0iWNv6DFhbN7Eje8A0kipmfPCSzgLgV-ttRACg,12986
|
|
8
|
+
sql_safe_mcp/db/__init__.py,sha256=9OzZMXtRCRhrc9UW7wyP3WpHqYdARd-t9CpEgNJ7n-U,34
|
|
9
|
+
sql_safe_mcp/db/extras.py,sha256=b8uPnmwD93VxsmV2nZdO-jFkoQNCYOZocwHSQntV-2I,962
|
|
10
|
+
sql_safe_mcp/db/mysql.py,sha256=y7xuoh2wsBEVbZyWOAUqxEFUHCL4a7bX9DlvmWC8S7o,2386
|
|
11
|
+
sql_safe_mcp/db/reflection.py,sha256=rc-Wze0mCX0mim6llr2PgirjxfouMTWZHyY9J2jYzs8,4611
|
|
12
|
+
sql_safe_mcp/db/registry.py,sha256=t3i4m1l8hpaM-Uh49Itm77F-lcbAvTUGRUsiwoCn7eU,4480
|
|
13
|
+
sql_safe_mcp/db/sqlserver.py,sha256=RWDa42UOsDg95Afrq9ll_hdmUgIE7Q_0nrBmyoRJ2v0,2296
|
|
14
|
+
sql_safe_mcp/security/__init__.py,sha256=BILBe5I3egmNNauOHkXfWCpKgGIF38rXcuRbX2RejZQ,66
|
|
15
|
+
sql_safe_mcp/security/dialect.py,sha256=mrbFCYvkphuDV74CiRci5ZITCIv5p-BCqr-9ZlfPMno,1130
|
|
16
|
+
sql_safe_mcp/security/executor.py,sha256=YGO9sXgj3FwfAhgx8xQbWjCEY1Dboi2Wr66bHxKye_4,4415
|
|
17
|
+
sql_safe_mcp/security/lineage.py,sha256=l4bkkbZYNG0AW7Ez-17PM7S6gF4cFtAHBZWi7DRt9kA,8034
|
|
18
|
+
sql_safe_mcp/security/parser.py,sha256=TCTlQmm1wsdQEOxgiM4DG7DY9ra0CpxS8fX7RsLH30w,7535
|
|
19
|
+
sql_safe_mcp/security/pipeline.py,sha256=PleegA8l4fm9ENesJsmcEcsel_YnrZD-1pyaGdlRp_s,1464
|
|
20
|
+
sql_safe_mcp/security/policy.py,sha256=qAyrHzsS_q2ZHEIj9H5zm-jHng9xps84nw1Z0HNDw34,3778
|
|
21
|
+
sql_safe_mcp/security/reasons.py,sha256=xOzxvO0txedkjB-gt09_CZgNMda9Luuwe7n-kq2t0m8,2678
|
|
22
|
+
sql_safe_mcp/security/schema.py,sha256=uhGd_79ntJb1iGT9RWymAwyTlpEEeyfMZlucWKo8ZH8,5007
|
|
23
|
+
sql_safe_mcp/security/tokens.py,sha256=XnTwlYpdDxIW41aM2-tvcSA6KefAd2FMzq8_POosSWc,7134
|
|
24
|
+
sql_safe_mcp/security/validated_query.py,sha256=Bi6mriaT4xkOhoF6Kh3eiKPloizrMBQrOuYtqzUDnV4,6987
|
|
25
|
+
sql_safe_mcp-1.2.0.dist-info/METADATA,sha256=AVDnoiAefEp3LdeVUxC3lZKSNkk3wCQAugCzlAJ6k0s,10850
|
|
26
|
+
sql_safe_mcp-1.2.0.dist-info/WHEEL,sha256=THafob7ofN-NsuMN7Mg4qZyHaQI7KkD-QlcQatYhXPo,87
|
|
27
|
+
sql_safe_mcp-1.2.0.dist-info/entry_points.txt,sha256=kHW1kqvrxB7wgJ3rckGvWR95JEoT_zjql7-ASTKcxyI,60
|
|
28
|
+
sql_safe_mcp-1.2.0.dist-info/licenses/LICENSE,sha256=D5ajj8LaHI_KEmp64J78GqH7a71vwYWZIg3spYMVYJY,1074
|
|
29
|
+
sql_safe_mcp-1.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Anton Padapryhara
|
|
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.
|