strict-semantic-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.
Files changed (47) hide show
  1. strict_semantic_mcp-0.1.0/LICENSE +202 -0
  2. strict_semantic_mcp-0.1.0/NOTICE +5 -0
  3. strict_semantic_mcp-0.1.0/PKG-INFO +203 -0
  4. strict_semantic_mcp-0.1.0/README.md +165 -0
  5. strict_semantic_mcp-0.1.0/pyproject.toml +58 -0
  6. strict_semantic_mcp-0.1.0/setup.cfg +4 -0
  7. strict_semantic_mcp-0.1.0/src/strict_semantic/__init__.py +22 -0
  8. strict_semantic_mcp-0.1.0/src/strict_semantic/cli.py +106 -0
  9. strict_semantic_mcp-0.1.0/src/strict_semantic/compiler/__init__.py +94 -0
  10. strict_semantic_mcp-0.1.0/src/strict_semantic/compiler/guardrails.py +150 -0
  11. strict_semantic_mcp-0.1.0/src/strict_semantic/compiler/resolver.py +90 -0
  12. strict_semantic_mcp-0.1.0/src/strict_semantic/compiler/sql_builder.py +436 -0
  13. strict_semantic_mcp-0.1.0/src/strict_semantic/connectors/__init__.py +29 -0
  14. strict_semantic_mcp-0.1.0/src/strict_semantic/connectors/base.py +16 -0
  15. strict_semantic_mcp-0.1.0/src/strict_semantic/connectors/bigquery.py +53 -0
  16. strict_semantic_mcp-0.1.0/src/strict_semantic/connectors/duckdb.py +25 -0
  17. strict_semantic_mcp-0.1.0/src/strict_semantic/eval/__init__.py +0 -0
  18. strict_semantic_mcp-0.1.0/src/strict_semantic/eval/runner.py +120 -0
  19. strict_semantic_mcp-0.1.0/src/strict_semantic/linter/__init__.py +3 -0
  20. strict_semantic_mcp-0.1.0/src/strict_semantic/linter/engine.py +85 -0
  21. strict_semantic_mcp-0.1.0/src/strict_semantic/linter/rules_governance.py +92 -0
  22. strict_semantic_mcp-0.1.0/src/strict_semantic/linter/rules_logic.py +281 -0
  23. strict_semantic_mcp-0.1.0/src/strict_semantic/linter/rules_structure.py +162 -0
  24. strict_semantic_mcp-0.1.0/src/strict_semantic/mcp_server/__init__.py +0 -0
  25. strict_semantic_mcp-0.1.0/src/strict_semantic/mcp_server/server.py +279 -0
  26. strict_semantic_mcp-0.1.0/src/strict_semantic/models/__init__.py +0 -0
  27. strict_semantic_mcp-0.1.0/src/strict_semantic/models/ast.py +202 -0
  28. strict_semantic_mcp-0.1.0/src/strict_semantic/models/errors.py +75 -0
  29. strict_semantic_mcp-0.1.0/src/strict_semantic/models/query.py +63 -0
  30. strict_semantic_mcp-0.1.0/src/strict_semantic/parsers/__init__.py +34 -0
  31. strict_semantic_mcp-0.1.0/src/strict_semantic/parsers/common.py +196 -0
  32. strict_semantic_mcp-0.1.0/src/strict_semantic/parsers/snowflake_ddl.py +232 -0
  33. strict_semantic_mcp-0.1.0/src/strict_semantic/parsers/yaml_spec.py +108 -0
  34. strict_semantic_mcp-0.1.0/src/strict_semantic/plugins/__init__.py +0 -0
  35. strict_semantic_mcp-0.1.0/src/strict_semantic/plugins/base.py +27 -0
  36. strict_semantic_mcp-0.1.0/src/strict_semantic_mcp.egg-info/PKG-INFO +203 -0
  37. strict_semantic_mcp-0.1.0/src/strict_semantic_mcp.egg-info/SOURCES.txt +45 -0
  38. strict_semantic_mcp-0.1.0/src/strict_semantic_mcp.egg-info/dependency_links.txt +1 -0
  39. strict_semantic_mcp-0.1.0/src/strict_semantic_mcp.egg-info/entry_points.txt +3 -0
  40. strict_semantic_mcp-0.1.0/src/strict_semantic_mcp.egg-info/requires.txt +18 -0
  41. strict_semantic_mcp-0.1.0/src/strict_semantic_mcp.egg-info/top_level.txt +1 -0
  42. strict_semantic_mcp-0.1.0/tests/test_compiler_determinism.py +63 -0
  43. strict_semantic_mcp-0.1.0/tests/test_duckdb_execution.py +180 -0
  44. strict_semantic_mcp-0.1.0/tests/test_golden.py +260 -0
  45. strict_semantic_mcp-0.1.0/tests/test_linter_rules.py +287 -0
  46. strict_semantic_mcp-0.1.0/tests/test_mcp_server.py +94 -0
  47. strict_semantic_mcp-0.1.0/tests/test_parsers.py +115 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Son Chau
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ strict-semantic-mcp
2
+ Copyright 2026 Son Chau
3
+
4
+ This product includes software developed by Son Chau
5
+ (https://github.com/noscn/strict-semantic-mcp).
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.4
2
+ Name: strict-semantic-mcp
3
+ Version: 0.1.0
4
+ Summary: Strict semantic-view linter and deterministic, FinOps-safe SQL compiler with an MCP server for AI data agents.
5
+ Author-email: Son Chau <46123450+noscn@users.noreply.github.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/noscn/strict-semantic-mcp
8
+ Project-URL: Issues, https://github.com/noscn/strict-semantic-mcp/issues
9
+ Project-URL: Changelog, https://github.com/noscn/strict-semantic-mcp/blob/main/docs/REVISIONS.md
10
+ Keywords: semantic-layer,mcp,text-to-sql,sqlglot,bigquery,data-governance,finops
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Database
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ License-File: NOTICE
23
+ Requires-Dist: sqlglot>=26
24
+ Requires-Dist: pydantic>=2.5
25
+ Requires-Dist: pyyaml>=6
26
+ Provides-Extra: mcp
27
+ Requires-Dist: mcp>=2; extra == "mcp"
28
+ Provides-Extra: bigquery
29
+ Requires-Dist: google-cloud-bigquery>=3; extra == "bigquery"
30
+ Provides-Extra: duckdb
31
+ Requires-Dist: duckdb>=1; extra == "duckdb"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=8; extra == "dev"
34
+ Requires-Dist: duckdb>=1; extra == "dev"
35
+ Requires-Dist: ruff>=0.6; extra == "dev"
36
+ Requires-Dist: mcp>=2; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # strict-semantic-mcp
40
+
41
+ [![CI](https://github.com/noscn/strict-semantic-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/noscn/strict-semantic-mcp/actions/workflows/ci.yml)
42
+
43
+ **A CI linter for Snowflake-style semantic views, and a deterministic, FinOps-safe
44
+ semantic compiler + MCP server for AI data agents on BigQuery, DuckDB, Snowflake
45
+ and Postgres.**
46
+
47
+ Data warehouses like BigQuery have no native, strictly-enforced semantic views.
48
+ When text-to-SQL agents query them through loose YAML or flexible graph layers,
49
+ the failure modes are always the same: non-deterministic SQL, fan-out double
50
+ counting, ambiguous join paths, raw-row dumps, and runaway scan costs.
51
+
52
+ This project makes the semantic model a **blueprint, never a materialization**:
53
+
54
+ ```
55
+ .sql DDL / .yaml spec ──parse──▶ canonical AST (Pydantic v2)
56
+ ──lint (SV-R1..R10)──▶ valid blueprint
57
+ ──compile(request)──▶ one deterministic SQL statement ──connector──▶ rows
58
+ ```
59
+
60
+ - **Dual input, one AST.** Snowflake `CREATE SEMANTIC VIEW` DDL (human-authored)
61
+ and a native YAML contract (automation-friendly) build byte-identical models.
62
+ - **Static ground rules (SV-R1..R10).** Primary keys and grain comments, a
63
+ directed many-to-one join DAG with exactly one path between any two tables,
64
+ no numeric dimensions, no `CURRENT_DATE`, snapshot metrics declared
65
+ `NON ADDITIVE BY`, globally unique field names and synonyms, a security
66
+ deny-list, comment templates. `strict-semantic lint` blocks CI on ERRORs.
67
+ - **Deterministic compilation.** Same request, same SQL, byte for byte. Joins
68
+ only walk child→parent (zero fan-out, enforced); metrics of different grains
69
+ drill across via `UNION ALL`; derived ratios divide NULL-safely; every
70
+ expression is built as a sqlglot AST — no string concatenation anywhere.
71
+ - **FinOps guardrails.** At least one metric per query (no raw dumps),
72
+ partition filters required and pushed into each table's subquery (the only
73
+ placement BigQuery honors on joined tables), `LIMIT` injected and capped,
74
+ BigQuery dry-run byte ceiling.
75
+ - **MCP server (mcp ≥ 2).** Five tools: `list_semantic_views`,
76
+ `inspect_semantic_view`, `get_dimension_values`, `compile_semantic_query`,
77
+ `execute_semantic_query`. The agent picks names from the catalog and never
78
+ writes SQL; every refusal carries an error code and a repair hint.
79
+ - **Golden Questions eval.** `strict-semantic eval cases.yaml` grades
80
+ answer/refuse/clarify cases against DuckDB deterministically — no LLM judge.
81
+ - **Open-core plugin hooks.** `on_model_loaded`, `before_compile` (RBAC filter
82
+ injection), `after_compile` (cache/lineage), `on_query_executed` (audit).
83
+
84
+ ## Quickstart
85
+
86
+ ```bash
87
+ python -m venv .venv && .venv/bin/pip install -e '.[dev,mcp]'
88
+ .venv/bin/python -m pytest # 64 tests
89
+ .venv/bin/strict-semantic lint tests/fixtures/ecommerce.sql
90
+ .venv/bin/strict-semantic eval tests/fixtures/golden_questions.yaml
91
+ .venv/bin/strict-semantic compile tests/fixtures/ecommerce.yaml \
92
+ -m revenue -m aov -d region \
93
+ -f '{"field":"order_date","op":">=","value":"2026-01-01"}' \
94
+ -f '{"field":"order_date","op":"<","value":"2026-02-01"}' --dialect bigquery
95
+ ```
96
+
97
+ Run the MCP server against the demo warehouse (in-memory DuckDB):
98
+
99
+ ```bash
100
+ STRICT_SEMANTIC_CONFIG=$PWD/examples/config.duckdb.yml .venv/bin/strict-semantic-mcp
101
+ ```
102
+
103
+ or register it with Claude Code:
104
+
105
+ ```bash
106
+ claude mcp add strict-semantic -e STRICT_SEMANTIC_CONFIG=$PWD/examples/config.duckdb.yml -- $PWD/.venv/bin/strict-semantic-mcp
107
+ ```
108
+
109
+ For BigQuery, copy `examples/config.bigquery.example.yml`, point `views:` at
110
+ your private spec folder, and set `max_bytes`.
111
+
112
+ ## Writing a semantic view
113
+
114
+ Snowflake DDL (`.sql`) and the native YAML (`.yml`) are equivalent; metadata the
115
+ DDL has no slot for travels in structured comment directives (enforced by the
116
+ linter as SV-R8.1 templates):
117
+
118
+ ```sql
119
+ CREATE SEMANTIC VIEW ecommerce
120
+ TABLES (
121
+ orders AS shop.orders PRIMARY KEY (order_id)
122
+ COMMENT = 'One row per order. Primary date: order_date. Partition: order_date BY order_date. Source: shop.orders.',
123
+ customers AS shop.customers PRIMARY KEY (customer_id)
124
+ COMMENT = 'One row per customer. Primary date: signup_date. Source: shop.customers.'
125
+ )
126
+ RELATIONSHIPS ( orders_customers AS orders (customer_id) REFERENCES customers (customer_id) )
127
+ DIMENSIONS (
128
+ customers.region AS region WITH SYNONYMS ('market') COMMENT = 'Customer home region. Values: EU, US, APAC.',
129
+ orders.order_date AS order_date COMMENT = 'Date the order was placed. Grains: day, week, month.'
130
+ )
131
+ METRICS (
132
+ orders.order_count AS COUNT(order_id) COMMENT = 'Number of orders placed. Population: all orders. Additivity: additive.'
133
+ )
134
+ COMMENT = 'Retail sales.'
135
+ ```
136
+
137
+ Directives: `One row per …` (grain), `Primary date: col.`,
138
+ `Point-in-time snapshot.`, `Partition: col BY dimension (lookback Nd, lookahead Nd).`,
139
+ `Grains: day, month.`, `Type: timestamp.`, `Values: a, b, c.`
140
+ See `tests/fixtures/ecommerce.{sql,yaml}` for the full twin fixtures.
141
+
142
+ ## Querying
143
+
144
+ ```json
145
+ {"metrics": ["revenue", "aov"], "dimensions": ["region", "order_date__month"],
146
+ "filters": [{"field": "order_date", "op": "between", "value": ["2026-01-01", "2026-03-31"]},
147
+ {"field": "aov", "op": ">", "value": 50}],
148
+ "order_by": ["-revenue"], "limit": 100}
149
+ ```
150
+
151
+ Time dimensions take a `__grain` suffix. Filters on dimensions apply before
152
+ aggregation, filters on metrics after. Dimension-only queries are refused
153
+ (`ERR_METRIC_REQUIRED`) — value discovery goes through `get_dimension_values`,
154
+ a bounded `SELECT DISTINCT … LIMIT ≤ 50`.
155
+
156
+ ## Layout
157
+
158
+ ```
159
+ src/strict_semantic/
160
+ ├── models/ # canonical AST, error codes, request/response contracts
161
+ ├── parsers/ # Snowflake DDL (token-stream) + native YAML -> one builder
162
+ ├── linter/ # SV-R1..R10 engine: structure / logic / governance rules
163
+ ├── compiler/ # join-graph resolver, FinOps guardrails, sqlglot SQL builder
164
+ ├── connectors/ # DuckDB, BigQuery (dry-run + byte cap), protocol
165
+ ├── plugins/ # open-core lifecycle hooks
166
+ ├── eval/ # Golden Questions runner (deterministic, no LLM)
167
+ └── mcp_server/ # the five MCP tools over stdio
168
+ ```
169
+
170
+ Design departures from the original blueprint, with reasons, are in
171
+ [docs/REVISIONS.md](docs/REVISIONS.md).
172
+
173
+ ## Security & deployment responsibility
174
+
175
+ The server speaks **stdio** and is designed to run next to the agent, on your
176
+ machine, with your credentials. If you expose it over a network (HTTP/SSE,
177
+ a gateway, a shared host), authentication, transport security and tenant
178
+ isolation are yours to provide — nothing here does that for you.
179
+
180
+ Expect defense in depth from the warehouse side too: run the connector with a
181
+ **least-privilege, read-only** account scoped to the datasets the views name.
182
+ The compiler never concatenates SQL strings — filter values become typed
183
+ sqlglot literals, operators come from a fixed whitelist, and every identifier
184
+ must resolve against the linted model — but the SQL that reaches your warehouse
185
+ should still be gated by the warehouse's own permissions. Per the Apache 2.0
186
+ license, the software is provided as is, without warranty; securing the
187
+ deployment is the deployer's responsibility.
188
+
189
+ Report vulnerabilities privately via GitHub Security Advisories, not public
190
+ issues.
191
+
192
+ ## Contributing
193
+
194
+ Scope is deliberately strict and minimal — read
195
+ [CONTRIBUTING.md](CONTRIBUTING.md) before proposing features. Short version:
196
+ determinism is non-negotiable, escape hatches get declined, and extensions
197
+ belong in plugins.
198
+
199
+ ## License
200
+
201
+ Apache 2.0 (see [LICENSE](LICENSE) and [NOTICE](NOTICE)). Fixtures and examples
202
+ are a generic e-commerce schema; keep your company's semantic views in a
203
+ private repository and point the server at them via `STRICT_SEMANTIC_CONFIG`.
@@ -0,0 +1,165 @@
1
+ # strict-semantic-mcp
2
+
3
+ [![CI](https://github.com/noscn/strict-semantic-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/noscn/strict-semantic-mcp/actions/workflows/ci.yml)
4
+
5
+ **A CI linter for Snowflake-style semantic views, and a deterministic, FinOps-safe
6
+ semantic compiler + MCP server for AI data agents on BigQuery, DuckDB, Snowflake
7
+ and Postgres.**
8
+
9
+ Data warehouses like BigQuery have no native, strictly-enforced semantic views.
10
+ When text-to-SQL agents query them through loose YAML or flexible graph layers,
11
+ the failure modes are always the same: non-deterministic SQL, fan-out double
12
+ counting, ambiguous join paths, raw-row dumps, and runaway scan costs.
13
+
14
+ This project makes the semantic model a **blueprint, never a materialization**:
15
+
16
+ ```
17
+ .sql DDL / .yaml spec ──parse──▶ canonical AST (Pydantic v2)
18
+ ──lint (SV-R1..R10)──▶ valid blueprint
19
+ ──compile(request)──▶ one deterministic SQL statement ──connector──▶ rows
20
+ ```
21
+
22
+ - **Dual input, one AST.** Snowflake `CREATE SEMANTIC VIEW` DDL (human-authored)
23
+ and a native YAML contract (automation-friendly) build byte-identical models.
24
+ - **Static ground rules (SV-R1..R10).** Primary keys and grain comments, a
25
+ directed many-to-one join DAG with exactly one path between any two tables,
26
+ no numeric dimensions, no `CURRENT_DATE`, snapshot metrics declared
27
+ `NON ADDITIVE BY`, globally unique field names and synonyms, a security
28
+ deny-list, comment templates. `strict-semantic lint` blocks CI on ERRORs.
29
+ - **Deterministic compilation.** Same request, same SQL, byte for byte. Joins
30
+ only walk child→parent (zero fan-out, enforced); metrics of different grains
31
+ drill across via `UNION ALL`; derived ratios divide NULL-safely; every
32
+ expression is built as a sqlglot AST — no string concatenation anywhere.
33
+ - **FinOps guardrails.** At least one metric per query (no raw dumps),
34
+ partition filters required and pushed into each table's subquery (the only
35
+ placement BigQuery honors on joined tables), `LIMIT` injected and capped,
36
+ BigQuery dry-run byte ceiling.
37
+ - **MCP server (mcp ≥ 2).** Five tools: `list_semantic_views`,
38
+ `inspect_semantic_view`, `get_dimension_values`, `compile_semantic_query`,
39
+ `execute_semantic_query`. The agent picks names from the catalog and never
40
+ writes SQL; every refusal carries an error code and a repair hint.
41
+ - **Golden Questions eval.** `strict-semantic eval cases.yaml` grades
42
+ answer/refuse/clarify cases against DuckDB deterministically — no LLM judge.
43
+ - **Open-core plugin hooks.** `on_model_loaded`, `before_compile` (RBAC filter
44
+ injection), `after_compile` (cache/lineage), `on_query_executed` (audit).
45
+
46
+ ## Quickstart
47
+
48
+ ```bash
49
+ python -m venv .venv && .venv/bin/pip install -e '.[dev,mcp]'
50
+ .venv/bin/python -m pytest # 64 tests
51
+ .venv/bin/strict-semantic lint tests/fixtures/ecommerce.sql
52
+ .venv/bin/strict-semantic eval tests/fixtures/golden_questions.yaml
53
+ .venv/bin/strict-semantic compile tests/fixtures/ecommerce.yaml \
54
+ -m revenue -m aov -d region \
55
+ -f '{"field":"order_date","op":">=","value":"2026-01-01"}' \
56
+ -f '{"field":"order_date","op":"<","value":"2026-02-01"}' --dialect bigquery
57
+ ```
58
+
59
+ Run the MCP server against the demo warehouse (in-memory DuckDB):
60
+
61
+ ```bash
62
+ STRICT_SEMANTIC_CONFIG=$PWD/examples/config.duckdb.yml .venv/bin/strict-semantic-mcp
63
+ ```
64
+
65
+ or register it with Claude Code:
66
+
67
+ ```bash
68
+ claude mcp add strict-semantic -e STRICT_SEMANTIC_CONFIG=$PWD/examples/config.duckdb.yml -- $PWD/.venv/bin/strict-semantic-mcp
69
+ ```
70
+
71
+ For BigQuery, copy `examples/config.bigquery.example.yml`, point `views:` at
72
+ your private spec folder, and set `max_bytes`.
73
+
74
+ ## Writing a semantic view
75
+
76
+ Snowflake DDL (`.sql`) and the native YAML (`.yml`) are equivalent; metadata the
77
+ DDL has no slot for travels in structured comment directives (enforced by the
78
+ linter as SV-R8.1 templates):
79
+
80
+ ```sql
81
+ CREATE SEMANTIC VIEW ecommerce
82
+ TABLES (
83
+ orders AS shop.orders PRIMARY KEY (order_id)
84
+ COMMENT = 'One row per order. Primary date: order_date. Partition: order_date BY order_date. Source: shop.orders.',
85
+ customers AS shop.customers PRIMARY KEY (customer_id)
86
+ COMMENT = 'One row per customer. Primary date: signup_date. Source: shop.customers.'
87
+ )
88
+ RELATIONSHIPS ( orders_customers AS orders (customer_id) REFERENCES customers (customer_id) )
89
+ DIMENSIONS (
90
+ customers.region AS region WITH SYNONYMS ('market') COMMENT = 'Customer home region. Values: EU, US, APAC.',
91
+ orders.order_date AS order_date COMMENT = 'Date the order was placed. Grains: day, week, month.'
92
+ )
93
+ METRICS (
94
+ orders.order_count AS COUNT(order_id) COMMENT = 'Number of orders placed. Population: all orders. Additivity: additive.'
95
+ )
96
+ COMMENT = 'Retail sales.'
97
+ ```
98
+
99
+ Directives: `One row per …` (grain), `Primary date: col.`,
100
+ `Point-in-time snapshot.`, `Partition: col BY dimension (lookback Nd, lookahead Nd).`,
101
+ `Grains: day, month.`, `Type: timestamp.`, `Values: a, b, c.`
102
+ See `tests/fixtures/ecommerce.{sql,yaml}` for the full twin fixtures.
103
+
104
+ ## Querying
105
+
106
+ ```json
107
+ {"metrics": ["revenue", "aov"], "dimensions": ["region", "order_date__month"],
108
+ "filters": [{"field": "order_date", "op": "between", "value": ["2026-01-01", "2026-03-31"]},
109
+ {"field": "aov", "op": ">", "value": 50}],
110
+ "order_by": ["-revenue"], "limit": 100}
111
+ ```
112
+
113
+ Time dimensions take a `__grain` suffix. Filters on dimensions apply before
114
+ aggregation, filters on metrics after. Dimension-only queries are refused
115
+ (`ERR_METRIC_REQUIRED`) — value discovery goes through `get_dimension_values`,
116
+ a bounded `SELECT DISTINCT … LIMIT ≤ 50`.
117
+
118
+ ## Layout
119
+
120
+ ```
121
+ src/strict_semantic/
122
+ ├── models/ # canonical AST, error codes, request/response contracts
123
+ ├── parsers/ # Snowflake DDL (token-stream) + native YAML -> one builder
124
+ ├── linter/ # SV-R1..R10 engine: structure / logic / governance rules
125
+ ├── compiler/ # join-graph resolver, FinOps guardrails, sqlglot SQL builder
126
+ ├── connectors/ # DuckDB, BigQuery (dry-run + byte cap), protocol
127
+ ├── plugins/ # open-core lifecycle hooks
128
+ ├── eval/ # Golden Questions runner (deterministic, no LLM)
129
+ └── mcp_server/ # the five MCP tools over stdio
130
+ ```
131
+
132
+ Design departures from the original blueprint, with reasons, are in
133
+ [docs/REVISIONS.md](docs/REVISIONS.md).
134
+
135
+ ## Security & deployment responsibility
136
+
137
+ The server speaks **stdio** and is designed to run next to the agent, on your
138
+ machine, with your credentials. If you expose it over a network (HTTP/SSE,
139
+ a gateway, a shared host), authentication, transport security and tenant
140
+ isolation are yours to provide — nothing here does that for you.
141
+
142
+ Expect defense in depth from the warehouse side too: run the connector with a
143
+ **least-privilege, read-only** account scoped to the datasets the views name.
144
+ The compiler never concatenates SQL strings — filter values become typed
145
+ sqlglot literals, operators come from a fixed whitelist, and every identifier
146
+ must resolve against the linted model — but the SQL that reaches your warehouse
147
+ should still be gated by the warehouse's own permissions. Per the Apache 2.0
148
+ license, the software is provided as is, without warranty; securing the
149
+ deployment is the deployer's responsibility.
150
+
151
+ Report vulnerabilities privately via GitHub Security Advisories, not public
152
+ issues.
153
+
154
+ ## Contributing
155
+
156
+ Scope is deliberately strict and minimal — read
157
+ [CONTRIBUTING.md](CONTRIBUTING.md) before proposing features. Short version:
158
+ determinism is non-negotiable, escape hatches get declined, and extensions
159
+ belong in plugins.
160
+
161
+ ## License
162
+
163
+ Apache 2.0 (see [LICENSE](LICENSE) and [NOTICE](NOTICE)). Fixtures and examples
164
+ are a generic e-commerce schema; keep your company's semantic views in a
165
+ private repository and point the server at them via `STRICT_SEMANTIC_CONFIG`.
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "strict-semantic-mcp"
3
+ version = "0.1.0"
4
+ description = "Strict semantic-view linter and deterministic, FinOps-safe SQL compiler with an MCP server for AI data agents."
5
+ authors = [{ name = "Son Chau", email = "46123450+noscn@users.noreply.github.com" }]
6
+ readme = "README.md"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ requires-python = ">=3.10"
10
+ dependencies = ["sqlglot>=26", "pydantic>=2.5", "pyyaml>=6"]
11
+ keywords = ["semantic-layer", "mcp", "text-to-sql", "sqlglot", "bigquery", "data-governance", "finops"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Topic :: Database",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ mcp = ["mcp>=2"]
25
+ bigquery = ["google-cloud-bigquery>=3"]
26
+ duckdb = ["duckdb>=1"]
27
+ dev = ["pytest>=8", "duckdb>=1", "ruff>=0.6", "mcp>=2"]
28
+
29
+ [project.urls]
30
+ Repository = "https://github.com/noscn/strict-semantic-mcp"
31
+ Issues = "https://github.com/noscn/strict-semantic-mcp/issues"
32
+ Changelog = "https://github.com/noscn/strict-semantic-mcp/blob/main/docs/REVISIONS.md"
33
+
34
+ [project.scripts]
35
+ strict-semantic = "strict_semantic.cli:main"
36
+ strict-semantic-mcp = "strict_semantic.mcp_server.server:main"
37
+
38
+ [build-system]
39
+ requires = ["setuptools>=77"]
40
+ build-backend = "setuptools.build_meta"
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+
48
+ [tool.ruff]
49
+ line-length = 125
50
+ target-version = "py310"
51
+
52
+ [tool.ruff.lint]
53
+ select = ["E", "F", "W", "I", "UP", "B"]
54
+
55
+ [tool.mypy]
56
+ python_version = "3.10"
57
+ strict = false
58
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,22 @@
1
+ """strict-semantic-mcp: strict semantic views, linted at load time and compiled
2
+ deterministically to SQL. The view is a blueprint only — never materialized."""
3
+
4
+ from .models.ast import SemanticView
5
+ from .models.errors import CompilerError, LintFinding, Severity
6
+ from .models.query import CompiledQuery, Filter, QueryResult, SemanticQueryRequest
7
+ from .parsers import load_view, load_views
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = [
11
+ "CompiledQuery",
12
+ "CompilerError",
13
+ "Filter",
14
+ "LintFinding",
15
+ "QueryResult",
16
+ "SemanticQueryRequest",
17
+ "SemanticView",
18
+ "Severity",
19
+ "load_view",
20
+ "load_views",
21
+ "__version__",
22
+ ]