qodalis-cli-server-plugin-databases 1.0.0b30__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.
@@ -0,0 +1,38 @@
1
+ """The admin dashboard's Databases page (``@qodalis/cli-dashboard-module-databases``), served at
2
+ ``/qcli/databases``, outside the API, so the dashboard's ``import()`` needs no token; it also puts cards on the
3
+ dashboard's Overview."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ from typing import Optional
9
+
10
+ from qodalis_cli_server_abstractions.dashboard_modules import DashboardModulePage, module_page_of
11
+
12
+ from .databases import DATABASES_READ
13
+
14
+ DATABASES_DASHBOARD_PREFIX = "/qcli/databases"
15
+
16
+ #: The page's registration (entry and styles are added when served).
17
+ DATABASES_DASHBOARD_PAGE = {
18
+ "id": "databases",
19
+ "title": "Databases",
20
+ "titles": {
21
+ "es": "Bases de datos", "fr": "Bases de données", "de": "Datenbanken", "pt": "Bancos de dados",
22
+ "it": "Database", "ja": "データベース", "ko": "데이터베이스", "zh": "数据库", "ru": "Базы данных",
23
+ "ro": "Baze de date",
24
+ },
25
+ "icon": "🗄️",
26
+ "group": "data",
27
+ "order": 20,
28
+ "permission": DATABASES_READ,
29
+ "widgets": ["overview"],
30
+ }
31
+
32
+
33
+ def databases_page(directory: str | bool | None = None) -> Optional[DashboardModulePage]:
34
+ """The page: ``directory`` another build, ``False`` none, default the copy in the package
35
+ (``scripts/copy_dashboard.py``); ``None`` when there is no build."""
36
+ return module_page_of(
37
+ os.path.dirname(os.path.abspath(__file__)), directory, DATABASES_DASHBOARD_PREFIX, DATABASES_DASHBOARD_PAGE,
38
+ )
@@ -0,0 +1,112 @@
1
+ """The registered databases: summaries, stats and what happens around a migration run (event, audit entry)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from typing import Any, Literal
8
+
9
+ from qodalis_cli_server_abstractions import AuditEntry, CliEventAudience, IAuditStore, ICliEventBus
10
+
11
+ from .runner import CliMigrationError, CliMigrationRun, CliMigrationRunner, CliMigrationRunOptions
12
+ from .stats import collect_size, collect_stats
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ #: The event published after every migration run (audience ``databases:read``).
17
+ MIGRATION_RUN_EVENT = "databases:migration-run"
18
+
19
+ DATABASES_READ = "databases:read"
20
+ DATABASES_MIGRATE = "databases:migrate"
21
+
22
+
23
+ class CliDatabases:
24
+ """The registered databases: overview, stats, and migration runs with their event and audit entry."""
25
+
26
+ def __init__(self) -> None:
27
+ self._runners: dict[str, CliMigrationRunner] = {}
28
+ self.event_bus: ICliEventBus | None = None
29
+ self.audit_store: IAuditStore | None = None
30
+
31
+ def add(self, runner: CliMigrationRunner) -> None:
32
+ if runner.name in self._runners:
33
+ raise ValueError(f"migration database already added: {runner.name}")
34
+ self._runners[runner.name] = runner
35
+
36
+ def database(self, name: str) -> CliMigrationRunner | None:
37
+ return self._runners.get(name)
38
+
39
+ def require(self, name: str) -> CliMigrationRunner:
40
+ runner = self._runners.get(name)
41
+ if runner is None:
42
+ raise CliMigrationError(f"unknown database: {name}", 404)
43
+ return runner
44
+
45
+ @property
46
+ def databases(self) -> list[CliMigrationRunner]:
47
+ return list(self._runners.values())
48
+
49
+ async def _summary(self, db: CliMigrationRunner) -> dict[str, Any]:
50
+ base: dict[str, Any] = {"name": db.name, "dialect": db.dialect, "sources": db.source_names}
51
+ try:
52
+ states = await db.status()
53
+ runs, _ = await db.runs(1, 0)
54
+ except Exception as exc: # noqa: BLE001 - shown on the database
55
+ return {**base, "applied": 0, "pending": 0, "problems": 0, "error": str(exc)}
56
+ summary: dict[str, Any] = {
57
+ **base,
58
+ "applied": sum(1 for s in states if s.status == "applied"),
59
+ "pending": sum(1 for s in states if s.status in ("pending", "failed")),
60
+ "problems": sum(1 for s in states if s.status in ("changed", "missing", "failed")),
61
+ }
62
+ if runs:
63
+ last = runs[0].to_dict()
64
+ summary["lastRun"] = {
65
+ k: last[k] for k in ("id", "direction", "status", "startedAt", "trigger", "finishedAt", "actor", "error")
66
+ if k in last
67
+ }
68
+ size = await collect_size(db.options.connection)
69
+ if size is not None:
70
+ summary["sizeBytes"] = size
71
+ return summary
72
+
73
+ async def summary(self, name: str) -> dict[str, Any]:
74
+ """One database's summary (``GET /api/v1/qcli/databases/{db}``)."""
75
+ return await self._summary(self.require(name))
76
+
77
+ async def stats(self, name: str) -> dict[str, Any]:
78
+ """Size, connections, load counters and largest tables of a database (``GET /{db}/stats``)."""
79
+ db = self.require(name)
80
+ return await collect_stats(db.name, db.options.connection)
81
+
82
+ async def overview(self) -> list[dict[str, Any]]:
83
+ """Every database: applied, pending, problems, the last run and the size (``GET /api/v1/qcli/databases``)."""
84
+ return list(await asyncio.gather(*(self._summary(db) for db in self.databases)))
85
+
86
+ async def run(self, name: str, direction: Literal["up", "down"], options: CliMigrationRunOptions) -> CliMigrationRun:
87
+ """Runs up or down on a database, then publishes the event and writes the audit entry."""
88
+ db = self.require(name)
89
+ result = await (db.up(options) if direction == "up" else db.down(options))
90
+ assert isinstance(result, CliMigrationRun)
91
+ run = result
92
+ summary = ", ".join(f"{a['source']}:{a['id']}" for a in run.applied) or "nothing to do"
93
+ if self.event_bus is not None:
94
+ data: dict[str, Any] = {
95
+ "database": name, "run": run.id, "direction": direction, "status": run.status, "count": len(run.applied),
96
+ }
97
+ if run.error:
98
+ data["error"] = run.error
99
+ await self.event_bus.publish(MIGRATION_RUN_EVENT, data, CliEventAudience(permission=DATABASES_READ))
100
+ if self.audit_store is not None:
101
+ try:
102
+ await self.audit_store.log(AuditEntry(
103
+ event=f"migrations.{direction}",
104
+ username=run.actor or run.trigger,
105
+ actor=run.actor,
106
+ target=f"database:{name}",
107
+ details=f"{summary}; failed: {run.error}" if run.status == "failed" else summary,
108
+ properties={"run": run.id, "status": run.status, "trigger": run.trigger, "applied": len(run.applied)},
109
+ ))
110
+ except Exception: # noqa: BLE001 - the run happened; the audit log is best effort
111
+ logger.exception("could not audit the migration run %s", run.id)
112
+ return run
@@ -0,0 +1,228 @@
1
+ """SQL per dialect: quoting, the history tables, schema checks, renames and the migration lock."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from qodalis_cli_server_abstractions import is_sql_identifier
8
+
9
+ from .connection import CliSqlSession
10
+
11
+
12
+ def _checked(name: str) -> str:
13
+ if not is_sql_identifier(name):
14
+ raise ValueError(f"invalid identifier: {name}")
15
+ return name
16
+
17
+
18
+ def quote_ident(dialect: str, name: str) -> str:
19
+ """An identifier quoted for the dialect (validated first, so a name can never inject SQL)."""
20
+ n = _checked(name)
21
+ if dialect == "mysql":
22
+ return f"`{n}`"
23
+ if dialect == "mssql":
24
+ return f"[{n}]"
25
+ return f'"{n}"'
26
+
27
+
28
+ def quote_table(dialect: str, table: str, schema: str | None = None) -> str:
29
+ """A table name with its schema, quoted (``"qcli"."QcliFiles"``); SQLite and MySQL have no schemas here."""
30
+ t = quote_ident(dialect, table)
31
+ if schema and dialect in ("postgres", "mssql"):
32
+ return f"{quote_ident(dialect, schema)}.{t}"
33
+ return t
34
+
35
+
36
+ #: Column types the history tables use, by dialect.
37
+ _TYPES: dict[str, dict[str, str]] = {
38
+ "postgres": {"key": "varchar(150)", "text": "varchar(255)", "long": "text", "time": "timestamptz", "int": "integer"},
39
+ "mysql": {"key": "varchar(150)", "text": "varchar(255)", "long": "longtext", "time": "datetime(3)", "int": "int"},
40
+ "mssql": {"key": "nvarchar(150)", "text": "nvarchar(255)", "long": "nvarchar(max)", "time": "datetime2", "int": "int"},
41
+ "sqlite": {"key": "TEXT", "text": "TEXT", "long": "TEXT", "time": "TEXT", "int": "INTEGER"},
42
+ }
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class HistoryTables:
47
+ migrations: str
48
+ runs: str
49
+
50
+
51
+ async def ensure_history_tables(db: CliSqlSession, tables: HistoryTables, schema: str | None = None) -> None:
52
+ """Creates the history tables when missing (``QcliMigrations``, ``QcliMigrationRuns``)."""
53
+ d = db.dialect
54
+ t = _TYPES[d]
55
+
56
+ def q(name: str) -> str:
57
+ return quote_ident(d, name)
58
+
59
+ async def create(table: str, columns: list[str]) -> None:
60
+ if await table_exists(db, table, schema):
61
+ return
62
+ await db.exec(f"CREATE TABLE {quote_table(d, table, schema)} ({', '.join(columns)})")
63
+
64
+ await create(tables.migrations, [
65
+ f"{q('Source')} {t['key']} NOT NULL",
66
+ f"{q('Id')} {t['key']} NOT NULL",
67
+ f"{q('Name')} {t['text']} NOT NULL",
68
+ f"{q('Checksum')} {t['key']} NULL",
69
+ f"{q('AppliedAt')} {t['time']} NOT NULL",
70
+ f"{q('DurationMs')} {t['int']} NOT NULL",
71
+ f"{q('AppliedBy')} {t['text']} NULL",
72
+ f"{q('RunId')} {t['key']} NULL",
73
+ f"CONSTRAINT {q('PK_' + tables.migrations)} PRIMARY KEY ({q('Source')}, {q('Id')})",
74
+ ])
75
+ await create(tables.runs, [
76
+ f"{q('Id')} {t['key']} NOT NULL",
77
+ f"{q('Direction')} {t['key']} NOT NULL",
78
+ f"{q('Target')} {t['key']} NULL",
79
+ f"{q('Trigger')} {t['key']} NOT NULL",
80
+ f"{q('Actor')} {t['text']} NULL",
81
+ f"{q('StartedAt')} {t['time']} NOT NULL",
82
+ f"{q('FinishedAt')} {t['time']} NULL",
83
+ f"{q('Status')} {t['key']} NOT NULL",
84
+ f"{q('Error')} {t['long']} NULL",
85
+ f"{q('Applied')} {t['long']} NULL",
86
+ f"CONSTRAINT {q('PK_' + tables.runs)} PRIMARY KEY ({q('Id')})",
87
+ ])
88
+
89
+
90
+ async def table_exists(db: CliSqlSession, table: str, schema: str | None = None) -> bool:
91
+ """True when the table exists (in ``schema``, or the connection's default schema)."""
92
+ _checked(table)
93
+ d = db.dialect
94
+ if d == "postgres":
95
+ rows = await db.query(
96
+ "SELECT 1 AS x FROM information_schema.tables WHERE table_name = ? "
97
+ "AND table_schema = COALESCE(?::text, current_schema())",
98
+ [table, schema],
99
+ )
100
+ elif d == "mysql":
101
+ rows = await db.query(
102
+ "SELECT 1 AS x FROM information_schema.tables WHERE table_name = ? AND table_schema = DATABASE()", [table],
103
+ )
104
+ elif d == "mssql":
105
+ rows = await db.query(
106
+ "SELECT 1 AS x FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ? AND TABLE_SCHEMA = COALESCE(?, SCHEMA_NAME())",
107
+ [table, schema],
108
+ )
109
+ else:
110
+ rows = await db.query("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?", [table])
111
+ return len(rows) > 0
112
+
113
+
114
+ async def column_exists(db: CliSqlSession, table: str, column: str, schema: str | None = None) -> bool:
115
+ """True when the table has the column."""
116
+ _checked(table)
117
+ _checked(column)
118
+ d = db.dialect
119
+ if d == "postgres":
120
+ rows = await db.query(
121
+ "SELECT 1 AS x FROM information_schema.columns WHERE table_name = ? AND column_name = ? "
122
+ "AND table_schema = COALESCE(?::text, current_schema())",
123
+ [table, column, schema],
124
+ )
125
+ elif d == "mysql":
126
+ rows = await db.query(
127
+ "SELECT 1 AS x FROM information_schema.columns WHERE table_name = ? AND column_name = ? "
128
+ "AND table_schema = DATABASE()",
129
+ [table, column],
130
+ )
131
+ elif d == "mssql":
132
+ rows = await db.query(
133
+ "SELECT 1 AS x FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ? "
134
+ "AND TABLE_SCHEMA = COALESCE(?, SCHEMA_NAME())",
135
+ [table, column, schema],
136
+ )
137
+ else:
138
+ return any(c["name"] == column for c in await db.query(f"PRAGMA table_info({quote_ident('sqlite', table)})"))
139
+ return len(rows) > 0
140
+
141
+
142
+ async def rename_table(db: CliSqlSession, source: str, to: str, schema: str | None = None) -> None:
143
+ """Renames a table (in its schema)."""
144
+ d = db.dialect
145
+ if d == "mssql":
146
+ name = f"{_checked(schema)}.{_checked(source)}" if schema else _checked(source)
147
+ await db.query("EXEC sp_rename ?, ?", [name, _checked(to)])
148
+ elif d == "mysql":
149
+ await db.exec(f"RENAME TABLE {quote_ident(d, source)} TO {quote_ident(d, to)}")
150
+ else:
151
+ await db.exec(f"ALTER TABLE {quote_table(d, source, schema)} RENAME TO {quote_ident(d, to)}")
152
+
153
+
154
+ async def rename_column(db: CliSqlSession, table: str, source: str, to: str, schema: str | None = None) -> None:
155
+ """Renames a column (SQLite 3.25 and later)."""
156
+ d = db.dialect
157
+ if d == "mssql":
158
+ name = f"{_checked(schema) + '.' if schema else ''}{_checked(table)}.{_checked(source)}"
159
+ await db.query("EXEC sp_rename ?, ?, 'COLUMN'", [name, _checked(to)])
160
+ else:
161
+ await db.exec(
162
+ f"ALTER TABLE {quote_table(d, table, schema)} RENAME COLUMN {quote_ident(d, source)} TO {quote_ident(d, to)}"
163
+ )
164
+
165
+
166
+ async def adopt_legacy_table(
167
+ db: CliSqlSession,
168
+ legacy: str,
169
+ table: str,
170
+ columns: dict[str, str] | None = None,
171
+ schema: str | None = None,
172
+ ) -> bool:
173
+ """Moves a table of a previous release to its new name and columns (cli-server-dotnet#99): when ``legacy``
174
+ exists and ``table`` does not, renames the table, then each column of ``columns`` (old -> new) present
175
+ under its old name. Returns True when it renamed anything."""
176
+ if legacy == table or not await table_exists(db, legacy, schema) or await table_exists(db, table, schema):
177
+ return False
178
+ await rename_table(db, legacy, table, schema)
179
+ for source, to in (columns or {}).items():
180
+ if source != to and await column_exists(db, table, source, schema):
181
+ await rename_column(db, table, source, to, schema)
182
+ return True
183
+
184
+
185
+ #: Statements that open, commit and roll back a transaction.
186
+ TRANSACTION: dict[str, dict[str, str]] = {
187
+ "postgres": {"begin": "BEGIN", "commit": "COMMIT", "rollback": "ROLLBACK"},
188
+ "mysql": {"begin": "START TRANSACTION", "commit": "COMMIT", "rollback": "ROLLBACK"},
189
+ "mssql": {
190
+ "begin": "BEGIN TRANSACTION",
191
+ "commit": "COMMIT TRANSACTION",
192
+ "rollback": "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION",
193
+ },
194
+ "sqlite": {"begin": "BEGIN IMMEDIATE", "commit": "COMMIT", "rollback": "ROLLBACK"},
195
+ }
196
+
197
+
198
+ async def acquire_lock(db: CliSqlSession, key: str, wait: bool) -> bool:
199
+ """Takes the database's migration lock on the session: waits for it (``wait``), or returns False at once
200
+ when another process holds it. SQLite has one writer per database file and no session locks: always
201
+ True."""
202
+ d = db.dialect
203
+ if d == "postgres":
204
+ fn = "pg_advisory_lock" if wait else "pg_try_advisory_lock"
205
+ rows = await db.query(f"SELECT {fn}(hashtext(?::text))::text AS ok", [key])
206
+ return wait or (rows[0]["ok"] if rows else None) in ("true", "t")
207
+ if d == "mysql":
208
+ rows = await db.query("SELECT GET_LOCK(?, ?) AS ok", [key, -1 if wait else 0])
209
+ return rows[0]["ok"] is not None and int(rows[0]["ok"]) == 1
210
+ if d == "mssql":
211
+ rows = await db.query(
212
+ "DECLARE @r int; EXEC @r = sp_getapplock @Resource = ?, @LockMode = 'Exclusive', "
213
+ "@LockOwner = 'Session', @LockTimeout = ?; SELECT @r AS ok",
214
+ [key, -1 if wait else 0],
215
+ )
216
+ return bool(rows) and int(rows[0]["ok"]) >= 0
217
+ return True
218
+
219
+
220
+ async def release_lock(db: CliSqlSession, key: str) -> None:
221
+ """Releases the lock :func:`acquire_lock` took."""
222
+ d = db.dialect
223
+ if d == "postgres":
224
+ await db.query("SELECT pg_advisory_unlock(hashtext(?::text))::text AS ok", [key])
225
+ elif d == "mysql":
226
+ await db.query("SELECT RELEASE_LOCK(?) AS ok", [key])
227
+ elif d == "mssql":
228
+ await db.query("EXEC sp_releaseapplock @Resource = ?, @LockOwner = 'Session'", [key])
@@ -0,0 +1,174 @@
1
+ """MCP tools of the databases plugin (``databases_*``, ``migrations_*``), registered on the CLI server's MCP tool registry when
2
+ the plugin is mounted. Imported lazily (requires ``qodalis_cli``)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from typing import Any, Awaitable, Callable
8
+
9
+ from qodalis_cli.mcp import McpCallContext, McpTool, McpToolResult, object_schema
10
+
11
+ from .commands import describe_databases, describe_stats
12
+ from .controller import TO_REQUIRED, caller_name
13
+ from .databases import DATABASES_READ, DATABASES_MIGRATE, CliDatabases
14
+ from .runner import CliMigrationRunOptions
15
+
16
+ READ_ONLY = {"readOnlyHint": True}
17
+ DESTRUCTIVE = {"destructiveHint": True}
18
+
19
+ _DATABASE = {"type": "string", "description": "Database name (see databases_list)"}
20
+ _FORCE = {"type": "boolean", "description": "Run although a migration is changed or missing"}
21
+
22
+ Handler = Callable[[dict[str, Any], McpCallContext], Awaitable[McpToolResult]]
23
+
24
+
25
+ def _guarded(fn: Handler) -> Handler:
26
+ async def call(args: dict[str, Any], context: McpCallContext) -> McpToolResult:
27
+ try:
28
+ return await fn(args, context)
29
+ except Exception as exc: # noqa: BLE001 - the tool's error
30
+ return McpToolResult.error(getattr(exc, "message", None) or str(exc))
31
+
32
+ return call
33
+
34
+
35
+ def _optional(value: Any) -> str | None:
36
+ return value if isinstance(value, str) and value else None
37
+
38
+
39
+ class DatabasesMcpToolProvider:
40
+ """``databases_list``, ``databases_stats``, ``migrations_status``, ``migrations_runs``, ``migrations_sql``
41
+ (``databases:read``), ``migrations_up`` and ``migrations_down`` (``databases:migrate``)."""
42
+
43
+ name = "databases"
44
+
45
+ def __init__(self, databases: CliDatabases) -> None:
46
+ self.databases = databases
47
+
48
+ def get_tools(self, context: McpCallContext) -> list[McpTool]:
49
+ m = self.databases
50
+
51
+ async def status(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
52
+ if not _optional(args.get("database")):
53
+ databases = await m.overview()
54
+ lines = []
55
+ for d in databases:
56
+ if d.get("error"):
57
+ lines.append(f"{d['name']} ({d['dialect']}): error: {d['error']}")
58
+ else:
59
+ problems = f", {d['problems']} problem(s)" if d["problems"] else ""
60
+ lines.append(f"{d['name']} ({d['dialect']}): {d['applied']} applied, {d['pending']} pending{problems}")
61
+ return McpToolResult(text="\n".join(lines) or "No databases", structured={"databases": databases})
62
+ db = m.require(args["database"])
63
+ states = [s.to_dict() for s in await db.status()]
64
+ text = "\n".join(f"{s['status']:<8} {s['source']}:{s['id']} {s['name']}" for s in states)
65
+ return McpToolResult(
66
+ text=text or "No migrations",
67
+ structured={"name": db.name, "dialect": db.dialect, "sources": db.source_names, "migrations": states},
68
+ )
69
+
70
+ async def list_databases(_args: dict[str, Any], _: McpCallContext) -> McpToolResult:
71
+ databases = await m.overview()
72
+ return McpToolResult(text=describe_databases(databases), structured={"databases": databases})
73
+
74
+ async def stats(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
75
+ value = await m.stats(m.require(args["database"]).name)
76
+ return McpToolResult(text=describe_stats(value), structured=value)
77
+
78
+ async def runs(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
79
+ try:
80
+ limit = int(args.get("limit") or 20)
81
+ except (TypeError, ValueError):
82
+ limit = 20
83
+ limit = min(max(limit, 1), 100)
84
+ items, total = await m.require(args["database"]).runs(limit, 0)
85
+ value = {"items": [r.to_dict() for r in items], "total": total}
86
+ return McpToolResult(text=json.dumps(value, indent=2, ensure_ascii=False), structured=value)
87
+
88
+ async def sql(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
89
+ db = m.require(args["database"])
90
+ to = _optional(args.get("to"))
91
+ if args.get("direction") == "down":
92
+ if not to:
93
+ return McpToolResult.error(TO_REQUIRED)
94
+ result = await db.down(CliMigrationRunOptions(to=to, dry_run=True))
95
+ return McpToolResult(text=result["sql"] or "Nothing to roll back", structured=result) # type: ignore[index,arg-type]
96
+ result = await db.up(CliMigrationRunOptions(to=to, dry_run=True))
97
+ return McpToolResult(text=result["sql"] or "Nothing pending", structured=result) # type: ignore[index,arg-type]
98
+
99
+ def run(direction: str) -> Handler:
100
+ async def call(args: dict[str, Any], ctx: McpCallContext) -> McpToolResult:
101
+ options = CliMigrationRunOptions(
102
+ to=_optional(args.get("to")), force=args.get("force") is True, actor=caller_name(ctx.auth), trigger="mcp",
103
+ )
104
+ if direction == "down" and not options.to:
105
+ return McpToolResult.error(TO_REQUIRED)
106
+ result = await m.run(m.require(args["database"]).name, direction, options) # type: ignore[arg-type]
107
+ verb = "Applied" if direction == "up" else "Rolled back"
108
+ text = f"{verb} {len(result.applied)} migration(s) ({result.status})" + (f": {result.error}" if result.error else "")
109
+ return McpToolResult(text=text, structured=result.to_dict(), is_error=result.status == "failed")
110
+
111
+ return call
112
+
113
+ return [
114
+ McpTool(
115
+ "databases_list",
116
+ "The server's databases: dialect, size, and applied, pending and problem migration counts",
117
+ object_schema({}),
118
+ _guarded(list_databases), [DATABASES_READ], dict(READ_ONLY),
119
+ ),
120
+ McpTool(
121
+ "databases_stats",
122
+ "A database's server version and uptime, size (data, indexes, log), connections (active, open, max), "
123
+ "load counters (queries, transactions, rows; cumulative since start), cache hit ratio and largest tables",
124
+ object_schema({"database": _DATABASE}, ["database"]),
125
+ _guarded(stats), [DATABASES_READ], dict(READ_ONLY),
126
+ ),
127
+ McpTool(
128
+ "migrations_status",
129
+ "Without a database: every database with its applied, pending and problem counts. With one: its "
130
+ "migrations and their status (applied, pending, changed, missing, failed)",
131
+ object_schema({"database": _DATABASE}),
132
+ _guarded(status), [DATABASES_READ], dict(READ_ONLY),
133
+ ),
134
+ McpTool(
135
+ "migrations_runs",
136
+ "Run history of a database, newest first: direction, trigger, who, status, error and what each run applied",
137
+ object_schema({
138
+ "database": _DATABASE,
139
+ "limit": {"type": "integer", "default": 20, "description": "Maximum runs (1-100)"},
140
+ }, ["database"]),
141
+ _guarded(runs), [DATABASES_READ], dict(READ_ONLY),
142
+ ),
143
+ McpTool(
144
+ "migrations_sql",
145
+ "The SQL a run would execute, without running it (dry run)",
146
+ object_schema({
147
+ "database": _DATABASE,
148
+ "direction": {"type": "string", "description": "up (default) or down"},
149
+ "to": {"type": "string", "description": "As for migrations_up / migrations_down"},
150
+ }, ["database"]),
151
+ _guarded(sql), [DATABASES_READ], dict(READ_ONLY),
152
+ ),
153
+ McpTool(
154
+ "migrations_up",
155
+ "Apply the pending migrations of a database (all, or up to one), under its lock; refused while a "
156
+ "migration is changed or missing unless force",
157
+ object_schema({
158
+ "database": _DATABASE,
159
+ "to": {"type": "string", "description": "Stop after this migration (id or source:id); omit for all pending"},
160
+ "force": _FORCE,
161
+ }, ["database"]),
162
+ _guarded(run("up")), [DATABASES_MIGRATE],
163
+ ),
164
+ McpTool(
165
+ "migrations_down",
166
+ "Roll back the migrations of a database applied after a migration (to), running their down scripts",
167
+ object_schema({
168
+ "database": _DATABASE,
169
+ "to": {"type": "string", "description": "Roll back to this migration, keeping it (id or source:id), or base for everything"},
170
+ "force": _FORCE,
171
+ }, ["database", "to"]),
172
+ _guarded(run("down")), [DATABASES_MIGRATE], dict(DESTRUCTIVE),
173
+ ),
174
+ ]