dbgate-dashboard-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.
@@ -0,0 +1,9 @@
1
+ /.mcp.json
2
+ /.claude
3
+
4
+ __pycache__/
5
+ *.py[cod]
6
+ .venv/
7
+ .pytest_cache/
8
+ .coverage
9
+ dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evgenii Danilin
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,147 @@
1
+ Metadata-Version: 2.5
2
+ Name: dbgate-dashboard-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for querying databases through a running DbGate dashboard.
5
+ Author-email: Evgenii Danilin <evgenii.danilin.m@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: database,dbgate,mcp,mysql,postgres,sql,sqlite
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: httpx>=0.27
11
+ Requires-Dist: mcp<3,>=2.0.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # dbgate-dashboard-mcp
15
+
16
+ An MCP server that gives an agent access to databases **through a running [DbGate](https://dbgate.org/) dashboard**. No database drivers are needed: DbGate itself holds the connections, engine plugins and pool, and the server talks to it over HTTP.
17
+
18
+ Engines: MySQL, PostgreSQL, SQLite (SQL tools), MongoDB and Redis (dedicated tools below).
19
+
20
+ ## Installation
21
+
22
+ ```jsonc
23
+ // .mcp.json
24
+ {
25
+ "mcpServers": {
26
+ "dbgate-dashboard": {
27
+ "command": "uvx",
28
+ "args": ["dbgate-dashboard-mcp@latest"],
29
+ "env": {
30
+ "DBGATE_URL": "http://localhost:3000"
31
+ }
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ A remote dashboard through an SSH tunnel — `DBGATE_URL` then means the address **on the remote side**:
38
+
39
+ ```jsonc
40
+ "env": {
41
+ "DBGATE_URL": "http://localhost:3000",
42
+ "SSH_PROXY_TO": "user@remote-host"
43
+ }
44
+ ```
45
+
46
+ An HTTPS dashboard behind a reverse proxy works the same way — the port comes from the scheme (443), while `Host` and SNI stay canonical, so certificate verification is not disabled:
47
+
48
+ ```jsonc
49
+ "env": {
50
+ "DBGATE_URL": "https://dbgate.example.com",
51
+ "SSH_PROXY_TO": "user@remote-host"
52
+ }
53
+ ```
54
+
55
+ The tunnel only changes the connect address: `DBGATE_URL` is not rewritten, otherwise the proxy would receive `Host: 127.0.0.1:<port>` and answer with a redirect, and TLS would not match the certificate.
56
+
57
+ ### Tunnel loss
58
+
59
+ If ssh dies mid-session, the next call does not fail: the tunnel is reopened and the request is retried **once**. A second drop in a row is returned as an error, so an unreachable remote host does not send every tool into endless retries.
60
+
61
+ A reconnect is invisible by itself — a retried call looks like an ordinary one — so the tool result gets a `notices` field:
62
+
63
+ ```jsonc
64
+ {
65
+ "connections": [ /* ... */ ],
66
+ "notices": [
67
+ "ssh tunnel dropped (ConnectError) and was reopened on 127.0.0.1:49173; the call was retried and this result is from the new connection"
68
+ ]
69
+ }
70
+ ```
71
+
72
+ The field appears only when there is something to report, and exactly once: the queue is drained when delivered.
73
+
74
+ ## Environment variables
75
+
76
+ | Variable | Default | Purpose |
77
+ |---|---|---|
78
+ | `DBGATE_URL` | `http://localhost:3000` | dashboard address (with a tunnel — the remote side) |
79
+ | `DBGATE_LOGIN` | — | login, if authentication is enabled in DbGate |
80
+ | `DBGATE_PASSWORD` | — | its password |
81
+ | `SSH_PROXY_TO` | — | `user@host` for the SSH tunnel (`ssh -N -L`) |
82
+ | `SSH_PROXY_PORT` | auto | fixed local port for the tunnel |
83
+
84
+ ## Tools
85
+
86
+ | Tool | What it does |
87
+ |---|---|
88
+ | `list_connections` | dashboard connections: `conid`, engine, default database |
89
+ | `list_databases` | databases on a connection |
90
+ | `list_tables` | tables, views and matviews (no columns) |
91
+ | `describe_table` | columns, PK, FKs and indexes of one object |
92
+ | `query` | a read query; appends `LIMIT` and truncates the result |
93
+ | `execute` | any SQL, including writes and DDL, unmodified |
94
+ | `find_documents` | documents of a Mongo collection with filter and sort |
95
+ | `redis_keys` | browse the Redis keyspace level by level |
96
+ | `redis_get` | type, TTL and value of one key |
97
+ | `redis_command` | any Redis command, including writes |
98
+
99
+ `conid` is required by every tool — take it from `list_connections`. `database` can be omitted: the connection's default database is used.
100
+
101
+ `query` limits the output twice: it appends `LIMIT n` if the SQL has no limit of its own, and in any case cuts the response to `n` rows (`truncated: true` when cut). The DbGate API has no limit parameter, so the bound has to be held on both sides.
102
+
103
+ `LIMIT` is appended only to statements that accept it (`SELECT`, `WITH`, `VALUES`, `TABLE`). `SHOW`, `PRAGMA`, `DESCRIBE`, `EXPLAIN` go to the engine as is — with a `LIMIT` glued on they would be a syntax error; cutting to `n` rows still applies to them.
104
+
105
+ `execute` passes SQL through unchanged and without a safety net — including `INSERT`/`UPDATE`/`DELETE` and DDL. Restrict permissions on the connection itself in DbGate.
106
+
107
+ ## MongoDB and Redis
108
+
109
+ `find_documents` takes a regular Mongo filter — `{"artistId": {"$gt": 5}}`, `{"title": {"$regex": "Rock"}}`, `$in`, `$and`/`$or`. It is translated into a DbGate condition, because the dashboard API does not accept a raw Mongo filter. An unsupported operator (`$exists`, `$elemMatch`) returns an explicit error. `$regex` becomes a LIKE wrapped in `%…%`, so `%` and `_` inside the pattern act as wildcards.
110
+
111
+ Collections show up in the common `list_tables` with `type: "collection"`; `describe_table` for a collection returns the document count and the unique key — DbGate's Mongo structure has no columns.
112
+
113
+ Redis navigation has two levels: `redis_keys` without `root` shows prefixes (`album`, `track`, …), with `root` — the keys under it. `redis_get` reads a value as one page no longer than `limit` (`truncated: true` if the value continues); for the full data of a large key use `redis_command`, which runs an arbitrary command. For a missing key `redis_get` returns the error `key '…' not found`.
114
+
115
+ The command name in `redis_command` is case-insensitive — it is lowercased, because DbGate calls the method of the same name on its Redis client, and all those methods are lowercase.
116
+
117
+ A Redis connection has no default database, so `database` can be omitted: the server takes the first one in the list (`db0`). A freshly opened DbGate connection returns an empty database list while it starts up, so an empty answer is asked again — without that, database resolution sometimes failed with `has no default database`.
118
+
119
+ ## Development
120
+
121
+ ```bash
122
+ uv sync # venv + runtime + dev group
123
+ uv run pytest # full suite; addopts enforces --cov-fail-under=100
124
+ uv run pytest tests/test_server.py --no-cov # partial run — only with --no-cov
125
+ python -m dbgate_dashboard_mcp # run over stdio
126
+ ```
127
+
128
+ Tests need neither network nor a running DbGate: `httpx` and `subprocess` are faked.
129
+
130
+ ## Manual check on the test stand
131
+
132
+ The repository ships a `docker-compose.yml` with DbGate and five databases (Chinook in MySQL, PostgreSQL, SQLite, MongoDB, Redis). Seeds live in `init/`: [Chinook](https://github.com/lerocha/chinook-database) (MIT, © Luis Rocha), adapted for each engine.
133
+
134
+ ```bash
135
+ docker compose up -d
136
+ TOKEN=$(curl -s -X POST http://localhost:3000/auth/login \
137
+ -H 'Content-Type: application/json' -d '{"amoid":"none"}' \
138
+ | python3 -c 'import sys,json;print(json.load(sys.stdin)["accessToken"])')
139
+ curl -s -X POST http://localhost:3000/connections/list \
140
+ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{}'
141
+ ```
142
+
143
+ Then connect the server in an MCP client with `DBGATE_URL=http://localhost:3000` and call `list_connections`.
144
+
145
+ ## How the DbGate API works
146
+
147
+ Useful when extending the server: DbGate is RPC over HTTP, not REST. Controller methods are mounted as kebab-case paths (`queryData` → `/database-connections/query-data`), almost all of them `POST` with a single JSON object of arguments. `POST /auth/login {"amoid":"none"}` issues a token that lives 24 h. SQL errors arrive with **HTTP 200** and an `errorMessage` field, so success is decided by the response body, not the status code.
@@ -0,0 +1,134 @@
1
+ # dbgate-dashboard-mcp
2
+
3
+ An MCP server that gives an agent access to databases **through a running [DbGate](https://dbgate.org/) dashboard**. No database drivers are needed: DbGate itself holds the connections, engine plugins and pool, and the server talks to it over HTTP.
4
+
5
+ Engines: MySQL, PostgreSQL, SQLite (SQL tools), MongoDB and Redis (dedicated tools below).
6
+
7
+ ## Installation
8
+
9
+ ```jsonc
10
+ // .mcp.json
11
+ {
12
+ "mcpServers": {
13
+ "dbgate-dashboard": {
14
+ "command": "uvx",
15
+ "args": ["dbgate-dashboard-mcp@latest"],
16
+ "env": {
17
+ "DBGATE_URL": "http://localhost:3000"
18
+ }
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ A remote dashboard through an SSH tunnel — `DBGATE_URL` then means the address **on the remote side**:
25
+
26
+ ```jsonc
27
+ "env": {
28
+ "DBGATE_URL": "http://localhost:3000",
29
+ "SSH_PROXY_TO": "user@remote-host"
30
+ }
31
+ ```
32
+
33
+ An HTTPS dashboard behind a reverse proxy works the same way — the port comes from the scheme (443), while `Host` and SNI stay canonical, so certificate verification is not disabled:
34
+
35
+ ```jsonc
36
+ "env": {
37
+ "DBGATE_URL": "https://dbgate.example.com",
38
+ "SSH_PROXY_TO": "user@remote-host"
39
+ }
40
+ ```
41
+
42
+ The tunnel only changes the connect address: `DBGATE_URL` is not rewritten, otherwise the proxy would receive `Host: 127.0.0.1:<port>` and answer with a redirect, and TLS would not match the certificate.
43
+
44
+ ### Tunnel loss
45
+
46
+ If ssh dies mid-session, the next call does not fail: the tunnel is reopened and the request is retried **once**. A second drop in a row is returned as an error, so an unreachable remote host does not send every tool into endless retries.
47
+
48
+ A reconnect is invisible by itself — a retried call looks like an ordinary one — so the tool result gets a `notices` field:
49
+
50
+ ```jsonc
51
+ {
52
+ "connections": [ /* ... */ ],
53
+ "notices": [
54
+ "ssh tunnel dropped (ConnectError) and was reopened on 127.0.0.1:49173; the call was retried and this result is from the new connection"
55
+ ]
56
+ }
57
+ ```
58
+
59
+ The field appears only when there is something to report, and exactly once: the queue is drained when delivered.
60
+
61
+ ## Environment variables
62
+
63
+ | Variable | Default | Purpose |
64
+ |---|---|---|
65
+ | `DBGATE_URL` | `http://localhost:3000` | dashboard address (with a tunnel — the remote side) |
66
+ | `DBGATE_LOGIN` | — | login, if authentication is enabled in DbGate |
67
+ | `DBGATE_PASSWORD` | — | its password |
68
+ | `SSH_PROXY_TO` | — | `user@host` for the SSH tunnel (`ssh -N -L`) |
69
+ | `SSH_PROXY_PORT` | auto | fixed local port for the tunnel |
70
+
71
+ ## Tools
72
+
73
+ | Tool | What it does |
74
+ |---|---|
75
+ | `list_connections` | dashboard connections: `conid`, engine, default database |
76
+ | `list_databases` | databases on a connection |
77
+ | `list_tables` | tables, views and matviews (no columns) |
78
+ | `describe_table` | columns, PK, FKs and indexes of one object |
79
+ | `query` | a read query; appends `LIMIT` and truncates the result |
80
+ | `execute` | any SQL, including writes and DDL, unmodified |
81
+ | `find_documents` | documents of a Mongo collection with filter and sort |
82
+ | `redis_keys` | browse the Redis keyspace level by level |
83
+ | `redis_get` | type, TTL and value of one key |
84
+ | `redis_command` | any Redis command, including writes |
85
+
86
+ `conid` is required by every tool — take it from `list_connections`. `database` can be omitted: the connection's default database is used.
87
+
88
+ `query` limits the output twice: it appends `LIMIT n` if the SQL has no limit of its own, and in any case cuts the response to `n` rows (`truncated: true` when cut). The DbGate API has no limit parameter, so the bound has to be held on both sides.
89
+
90
+ `LIMIT` is appended only to statements that accept it (`SELECT`, `WITH`, `VALUES`, `TABLE`). `SHOW`, `PRAGMA`, `DESCRIBE`, `EXPLAIN` go to the engine as is — with a `LIMIT` glued on they would be a syntax error; cutting to `n` rows still applies to them.
91
+
92
+ `execute` passes SQL through unchanged and without a safety net — including `INSERT`/`UPDATE`/`DELETE` and DDL. Restrict permissions on the connection itself in DbGate.
93
+
94
+ ## MongoDB and Redis
95
+
96
+ `find_documents` takes a regular Mongo filter — `{"artistId": {"$gt": 5}}`, `{"title": {"$regex": "Rock"}}`, `$in`, `$and`/`$or`. It is translated into a DbGate condition, because the dashboard API does not accept a raw Mongo filter. An unsupported operator (`$exists`, `$elemMatch`) returns an explicit error. `$regex` becomes a LIKE wrapped in `%…%`, so `%` and `_` inside the pattern act as wildcards.
97
+
98
+ Collections show up in the common `list_tables` with `type: "collection"`; `describe_table` for a collection returns the document count and the unique key — DbGate's Mongo structure has no columns.
99
+
100
+ Redis navigation has two levels: `redis_keys` without `root` shows prefixes (`album`, `track`, …), with `root` — the keys under it. `redis_get` reads a value as one page no longer than `limit` (`truncated: true` if the value continues); for the full data of a large key use `redis_command`, which runs an arbitrary command. For a missing key `redis_get` returns the error `key '…' not found`.
101
+
102
+ The command name in `redis_command` is case-insensitive — it is lowercased, because DbGate calls the method of the same name on its Redis client, and all those methods are lowercase.
103
+
104
+ A Redis connection has no default database, so `database` can be omitted: the server takes the first one in the list (`db0`). A freshly opened DbGate connection returns an empty database list while it starts up, so an empty answer is asked again — without that, database resolution sometimes failed with `has no default database`.
105
+
106
+ ## Development
107
+
108
+ ```bash
109
+ uv sync # venv + runtime + dev group
110
+ uv run pytest # full suite; addopts enforces --cov-fail-under=100
111
+ uv run pytest tests/test_server.py --no-cov # partial run — only with --no-cov
112
+ python -m dbgate_dashboard_mcp # run over stdio
113
+ ```
114
+
115
+ Tests need neither network nor a running DbGate: `httpx` and `subprocess` are faked.
116
+
117
+ ## Manual check on the test stand
118
+
119
+ The repository ships a `docker-compose.yml` with DbGate and five databases (Chinook in MySQL, PostgreSQL, SQLite, MongoDB, Redis). Seeds live in `init/`: [Chinook](https://github.com/lerocha/chinook-database) (MIT, © Luis Rocha), adapted for each engine.
120
+
121
+ ```bash
122
+ docker compose up -d
123
+ TOKEN=$(curl -s -X POST http://localhost:3000/auth/login \
124
+ -H 'Content-Type: application/json' -d '{"amoid":"none"}' \
125
+ | python3 -c 'import sys,json;print(json.load(sys.stdin)["accessToken"])')
126
+ curl -s -X POST http://localhost:3000/connections/list \
127
+ -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{}'
128
+ ```
129
+
130
+ Then connect the server in an MCP client with `DBGATE_URL=http://localhost:3000` and call `list_connections`.
131
+
132
+ ## How the DbGate API works
133
+
134
+ Useful when extending the server: DbGate is RPC over HTTP, not REST. Controller methods are mounted as kebab-case paths (`queryData` → `/database-connections/query-data`), almost all of them `POST` with a single JSON object of arguments. `POST /auth/login {"amoid":"none"}` issues a token that lives 24 h. SQL errors arrive with **HTTP 200** and an `errorMessage` field, so success is decided by the response body, not the status code.
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dbgate-dashboard-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for querying databases through a running DbGate dashboard."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Evgenii Danilin", email = "evgenii.danilin.m@gmail.com" }]
13
+ keywords = ["mcp", "dbgate", "database", "sql", "postgres", "mysql", "sqlite"]
14
+ dependencies = [
15
+ "mcp>=2.0.0,<3",
16
+ "httpx>=0.27",
17
+ ]
18
+
19
+ [dependency-groups]
20
+ dev = ["pytest>=8", "pytest-cov>=5"]
21
+
22
+ [project.scripts]
23
+ dbgate-dashboard-mcp = "dbgate_dashboard_mcp.server:main"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/dbgate_dashboard_mcp"]
27
+
28
+ [tool.hatch.build.targets.sdist]
29
+ only-include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
30
+
31
+ [tool.pytest.ini_options]
32
+ testpaths = ["tests"]
33
+ addopts = "--cov --cov-branch --cov-report=term-missing --cov-fail-under=100"
34
+
35
+ [tool.coverage.run]
36
+ source = ["dbgate_dashboard_mcp"]
37
+ omit = ["*/__main__.py"] # entry shim: only runs under `python -m`, no logic
38
+
39
+ [tool.coverage.report]
40
+ exclude_lines = [
41
+ "pragma: no cover",
42
+ 'if __name__ == .__main__.:',
43
+ ]
@@ -0,0 +1 @@
1
+ """MCP server for querying databases through a running DbGate dashboard."""
@@ -0,0 +1,5 @@
1
+ """``python -m dbgate_dashboard_mcp`` entry point."""
2
+
3
+ from .server import main
4
+
5
+ main()
@@ -0,0 +1,177 @@
1
+ """Thin HTTP client for the DbGate dashboard API. Zero MCP awareness.
2
+
3
+ DbGate exposes RPC-over-HTTP: controller methods are mounted as kebab-case
4
+ paths (``queryData`` → ``/database-connections/query-data``), every endpoint is
5
+ ``POST`` and takes one JSON object of arguments. All calls require a JWT
6
+ obtained from ``POST /auth/login``; the token lives 24 h, so instead of
7
+ tracking its expiry we relogin once on a 401.
8
+
9
+ DbGate reports SQL failures with **HTTP 200** and an ``errorMessage`` field in
10
+ the body, so success is decided by the body, not by the status code.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ import httpx
20
+
21
+ from .transport import TunneledTransport
22
+
23
+ DEFAULT_URL = "http://localhost:3000"
24
+ TIMEOUT = 30.0
25
+
26
+ _token: str | None = None
27
+
28
+ # When an ssh tunnel is open, only the *connect address* changes: ``DBGATE_URL``
29
+ # keeps naming the dashboard, so every request still carries the real ``Host``
30
+ # and negotiates TLS against the real certificate.
31
+ _tunnel: tuple[str, int] | None = None
32
+ _rebuild: Callable[[], tuple[str, int]] | None = None
33
+ _notices: list[str] = []
34
+
35
+
36
+ class DbGateError(Exception):
37
+ """DbGate refused the request or reported an error in the response body."""
38
+
39
+
40
+ def base_url() -> str:
41
+ """Dashboard base URL from ``DBGATE_URL``, without a trailing slash."""
42
+ return os.environ.get("DBGATE_URL", DEFAULT_URL).rstrip("/")
43
+
44
+
45
+ def reset_token() -> None:
46
+ """Drop the cached token (used by tests and after a 401)."""
47
+ global _token
48
+ _token = None
49
+
50
+
51
+ def use_tunnel(host: str, port: int) -> None:
52
+ """Route every subsequent call through a forwarded local endpoint."""
53
+ global _tunnel
54
+ _tunnel = (host, port)
55
+
56
+
57
+ def on_tunnel_lost(rebuild: Callable[[], tuple[str, int]] | None) -> None:
58
+ """Register how to reopen the tunnel; it returns the new ``(host, port)``.
59
+
60
+ Without one a dropped tunnel is simply reported. With one, the call that
61
+ hit the dead port is retried once against the reopened forward.
62
+ """
63
+ global _rebuild
64
+ _rebuild = rebuild
65
+
66
+
67
+ def take_notices() -> list[str]:
68
+ """Drain the out-of-band messages worth showing the caller.
69
+
70
+ A reconnect is invisible in the result — the retried call just succeeds —
71
+ so the event is queued here for the tool layer to attach, and drained so it
72
+ is reported once rather than on every later call.
73
+ """
74
+ global _notices
75
+ notices, _notices = _notices, []
76
+ return notices
77
+
78
+
79
+ def reset_tunnel() -> None:
80
+ """Forget the tunnel, how to rebuild it, and anything pending about it."""
81
+ global _tunnel, _rebuild, _notices
82
+ _tunnel = None
83
+ _rebuild = None
84
+ _notices = []
85
+
86
+
87
+ def _client() -> httpx.AsyncClient:
88
+ """An httpx client aimed at the tunnel when there is one."""
89
+ transport = TunneledTransport(*_tunnel) if _tunnel else None
90
+ return httpx.AsyncClient(timeout=TIMEOUT, transport=transport)
91
+
92
+
93
+ async def _login(client: httpx.AsyncClient) -> str:
94
+ """Obtain a JWT. ``amoid=none`` is DbGate's no-auth-provider login."""
95
+ payload: dict[str, Any] = {"amoid": "none"}
96
+ login = os.environ.get("DBGATE_LOGIN")
97
+ if login:
98
+ payload["login"] = login
99
+ payload["password"] = os.environ.get("DBGATE_PASSWORD") or ""
100
+ resp = await client.post(f"{base_url()}/auth/login", json=payload)
101
+ if resp.status_code != 200:
102
+ raise DbGateError(f"login failed: HTTP {resp.status_code}")
103
+ token = resp.json().get("accessToken")
104
+ if not token:
105
+ raise DbGateError("login failed: no accessToken in response")
106
+ return token
107
+
108
+
109
+ async def _post(
110
+ client: httpx.AsyncClient, path: str, payload: dict[str, Any], token: str
111
+ ):
112
+ return await client.post(
113
+ f"{base_url()}/{path}",
114
+ json=payload,
115
+ headers={"Authorization": f"Bearer {token}"},
116
+ )
117
+
118
+
119
+ async def _attempt(path: str, body: dict[str, Any]) -> Any:
120
+ """One round trip, on a client built against the current endpoint."""
121
+ global _token
122
+ async with _client() as client:
123
+ if _token is None:
124
+ _token = await _login(client)
125
+ resp = await _post(client, path, body, _token)
126
+ if resp.status_code == 401:
127
+ _token = await _login(client)
128
+ resp = await _post(client, path, body, _token)
129
+ if resp.status_code != 200:
130
+ raise DbGateError(f"{path}: HTTP {resp.status_code} {resp.text[:200]}")
131
+ data = resp.json()
132
+ if isinstance(data, dict):
133
+ error = data.get("errorMessage") or data.get("apiErrorMessage")
134
+ if error:
135
+ raise DbGateError(str(error))
136
+ return data
137
+
138
+
139
+ def _unreachable(exc: httpx.TransportError) -> DbGateError:
140
+ """Wrap a transport failure so it says something.
141
+
142
+ httpx often raises these with an empty message, which turns the tools'
143
+ ``{"error": str(exc)}`` contract into ``{"error": ""}`` — the class name and
144
+ the endpoint are what actually identify the problem.
145
+ """
146
+ return DbGateError(f"{base_url()} unreachable: {type(exc).__name__}: {exc}".rstrip(": "))
147
+
148
+
149
+ async def call(path: str, payload: dict[str, Any] | None = None) -> Any:
150
+ """POST ``payload`` to a DbGate RPC ``path`` and return the parsed body.
151
+
152
+ Raises :class:`DbGateError` on a failed login, a non-200 response, or a
153
+ body carrying ``errorMessage`` / ``apiErrorMessage``.
154
+
155
+ A transport failure means the endpoint stopped accepting — with an ssh
156
+ tunnel that usually means ssh died. When a rebuild callback is registered
157
+ the tunnel is reopened and the call retried exactly once; a second failure
158
+ is reported rather than retried, so a genuinely dead remote host fails fast
159
+ instead of looping.
160
+ """
161
+ global _tunnel
162
+ body = payload or {}
163
+ try:
164
+ return await _attempt(path, body)
165
+ except httpx.TransportError as first:
166
+ if _rebuild is None:
167
+ raise _unreachable(first) from first
168
+ _tunnel = _rebuild()
169
+ _notices.append(
170
+ f"ssh tunnel dropped ({type(first).__name__}) and was reopened on "
171
+ f"{_tunnel[0]}:{_tunnel[1]}; the call was retried and this result is "
172
+ f"from the new connection"
173
+ )
174
+ try:
175
+ return await _attempt(path, body)
176
+ except httpx.TransportError as second:
177
+ raise _unreachable(second) from second
@@ -0,0 +1,105 @@
1
+ """Translate a raw MongoDB filter into DbGate's condition AST.
2
+
3
+ DbGate's ``collection-data`` endpoint does not accept a Mongo filter document:
4
+ it wants its own condition tree (``{"conditionType": "binary", ...}``) and
5
+ rejects anything else with ``Unknown condition type undefined``. Agents write
6
+ Mongo filters naturally, so the translation happens here — a pure function with
7
+ no I/O, covering the operators the AST can express.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ _COMPARISON = {
15
+ "$eq": "=",
16
+ "$ne": "!=",
17
+ "$gt": ">",
18
+ "$gte": ">=",
19
+ "$lt": "<",
20
+ "$lte": "<=",
21
+ }
22
+ _LOGICAL = {"$and": "and", "$or": "or"}
23
+
24
+
25
+ def _column(name: str) -> dict:
26
+ return {"exprType": "column", "columnName": name}
27
+
28
+
29
+ def _value(value: Any) -> dict:
30
+ return {"exprType": "value", "value": value}
31
+
32
+
33
+ def _binary(field: str, operator: str, value: Any) -> dict:
34
+ return {
35
+ "conditionType": "binary",
36
+ "operator": operator,
37
+ "left": _column(field),
38
+ "right": _value(value),
39
+ }
40
+
41
+
42
+ def _combine(conditions: list[dict], kind: str = "and") -> dict | None:
43
+ """Fold a list of conditions: none → None, one → itself, many → and/or."""
44
+ if not conditions:
45
+ return None
46
+ if len(conditions) == 1:
47
+ return conditions[0]
48
+ return {"conditionType": kind, "conditions": conditions}
49
+
50
+
51
+ def _field_conditions(field: str, spec: Any) -> list[dict]:
52
+ """Conditions for one field: a bare value, or a dict of Mongo operators."""
53
+ if not isinstance(spec, dict):
54
+ return [_binary(field, "=", spec)]
55
+ out = []
56
+ for operator, operand in spec.items():
57
+ if operator in _COMPARISON:
58
+ out.append(_binary(field, _COMPARISON[operator], operand))
59
+ elif operator == "$regex":
60
+ out.append(
61
+ {
62
+ "conditionType": "like",
63
+ "left": _column(field),
64
+ "right": _value(f"%{operand}%"),
65
+ }
66
+ )
67
+ elif operator == "$in":
68
+ if not isinstance(operand, list):
69
+ raise ValueError("$in expects a list of values")
70
+ out.append(
71
+ {"conditionType": "in", "expr": _column(field), "values": operand}
72
+ )
73
+ else:
74
+ raise ValueError(f"unsupported filter operator '{operator}'")
75
+ return out
76
+
77
+
78
+ def to_condition(filter: dict | None) -> dict | None:
79
+ """Translate a Mongo filter document into a DbGate condition, or None."""
80
+ if not filter:
81
+ return None
82
+ conditions: list[dict] = []
83
+ for key, spec in filter.items():
84
+ if key in _LOGICAL:
85
+ if not isinstance(spec, list):
86
+ raise ValueError(f"{key} expects a list of filters")
87
+ branches = [c for c in (to_condition(f) for f in spec) if c is not None]
88
+ combined = _combine(branches, _LOGICAL[key])
89
+ if combined is not None:
90
+ conditions.append(combined)
91
+ elif key.startswith("$"):
92
+ raise ValueError(f"unsupported filter operator '{key}'")
93
+ else:
94
+ conditions.extend(_field_conditions(key, spec))
95
+ return _combine(conditions)
96
+
97
+
98
+ def to_sort(sort: dict | None) -> list[dict] | None:
99
+ """Translate ``{"field": 1 | -1}`` into DbGate's sort list."""
100
+ if not sort:
101
+ return None
102
+ return [
103
+ {"columnName": field, "direction": "ASC" if direction >= 0 else "DESC"}
104
+ for field, direction in sort.items()
105
+ ]