lakelogic-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.
- lakelogic_mcp-0.1.0/.github/workflows/publish.yml +32 -0
- lakelogic_mcp-0.1.0/.github/workflows/test.yml +20 -0
- lakelogic_mcp-0.1.0/.gitignore +5 -0
- lakelogic_mcp-0.1.0/LICENSE +201 -0
- lakelogic_mcp-0.1.0/PKG-INFO +86 -0
- lakelogic_mcp-0.1.0/README.md +72 -0
- lakelogic_mcp-0.1.0/pyproject.toml +28 -0
- lakelogic_mcp-0.1.0/src/lakelogic_mcp/__init__.py +3 -0
- lakelogic_mcp-0.1.0/src/lakelogic_mcp/server.py +111 -0
- lakelogic_mcp-0.1.0/src/lakelogic_mcp/tools.py +302 -0
- lakelogic_mcp-0.1.0/tests/test_server_over_mcp.py +55 -0
- lakelogic_mcp-0.1.0/tests/test_tools.py +146 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
# A pushed `v*` tag builds, tests and publishes. PyPI Trusted Publishing (OIDC): no stored token.
|
|
4
|
+
# PyPI must have a trusted publisher for (owner=LakeLogic, repo=lakelogic-mcp,
|
|
5
|
+
# workflow=publish.yml, environment=pypi); add it as a "pending publisher" before the first release.
|
|
6
|
+
|
|
7
|
+
on:
|
|
8
|
+
push:
|
|
9
|
+
tags:
|
|
10
|
+
- "v*"
|
|
11
|
+
|
|
12
|
+
permissions:
|
|
13
|
+
contents: read
|
|
14
|
+
id-token: write
|
|
15
|
+
|
|
16
|
+
jobs:
|
|
17
|
+
pypi-publish:
|
|
18
|
+
runs-on: ubuntu-latest
|
|
19
|
+
environment: pypi
|
|
20
|
+
steps:
|
|
21
|
+
- uses: actions/checkout@v4
|
|
22
|
+
- uses: actions/setup-python@v5
|
|
23
|
+
with:
|
|
24
|
+
python-version: "3.12"
|
|
25
|
+
- name: Tag matches the version
|
|
26
|
+
run: |
|
|
27
|
+
v=$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
|
|
28
|
+
test "v$v" = "${GITHUB_REF_NAME}" || { echo "tag ${GITHUB_REF_NAME} != pyproject v$v"; exit 1; }
|
|
29
|
+
- run: pip install -e ".[dev]" build
|
|
30
|
+
- run: pytest -q
|
|
31
|
+
- run: python -m build
|
|
32
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: Test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.11", "3.12"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: pip install -e ".[dev]"
|
|
20
|
+
- run: pytest -q
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 LakeLogic
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: lakelogic-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A local MCP server that lets AI assistants validate, lint and explain Open Lakehouse Contracts.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: lakelogic>=1.78.0
|
|
9
|
+
Requires-Dist: mcp>=1.2
|
|
10
|
+
Requires-Dist: open-lakehouse-contract>=0.24.0
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# lakelogic-mcp
|
|
16
|
+
|
|
17
|
+
A **local** MCP server that lets AI assistants (Claude Code, Claude Desktop, Cursor and any MCP client)
|
|
18
|
+
check the Open Lakehouse Contracts (OLC) they write, using LakeLogic itself instead of guessing.
|
|
19
|
+
|
|
20
|
+
- Runs on your machine over stdio. **No network, no account, no telemetry.**
|
|
21
|
+
- **Never touches a platform.** Two tools act locally: `generate_test_data` writes a data file and
|
|
22
|
+
`run_contract` runs a contract on it with Polars or DuckDB. Nothing is written to a contract's target.
|
|
23
|
+
- Reads and writes only inside the project folder it was started in.
|
|
24
|
+
|
|
25
|
+
## Tools
|
|
26
|
+
|
|
27
|
+
| Tool | Answers |
|
|
28
|
+
|---|---|
|
|
29
|
+
| `validate_contract` | Is this a legal OLC contract? Each error's location and problem |
|
|
30
|
+
| `lint_contract` | Is it a good one? Governance findings from `lakelogic lint`, each with its fix |
|
|
31
|
+
| `explain_rule` | Why does a lint rule exist? What it checks, why it matters, a failing and a fixed contract |
|
|
32
|
+
| `contract_reference` | How is one part of a contract written? (`anatomy`, `quality`, `materialization`, …) |
|
|
33
|
+
| `export_odcs` | The contract as an Open Data Contract Standard document |
|
|
34
|
+
| `generate_test_data` | Synthetic data shaped by the contract, with a share of rows that deliberately break its rules |
|
|
35
|
+
| `run_contract` | How many rows pass, how many are quarantined, and why (Polars or DuckDB, local only) |
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
claude mcp add lakelogic -- uvx lakelogic-mcp
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Try it locally (development checkout)
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
cd C:\_Personal\_SaaS\lakelogic-mcp
|
|
47
|
+
uv venv .venv
|
|
48
|
+
uv pip install --python .venv\Scripts\python.exe "mcp>=1.2" pytest -e ..\open-lakehouse-contract -e ..\lakelogic
|
|
49
|
+
uv pip install --python .venv\Scripts\python.exe --no-deps -e .
|
|
50
|
+
.venv\Scripts\python.exe -m pytest
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Register it with Claude Code
|
|
54
|
+
|
|
55
|
+
From the project whose contracts you want checked:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
claude mcp add lakelogic -- C:\_Personal\_SaaS\lakelogic-mcp\.venv\Scripts\lakelogic-mcp.exe
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Then ask, for example:
|
|
62
|
+
|
|
63
|
+
- "Lint the contracts in this folder and fix what you find."
|
|
64
|
+
- "Why is KEY-002 flagged on silver_trips.yaml?"
|
|
65
|
+
- "Write a silver contract for orders and check it before you show me."
|
|
66
|
+
|
|
67
|
+
### Claude Desktop / Cursor
|
|
68
|
+
|
|
69
|
+
Add to the client's MCP settings (`claude_desktop_config.json`, or Cursor's `mcp.json`):
|
|
70
|
+
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"mcpServers": {
|
|
74
|
+
"lakelogic": {
|
|
75
|
+
"command": "C:\\_Personal\\_SaaS\\lakelogic-mcp\\.venv\\Scripts\\lakelogic-mcp.exe",
|
|
76
|
+
"args": ["--root", "C:\\path\\to\\your\\contracts\\project"]
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Once published
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
uvx lakelogic-mcp # Claude Code: claude mcp add lakelogic -- uvx lakelogic-mcp
|
|
86
|
+
```
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# lakelogic-mcp
|
|
2
|
+
|
|
3
|
+
A **local** MCP server that lets AI assistants (Claude Code, Claude Desktop, Cursor and any MCP client)
|
|
4
|
+
check the Open Lakehouse Contracts (OLC) they write, using LakeLogic itself instead of guessing.
|
|
5
|
+
|
|
6
|
+
- Runs on your machine over stdio. **No network, no account, no telemetry.**
|
|
7
|
+
- **Never touches a platform.** Two tools act locally: `generate_test_data` writes a data file and
|
|
8
|
+
`run_contract` runs a contract on it with Polars or DuckDB. Nothing is written to a contract's target.
|
|
9
|
+
- Reads and writes only inside the project folder it was started in.
|
|
10
|
+
|
|
11
|
+
## Tools
|
|
12
|
+
|
|
13
|
+
| Tool | Answers |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `validate_contract` | Is this a legal OLC contract? Each error's location and problem |
|
|
16
|
+
| `lint_contract` | Is it a good one? Governance findings from `lakelogic lint`, each with its fix |
|
|
17
|
+
| `explain_rule` | Why does a lint rule exist? What it checks, why it matters, a failing and a fixed contract |
|
|
18
|
+
| `contract_reference` | How is one part of a contract written? (`anatomy`, `quality`, `materialization`, …) |
|
|
19
|
+
| `export_odcs` | The contract as an Open Data Contract Standard document |
|
|
20
|
+
| `generate_test_data` | Synthetic data shaped by the contract, with a share of rows that deliberately break its rules |
|
|
21
|
+
| `run_contract` | How many rows pass, how many are quarantined, and why (Polars or DuckDB, local only) |
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
claude mcp add lakelogic -- uvx lakelogic-mcp
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Try it locally (development checkout)
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
cd C:\_Personal\_SaaS\lakelogic-mcp
|
|
33
|
+
uv venv .venv
|
|
34
|
+
uv pip install --python .venv\Scripts\python.exe "mcp>=1.2" pytest -e ..\open-lakehouse-contract -e ..\lakelogic
|
|
35
|
+
uv pip install --python .venv\Scripts\python.exe --no-deps -e .
|
|
36
|
+
.venv\Scripts\python.exe -m pytest
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Register it with Claude Code
|
|
40
|
+
|
|
41
|
+
From the project whose contracts you want checked:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
claude mcp add lakelogic -- C:\_Personal\_SaaS\lakelogic-mcp\.venv\Scripts\lakelogic-mcp.exe
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Then ask, for example:
|
|
48
|
+
|
|
49
|
+
- "Lint the contracts in this folder and fix what you find."
|
|
50
|
+
- "Why is KEY-002 flagged on silver_trips.yaml?"
|
|
51
|
+
- "Write a silver contract for orders and check it before you show me."
|
|
52
|
+
|
|
53
|
+
### Claude Desktop / Cursor
|
|
54
|
+
|
|
55
|
+
Add to the client's MCP settings (`claude_desktop_config.json`, or Cursor's `mcp.json`):
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"mcpServers": {
|
|
60
|
+
"lakelogic": {
|
|
61
|
+
"command": "C:\\_Personal\\_SaaS\\lakelogic-mcp\\.venv\\Scripts\\lakelogic-mcp.exe",
|
|
62
|
+
"args": ["--root", "C:\\path\\to\\your\\contracts\\project"]
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Once published
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
uvx lakelogic-mcp # Claude Code: claude mcp add lakelogic -- uvx lakelogic-mcp
|
|
72
|
+
```
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "lakelogic-mcp"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A local MCP server that lets AI assistants validate, lint and explain Open Lakehouse Contracts."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = { text = "Apache-2.0" }
|
|
8
|
+
dependencies = [
|
|
9
|
+
"mcp>=1.2", # 1.x (FastMCP) and 2.x (MCPServer) both supported
|
|
10
|
+
"lakelogic>=1.78.0", # the lint rule catalogue (explain_rule) ships in 1.78.0
|
|
11
|
+
"open-lakehouse-contract>=0.24.0",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
lakelogic-mcp = "lakelogic_mcp.server:main"
|
|
16
|
+
|
|
17
|
+
[project.optional-dependencies]
|
|
18
|
+
dev = ["pytest>=8"]
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = ["hatchling"]
|
|
22
|
+
build-backend = "hatchling.build"
|
|
23
|
+
|
|
24
|
+
[tool.hatch.build.targets.wheel]
|
|
25
|
+
packages = ["src/lakelogic_mcp"]
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""The MCP server: the tools over stdio. Local only: no network, no account, no telemetry.
|
|
2
|
+
|
|
3
|
+
lakelogic-mcp # serve the current folder
|
|
4
|
+
lakelogic-mcp --root <folder> # serve another folder
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
from typing import Any, Dict, Optional
|
|
11
|
+
|
|
12
|
+
try: # MCP SDK 2.x
|
|
13
|
+
from mcp.server.mcpserver import MCPServer as _Server
|
|
14
|
+
except ImportError: # MCP SDK 1.x
|
|
15
|
+
from mcp.server.fastmcp import FastMCP as _Server
|
|
16
|
+
from mcp.types import ToolAnnotations
|
|
17
|
+
|
|
18
|
+
from lakelogic_mcp import tools
|
|
19
|
+
|
|
20
|
+
#: Writes files inside the project and runs code on them; never touches a platform.
|
|
21
|
+
_LOCAL_WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)
|
|
22
|
+
|
|
23
|
+
#: These tools only read and checks: clients may call them without asking each time.
|
|
24
|
+
_READ_ONLY = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
|
|
25
|
+
|
|
26
|
+
mcp = _Server(
|
|
27
|
+
"lakelogic",
|
|
28
|
+
instructions=(
|
|
29
|
+
"Tools for Open Lakehouse Contracts (OLC). After writing or changing a contract, call "
|
|
30
|
+
"validate_contract (is it legal OLC?) and then lint_contract (is it a good one?), and fix what "
|
|
31
|
+
"they report before showing it. Use explain_rule to learn why a lint rule exists, and "
|
|
32
|
+
"contract_reference to read how a part of the contract is written. To show a contract working, "
|
|
33
|
+
"call generate_test_data and then run_contract on the file it wrote."
|
|
34
|
+
),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _call(fn, *args, **kwargs) -> Dict[str, Any]:
|
|
39
|
+
try:
|
|
40
|
+
return fn(*args, **kwargs)
|
|
41
|
+
except tools.ToolError as exc:
|
|
42
|
+
return {"error": str(exc)}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@mcp.tool(annotations=_READ_ONLY)
|
|
46
|
+
def validate_contract(path: Optional[str] = None, contract_yaml: Optional[str] = None) -> Dict[str, Any]:
|
|
47
|
+
"""Check whether a contract is LEGAL Open Lakehouse Contract (OLC): known keys, right shapes, required
|
|
48
|
+
fields. Use it after writing or editing a contract. Give `path` (a file in this project) or
|
|
49
|
+
`contract_yaml` (the text). Returns `valid` and, if not, each error's location and problem."""
|
|
50
|
+
return _call(tools.validate_contract, path=path, contract_yaml=contract_yaml)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@mcp.tool(annotations=_READ_ONLY)
|
|
54
|
+
def lint_contract(path: Optional[str] = None, contract_yaml: Optional[str] = None) -> Dict[str, Any]:
|
|
55
|
+
"""Check whether a contract is a GOOD one: governance gaps such as a merge with no key, unordered
|
|
56
|
+
deduplication, untagged personal data, a step no engine runs. Use it after validate_contract passes.
|
|
57
|
+
Returns `clean` and findings, each with its rule code, severity and fix."""
|
|
58
|
+
return _call(tools.lint_contract, path=path, contract_yaml=contract_yaml)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@mcp.tool(annotations=_READ_ONLY)
|
|
62
|
+
def explain_rule(code: str) -> Dict[str, Any]:
|
|
63
|
+
"""Explain one lint rule (e.g. KEY-002): what it checks, why it matters, a failing contract and the
|
|
64
|
+
fixed contract. Use it when a lint finding is unclear."""
|
|
65
|
+
return _call(tools.explain_rule, code)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@mcp.tool(annotations=_READ_ONLY)
|
|
69
|
+
def contract_reference(topic: str) -> Dict[str, Any]:
|
|
70
|
+
"""Read the OLC reference for one part of a contract. Topics include anatomy (every key),
|
|
71
|
+
quality, transformation, materialization, ingestion, security, slo, execution-order."""
|
|
72
|
+
return _call(tools.contract_reference, topic)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@mcp.tool(annotations=_READ_ONLY)
|
|
76
|
+
def export_odcs(path: str) -> Dict[str, Any]:
|
|
77
|
+
"""Convert a contract file in this project to an Open Data Contract Standard (ODCS) document."""
|
|
78
|
+
return _call(tools.export_odcs, path)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@mcp.tool(annotations=_LOCAL_WRITE)
|
|
82
|
+
def generate_test_data(
|
|
83
|
+
path: str, rows: int = 100, invalid_ratio: float = 0.1, seed: Optional[int] = None, output: Optional[str] = None
|
|
84
|
+
) -> Dict[str, Any]:
|
|
85
|
+
"""Write synthetic test data for a contract (default test_data/<contract>.csv): right types,
|
|
86
|
+
accepted values and ranges, with `invalid_ratio` of rows deliberately breaking the quality rules
|
|
87
|
+
so a run shows quarantine working. Follow with run_contract."""
|
|
88
|
+
return _call(tools.generate_test_data, path, rows=rows, invalid_ratio=invalid_ratio, seed=seed, output=output)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@mcp.tool(annotations=_LOCAL_WRITE)
|
|
92
|
+
def run_contract(
|
|
93
|
+
path: str, source: str, engine: str = "polars", sample: int = 10, write_outputs: bool = False
|
|
94
|
+
) -> Dict[str, Any]:
|
|
95
|
+
"""Run a contract on a local data file (CSV/Parquet) with Polars or DuckDB: good rows,
|
|
96
|
+
quarantined rows, and each quarantine reason with its count. Writes nothing to the contract's
|
|
97
|
+
target. `write_outputs` saves good/bad rows under runs/."""
|
|
98
|
+
return _call(tools.run_contract, path, source, engine=engine, sample=sample, write_outputs=write_outputs)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def main(argv: Optional[list[str]] = None) -> None:
|
|
102
|
+
parser = argparse.ArgumentParser(prog="lakelogic-mcp")
|
|
103
|
+
parser.add_argument("--root", help="the project folder tools may read (default: the current folder)")
|
|
104
|
+
args = parser.parse_args(argv)
|
|
105
|
+
if args.root:
|
|
106
|
+
tools.set_root(args.root)
|
|
107
|
+
mcp.run() # stdio
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
main()
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""The tools, as plain functions. Thin adapters over LakeLogic Core and OLC: any real logic
|
|
2
|
+
belongs in Core or OLC, never here.
|
|
3
|
+
|
|
4
|
+
Most tools READ and CHECK. Two act: `generate_test_data` writes a data file and `run_contract`
|
|
5
|
+
runs a contract on one, locally (Polars or DuckDB), so an assistant can show a contract working
|
|
6
|
+
before it goes near a platform. Paths are confined to the folder the server
|
|
7
|
+
was started in (``ROOT``), so an assistant cannot read files outside the project it was opened on.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
#: The only folder tools may read from. Set by the server at start (``--root``, default: cwd).
|
|
17
|
+
ROOT = Path(os.environ.get("LAKELOGIC_MCP_ROOT") or os.getcwd()).resolve()
|
|
18
|
+
|
|
19
|
+
REFERENCE_TOPICS = (
|
|
20
|
+
"anatomy",
|
|
21
|
+
"execution-order",
|
|
22
|
+
"ingestion",
|
|
23
|
+
"lifecycle",
|
|
24
|
+
"quality",
|
|
25
|
+
"security",
|
|
26
|
+
"compliance",
|
|
27
|
+
"transformation",
|
|
28
|
+
"external-logic",
|
|
29
|
+
"materialization",
|
|
30
|
+
"server",
|
|
31
|
+
"lineage",
|
|
32
|
+
"data-products",
|
|
33
|
+
"slo",
|
|
34
|
+
"notifications",
|
|
35
|
+
"extraction",
|
|
36
|
+
"conformance",
|
|
37
|
+
"cli",
|
|
38
|
+
"schema",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ToolError(ValueError):
|
|
43
|
+
"""A request the tool refuses, with a message the assistant can act on."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def set_root(path: str | Path) -> Path:
|
|
47
|
+
global ROOT
|
|
48
|
+
ROOT = Path(path).resolve()
|
|
49
|
+
return ROOT
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _resolve(path: str) -> Path:
|
|
53
|
+
"""``path`` inside ROOT, or a refusal. Relative paths are relative to ROOT."""
|
|
54
|
+
candidate = Path(path)
|
|
55
|
+
full = (candidate if candidate.is_absolute() else ROOT / candidate).resolve()
|
|
56
|
+
if full != ROOT and ROOT not in full.parents:
|
|
57
|
+
raise ToolError(
|
|
58
|
+
f"'{path}' is outside the project folder this server was started in ({ROOT}). "
|
|
59
|
+
"Only files inside it can be read."
|
|
60
|
+
)
|
|
61
|
+
if not full.is_file():
|
|
62
|
+
raise ToolError(f"No contract file at '{path}' (looked in {full}).")
|
|
63
|
+
return full
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _resolve_output(path: str) -> Path:
|
|
67
|
+
"""Where a tool may WRITE: inside ROOT, parent folders created."""
|
|
68
|
+
candidate = Path(path)
|
|
69
|
+
full = (candidate if candidate.is_absolute() else ROOT / candidate).resolve()
|
|
70
|
+
if ROOT not in full.parents:
|
|
71
|
+
raise ToolError(f"'{path}' is outside the project folder ({ROOT}). Files can only be written inside it.")
|
|
72
|
+
full.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
return full
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _resolve_data(path: str) -> Path:
|
|
77
|
+
full = _resolve_output(path)
|
|
78
|
+
if not full.is_file():
|
|
79
|
+
raise ToolError(f"No data file at '{path}' (looked in {full}).")
|
|
80
|
+
return full
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _parse(contract_yaml: str) -> Any:
|
|
84
|
+
from olc.validate import load_contract_yaml
|
|
85
|
+
|
|
86
|
+
try:
|
|
87
|
+
doc = load_contract_yaml(contract_yaml)
|
|
88
|
+
except Exception as exc: # noqa: BLE001 - reported to the assistant as findings
|
|
89
|
+
raise ToolError(f"Not valid YAML: {exc}") from None
|
|
90
|
+
if not isinstance(doc, dict):
|
|
91
|
+
raise ToolError("A contract is a YAML mapping (key: value pairs) at the top level.")
|
|
92
|
+
return doc
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _contract_text(path: Optional[str], contract_yaml: Optional[str]) -> tuple[str, str]:
|
|
96
|
+
if bool(path) == bool(contract_yaml):
|
|
97
|
+
raise ToolError("Give exactly one of `path` (a contract file) or `contract_yaml` (the contract text).")
|
|
98
|
+
if path:
|
|
99
|
+
full = _resolve(path)
|
|
100
|
+
return full.read_text(encoding="utf-8"), str(full.relative_to(ROOT))
|
|
101
|
+
return contract_yaml or "", "inline contract"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# ── tools ────────────────────────────────────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def validate_contract(path: Optional[str] = None, contract_yaml: Optional[str] = None) -> Dict[str, Any]:
|
|
108
|
+
"""Is this a LEGAL OLC contract? Checks it against the strict OLC model."""
|
|
109
|
+
from olc.models import load_strict
|
|
110
|
+
|
|
111
|
+
text, source = _contract_text(path, contract_yaml)
|
|
112
|
+
doc = _parse(text)
|
|
113
|
+
try:
|
|
114
|
+
load_strict(doc)
|
|
115
|
+
except Exception as exc: # noqa: BLE001 - pydantic's errors, flattened for the assistant
|
|
116
|
+
errors = getattr(exc, "errors", None)
|
|
117
|
+
found: List[Dict[str, str]] = []
|
|
118
|
+
if callable(errors):
|
|
119
|
+
for e in errors():
|
|
120
|
+
found.append({"location": ".".join(str(p) for p in e.get("loc", ())) or "<root>", "problem": e.get("msg", "")})
|
|
121
|
+
else:
|
|
122
|
+
found.append({"location": "<root>", "problem": str(exc)})
|
|
123
|
+
return {"contract": source, "valid": False, "errors": found}
|
|
124
|
+
return {"contract": source, "valid": True, "errors": []}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def lint_contract(path: Optional[str] = None, contract_yaml: Optional[str] = None) -> Dict[str, Any]:
|
|
128
|
+
"""Is this a GOOD contract? Governance findings from `lakelogic lint`, each with its fix.
|
|
129
|
+
|
|
130
|
+
With `path`, the contract's domain and system settings (`_domain.yaml` / `_system.yaml`
|
|
131
|
+
above it) are taken into account, exactly as `lakelogic lint` does.
|
|
132
|
+
"""
|
|
133
|
+
from lakelogic.core.contract_lint import review_contract, review_contract_dict
|
|
134
|
+
|
|
135
|
+
if path:
|
|
136
|
+
full = _resolve(path)
|
|
137
|
+
findings = review_contract(full)
|
|
138
|
+
source = str(full.relative_to(ROOT))
|
|
139
|
+
else:
|
|
140
|
+
text, source = _contract_text(None, contract_yaml)
|
|
141
|
+
findings = review_contract_dict(_parse(text), "inline", None)
|
|
142
|
+
rows = [
|
|
143
|
+
{
|
|
144
|
+
"rule": f.check_id,
|
|
145
|
+
"severity": f.severity,
|
|
146
|
+
"message": f.message,
|
|
147
|
+
"field": f.field,
|
|
148
|
+
"fix": f.suggestion,
|
|
149
|
+
}
|
|
150
|
+
for f in findings
|
|
151
|
+
]
|
|
152
|
+
return {
|
|
153
|
+
"contract": source,
|
|
154
|
+
"clean": not any(r["severity"] in ("critical", "warning") for r in rows),
|
|
155
|
+
"findings": rows,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def explain_rule(code: str) -> Dict[str, Any]:
|
|
160
|
+
"""Why a lint rule exists: what it checks, why it matters, a failing and a fixed contract."""
|
|
161
|
+
from lakelogic.core.contract_lint_catalogue import CATALOGUE
|
|
162
|
+
|
|
163
|
+
entry = CATALOGUE.get(code.strip().upper())
|
|
164
|
+
if entry is None:
|
|
165
|
+
raise ToolError(f"No lint rule '{code}'. Known rules: {', '.join(sorted(CATALOGUE))}.")
|
|
166
|
+
return {
|
|
167
|
+
"rule": entry.code,
|
|
168
|
+
"title": entry.title,
|
|
169
|
+
"severity": entry.severity,
|
|
170
|
+
"checks": entry.checks,
|
|
171
|
+
"why": entry.why,
|
|
172
|
+
"failing_example": entry.failing,
|
|
173
|
+
"fixed_example": entry.fixed,
|
|
174
|
+
"fixed_example_is_standard_olc": entry.olc_valid,
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def contract_reference(topic: str) -> Dict[str, Any]:
|
|
179
|
+
"""The OLC reference page for one part of a contract (e.g. `quality`, `materialization`)."""
|
|
180
|
+
import olc
|
|
181
|
+
|
|
182
|
+
key = topic.strip().lower().replace(" ", "-").replace("_", "-")
|
|
183
|
+
if key not in REFERENCE_TOPICS:
|
|
184
|
+
raise ToolError(f"No reference page '{topic}'. Topics: {', '.join(REFERENCE_TOPICS)}.")
|
|
185
|
+
page = Path(olc.__file__).resolve().parent / "_bundled" / "docs" / "reference" / f"{key}.md"
|
|
186
|
+
if not page.exists():
|
|
187
|
+
raise ToolError(f"The installed OLC package has no '{key}' page.")
|
|
188
|
+
return {"topic": key, "markdown": page.read_text(encoding="utf-8")}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def export_odcs(path: str) -> Dict[str, Any]:
|
|
192
|
+
"""The contract as an Open Data Contract Standard (ODCS) document."""
|
|
193
|
+
from lakelogic.core.models import DataContract
|
|
194
|
+
|
|
195
|
+
full = _resolve(path)
|
|
196
|
+
try:
|
|
197
|
+
document = DataContract.from_yaml(str(full)).to_odcs()
|
|
198
|
+
except Exception as exc: # noqa: BLE001
|
|
199
|
+
raise ToolError(f"Could not export '{path}': {exc}") from None
|
|
200
|
+
return {"contract": str(full.relative_to(ROOT)), "odcs": document}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
RUN_ENGINES = ("polars", "duckdb")
|
|
204
|
+
ERROR_COLUMN = "_lakelogic_errors"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def generate_test_data(
|
|
208
|
+
path: str, rows: int = 100, invalid_ratio: float = 0.1, seed: Optional[int] = None, output: Optional[str] = None
|
|
209
|
+
) -> Dict[str, Any]:
|
|
210
|
+
"""Synthetic data shaped by the contract: its types, nullability, accepted values and ranges.
|
|
211
|
+
`invalid_ratio` of the rows deliberately break the quality rules, so a run shows quarantine working."""
|
|
212
|
+
from lakelogic.core.generator import DataGenerator
|
|
213
|
+
|
|
214
|
+
full = _resolve(path)
|
|
215
|
+
if not 1 <= rows <= 100_000:
|
|
216
|
+
raise ToolError("rows must be between 1 and 100000.")
|
|
217
|
+
if not 0.0 <= invalid_ratio <= 1.0:
|
|
218
|
+
raise ToolError("invalid_ratio must be between 0.0 and 1.0.")
|
|
219
|
+
out = _resolve_output(output or f"test_data/{full.stem}.csv")
|
|
220
|
+
if out.suffix.lower() not in (".csv", ".parquet"):
|
|
221
|
+
raise ToolError("output must end in .csv or .parquet.")
|
|
222
|
+
try:
|
|
223
|
+
df = DataGenerator(full, seed=seed).generate(rows=rows, invalid_ratio=invalid_ratio, output_format="polars")
|
|
224
|
+
except Exception as exc: # noqa: BLE001
|
|
225
|
+
raise ToolError(f"Could not generate data for '{path}': {exc}") from None
|
|
226
|
+
df.write_csv(out) if out.suffix.lower() == ".csv" else df.write_parquet(out)
|
|
227
|
+
return {
|
|
228
|
+
"contract": str(full.relative_to(ROOT)),
|
|
229
|
+
"data_file": str(out.relative_to(ROOT)),
|
|
230
|
+
"rows": df.height,
|
|
231
|
+
"columns": df.columns,
|
|
232
|
+
"intended_invalid_rows": round(rows * invalid_ratio),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def run_contract(
|
|
237
|
+
path: str, source: str, engine: str = "polars", sample: int = 10, write_outputs: bool = False
|
|
238
|
+
) -> Dict[str, Any]:
|
|
239
|
+
"""Run the contract on a local data file: how many rows pass, how many are quarantined, and why.
|
|
240
|
+
Nothing is materialized to the contract's target; `write_outputs` saves good/bad rows under runs/."""
|
|
241
|
+
from lakelogic import DataProcessor
|
|
242
|
+
|
|
243
|
+
full = _resolve(path)
|
|
244
|
+
data = _resolve_data(source)
|
|
245
|
+
if engine not in RUN_ENGINES:
|
|
246
|
+
raise ToolError(f"engine must be one of {', '.join(RUN_ENGINES)} locally. Spark, Snowflake and BigQuery run on the platform.")
|
|
247
|
+
try:
|
|
248
|
+
# Read the file by ITS type and hand the rows to the contract: `run_source` would read it
|
|
249
|
+
# with the contract's own source/target format (e.g. Delta), which a local file is not.
|
|
250
|
+
frame = _read_local(data, engine)
|
|
251
|
+
result = DataProcessor(engine=engine, contract=str(full)).run(frame)
|
|
252
|
+
except Exception as exc: # noqa: BLE001 - a failed run is the answer, not a server error
|
|
253
|
+
return {"contract": str(full.relative_to(ROOT)), "ran": False, "error": f"{type(exc).__name__}: {exc}"}
|
|
254
|
+
good, bad = _to_polars(result.good), _to_polars(result.bad)
|
|
255
|
+
reasons: Dict[str, int] = {}
|
|
256
|
+
if bad is not None and ERROR_COLUMN in bad.columns:
|
|
257
|
+
for errs in bad[ERROR_COLUMN].to_list():
|
|
258
|
+
for e in errs if isinstance(errs, list) else [errs]:
|
|
259
|
+
if e:
|
|
260
|
+
reasons[str(e)] = reasons.get(str(e), 0) + 1
|
|
261
|
+
out: Dict[str, Any] = {
|
|
262
|
+
"contract": str(full.relative_to(ROOT)),
|
|
263
|
+
"ran": True,
|
|
264
|
+
"engine": engine,
|
|
265
|
+
"good_rows": 0 if good is None else good.height,
|
|
266
|
+
"quarantined_rows": 0 if bad is None else bad.height,
|
|
267
|
+
"quarantine_reasons": dict(sorted(reasons.items(), key=lambda kv: -kv[1])),
|
|
268
|
+
"quarantined_sample": [] if bad is None else bad.head(sample).to_dicts(),
|
|
269
|
+
}
|
|
270
|
+
if write_outputs:
|
|
271
|
+
stem = full.stem
|
|
272
|
+
for name, df in (("good", good), ("bad", bad)):
|
|
273
|
+
if df is not None:
|
|
274
|
+
target = _resolve_output(f"runs/{stem}_{name}.parquet")
|
|
275
|
+
df.write_parquet(target)
|
|
276
|
+
out[f"{name}_file"] = str(target.relative_to(ROOT))
|
|
277
|
+
return out
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _read_local(data: Path, engine: str) -> Any:
|
|
281
|
+
suffix = data.suffix.lower()
|
|
282
|
+
if suffix not in (".csv", ".parquet"):
|
|
283
|
+
raise ToolError("source must be a .csv or .parquet file.")
|
|
284
|
+
import polars as pl
|
|
285
|
+
|
|
286
|
+
frame = pl.read_csv(data, infer_schema_length=10_000) if suffix == ".csv" else pl.read_parquet(data)
|
|
287
|
+
# DuckDB gets Arrow: a relation built on another connection cannot be read by the engine's own.
|
|
288
|
+
return frame.to_arrow() if engine == "duckdb" else frame
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _to_polars(df: Any) -> Any:
|
|
292
|
+
if df is None:
|
|
293
|
+
return None
|
|
294
|
+
import polars as pl
|
|
295
|
+
|
|
296
|
+
if isinstance(df, pl.DataFrame):
|
|
297
|
+
return df
|
|
298
|
+
if hasattr(df, "pl"): # DuckDB relation
|
|
299
|
+
return df.pl()
|
|
300
|
+
if hasattr(df, "to_pandas") or hasattr(df, "columns"):
|
|
301
|
+
return pl.from_pandas(df) if not hasattr(df, "pl") else df.pl()
|
|
302
|
+
raise ToolError(f"Unexpected result type {type(df).__name__}.")
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""End to end: start the real server as a subprocess and talk to it over MCP (stdio), as a client
|
|
2
|
+
such as Claude Code does."""
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from mcp import ClientSession, StdioServerParameters
|
|
10
|
+
from mcp.client.stdio import stdio_client
|
|
11
|
+
|
|
12
|
+
EXPECTED_TOOLS = {
|
|
13
|
+
"validate_contract", "lint_contract", "explain_rule", "contract_reference", "export_odcs",
|
|
14
|
+
"generate_test_data", "run_contract",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
CONTRACT = """version: 1.0.0
|
|
18
|
+
info: { title: Trips, table_name: trips }
|
|
19
|
+
model:
|
|
20
|
+
fields:
|
|
21
|
+
- { name: trip_id, type: string }
|
|
22
|
+
primary_key: [trip_id]
|
|
23
|
+
materialization: { strategy: scd2, format: delta }
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def _session_run(root: Path):
|
|
28
|
+
params = StdioServerParameters(
|
|
29
|
+
command=sys.executable, args=["-m", "lakelogic_mcp.server", "--root", str(root)]
|
|
30
|
+
)
|
|
31
|
+
async with stdio_client(params) as (read, write):
|
|
32
|
+
async with ClientSession(read, write) as session:
|
|
33
|
+
await session.initialize()
|
|
34
|
+
listed = await session.list_tools()
|
|
35
|
+
lint = await session.call_tool("lint_contract", {"path": "trips.yaml"})
|
|
36
|
+
outside = await session.call_tool("validate_contract", {"path": "../elsewhere.yaml"})
|
|
37
|
+
return listed, lint, outside
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _payload(result):
|
|
41
|
+
return json.loads(result.content[0].text)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_the_server_lists_its_tools_and_answers_over_mcp(tmp_path):
|
|
45
|
+
(tmp_path / "trips.yaml").write_text(CONTRACT, encoding="utf-8")
|
|
46
|
+
listed, lint, outside = asyncio.run(_session_run(tmp_path))
|
|
47
|
+
|
|
48
|
+
tools = {t.name: t for t in listed.tools}
|
|
49
|
+
assert set(tools) == EXPECTED_TOOLS
|
|
50
|
+
assert all(t.description for t in tools.values())
|
|
51
|
+
|
|
52
|
+
found = _payload(lint)
|
|
53
|
+
assert found["clean"] is False and [f["rule"] for f in found["findings"]] == ["SCD-001"]
|
|
54
|
+
|
|
55
|
+
assert "outside the project folder" in _payload(outside)["error"]
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Each tool against real contracts, and the one boundary that matters: nothing outside the project."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from lakelogic_mcp import tools
|
|
8
|
+
|
|
9
|
+
GOOD = """version: 1.0.0
|
|
10
|
+
info: { title: Trips, table_name: trips }
|
|
11
|
+
model:
|
|
12
|
+
fields:
|
|
13
|
+
- { name: trip_id, type: string, required: true }
|
|
14
|
+
- { name: updated_at, type: timestamp }
|
|
15
|
+
primary_key: [trip_id]
|
|
16
|
+
transformations:
|
|
17
|
+
- deduplicate: { on: [trip_id], sort_by: [updated_at], order: desc }
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
# Valid OLC, but the dedup sorts by its own key: KEY-002 (only caught once `on:` is read as a
|
|
21
|
+
# field name, not the boolean YAML 1.1 makes of it).
|
|
22
|
+
SORTED_BY_KEY = GOOD.replace("sort_by: [updated_at]", "sort_by: [trip_id]")
|
|
23
|
+
|
|
24
|
+
INVALID = """version: 1.0.0
|
|
25
|
+
info: { title: Trips }
|
|
26
|
+
model:
|
|
27
|
+
fields:
|
|
28
|
+
- { name: trip_id, type: string }
|
|
29
|
+
materialization:
|
|
30
|
+
primary_key: [trip_id]
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.fixture()
|
|
35
|
+
def project(tmp_path):
|
|
36
|
+
tools.set_root(tmp_path)
|
|
37
|
+
(tmp_path / "contracts").mkdir()
|
|
38
|
+
(tmp_path / "contracts" / "good.yaml").write_text(GOOD, encoding="utf-8")
|
|
39
|
+
(tmp_path / "contracts" / "sorted_by_key.yaml").write_text(SORTED_BY_KEY, encoding="utf-8")
|
|
40
|
+
(tmp_path / "contracts" / "invalid.yaml").write_text(INVALID, encoding="utf-8")
|
|
41
|
+
yield tmp_path
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_validate_accepts_a_legal_contract(project):
|
|
45
|
+
assert tools.validate_contract(path="contracts/good.yaml") == {
|
|
46
|
+
"contract": str(Path("contracts/good.yaml")), "valid": True, "errors": []
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_validate_names_where_an_illegal_contract_is_wrong(project):
|
|
51
|
+
result = tools.validate_contract(path="contracts/invalid.yaml")
|
|
52
|
+
assert result["valid"] is False
|
|
53
|
+
assert any("primary_key" in e["problem"] or "primary_key" in e["location"] for e in result["errors"])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_validate_takes_inline_text_too(project):
|
|
57
|
+
assert tools.validate_contract(contract_yaml=GOOD)["valid"] is True
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_lint_is_clean_for_a_good_contract_and_names_the_rule_otherwise(project):
|
|
61
|
+
assert tools.lint_contract(path="contracts/good.yaml") == {
|
|
62
|
+
"contract": str(Path("contracts/good.yaml")), "clean": True, "findings": []
|
|
63
|
+
}
|
|
64
|
+
result = tools.lint_contract(path="contracts/sorted_by_key.yaml")
|
|
65
|
+
assert result["clean"] is False
|
|
66
|
+
assert [f["rule"] for f in result["findings"]] == ["KEY-002"]
|
|
67
|
+
assert result["findings"][0]["fix"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_explain_rule_returns_the_catalogue_entry(project):
|
|
71
|
+
entry = tools.explain_rule("key-002")
|
|
72
|
+
assert entry["rule"] == "KEY-002" and entry["why"] and "sort_by" in entry["failing_example"]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_explain_rule_lists_the_rules_when_the_code_is_unknown(project):
|
|
76
|
+
with pytest.raises(tools.ToolError, match="Known rules: .*KEY-002"):
|
|
77
|
+
tools.explain_rule("NOPE-001")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_contract_reference_reads_the_bundled_page(project):
|
|
81
|
+
page = tools.contract_reference("Quality")
|
|
82
|
+
assert page["topic"] == "quality" and len(page["markdown"]) > 200
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_export_odcs(project):
|
|
86
|
+
out = tools.export_odcs("contracts/good.yaml")
|
|
87
|
+
assert out["odcs"]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@pytest.mark.parametrize("path", ["../outside.yaml", "C:/Windows/win.ini", "/etc/passwd"])
|
|
91
|
+
def test_nothing_outside_the_project_can_be_read(project, path):
|
|
92
|
+
(project.parent / "outside.yaml").write_text(GOOD, encoding="utf-8")
|
|
93
|
+
with pytest.raises(tools.ToolError, match="outside the project folder|No contract file"):
|
|
94
|
+
tools.validate_contract(path=path)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_exactly_one_input(project):
|
|
98
|
+
with pytest.raises(tools.ToolError, match="exactly one"):
|
|
99
|
+
tools.validate_contract()
|
|
100
|
+
with pytest.raises(tools.ToolError, match="exactly one"):
|
|
101
|
+
tools.validate_contract(path="contracts/good.yaml", contract_yaml=GOOD)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
ORDERS = """version: 1.0.0
|
|
105
|
+
info: { title: Orders, table_name: orders }
|
|
106
|
+
model:
|
|
107
|
+
fields:
|
|
108
|
+
- { name: order_id, type: string, required: true }
|
|
109
|
+
- { name: amount, type: double, min: 0 }
|
|
110
|
+
quality:
|
|
111
|
+
row_rules:
|
|
112
|
+
- { name: amount_positive, sql: "amount >= 0" }
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.mark.parametrize("engine", ["polars", "duckdb"])
|
|
117
|
+
def test_generate_then_run_quarantines_the_broken_rows(project, engine):
|
|
118
|
+
(project / "orders.yaml").write_text(ORDERS, encoding="utf-8")
|
|
119
|
+
made = tools.generate_test_data("orders.yaml", rows=40, invalid_ratio=0.25, seed=7)
|
|
120
|
+
assert made["rows"] == 40 and (project / made["data_file"]).is_file()
|
|
121
|
+
|
|
122
|
+
run = tools.run_contract("orders.yaml", made["data_file"], engine=engine, write_outputs=True)
|
|
123
|
+
assert run["ran"] is True
|
|
124
|
+
assert run["good_rows"] + run["quarantined_rows"] == 40
|
|
125
|
+
assert run["quarantined_rows"] > 0 and run["quarantine_reasons"]
|
|
126
|
+
assert (project / run["bad_file"]).is_file()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_run_refuses_platform_engines_and_outside_paths(project):
|
|
130
|
+
(project / "orders.yaml").write_text(ORDERS, encoding="utf-8")
|
|
131
|
+
(project / "d.csv").write_text("order_id,amount\na,1\n", encoding="utf-8")
|
|
132
|
+
with pytest.raises(tools.ToolError, match="engine must be"):
|
|
133
|
+
tools.run_contract("orders.yaml", "d.csv", engine="spark")
|
|
134
|
+
with pytest.raises(tools.ToolError, match="outside the project folder"):
|
|
135
|
+
tools.generate_test_data("orders.yaml", output="../escape.csv")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_run_reads_the_file_by_its_type_even_when_the_contract_says_delta(project):
|
|
139
|
+
"""Found by a real Claude Code session: a contract with `format: delta` made run_contract open
|
|
140
|
+
the CSV as a Delta table ("Invalid table location")."""
|
|
141
|
+
(project / "orders.yaml").write_text(ORDERS + "materialization: { strategy: merge, format: delta }\n", encoding="utf-8")
|
|
142
|
+
made = tools.generate_test_data("orders.yaml", rows=20, invalid_ratio=0.2, seed=3)
|
|
143
|
+
for engine in ("polars", "duckdb"):
|
|
144
|
+
run = tools.run_contract("orders.yaml", made["data_file"], engine=engine)
|
|
145
|
+
assert run["ran"] is True, run
|
|
146
|
+
assert run["good_rows"] + run["quarantined_rows"] == 20
|