datapilot-mcp 0.1.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.
- datapilot_mcp/__init__.py +5 -0
- datapilot_mcp/cli.py +236 -0
- datapilot_mcp/config.py +205 -0
- datapilot_mcp/database/__init__.py +1 -0
- datapilot_mcp/database/connections.py +321 -0
- datapilot_mcp/database/manager.py +150 -0
- datapilot_mcp/database/profiling.py +339 -0
- datapilot_mcp/database/query_engine.py +227 -0
- datapilot_mcp/database/schema_registry.py +339 -0
- datapilot_mcp/database/sql_security.py +228 -0
- datapilot_mcp/errors.py +67 -0
- datapilot_mcp/logging_config.py +110 -0
- datapilot_mcp/server.py +690 -0
- datapilot_mcp/tools/__init__.py +1 -0
- datapilot_mcp/tools/naming.py +79 -0
- datapilot_mcp-0.1.0.dist-info/METADATA +402 -0
- datapilot_mcp-0.1.0.dist-info/RECORD +20 -0
- datapilot_mcp-0.1.0.dist-info/WHEEL +4 -0
- datapilot_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- datapilot_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
datapilot_mcp/cli.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Command line interface.
|
|
2
|
+
|
|
3
|
+
The CLI exists so that the server can be exercised without an MCP client in
|
|
4
|
+
the loop. When something is wrong, `datapilot-mcp doctor` and
|
|
5
|
+
`datapilot-mcp inspect` answer "is it me or is it the agent?" in one step,
|
|
6
|
+
which is the question that otherwise costs an hour.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Annotated
|
|
15
|
+
|
|
16
|
+
import typer
|
|
17
|
+
|
|
18
|
+
from .config import load_settings
|
|
19
|
+
from .errors import DataPilotError
|
|
20
|
+
from .logging_config import configure_logging
|
|
21
|
+
|
|
22
|
+
app = typer.Typer(
|
|
23
|
+
name="datapilot-mcp",
|
|
24
|
+
help="Safe database exploration and multi-agent memory over MCP.",
|
|
25
|
+
no_args_is_help=True,
|
|
26
|
+
add_completion=False,
|
|
27
|
+
)
|
|
28
|
+
db_app = typer.Typer(help="Inspect databases without starting a server.")
|
|
29
|
+
app.add_typer(db_app, name="database")
|
|
30
|
+
|
|
31
|
+
ConfigOpt = Annotated[
|
|
32
|
+
Path | None, typer.Option("--config", "-c", help="Path to a TOML config file.")
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _settings(config: Path | None):
|
|
37
|
+
try:
|
|
38
|
+
return load_settings(config)
|
|
39
|
+
except DataPilotError as exc:
|
|
40
|
+
typer.secho(f"configuration error: {exc}", fg="red", err=True)
|
|
41
|
+
raise typer.Exit(2) from exc
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@app.command()
|
|
45
|
+
def serve(
|
|
46
|
+
config: ConfigOpt = None,
|
|
47
|
+
transport: Annotated[
|
|
48
|
+
str, typer.Option(help="stdio, sse or streamable-http.")
|
|
49
|
+
] = "stdio",
|
|
50
|
+
database: Annotated[
|
|
51
|
+
Path | None,
|
|
52
|
+
typer.Option("--database", "-d", help="SQLite file to open on startup."),
|
|
53
|
+
] = None,
|
|
54
|
+
alias: Annotated[str, typer.Option(help="Alias for --database.")] = "main",
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Run the MCP server.
|
|
57
|
+
|
|
58
|
+
With --database, the file is opened and its schema discovered before the
|
|
59
|
+
first client request, so an agent sees the generated table tools
|
|
60
|
+
immediately rather than having to call connect_database first.
|
|
61
|
+
"""
|
|
62
|
+
settings = _settings(config)
|
|
63
|
+
configure_logging(settings.server.log_level, settings.server.log_format)
|
|
64
|
+
|
|
65
|
+
from .database.connections import ConnectionSpec
|
|
66
|
+
from .server import build_server
|
|
67
|
+
|
|
68
|
+
server = build_server(settings)
|
|
69
|
+
if database is not None:
|
|
70
|
+
try:
|
|
71
|
+
server.manager.connect(
|
|
72
|
+
ConnectionSpec(
|
|
73
|
+
alias=alias,
|
|
74
|
+
backend="sqlite",
|
|
75
|
+
database=str(database),
|
|
76
|
+
readonly=settings.database.readonly,
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
server.regenerate_table_tools(alias)
|
|
80
|
+
except DataPilotError as exc:
|
|
81
|
+
typer.secho(f"could not open {database}: {exc}", fg="red", err=True)
|
|
82
|
+
raise typer.Exit(1) from exc
|
|
83
|
+
|
|
84
|
+
server.mcp.run(transport=transport) # type: ignore[arg-type]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@app.command()
|
|
88
|
+
def doctor(config: ConfigOpt = None) -> None:
|
|
89
|
+
"""Check the installation and report what is and is not available."""
|
|
90
|
+
settings = _settings(config)
|
|
91
|
+
rows: list[tuple[str, str, str]] = []
|
|
92
|
+
|
|
93
|
+
import importlib
|
|
94
|
+
|
|
95
|
+
for module, purpose in (
|
|
96
|
+
("mcp", "MCP protocol"),
|
|
97
|
+
("sqlalchemy", "database access"),
|
|
98
|
+
("sqlglot", "SQL validation"),
|
|
99
|
+
("structlog", "logging"),
|
|
100
|
+
("psycopg", "PostgreSQL driver"),
|
|
101
|
+
("pandas", "dataframe analysis"),
|
|
102
|
+
("duckdb", "analytical queries"),
|
|
103
|
+
("plotly", "interactive charts"),
|
|
104
|
+
("matplotlib", "static charts"),
|
|
105
|
+
("pyarrow", "Parquet export"),
|
|
106
|
+
("openpyxl", "Excel export"),
|
|
107
|
+
):
|
|
108
|
+
try:
|
|
109
|
+
mod = importlib.import_module(module)
|
|
110
|
+
version = getattr(mod, "__version__", "present")
|
|
111
|
+
rows.append((module, f"ok {version}", purpose))
|
|
112
|
+
except ImportError:
|
|
113
|
+
required = module in {"mcp", "sqlalchemy", "sqlglot", "structlog"}
|
|
114
|
+
rows.append(
|
|
115
|
+
(module, "MISSING" if required else "not installed", purpose)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
typer.echo(f"python {sys.version.split()[0]}")
|
|
119
|
+
typer.echo(f"read-only {settings.database.readonly}")
|
|
120
|
+
typer.echo(f"max rows {settings.database.max_rows}")
|
|
121
|
+
typer.echo(f"query timeout {settings.database.query_timeout_seconds}s")
|
|
122
|
+
typer.echo(f"export directory {settings.resolved_export_directory()}")
|
|
123
|
+
typer.echo("")
|
|
124
|
+
for name, status, purpose in rows:
|
|
125
|
+
mark = "x" if status.startswith("MISSING") else ("-" if "not installed" in status else "+")
|
|
126
|
+
typer.echo(f" {mark} {name:<14} {status:<16} {purpose}")
|
|
127
|
+
|
|
128
|
+
missing = [r[0] for r in rows if r[1].startswith("MISSING")]
|
|
129
|
+
if missing:
|
|
130
|
+
typer.secho(
|
|
131
|
+
f"\nrequired packages missing: {', '.join(missing)}", fg="red", err=True
|
|
132
|
+
)
|
|
133
|
+
raise typer.Exit(1)
|
|
134
|
+
typer.secho("\nready", fg="green")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@db_app.command("test")
|
|
138
|
+
def database_test(
|
|
139
|
+
database: Annotated[Path, typer.Argument(help="SQLite file to open.")],
|
|
140
|
+
config: ConfigOpt = None,
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Open a database read-only and confirm writes are actually refused."""
|
|
143
|
+
settings = _settings(config)
|
|
144
|
+
configure_logging("WARNING", settings.server.log_format)
|
|
145
|
+
from .database.connections import ConnectionSpec, create_engine_for, verify_connection
|
|
146
|
+
|
|
147
|
+
spec = ConnectionSpec(alias="test", backend="sqlite", database=str(database))
|
|
148
|
+
try:
|
|
149
|
+
info = verify_connection(create_engine_for(spec), spec)
|
|
150
|
+
except DataPilotError as exc:
|
|
151
|
+
typer.secho(str(exc), fg="red", err=True)
|
|
152
|
+
raise typer.Exit(1) from exc
|
|
153
|
+
typer.echo(json.dumps(info, indent=2, default=str))
|
|
154
|
+
if not info.get("readonly_enforced"):
|
|
155
|
+
typer.secho(
|
|
156
|
+
"WARNING: this connection accepted a write. Do not expose it.",
|
|
157
|
+
fg="red",
|
|
158
|
+
err=True,
|
|
159
|
+
)
|
|
160
|
+
raise typer.Exit(1)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@db_app.command("inspect")
|
|
164
|
+
def database_inspect(
|
|
165
|
+
database: Annotated[Path, typer.Argument(help="SQLite file to inspect.")],
|
|
166
|
+
table: Annotated[str | None, typer.Option(help="Describe just this table.")] = None,
|
|
167
|
+
config: ConfigOpt = None,
|
|
168
|
+
) -> None:
|
|
169
|
+
"""Print the discovered schema as JSON."""
|
|
170
|
+
settings = _settings(config)
|
|
171
|
+
configure_logging("WARNING", settings.server.log_format)
|
|
172
|
+
from .database.connections import ConnectionSpec
|
|
173
|
+
from .database.manager import DatabaseManager
|
|
174
|
+
|
|
175
|
+
mgr = DatabaseManager(settings)
|
|
176
|
+
try:
|
|
177
|
+
mgr.connect(ConnectionSpec(alias="i", backend="sqlite", database=str(database)))
|
|
178
|
+
schema = mgr.schema("i")
|
|
179
|
+
if table:
|
|
180
|
+
info = schema.get(table)
|
|
181
|
+
if info is None:
|
|
182
|
+
typer.secho(
|
|
183
|
+
f"no table {table!r}; found: {', '.join(schema.table_names())}",
|
|
184
|
+
fg="red",
|
|
185
|
+
err=True,
|
|
186
|
+
)
|
|
187
|
+
raise typer.Exit(1)
|
|
188
|
+
typer.echo(json.dumps(info.to_dict(), indent=2, default=str))
|
|
189
|
+
else:
|
|
190
|
+
typer.echo(
|
|
191
|
+
json.dumps(
|
|
192
|
+
{
|
|
193
|
+
"overview": schema.overview(),
|
|
194
|
+
"tables": schema.table_names(),
|
|
195
|
+
"relationships": schema.relationships(),
|
|
196
|
+
},
|
|
197
|
+
indent=2,
|
|
198
|
+
default=str,
|
|
199
|
+
)
|
|
200
|
+
)
|
|
201
|
+
finally:
|
|
202
|
+
mgr.dispose_all()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@app.command("tools")
|
|
206
|
+
def list_tools(
|
|
207
|
+
database: Annotated[
|
|
208
|
+
Path | None, typer.Option("--database", "-d", help="Open this SQLite file first.")
|
|
209
|
+
] = None,
|
|
210
|
+
config: ConfigOpt = None,
|
|
211
|
+
) -> None:
|
|
212
|
+
"""List the MCP tools an agent would see, including generated ones."""
|
|
213
|
+
settings = _settings(config)
|
|
214
|
+
configure_logging("WARNING", settings.server.log_format)
|
|
215
|
+
from .database.connections import ConnectionSpec
|
|
216
|
+
from .server import build_server
|
|
217
|
+
|
|
218
|
+
server = build_server(settings)
|
|
219
|
+
try:
|
|
220
|
+
if database is not None:
|
|
221
|
+
server.manager.connect(
|
|
222
|
+
ConnectionSpec(alias="main", backend="sqlite", database=str(database))
|
|
223
|
+
)
|
|
224
|
+
server.regenerate_table_tools("main")
|
|
225
|
+
import asyncio
|
|
226
|
+
|
|
227
|
+
tools = asyncio.run(server.mcp.list_tools())
|
|
228
|
+
for tool in sorted(tools, key=lambda t: t.name):
|
|
229
|
+
first_line = (tool.description or "").strip().splitlines()
|
|
230
|
+
typer.echo(f"{tool.name:<34} {first_line[0] if first_line else ''}")
|
|
231
|
+
finally:
|
|
232
|
+
server.close()
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
if __name__ == "__main__": # pragma: no cover
|
|
236
|
+
app()
|
datapilot_mcp/config.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Configuration.
|
|
2
|
+
|
|
3
|
+
Precedence, lowest to highest: built-in defaults, then a TOML file, then
|
|
4
|
+
environment variables, then explicit arguments. Each layer only overrides the
|
|
5
|
+
keys it actually sets, so a TOML file that mentions one option leaves the rest
|
|
6
|
+
at their defaults.
|
|
7
|
+
|
|
8
|
+
Secrets are deliberately absent from this tree. A database password is read
|
|
9
|
+
from the environment at connection time and is never stored in a config object,
|
|
10
|
+
so it cannot be reached by a tool that dumps configuration.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import tomllib
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Literal
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, Field, field_validator
|
|
21
|
+
|
|
22
|
+
from .errors import ConfigError
|
|
23
|
+
|
|
24
|
+
ENV_PREFIX = "DATAPILOT_"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ServerConfig(BaseModel):
|
|
28
|
+
"""Identity and transport of the MCP server itself."""
|
|
29
|
+
|
|
30
|
+
name: str = "datapilot-mcp"
|
|
31
|
+
transport: Literal["stdio", "sse", "streamable-http"] = "stdio"
|
|
32
|
+
host: str = "127.0.0.1"
|
|
33
|
+
port: int = 8000
|
|
34
|
+
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
|
|
35
|
+
log_format: Literal["console", "json"] = "console"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DatabaseConfig(BaseModel):
|
|
39
|
+
"""Limits applied to every database connection and query."""
|
|
40
|
+
|
|
41
|
+
readonly: bool = True
|
|
42
|
+
max_rows: int = Field(default=10_000, gt=0)
|
|
43
|
+
query_timeout_seconds: float = Field(default=30.0, gt=0)
|
|
44
|
+
statement_cache_size: int = Field(default=0, ge=0)
|
|
45
|
+
pool_size: int = Field(default=5, gt=0)
|
|
46
|
+
pool_max_overflow: int = Field(default=5, ge=0)
|
|
47
|
+
sample_rows: int = Field(default=10, gt=0)
|
|
48
|
+
|
|
49
|
+
@field_validator("readonly")
|
|
50
|
+
@classmethod
|
|
51
|
+
def _warn_on_write_mode(cls, value: bool) -> bool:
|
|
52
|
+
# Writable mode is deliberately awkward to switch on: it is a sharp
|
|
53
|
+
# edge, not a convenience, and nothing in this server needs it.
|
|
54
|
+
if not value and os.environ.get(f"{ENV_PREFIX}I_UNDERSTAND_WRITE_RISK") != "yes":
|
|
55
|
+
raise ValueError(
|
|
56
|
+
"database.readonly=false requires the environment variable "
|
|
57
|
+
f"{ENV_PREFIX}I_UNDERSTAND_WRITE_RISK=yes to be set. This server "
|
|
58
|
+
"is designed around read-only access and its SQL validation "
|
|
59
|
+
"assumes it."
|
|
60
|
+
)
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ToolExposureConfig(BaseModel):
|
|
65
|
+
"""How many generated tools to put in front of an agent.
|
|
66
|
+
|
|
67
|
+
A database with a thousand tables would otherwise generate thousands of
|
|
68
|
+
tools and overwhelm the client's tool list, so generation is bounded and
|
|
69
|
+
the generic tools remain available for everything not covered.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
generate_table_tools: bool = True
|
|
73
|
+
max_generated_tables: int = Field(default=40, ge=0)
|
|
74
|
+
include_tables: list[str] = Field(default_factory=list)
|
|
75
|
+
exclude_tables: list[str] = Field(default_factory=list)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class SecurityConfig(BaseModel):
|
|
79
|
+
"""Filesystem and connection restrictions."""
|
|
80
|
+
|
|
81
|
+
allow_filesystem_export: bool = True
|
|
82
|
+
allowed_export_directory: Path = Path("./data/artifacts")
|
|
83
|
+
allow_remote_connections: bool = False
|
|
84
|
+
max_export_rows: int = Field(default=1_000_000, gt=0)
|
|
85
|
+
max_export_bytes: int = Field(default=256 * 1024 * 1024, gt=0)
|
|
86
|
+
audit_log_enabled: bool = True
|
|
87
|
+
audit_log_path: Path = Path("./data/logs/audit.jsonl")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class AgentsConfig(BaseModel):
|
|
91
|
+
"""Multi-agent coordination store."""
|
|
92
|
+
|
|
93
|
+
enabled: bool = True
|
|
94
|
+
storage_path: Path = Path("./data/agents.sqlite3")
|
|
95
|
+
workspace_root: Path = Path("./data/workspaces")
|
|
96
|
+
memory_enabled: bool = True
|
|
97
|
+
task_leases_enabled: bool = True
|
|
98
|
+
lease_seconds: int = Field(default=900, gt=0)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class VisualizationConfig(BaseModel):
|
|
102
|
+
"""Chart rendering and artifact lifetime."""
|
|
103
|
+
|
|
104
|
+
enabled: bool = True
|
|
105
|
+
output_format: Literal["html", "png", "svg"] = "html"
|
|
106
|
+
artifact_ttl_hours: int = Field(default=24, gt=0)
|
|
107
|
+
max_points: int = Field(default=50_000, gt=0)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Settings(BaseModel):
|
|
111
|
+
"""The whole configuration tree."""
|
|
112
|
+
|
|
113
|
+
server: ServerConfig = Field(default_factory=ServerConfig)
|
|
114
|
+
database: DatabaseConfig = Field(default_factory=DatabaseConfig)
|
|
115
|
+
tools: ToolExposureConfig = Field(default_factory=ToolExposureConfig)
|
|
116
|
+
security: SecurityConfig = Field(default_factory=SecurityConfig)
|
|
117
|
+
agents: AgentsConfig = Field(default_factory=AgentsConfig)
|
|
118
|
+
visualization: VisualizationConfig = Field(default_factory=VisualizationConfig)
|
|
119
|
+
|
|
120
|
+
def resolved_export_directory(self) -> Path:
|
|
121
|
+
"""The export directory as an absolute, resolved path."""
|
|
122
|
+
return self.security.allowed_export_directory.expanduser().resolve()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
_ENV_MAP: dict[str, tuple[str, str, type]] = {
|
|
126
|
+
"TRANSPORT": ("server", "transport", str),
|
|
127
|
+
"HOST": ("server", "host", str),
|
|
128
|
+
"PORT": ("server", "port", int),
|
|
129
|
+
"LOG_LEVEL": ("server", "log_level", str),
|
|
130
|
+
"LOG_FORMAT": ("server", "log_format", str),
|
|
131
|
+
"READONLY": ("database", "readonly", bool),
|
|
132
|
+
"MAX_ROWS": ("database", "max_rows", int),
|
|
133
|
+
"QUERY_TIMEOUT_SECONDS": ("database", "query_timeout_seconds", float),
|
|
134
|
+
"GENERATE_TABLE_TOOLS": ("tools", "generate_table_tools", bool),
|
|
135
|
+
"MAX_GENERATED_TABLES": ("tools", "max_generated_tables", int),
|
|
136
|
+
"ALLOW_FILESYSTEM_EXPORT": ("security", "allow_filesystem_export", bool),
|
|
137
|
+
"ALLOWED_EXPORT_DIRECTORY": ("security", "allowed_export_directory", str),
|
|
138
|
+
"ALLOW_REMOTE_CONNECTIONS": ("security", "allow_remote_connections", bool),
|
|
139
|
+
"AGENTS_STORAGE_PATH": ("agents", "storage_path", str),
|
|
140
|
+
"WORKSPACE_ROOT": ("agents", "workspace_root", str),
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _coerce(raw: str, kind: type) -> Any:
|
|
145
|
+
if kind is bool:
|
|
146
|
+
lowered = raw.strip().lower()
|
|
147
|
+
if lowered in {"1", "true", "yes", "on"}:
|
|
148
|
+
return True
|
|
149
|
+
if lowered in {"0", "false", "no", "off"}:
|
|
150
|
+
return False
|
|
151
|
+
raise ConfigError(f"expected a boolean, got {raw!r}")
|
|
152
|
+
return kind(raw)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _deep_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]:
|
|
156
|
+
merged = dict(base)
|
|
157
|
+
for key, value in overlay.items():
|
|
158
|
+
if isinstance(value, dict) and isinstance(merged.get(key), dict):
|
|
159
|
+
merged[key] = _deep_merge(merged[key], value)
|
|
160
|
+
else:
|
|
161
|
+
merged[key] = value
|
|
162
|
+
return merged
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def env_overrides(environ: dict[str, str] | None = None) -> dict[str, Any]:
|
|
166
|
+
"""Read ``DATAPILOT_*`` variables into a partial settings mapping."""
|
|
167
|
+
source = os.environ if environ is None else environ
|
|
168
|
+
out: dict[str, Any] = {}
|
|
169
|
+
for suffix, (section, key, kind) in _ENV_MAP.items():
|
|
170
|
+
raw = source.get(f"{ENV_PREFIX}{suffix}")
|
|
171
|
+
if raw is None:
|
|
172
|
+
continue
|
|
173
|
+
try:
|
|
174
|
+
out.setdefault(section, {})[key] = _coerce(raw, kind)
|
|
175
|
+
except (ValueError, ConfigError) as exc:
|
|
176
|
+
raise ConfigError(f"{ENV_PREFIX}{suffix}: {exc}") from exc
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def load_settings(
|
|
181
|
+
config_file: Path | None = None,
|
|
182
|
+
overrides: dict[str, Any] | None = None,
|
|
183
|
+
environ: dict[str, str] | None = None,
|
|
184
|
+
) -> Settings:
|
|
185
|
+
"""Build settings from defaults, a TOML file, the environment and arguments."""
|
|
186
|
+
data: dict[str, Any] = {}
|
|
187
|
+
|
|
188
|
+
if config_file is not None:
|
|
189
|
+
path = Path(config_file).expanduser()
|
|
190
|
+
if not path.is_file():
|
|
191
|
+
raise ConfigError(f"configuration file not found: {path}")
|
|
192
|
+
try:
|
|
193
|
+
with path.open("rb") as handle:
|
|
194
|
+
data = _deep_merge(data, tomllib.load(handle))
|
|
195
|
+
except tomllib.TOMLDecodeError as exc:
|
|
196
|
+
raise ConfigError(f"{path} is not valid TOML: {exc}") from exc
|
|
197
|
+
|
|
198
|
+
data = _deep_merge(data, env_overrides(environ))
|
|
199
|
+
if overrides:
|
|
200
|
+
data = _deep_merge(data, overrides)
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
return Settings.model_validate(data)
|
|
204
|
+
except Exception as exc: # pydantic ValidationError and our own ValueErrors
|
|
205
|
+
raise ConfigError(f"invalid configuration: {exc}") from exc
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Database connection, introspection, validation and execution."""
|