bricksentry 0.1.9__tar.gz → 0.1.11__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.
Files changed (60) hide show
  1. {bricksentry-0.1.9 → bricksentry-0.1.11}/CHANGELOG.md +15 -0
  2. {bricksentry-0.1.9 → bricksentry-0.1.11}/PKG-INFO +14 -3
  3. {bricksentry-0.1.9 → bricksentry-0.1.11}/README.md +13 -2
  4. bricksentry-0.1.11/deploy/databricks-app/README.md +88 -0
  5. {bricksentry-0.1.9 → bricksentry-0.1.11}/pyproject.toml +1 -1
  6. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/__init__.py +1 -1
  7. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/backends/databricks_backend.py +19 -1
  8. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/cli.py +12 -3
  9. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/config.py +4 -1
  10. bricksentry-0.1.11/src/bricksentry/mcp_server.py +110 -0
  11. bricksentry-0.1.11/tests/test_0110.py +211 -0
  12. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_018.py +2 -1
  13. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_check_notebook.py +1 -1
  14. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_notify_templates.py +1 -1
  15. bricksentry-0.1.9/src/bricksentry/mcp_server.py +0 -55
  16. {bricksentry-0.1.9 → bricksentry-0.1.11}/.gitignore +0 -0
  17. {bricksentry-0.1.9 → bricksentry-0.1.11}/CONTRIBUTING.md +0 -0
  18. {bricksentry-0.1.9 → bricksentry-0.1.11}/LICENSE +0 -0
  19. {bricksentry-0.1.9 → bricksentry-0.1.11}/SECURITY.md +0 -0
  20. {bricksentry-0.1.9 → bricksentry-0.1.11}/action.yml +0 -0
  21. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/bricksentry.yml +0 -0
  22. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/bricksentry_check_my_table.ipynb +0 -0
  23. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/bricksentry_check_my_table.py +0 -0
  24. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
  25. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/bricksentry_quickstart.py +0 -0
  26. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/github-workflow.yml +0 -0
  27. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/databricks/policy.yml +0 -0
  28. {bricksentry-0.1.9 → bricksentry-0.1.11}/examples/demo/agent_loop_demo.py +0 -0
  29. {bricksentry-0.1.9 → bricksentry-0.1.11}/packages/bricksentry-mcp/LICENSE +0 -0
  30. {bricksentry-0.1.9 → bricksentry-0.1.11}/packages/bricksentry-mcp/README.md +0 -0
  31. {bricksentry-0.1.9 → bricksentry-0.1.11}/packages/bricksentry-mcp/src/bricksentry_mcp/__init__.py +0 -0
  32. {bricksentry-0.1.9 → bricksentry-0.1.11}/scripts/build_notebook.py +0 -0
  33. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/agent_tools.py +0 -0
  34. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/assess.py +0 -0
  35. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/backends/__init__.py +0 -0
  36. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/backends/base.py +0 -0
  37. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/backends/duckdb_backend.py +0 -0
  38. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/changes.py +0 -0
  39. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/demo.py +0 -0
  40. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/diff.py +0 -0
  41. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/explain.py +0 -0
  42. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/github.py +0 -0
  43. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/lineage.py +0 -0
  44. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/measures.py +0 -0
  45. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/models.py +0 -0
  46. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/notify.py +0 -0
  47. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/policy.py +0 -0
  48. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/policy_templates.py +0 -0
  49. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/preview.py +0 -0
  50. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/py.typed +0 -0
  51. {bricksentry-0.1.9 → bricksentry-0.1.11}/src/bricksentry/report.py +0 -0
  52. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/conftest.py +0 -0
  53. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_019.py +0 -0
  54. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_assess_policy.py +0 -0
  55. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_databricks_and_uc.py +0 -0
  56. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_demo.py +0 -0
  57. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_diff.py +0 -0
  58. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_notebook.py +0 -0
  59. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_preview_agents.py +0 -0
  60. {bricksentry-0.1.9 → bricksentry-0.1.11}/tests/test_sample_guard_and_store.py +0 -0
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.11 (2026-11-11)
4
+
5
+ From a full live test of 0.1.9 on Databricks serverless:
6
+
7
+ - Fix: when the Databricks SDK could not find credentials, the CLI showed the SDK's raw error. Run as a subprocess of a notebook it failed with a cryptic `parent_header` error. It now says it could not sign in to Databricks, lists the ways to provide credentials, and suggests the Python API inside notebooks.
8
+ - The `lineage.type` false warning that test also found was already fixed in 0.1.10.
9
+
10
+ ## 0.1.10 (2026-11-11)
11
+
12
+ - **Run the MCP server as a Databricks App.** New kit in `deploy/databricks-app`: `app.yaml`, an Asset Bundle with the SQL warehouse resource, a pinned `requirements.txt`, a starter `bricksentry.yml` and the Unity Catalog grants for the app's service principal. Deploy with `databricks bundle deploy` and `databricks bundle run`; agents connect to `https://<app-url>/mcp`.
13
+ - `bricksentry mcp --transport streamable-http` now listens on `0.0.0.0:$DATABRICKS_APP_PORT` on Databricks Apps, and takes `--host` / `--port` (or `BRICKSENTRY_HOST` / `BRICKSENTRY_PORT`) elsewhere. It runs stateless, so it works behind a load balancer.
14
+ - New `--read-only` (or `BRICKSENTRY_READ_ONLY=1`) leaves out `preview_write`, so a shared server never writes, not even to a sandbox clone.
15
+ - Fix: with mcp 1.x, the HTTP server rejected requests that came through a proxy (HTTP 421) because localhost-only host checking stayed on. It now applies only when listening on localhost, as in mcp 2.
16
+ - Fix: the config typo warnings added in 0.1.8 flagged valid lineage settings such as `lineage.type`, `exclude` and `exclude_dropped`. All lineage keys bricksentry reads are now recognised, and a test keeps the list in sync with the code.
17
+
3
18
  ## 0.1.9 (2026-11-11)
4
19
 
5
20
  - New notebook: **what did my last pipeline run do?** Point it at a Delta table; it finds the latest data change in the table's history, compares it with the version before using two shallow clones, and shows the verdict, rules, blast radius and the `RESTORE` command. Read-only on your table. Import from `examples/databricks/bricksentry_check_my_table.py`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bricksentry
3
- Version: 0.1.9
3
+ Version: 0.1.11
4
4
  Summary: Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
5
5
  Project-URL: Homepage, https://bricksentry.org
6
6
  Project-URL: Documentation, https://bricksentry.org/docs
@@ -163,6 +163,17 @@ The same tools are plain Python functions in `bricksentry.agent_tools`, so you c
163
163
 
164
164
  To watch the whole loop, run `bricksentry demo` (see the top of this page). `bricksentry demo --report report.md` also writes the pull-request comment a reviewer would see.
165
165
 
166
+ ### Host it in your workspace (Databricks Apps)
167
+
168
+ Run the MCP server as a Databricks App so every agent in your workspace can reach it over HTTPS, with no tokens to manage: it runs as the app's service principal, and Unity Catalog grants decide what it can read. [`deploy/databricks-app`](deploy/databricks-app) is a ready app (`app.yaml`, an Asset Bundle, the grants) that deploys with two commands:
169
+
170
+ ```bash
171
+ databricks bundle deploy --var warehouse_id=<your-sql-warehouse-id>
172
+ databricks bundle run bricksentry_mcp
173
+ ```
174
+
175
+ Agents connect to `https://<app-url>/mcp`. The kit starts the server with `--read-only`, which leaves out `preview_write`, so the app never writes. On any other host, `bricksentry mcp --transport streamable-http --host 0.0.0.0 --port 8000` serves the same endpoint. Unity Catalog *MCP Services* are for servers hosted outside Databricks, so a Databricks App is the recommended way to run bricksentry inside it; see the [kit's README](deploy/databricks-app/README.md).
176
+
166
177
  ## For data engineers: CLI and CI
167
178
 
168
179
  ```bash
@@ -205,7 +216,7 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
205
216
  Or use the bundled GitHub Action, which also writes the report to the job summary:
206
217
 
207
218
  ```yaml
208
- - uses: bricksentry/bricksentry@v0.1.9
219
+ - uses: bricksentry/bricksentry@v0.1.11
209
220
  with:
210
221
  config: bricksentry.yml
211
222
  fail-on: needs_human
@@ -230,7 +241,7 @@ jobs:
230
241
  fetch-depth: 0
231
242
  # Build this PR's version of your pipeline into a per-PR schema first,
232
243
  # for example: databricks bundle deploy -t ci && databricks bundle run -t ci
233
- - uses: bricksentry/bricksentry@v0.1.9
244
+ - uses: bricksentry/bricksentry@v0.1.11
234
245
  with:
235
246
  config: bricksentry.yml
236
247
  fail-on: needs_human
@@ -116,6 +116,17 @@ The same tools are plain Python functions in `bricksentry.agent_tools`, so you c
116
116
 
117
117
  To watch the whole loop, run `bricksentry demo` (see the top of this page). `bricksentry demo --report report.md` also writes the pull-request comment a reviewer would see.
118
118
 
119
+ ### Host it in your workspace (Databricks Apps)
120
+
121
+ Run the MCP server as a Databricks App so every agent in your workspace can reach it over HTTPS, with no tokens to manage: it runs as the app's service principal, and Unity Catalog grants decide what it can read. [`deploy/databricks-app`](deploy/databricks-app) is a ready app (`app.yaml`, an Asset Bundle, the grants) that deploys with two commands:
122
+
123
+ ```bash
124
+ databricks bundle deploy --var warehouse_id=<your-sql-warehouse-id>
125
+ databricks bundle run bricksentry_mcp
126
+ ```
127
+
128
+ Agents connect to `https://<app-url>/mcp`. The kit starts the server with `--read-only`, which leaves out `preview_write`, so the app never writes. On any other host, `bricksentry mcp --transport streamable-http --host 0.0.0.0 --port 8000` serves the same endpoint. Unity Catalog *MCP Services* are for servers hosted outside Databricks, so a Databricks App is the recommended way to run bricksentry inside it; see the [kit's README](deploy/databricks-app/README.md).
129
+
119
130
  ## For data engineers: CLI and CI
120
131
 
121
132
  ```bash
@@ -158,7 +169,7 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
158
169
  Or use the bundled GitHub Action, which also writes the report to the job summary:
159
170
 
160
171
  ```yaml
161
- - uses: bricksentry/bricksentry@v0.1.9
172
+ - uses: bricksentry/bricksentry@v0.1.11
162
173
  with:
163
174
  config: bricksentry.yml
164
175
  fail-on: needs_human
@@ -183,7 +194,7 @@ jobs:
183
194
  fetch-depth: 0
184
195
  # Build this PR's version of your pipeline into a per-PR schema first,
185
196
  # for example: databricks bundle deploy -t ci && databricks bundle run -t ci
186
- - uses: bricksentry/bricksentry@v0.1.9
197
+ - uses: bricksentry/bricksentry@v0.1.11
187
198
  with:
188
199
  config: bricksentry.yml
189
200
  fail-on: needs_human
@@ -0,0 +1,88 @@
1
+ # Run the bricksentry MCP server as a Databricks App
2
+
3
+ Host bricksentry inside your workspace so any agent (Claude Code, Cursor, Agent Bricks, your own
4
+ LangGraph or OpenAI Agents SDK code) can call it over HTTPS. bricksentry runs as the app's service
5
+ principal: there are no tokens to manage, Unity Catalog grants decide what it can read, and access to
6
+ the server itself is controlled with the app's permissions. Unity AI Gateway can monitor its traffic
7
+ next to your other MCP servers.
8
+
9
+ This folder is a complete app:
10
+
11
+ | File | What it is |
12
+ |---|---|
13
+ | `app.yaml` | Starts `bricksentry mcp --transport streamable-http --read-only`. bricksentry listens on `0.0.0.0:$DATABRICKS_APP_PORT` by itself. |
14
+ | `requirements.txt` | The pinned bricksentry release. |
15
+ | `bricksentry.yml` | Backend, policy (`builtin:agent-safe`) and the tables agents may check. **Edit `tables:` first.** |
16
+ | `databricks.yml` | Asset Bundle that creates the app with a SQL warehouse resource. |
17
+ | `grants.sql` | The Unity Catalog grants for the app's service principal. |
18
+
19
+ ## Deploy (about 10 minutes)
20
+
21
+ You need the [Databricks CLI](https://docs.databricks.com/dev-tools/cli/) logged in to your workspace,
22
+ permission to create apps, and a SQL warehouse ID.
23
+
24
+ ```bash
25
+ # 1. Copy this folder and edit bricksentry.yml: list your tables and their keys.
26
+ cp -r deploy/databricks-app my-bricksentry-app && cd my-bricksentry-app
27
+
28
+ # 2. Create and start the app.
29
+ databricks bundle deploy --var warehouse_id=<your-sql-warehouse-id>
30
+ databricks bundle run bricksentry_mcp
31
+ ```
32
+
33
+ 3. **Grant access.** Open the app in **Compute → Apps → mcp-bricksentry**, copy its service principal's
34
+ application ID, replace `<app-sp>` in `grants.sql`, and run it in the SQL editor.
35
+ 4. **Check it.** The app page shows the URL. The MCP endpoint is `https://<app-url>/mcp`. The app log
36
+ should show `bricksentry MCP server (streamable-http, read-only) on http://0.0.0.0:<port>/mcp`.
37
+
38
+ Without the bundle: create an app in the UI (**Compute → Apps → Create app → Custom**), add a SQL
39
+ warehouse resource with the key `sql-warehouse` and **Can use**, then `databricks sync . <workspace-path>` and
40
+ `databricks apps deploy mcp-bricksentry --source-code-path <workspace-path>`.
41
+
42
+ ## Connect an agent
43
+
44
+ Databricks Apps sit behind workspace sign-in, so clients send a Databricks OAuth token.
45
+
46
+ **Agent code in Databricks** (recommended), with `pip install databricks-mcp`:
47
+
48
+ ```python
49
+ from databricks.sdk import WorkspaceClient
50
+ from databricks_mcp import DatabricksMCPClient
51
+
52
+ client = DatabricksMCPClient(server_url="https://<app-url>/mcp", workspace_client=WorkspaceClient())
53
+ print([t.name for t in client.list_tools()])
54
+ ```
55
+
56
+ **Claude Code or another HTTP client** on your laptop:
57
+
58
+ ```bash
59
+ TOKEN=$(databricks auth token --host https://<workspace-host> | jq -r .access_token)
60
+ claude mcp add --transport http bricksentry https://<app-url>/mcp --header "Authorization: Bearer $TOKEN"
61
+ ```
62
+
63
+ OAuth tokens expire after about an hour; refresh with the same command. Give each agent identity
64
+ **Can use** on the app (app page → Permissions).
65
+
66
+ ## Read-only or previews
67
+
68
+ `--read-only` (the default here) leaves out `preview_write`, so the app only reads: agents use
69
+ `whats_downstream`, `rollback_plan`, `assess_change`, `explain_diff` and `safe_to_ship`. To let agents
70
+ preview a write on a disposable shallow clone, remove `--read-only` from `app.yaml` and run the
71
+ sandbox grants at the end of `grants.sql`.
72
+
73
+ ## Unity Catalog MCP Services
74
+
75
+ Unity Catalog can register an MCP server as an *MCP Service* governed by Unity AI Gateway, but that is
76
+ for servers hosted outside Databricks: apps on Databricks Apps can't be registered as MCP Services, and
77
+ Databricks says to connect to them directly instead. For bricksentry, the app above is the
78
+ recommended setup. If you do host it elsewhere, it needs a public HTTPS URL with Streamable HTTP, and
79
+ its own Databricks credentials for the SQL warehouse; see
80
+ [Register an external MCP server](https://docs.databricks.com/aws/en/ai-gateway/register-mcp-service).
81
+
82
+ ## Notes
83
+
84
+ - Saved assessments live in `/tmp` inside the app, so `safe_to_ship` and `explain_diff` find an
85
+ assessment from the same app instance. Call them right after `assess_change`, as agents normally do.
86
+ - Every check runs as the app's service principal, so all callers see what that principal can read.
87
+ Grant it only the schemas agents should check.
88
+ - App compute is billed at Databricks Apps rates.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bricksentry"
7
- version = "0.1.9"
7
+ version = "0.1.11"
8
8
  description = "Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -23,4 +23,4 @@ __all__ = [
23
23
  "TableDiff",
24
24
  "Verdict",
25
25
  ]
26
- __version__ = "0.1.9"
26
+ __version__ = "0.1.11"
@@ -43,7 +43,10 @@ class DatabricksBackend(Backend):
43
43
  from databricks.sdk import WorkspaceClient
44
44
  except ImportError as e: # pragma: no cover
45
45
  raise ImportError("Databricks backend needs `pip install bricksentry[databricks]`") from e
46
- client = WorkspaceClient(profile=profile) if profile else WorkspaceClient()
46
+ try:
47
+ client = WorkspaceClient(profile=profile) if profile else WorkspaceClient()
48
+ except Exception as e:
49
+ raise ValueError(_auth_help(e, profile)) from None
47
50
  self.client = client
48
51
  self.timeout_s = timeout_s
49
52
 
@@ -140,6 +143,21 @@ class DatabricksBackend(Backend):
140
143
  return int(v) if v is not None else None
141
144
 
142
145
 
146
+ def _auth_help(e: Exception, profile: str | None) -> str:
147
+ """One clear message when the Databricks SDK can't find credentials.
148
+
149
+ The SDK's own errors can be long or cryptic: for example a CLI started as a subprocess
150
+ of a notebook fails inside the notebook-auth code with a `parent_header` error."""
151
+ detail = (str(e).strip().splitlines() or [type(e).__name__])[0][:200]
152
+ what = f"credentials for profile {profile!r} in ~/.databrickscfg" if profile else "Databricks credentials"
153
+ return (
154
+ f"Could not sign in to Databricks: no usable {what} were found ({detail}). "
155
+ "Set DATABRICKS_HOST plus DATABRICKS_TOKEN (or DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET), "
156
+ "or run `databricks auth login`. In a notebook, use the Python API (from bricksentry import Sentry) "
157
+ "instead of calling the CLI in a subprocess, which can't use the notebook's credentials."
158
+ )
159
+
160
+
143
161
  def _state(resp: Any) -> str:
144
162
  st = getattr(getattr(resp, "status", None), "state", None)
145
163
  return getattr(st, "value", st) or "UNKNOWN"
@@ -202,15 +202,24 @@ def rollback(table, config_path):
202
202
 
203
203
 
204
204
  @main.command()
205
- @click.option("--transport", type=click.Choice(["stdio", "sse", "streamable-http"]), default="stdio")
205
+ @click.option("--transport", type=click.Choice(["stdio", "sse", "streamable-http"]), default="stdio",
206
+ show_default=True, help="stdio for local agents; streamable-http to serve over HTTP (e.g. Databricks Apps)")
207
+ @click.option("--host", default=None,
208
+ help="HTTP only. Default 127.0.0.1, or 0.0.0.0 on Databricks Apps. Env: BRICKSENTRY_HOST")
209
+ @click.option("--port", type=int, default=None,
210
+ help="HTTP only. Default 8000, or $DATABRICKS_APP_PORT on Databricks Apps. Env: BRICKSENTRY_PORT")
211
+ @click.option("--read-only", is_flag=True, default=False,
212
+ help="Leave out preview_write, so the server never writes, not even to a sandbox clone. "
213
+ "Env: BRICKSENTRY_READ_ONLY=1")
206
214
  @config_opt
207
- def mcp(transport, config_path):
215
+ def mcp(transport, host, port, read_only, config_path):
208
216
  """Start the MCP server for AI agents."""
209
217
  if config_path:
210
218
  os.environ["BRICKSENTRY_CONFIG"] = str(Path(config_path).resolve())
219
+ read_only = read_only or os.environ.get("BRICKSENTRY_READ_ONLY", "").strip().lower() in ("1", "true", "yes")
211
220
  from bricksentry.mcp_server import serve
212
221
 
213
- serve(transport)
222
+ serve(transport, host=host, port=port, read_only=read_only)
214
223
 
215
224
 
216
225
  _INIT_CONFIG = """# bricksentry configuration
@@ -45,7 +45,10 @@ TOP_LEVEL_KEYS = {
45
45
  }
46
46
  TABLE_KEYS = {"keys", "key", "segment_by", "paths", "candidate", "measures"}
47
47
  NOTIFY_KEYS = {"on", "slack_webhook", "teams_webhook", "mentions", "run_url"}
48
- LINEAGE_KEYS = {"depth", "lookback_days"}
48
+ LINEAGE_KEYS = {
49
+ "type", "depth", "lookback_days", "lineage_table", "tables_table", "tags_table", "max_nodes",
50
+ "exclude", "exclude_dropped", "edges", "owners", "tags",
51
+ }
49
52
 
50
53
 
51
54
  def _unknown(where: str, given: Any, known: set[str]) -> list[str]:
@@ -0,0 +1,110 @@
1
+ """MCP server exposing bricksentry's agent tools.
2
+
3
+ Run: ``bricksentry mcp`` (stdio) or ``bricksentry mcp --transport streamable-http``
4
+
5
+ Over HTTP the server listens on 127.0.0.1:8000 by default. On Databricks Apps it reads
6
+ ``DATABRICKS_APP_PORT`` and listens on 0.0.0.0, so ``bricksentry mcp --transport
7
+ streamable-http`` is all an ``app.yaml`` needs (see deploy/databricks-app). ``--host`` /
8
+ ``--port`` or ``BRICKSENTRY_HOST`` / ``BRICKSENTRY_PORT`` override this. The endpoint is ``/mcp``.
9
+
10
+ Claude Code: ``claude mcp add bricksentry -- uvx bricksentry-mcp --config /full/path/bricksentry.yml``
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import sys
17
+
18
+ from bricksentry import agent_tools
19
+
20
+ INSTRUCTIONS = """bricksentry checks whether a change to Databricks data is safe.
21
+ Recommended loop when you change a pipeline or table:
22
+ 1. whats_downstream(table) to learn the blast radius before editing.
23
+ 2. rollback_plan(table) and keep the SQL.
24
+ 3. preview_write(sql, target) for any direct write, or assess_change(tables) after
25
+ your change has built candidate tables.
26
+ 4. safe_to_ship(assessment_id) and follow `next_step` exactly.
27
+ Never bypass a needs_human or block verdict."""
28
+
29
+ READ_ONLY_NOTE = """
30
+ This server is read-only: preview_write is not available. Build candidate tables
31
+ in your pipeline and use assess_change instead."""
32
+
33
+
34
+ _LOCALHOST = ("127.0.0.1", "localhost", "::1")
35
+
36
+
37
+ def http_address(host: str | None = None, port: int | str | None = None) -> tuple[str, int]:
38
+ """Where the HTTP transports listen: flags, then BRICKSENTRY_HOST/PORT, then
39
+ Databricks Apps (DATABRICKS_APP_PORT on 0.0.0.0), then 127.0.0.1:8000."""
40
+ app_port = os.environ.get("DATABRICKS_APP_PORT")
41
+ port = port or os.environ.get("BRICKSENTRY_PORT") or app_port or 8000
42
+ host = host or os.environ.get("BRICKSENTRY_HOST") or ("0.0.0.0" if app_port else "127.0.0.1")
43
+ return host, int(port)
44
+
45
+
46
+ def tools(read_only: bool = False) -> list:
47
+ return [t for t in agent_tools.TOOLS if not read_only or t.__name__ in agent_tools.READ_ONLY]
48
+
49
+
50
+ def build_server(read_only: bool = False):
51
+ try: # mcp >= 2
52
+ from mcp.server.mcpserver import MCPServer as Server
53
+ except ImportError:
54
+ try: # mcp 1.x
55
+ from mcp.server.fastmcp import FastMCP as Server
56
+ except ImportError as e: # pragma: no cover
57
+ raise ImportError("The MCP server needs `pip install bricksentry[mcp]`") from e
58
+
59
+ try:
60
+ from mcp.types import ToolAnnotations
61
+ except ImportError: # pragma: no cover
62
+ ToolAnnotations = None
63
+
64
+ from bricksentry import __version__
65
+
66
+ instructions = INSTRUCTIONS + (READ_ONLY_NOTE if read_only else "")
67
+ try: # mcp >= 2 takes the version directly
68
+ server = Server(name="bricksentry", instructions=instructions, version=__version__)
69
+ except TypeError: # mcp 1.x: set it on the underlying low-level server
70
+ server = Server(name="bricksentry", instructions=instructions)
71
+ low = getattr(server, "_mcp_server", None)
72
+ if low is not None and hasattr(low, "version"):
73
+ low.version = __version__
74
+ for fn in tools(read_only):
75
+ ann = None
76
+ if ToolAnnotations is not None:
77
+ ro = fn.__name__ in agent_tools.READ_ONLY
78
+ ann = ToolAnnotations(readOnlyHint=ro, destructiveHint=False, idempotentHint=ro)
79
+ server.tool(name=fn.__name__, description=fn.__doc__, annotations=ann)(fn)
80
+ return server
81
+
82
+
83
+ def serve(
84
+ transport: str = "stdio",
85
+ host: str | None = None,
86
+ port: int | None = None,
87
+ read_only: bool = False,
88
+ ) -> None:
89
+ server = build_server(read_only=read_only)
90
+ if transport == "stdio":
91
+ server.run(transport="stdio")
92
+ return
93
+ host, port = http_address(host, port)
94
+ path = "/mcp" if transport == "streamable-http" else "/sse"
95
+ mode = ", read-only" if read_only else ""
96
+ print(f"bricksentry MCP server ({transport}{mode}) on http://{host}:{port}{path}", file=sys.stderr, flush=True)
97
+ kwargs = {"host": host, "port": port}
98
+ if transport == "streamable-http":
99
+ kwargs["stateless_http"] = True # no session affinity needed behind a load balancer (Databricks Apps)
100
+ try: # mcp >= 2: transport options are run() arguments
101
+ server.run(transport=transport, **kwargs)
102
+ except TypeError: # mcp 1.x: they are server settings
103
+ for k, v in kwargs.items():
104
+ setattr(server.settings, k, v)
105
+ if host not in _LOCALHOST and hasattr(server.settings, "transport_security"):
106
+ # mcp 1.x set localhost-only DNS-rebinding protection when the server was created
107
+ # (host defaulted to 127.0.0.1). Behind a proxy such as Databricks Apps the Host header
108
+ # is the app's domain, so keep mcp 2's behaviour: protection for localhost only.
109
+ server.settings.transport_security = None
110
+ server.run(transport=transport)
@@ -0,0 +1,211 @@
1
+ """0.1.10: serve MCP over HTTP on Databricks Apps, read-only mode, and the deploy kit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import time
11
+ import urllib.request
12
+ from pathlib import Path
13
+
14
+ import pytest
15
+ import yaml
16
+ from click.testing import CliRunner
17
+
18
+ import bricksentry
19
+ from bricksentry import mcp_server
20
+ from bricksentry.cli import main
21
+ from bricksentry.config import Config
22
+
23
+ ROOT = Path(__file__).resolve().parents[1]
24
+ KIT = ROOT / "deploy" / "databricks-app"
25
+
26
+
27
+ @pytest.fixture(autouse=True)
28
+ def _env(monkeypatch):
29
+ for k in ("DATABRICKS_APP_PORT", "BRICKSENTRY_HOST", "BRICKSENTRY_PORT", "BRICKSENTRY_READ_ONLY"):
30
+ monkeypatch.delenv(k, raising=False)
31
+
32
+
33
+ def test_http_address_defaults_and_overrides(monkeypatch):
34
+ assert mcp_server.http_address() == ("127.0.0.1", 8000)
35
+ monkeypatch.setenv("DATABRICKS_APP_PORT", "8123")
36
+ assert mcp_server.http_address() == ("0.0.0.0", 8123) # Databricks Apps
37
+ monkeypatch.setenv("BRICKSENTRY_PORT", "9000")
38
+ monkeypatch.setenv("BRICKSENTRY_HOST", "10.0.0.5")
39
+ assert mcp_server.http_address() == ("10.0.0.5", 9000)
40
+ assert mcp_server.http_address("127.0.0.1", 7000) == ("127.0.0.1", 7000) # flags win
41
+
42
+
43
+ def test_read_only_leaves_out_preview_write():
44
+ names = [t.__name__ for t in mcp_server.tools(read_only=True)]
45
+ assert "preview_write" not in names and len(names) == 5
46
+ assert len(mcp_server.tools()) == 6
47
+
48
+
49
+ def test_cli_passes_http_options(monkeypatch):
50
+ seen = {}
51
+ monkeypatch.setattr(mcp_server, "serve", lambda transport, **kw: seen.update(transport=transport, **kw))
52
+ r = CliRunner().invoke(main, ["mcp", "--transport", "streamable-http", "--host", "0.0.0.0", "--port", "9100",
53
+ "--read-only"])
54
+ assert r.exit_code == 0, r.output
55
+ assert seen == {"transport": "streamable-http", "host": "0.0.0.0", "port": 9100, "read_only": True}
56
+
57
+
58
+ def test_read_only_from_env(monkeypatch):
59
+ seen = {}
60
+ monkeypatch.setattr(mcp_server, "serve", lambda transport, **kw: seen.update(kw))
61
+ monkeypatch.setenv("BRICKSENTRY_READ_ONLY", "true")
62
+ CliRunner().invoke(main, ["mcp"])
63
+ assert seen["read_only"] is True
64
+
65
+
66
+ def _free_port() -> int:
67
+ s = socket.socket()
68
+ s.bind(("127.0.0.1", 0))
69
+ port = s.getsockname()[1]
70
+ s.close()
71
+ return port
72
+
73
+
74
+ def _post(port: int, body: dict, session: str | None = None) -> tuple[str, dict]:
75
+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
76
+ "Host": "mcp-bricksentry-1234.aws.databricksapps.com", # what the Apps proxy sends
77
+ "MCP-Protocol-Version": "2025-06-18"}
78
+ if session:
79
+ headers["Mcp-Session-Id"] = session
80
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/mcp", data=json.dumps(body).encode(),
81
+ method="POST", headers=headers)
82
+ with urllib.request.urlopen(req, timeout=15) as r:
83
+ return r.read().decode(), dict(r.headers)
84
+
85
+
86
+ def test_streamable_http_server_like_databricks_apps(tmp_path):
87
+ pytest.importorskip("mcp")
88
+ cfg = tmp_path / "bricksentry.yml"
89
+ cfg.write_text("backend: {type: duckdb}\nassessment_store: false\n")
90
+ port = _free_port()
91
+ env = dict(os.environ, DATABRICKS_APP_PORT=str(port))
92
+ p = subprocess.Popen([sys.executable, "-m", "bricksentry.cli", "mcp", "--transport", "streamable-http",
93
+ "--read-only", "--config", str(cfg)], env=env, stderr=subprocess.PIPE, text=True)
94
+ try:
95
+ for _ in range(100):
96
+ try:
97
+ socket.create_connection(("127.0.0.1", port), timeout=0.5).close()
98
+ break
99
+ except OSError:
100
+ time.sleep(0.1)
101
+ init, headers = _post(port, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
102
+ "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}}})
103
+ assert '"bricksentry"' in init and bricksentry.__version__ in init
104
+ session = headers.get("mcp-session-id") or headers.get("Mcp-Session-Id")
105
+ listed, _ = _post(port, {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}, session)
106
+ for name in ("assess_change", "safe_to_ship", "whats_downstream", "rollback_plan", "explain_diff"):
107
+ assert f'"{name}"' in listed
108
+ assert '"preview_write"' not in listed
109
+ finally:
110
+ p.terminate()
111
+ err = p.communicate(timeout=15)[1]
112
+ assert f"on http://0.0.0.0:{port}/mcp" in err
113
+
114
+
115
+ # --- the deploy kit -------------------------------------------------------------
116
+ def test_app_yaml_starts_a_valid_command():
117
+ app = yaml.safe_load((KIT / "app.yaml").read_text())
118
+ cmd = app["command"]
119
+ assert cmd[:2] == ["bricksentry", "mcp"] and "--read-only" in cmd
120
+ # every option in the command is one the CLI accepts
121
+ mcp_cmd = main.commands["mcp"]
122
+ ctx = mcp_cmd.make_context("mcp", list(cmd[2:]))
123
+ assert ctx.params["transport"] == "streamable-http"
124
+ assert ctx.params["config_path"] == "bricksentry.yml"
125
+ env = {e["name"]: e for e in app["env"]}
126
+ assert env["DATABRICKS_WAREHOUSE_ID"]["valueFrom"] == "sql-warehouse"
127
+
128
+
129
+ def test_bundle_declares_the_resource_app_yaml_uses():
130
+ bundle = yaml.safe_load((KIT / "databricks.yml").read_text())
131
+ app = bundle["resources"]["apps"]["bricksentry_mcp"]
132
+ names = {r["name"] for r in app["resources"]}
133
+ assert "sql-warehouse" in names
134
+ assert app["resources"][0]["sql_warehouse"]["permission"] == "CAN_USE"
135
+
136
+
137
+ def test_requirements_pin_this_release():
138
+ assert (KIT / "requirements.txt").read_text().strip() == f"bricksentry[databricks,mcp]=={bricksentry.__version__}"
139
+
140
+
141
+ def test_kit_config_loads_cleanly():
142
+ data = yaml.safe_load((KIT / "bricksentry.yml").read_text())
143
+ cfg = Config.from_dict(data)
144
+ assert cfg.warnings == []
145
+ assert cfg.policy is not None and cfg.spec("main.sales.orders").keys == ["order_id"]
146
+
147
+
148
+ def test_grants_cover_reads_and_lineage():
149
+ sql = (KIT / "grants.sql").read_text()
150
+ for needed in ("GRANT SELECT ON SCHEMA", "system.access.table_lineage", "`<app-sp>`"):
151
+ assert needed in sql
152
+
153
+
154
+ def test_every_lineage_key_the_code_reads_is_known():
155
+ """Config typo warnings must never flag a key that bricksentry actually uses."""
156
+ import re
157
+
158
+ from bricksentry.config import LINEAGE_KEYS, TOP_LEVEL_KEYS
159
+
160
+ used = set(re.findall(r'cfg\.get\("([a-z_]+)"', (ROOT / "src/bricksentry/lineage.py").read_text()))
161
+ used |= set(re.findall(r'lineage\.get\("([a-z_]+)"', (ROOT / "src/bricksentry/assess.py").read_text()))
162
+ assert used and used <= LINEAGE_KEYS, used - LINEAGE_KEYS
163
+ top = set(re.findall(r'data\.get\("([a-z_]+)"', (ROOT / "src/bricksentry/config.py").read_text()))
164
+ assert top - {"notify", "tables"} <= TOP_LEVEL_KEYS, top - TOP_LEVEL_KEYS
165
+
166
+
167
+ def test_documented_lineage_config_has_no_warnings():
168
+ from bricksentry.config import config_warnings
169
+
170
+ assert config_warnings({"lineage": {"type": "databricks", "depth": 3, "lookback_days": 90,
171
+ "exclude": ["*_sandbox.*"], "exclude_dropped": True}}) == []
172
+
173
+
174
+ def test_databricks_auth_failure_gives_one_clear_message(monkeypatch):
175
+ pytest.importorskip("databricks.sdk")
176
+ import databricks.sdk as sdk
177
+
178
+ from bricksentry.backends.databricks_backend import DatabricksBackend
179
+
180
+ class Boom:
181
+ def __init__(self, *a, **k):
182
+ raise AttributeError("'NoneType' object has no attribute 'parent_header'\n long sdk trace")
183
+
184
+ monkeypatch.setattr(sdk, "WorkspaceClient", Boom)
185
+ with pytest.raises(ValueError) as e:
186
+ DatabricksBackend(warehouse_id="abc123")
187
+ msg = str(e.value)
188
+ assert msg.startswith("Could not sign in to Databricks")
189
+ assert "parent_header" in msg and "long sdk trace" not in msg
190
+ assert "DATABRICKS_HOST" in msg and "databricks auth login" in msg
191
+
192
+
193
+ def test_cli_shows_the_auth_message_without_a_traceback(monkeypatch, tmp_path, capsys):
194
+ pytest.importorskip("databricks.sdk")
195
+ import databricks.sdk as sdk
196
+
197
+ from bricksentry import cli
198
+
199
+ class Boom:
200
+ def __init__(self, *a, **k):
201
+ raise AttributeError("'NoneType' object has no attribute 'parent_header'")
202
+
203
+ monkeypatch.setattr(sdk, "WorkspaceClient", Boom)
204
+ cfg = tmp_path / "bricksentry.yml"
205
+ cfg.write_text("backend: {type: databricks, warehouse_id: abc123}\n")
206
+ monkeypatch.setattr("sys.argv", ["bricksentry", "impact", "main.sales.orders", "-c", str(cfg)])
207
+ with pytest.raises(SystemExit) as e:
208
+ cli.entry()
209
+ assert e.value.code == 2
210
+ err = capsys.readouterr().err
211
+ assert "Could not sign in to Databricks" in err and "Traceback" not in err
@@ -184,7 +184,8 @@ def test_run_link_priority(monkeypatch):
184
184
  assert notify.run_link()[0] == "https://github.com/acme/data/actions/runs/77"
185
185
  assert notify.run_link(pr="5") == ("https://github.com/acme/data/pull/5", "Open pull request")
186
186
  assert notify.run_link(pr="5", run_url="https://ci.example.com/r/1") == ("https://ci.example.com/r/1", "Open run")
187
- assert notify.run_link(run_url="javascript:alert(1)")[0].startswith("https://github.com")
187
+ # a non-http(s) run_url is ignored, so the GitHub link is used instead
188
+ assert notify.run_link(run_url="javascript:alert(1)") == ("https://github.com/acme/data/actions/runs/77", "Open GitHub run")
188
189
 
189
190
 
190
191
  def test_databricks_job_run_link(monkeypatch):
@@ -126,7 +126,7 @@ def test_checks_the_latest_data_change_and_cleans_up(run_notebook):
126
126
 
127
127
  def test_share_link_prefills_the_form_without_names(run_notebook):
128
128
  ns, _, out = run_notebook()
129
- url = next(line for line in out.splitlines() if line.startswith("https://github.com/"))
129
+ url = next(line for line in out.splitlines() if urlparse(line).netloc == "github.com")
130
130
  q = parse_qs(urlparse(url).query)
131
131
  assert q["template"] == ["it_caught_this.yml"]
132
132
  assert q["verdict"] == ["block"]
@@ -173,7 +173,7 @@ def test_mcp_entry_runs_the_mcp_command(monkeypatch):
173
173
 
174
174
  seen = {}
175
175
  monkeypatch.setattr(sys, "argv", ["bricksentry-mcp", "--transport", "sse"])
176
- monkeypatch.setattr(ms, "serve", lambda transport: seen.setdefault("transport", transport))
176
+ monkeypatch.setattr(ms, "serve", lambda transport, **kw: seen.setdefault("transport", transport))
177
177
  cli.mcp_entry()
178
178
  assert seen["transport"] == "sse"
179
179
 
@@ -1,55 +0,0 @@
1
- """MCP server exposing bricksentry's agent tools.
2
-
3
- Run: ``bricksentry mcp`` (stdio) or ``bricksentry mcp --transport streamable-http``
4
-
5
- Claude Code: ``claude mcp add bricksentry -- uvx bricksentry-mcp --config /full/path/bricksentry.yml``
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- from bricksentry import agent_tools
11
-
12
- INSTRUCTIONS = """bricksentry checks whether a change to Databricks data is safe.
13
- Recommended loop when you change a pipeline or table:
14
- 1. whats_downstream(table) to learn the blast radius before editing.
15
- 2. rollback_plan(table) and keep the SQL.
16
- 3. preview_write(sql, target) for any direct write, or assess_change(tables) after
17
- your change has built candidate tables.
18
- 4. safe_to_ship(assessment_id) and follow `next_step` exactly.
19
- Never bypass a needs_human or block verdict."""
20
-
21
-
22
- def build_server():
23
- try: # mcp >= 2
24
- from mcp.server.mcpserver import MCPServer as Server
25
- except ImportError:
26
- try: # mcp 1.x
27
- from mcp.server.fastmcp import FastMCP as Server
28
- except ImportError as e: # pragma: no cover
29
- raise ImportError("The MCP server needs `pip install bricksentry[mcp]`") from e
30
-
31
- try:
32
- from mcp.types import ToolAnnotations
33
- except ImportError: # pragma: no cover
34
- ToolAnnotations = None
35
-
36
- from bricksentry import __version__
37
-
38
- try: # mcp >= 2 takes the version directly
39
- server = Server(name="bricksentry", instructions=INSTRUCTIONS, version=__version__)
40
- except TypeError: # mcp 1.x: set it on the underlying low-level server
41
- server = Server(name="bricksentry", instructions=INSTRUCTIONS)
42
- low = getattr(server, "_mcp_server", None)
43
- if low is not None and hasattr(low, "version"):
44
- low.version = __version__
45
- for fn in agent_tools.TOOLS:
46
- ann = None
47
- if ToolAnnotations is not None:
48
- ro = fn.__name__ in agent_tools.READ_ONLY
49
- ann = ToolAnnotations(readOnlyHint=ro, destructiveHint=False, idempotentHint=ro)
50
- server.tool(name=fn.__name__, description=fn.__doc__, annotations=ann)(fn)
51
- return server
52
-
53
-
54
- def serve(transport: str = "stdio") -> None:
55
- build_server().run(transport=transport)
File without changes
File without changes
File without changes
File without changes