google-cloud-db-context-engineering 0.5.1__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 (43) hide show
  1. google_cloud_db_context_engineering-0.5.1/LICENSE +202 -0
  2. google_cloud_db_context_engineering-0.5.1/PKG-INFO +160 -0
  3. google_cloud_db_context_engineering-0.5.1/README.md +144 -0
  4. google_cloud_db_context_engineering-0.5.1/pyproject.toml +62 -0
  5. google_cloud_db_context_engineering-0.5.1/setup.cfg +4 -0
  6. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/__init__.py +1 -0
  7. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/bootstrap/__init__.py +1 -0
  8. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/bootstrap/bootstrap_generator.py +74 -0
  9. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/common/__init__.py +0 -0
  10. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/common/config.py +10 -0
  11. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/common/context_mutator.py +132 -0
  12. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/common/parameterizer.py +192 -0
  13. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/dataset/__init__.py +0 -0
  14. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/dataset/dataset_generator.py +44 -0
  15. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/__init__.py +3 -0
  16. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/db_generators/__init__.py +0 -0
  17. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/db_generators/alloydb.py +72 -0
  18. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/db_generators/base.py +76 -0
  19. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/db_generators/mysql.py +69 -0
  20. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/db_generators/postgres.py +69 -0
  21. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/db_generators/spanner.py +62 -0
  22. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/evaluate_generator.py +239 -0
  23. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/evaluate/result_reader.py +181 -0
  24. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/facet/__init__.py +0 -0
  25. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/facet/facet_generator.py +68 -0
  26. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/main.py +450 -0
  27. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/model/__init__.py +0 -0
  28. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/model/context.py +86 -0
  29. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/prompts/__init__.py +9 -0
  30. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/prompts/targeted_facets.py +56 -0
  31. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/prompts/targeted_templates.py +57 -0
  32. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/prompts/targeted_value_search.py +93 -0
  33. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/template/__init__.py +0 -0
  34. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/template/template_generator.py +67 -0
  35. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/value_search/__init__.py +0 -0
  36. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/value_search/generator.py +91 -0
  37. google_cloud_db_context_engineering-0.5.1/src/google/cloud/db_context_enrichment/value_search/match_templates.py +267 -0
  38. google_cloud_db_context_engineering-0.5.1/src/google_cloud_db_context_engineering.egg-info/PKG-INFO +160 -0
  39. google_cloud_db_context_engineering-0.5.1/src/google_cloud_db_context_engineering.egg-info/SOURCES.txt +41 -0
  40. google_cloud_db_context_engineering-0.5.1/src/google_cloud_db_context_engineering.egg-info/dependency_links.txt +1 -0
  41. google_cloud_db_context_engineering-0.5.1/src/google_cloud_db_context_engineering.egg-info/entry_points.txt +2 -0
  42. google_cloud_db_context_engineering-0.5.1/src/google_cloud_db_context_engineering.egg-info/requires.txt +8 -0
  43. google_cloud_db_context_engineering-0.5.1/src/google_cloud_db_context_engineering.egg-info/top_level.txt +1 -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 [yyyy] [name of copyright owner]
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,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: google-cloud-db-context-engineering
3
+ Version: 0.5.1
4
+ Summary: A FastMCP server for generating natural language to SQL templates from database schemas.
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: fastmcp==3.3.1
9
+ Requires-Dist: google-genai==1.46.0
10
+ Requires-Dist: toolbox-core==0.5.2
11
+ Requires-Dist: google-cloud-geminidataanalytics==0.11.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+ Requires-Dist: pytest-asyncio; extra == "test"
15
+ Dynamic: license-file
16
+
17
+ This is not an officially supported Google product. This project is not eligible for the [Google Open Source Software Vulnerability Rewards Program](https://bughunters.google.com/open-source-security), [Google Cloud Platform/SecOps Terms of Service](https://cloud.google.com/terms), [How Gemini for Google Cloud uses your data](https://cloud.google.com/gemini/docs/discover/data-governance). This tool is provided "as is" without warranty of any kind. Users are solely responsible for understanding and managing the tool's interaction with their databases. Use of this tool constitutes acceptance of all risks associated with database access, reading, usage, and modifications.
18
+
19
+ # Context Engineering Agent
20
+
21
+ > [!IMPORTANT]
22
+ > **Repository Reorganization**
23
+ > The original Go-based **DB Schema Enricher CLI** has been archived and moved to the [legacy/go-enricher/](legacy/go-enricher/) directory. This repository root is now dedicated to the Python-based **Context Engineering Agent (MCP Server)**.
24
+
25
+ This project is a Gemini CLI extension that bridges the gap between Large Language Models (LLMs) and structured databases by generating and managing tailored context. This context helps the LLM understand database schema, business logic, and terminology, enabling more accurate Natural Language to SQL generation.
26
+
27
+ ## Core Concepts
28
+
29
+ A `ContextSet` is the central artifact generated by the Context Engineering Agent, containing structured knowledge in three primary forms:
30
+
31
+ * **Templates**: End-to-end mappings linking a natural language query to a complete, runnable SQL query. They teach the system overarching operational logic, table join infrastructures, and broad business rules.
32
+ * *Full Structure Example*:
33
+ ```json
34
+ {
35
+ "nl_query": "How many accounts are in London?",
36
+ "sql": "SELECT count(*) FROM account WHERE account.city = 'London'",
37
+ "intent": "How many accounts are in London?",
38
+ "manifest": "How many accounts are in a given city?",
39
+ "parameterized": {
40
+ "parameterized_sql": "SELECT count(*) FROM account WHERE account.city = $1",
41
+ "parameterized_intent": "How many accounts are in $1?"
42
+ }
43
+ }
44
+ ```
45
+ * **Facets**: Reusable, modular SQL fragments (like a `WHERE` clause or specialized join) linked to specific vocabulary or terminology. They are not standalone queries but dynamically injected filters.
46
+ * *Full Structure Example*:
47
+ ```json
48
+ {
49
+ "sql_snippet": "products.rating > 4.5",
50
+ "intent": "highly rated products (above 4.5)",
51
+ "manifest": "highly rated products (above a given number)",
52
+ "parameterized": {
53
+ "parameterized_sql_snippet": "products.rating > $1",
54
+ "parameterized_intent": "highly rated products (above $1)"
55
+ }
56
+ }
57
+ ```
58
+ * **Value Searches**: Specialized queries used when a value in the natural language query (e.g., "Lndn") does not perfectly match the stored value in the database ("London"). They employ mapping functions (like fuzzy trigram matching or semantic similarity) to find candidate values and their distance from the search term.
59
+ * *Full Structure Example* (Conceptual Fuzzy Match):
60
+ ```json
61
+ {
62
+ "concept_type": "City",
63
+ "query": "SELECT T.\"location\" AS value, 'users.location' AS columns, 'City' AS concept_type, fuzzy_distance(T.\"location\", $value) AS distance FROM \"users\" T WHERE fuzzy_match(T.\"location\", $value)",
64
+ "description": "Fuzzy match for city in location column"
65
+ }
66
+ ```
67
+
68
+ ## Prerequisites
69
+
70
+ Before you begin, ensure you have completed the following setup:
71
+
72
+ ### 1. Required Services & Access
73
+ * Enable the **Data Analytics API with Gemini**, **Gemini for Google Cloud API**, and **Dataplex Universal Catalog API** in your Google Cloud project.
74
+ * Ensure your IAM user or service account has the necessary roles for database access (appropriate for your database engine), `serviceusage.serviceUsageConsumer`, and `geminidataanalytics.queryDataUser`.
75
+ * Ensure the database instance has `executesql` permission enabled (Data API allowed).
76
+
77
+ ### 2. Gemini CLI
78
+ * Install the Gemini CLI. See [Get Started with Gemini CLI](https://geminicli.com/docs/get-started).
79
+ * Run `gemini --version` to ensure it's installed correctly.
80
+
81
+ ### 3. Google Cloud Authentication
82
+ * Configure Application Default Credentials (ADC) by running:
83
+ ```sh
84
+ gcloud auth application-default login
85
+ ```
86
+
87
+ ## Installation
88
+
89
+ To install the Context Engineering Agent via the Gemini CLI:
90
+
91
+ ```sh
92
+ gemini extensions install https://github.com/GoogleCloudPlatform/db-context-enrichment
93
+ ```
94
+
95
+ *Note: The extension requires a Gemini API key at installation or via environment variable `GEMINI_API_KEY`.*
96
+
97
+ ### Optional: VSCode Integration
98
+ For an enhanced editing and diffing experience when reviewing context changes:
99
+ 1. Install [VSCode](https://code.visualstudio.com/download).
100
+ 2. Install the **Gemini CLI Companion** extension from the VSCode Marketplace.
101
+ 3. Open your workspace folder in VSCode, open the integrated terminal, and run `gemini`. You can verify the IDE extension is active by running `/ide status`.
102
+
103
+ ## Workflows
104
+
105
+ The extension is designed to support the **Critical User Journeys (CUJs)** for context engineering, following an iterative optimization loop:
106
+
107
+ 1. **Bootstrap**: Generate an initial baseline context.
108
+ 2. **Evaluate**: Measure context effectiveness against a golden dataset.
109
+ 3. **Hill-Climbing**: Perform gap analysis on failures and generate automated fixes.
110
+ 4. **Iterate**: Apply the improved context and re-run evaluation to continuously improve quality.
111
+ 5. **Final Validation** (Optional): Verify mutations against a separated test set to ensure generalization and prevent overfitting.
112
+
113
+ ### Automated Iterative Optimization (Autoctx)
114
+
115
+ The extension automates this loop via the following commands. Start the Gemini CLI by running `gemini` in your workspace folder:
116
+
117
+ 1. **Initialize (`/autoctx:init`)**: Sets up your local workspace by creating an `autoctx/` directory. It checks for the presence of a valid `tools.yaml` configuration inside it. If missing, the agent will interactively prompt you for your database connection details and generate the file for you. It also creates the `state.md` file to track experiment progress and an `experiments/` directory, all within `autoctx/`.
118
+ 2. **Generate Dataset (`/autoctx:generate-dataset`)**: Rapidly creates or expands a baseline of evaluation questions (golden dataset). It asks you for sample queries or descriptions of what users might ask, and generates a JSON file with Natural Language Queries (NLQs) and Golden SQL statements.
119
+ 3. **Bootstrap (`/autoctx:bootstrap`)**: Generates an initial context set. It performs progressive schema discovery to understand your database structure and qualified tables. It then generates starting Templates and Facets based on the schema and any user-provided documentation or sample queries.
120
+ 4. **Evaluate (`/autoctx:evaluate`)**: Measures context effectiveness against your golden dataset. This step automatically generates all necessary Evalbench configuration files (`db_config.yaml`, `model_config.yaml`, `run_config.yaml`, `llmrater_config.yaml`) inside the experiment folder and runs the evaluation pipeline to produce accuracy scores and identify failure cases.
121
+ 5. **Hill-Climb (`/autoctx:hillclimb`)**: Performs gap analysis on failures identified in the evaluation step. It reads the failure cases, determines why the LLM failed to generate correct SQL, and proposes updates or new additions to the context set (Templates or Facets) to improve performance in the next iteration.
122
+
123
+ ### Targeted Manual Generation
124
+
125
+ These are more basic workflows for context engineering to manually author specific context elements:
126
+
127
+ * **Generate Templates (`/generate_targeted_templates`)**: Initiates a guided workflow where you provide a sample question and SQL, and the agent helps you parameterize and save it as a template.
128
+ * **Generate Facets (`/generate_targeted_facets`)**: Guides you to define a specific intent and the corresponding SQL snippet (e.g., filter condition) to save as a facet.
129
+ * **Generate Value Searches (`/generate_targeted_value_searches`)**: Helps you configure how the system searches for and matches specific values within a concept type (e.g., setting up exact match or trigram fuzzy search for product names).
130
+
131
+ ## Development and Testing
132
+
133
+ To develop a new feature and test it with the correct dependencies and full bundling (including Evalbench and Toolbox binaries), it is recommended to create a custom release in your **fork**.
134
+
135
+ ### 1. Integration Testing (Fork & Release Workflow)
136
+
137
+ 1. **Create a fork** of the repository on GitHub.
138
+ 2. **Set up the fork/upstream relationship** in your local environment:
139
+ ```sh
140
+ git clone https://github.com/YOUR-USERNAME/db-context-enrichment.git
141
+ git remote add upstream https://github.com/GoogleCloudPlatform/db-context-enrichment
142
+ ```
143
+ 3. **Develop changes** in a new branch in your local repo and push them to your fork.
144
+ 4. **Create a new release** for your fork on GitHub (e.g., using tag `0.0.1-test`).
145
+ 5. Wait for the release assets to be generated by GitHub Actions in your fork.
146
+ 6. **Install the custom release** via Gemini CLI:
147
+ ```sh
148
+ gemini extensions install https://github.com/YOUR-USERNAME/db-context-enrichment --ref 0.0.1-test
149
+ ```
150
+ *Note: Use `gemini extensions uninstall google-cloud-db-context-engineering` to remove previous installations if needed.*
151
+
152
+ ### 2. Official Release Pipeline
153
+ - Releases are versioned and prepared automatically by the Release Please GitHub App.
154
+ - When functional PRs are merged, Release Please opens/updates a pending Release PR (bumping the extension version and updating the changelog).
155
+ - **Merging the Release PR** signals Release Please to tag the commit and create an official GitHub Release.
156
+ - **The creation of the GitHub Release** triggers the `.github/workflows/release.yml` pipeline.
157
+ - The pipeline uses PyInstaller to build standalone binary executables for Linux (x64), macOS (arm64), and Windows (x64).
158
+ - The pipeline packages the binary, `LICENSE`, `GEMINI.md`, and dynamically updates `gemini-extension.json` into `.tar.gz` and `.zip` archives.
159
+ - These archives are automatically attached back to the GitHub release as downloadable assets.
160
+ - Users receive the update the next time they install or upgrade the extension via Gemini CLI (`gemini extensions update --all`).
@@ -0,0 +1,144 @@
1
+ This is not an officially supported Google product. This project is not eligible for the [Google Open Source Software Vulnerability Rewards Program](https://bughunters.google.com/open-source-security), [Google Cloud Platform/SecOps Terms of Service](https://cloud.google.com/terms), [How Gemini for Google Cloud uses your data](https://cloud.google.com/gemini/docs/discover/data-governance). This tool is provided "as is" without warranty of any kind. Users are solely responsible for understanding and managing the tool's interaction with their databases. Use of this tool constitutes acceptance of all risks associated with database access, reading, usage, and modifications.
2
+
3
+ # Context Engineering Agent
4
+
5
+ > [!IMPORTANT]
6
+ > **Repository Reorganization**
7
+ > The original Go-based **DB Schema Enricher CLI** has been archived and moved to the [legacy/go-enricher/](legacy/go-enricher/) directory. This repository root is now dedicated to the Python-based **Context Engineering Agent (MCP Server)**.
8
+
9
+ This project is a Gemini CLI extension that bridges the gap between Large Language Models (LLMs) and structured databases by generating and managing tailored context. This context helps the LLM understand database schema, business logic, and terminology, enabling more accurate Natural Language to SQL generation.
10
+
11
+ ## Core Concepts
12
+
13
+ A `ContextSet` is the central artifact generated by the Context Engineering Agent, containing structured knowledge in three primary forms:
14
+
15
+ * **Templates**: End-to-end mappings linking a natural language query to a complete, runnable SQL query. They teach the system overarching operational logic, table join infrastructures, and broad business rules.
16
+ * *Full Structure Example*:
17
+ ```json
18
+ {
19
+ "nl_query": "How many accounts are in London?",
20
+ "sql": "SELECT count(*) FROM account WHERE account.city = 'London'",
21
+ "intent": "How many accounts are in London?",
22
+ "manifest": "How many accounts are in a given city?",
23
+ "parameterized": {
24
+ "parameterized_sql": "SELECT count(*) FROM account WHERE account.city = $1",
25
+ "parameterized_intent": "How many accounts are in $1?"
26
+ }
27
+ }
28
+ ```
29
+ * **Facets**: Reusable, modular SQL fragments (like a `WHERE` clause or specialized join) linked to specific vocabulary or terminology. They are not standalone queries but dynamically injected filters.
30
+ * *Full Structure Example*:
31
+ ```json
32
+ {
33
+ "sql_snippet": "products.rating > 4.5",
34
+ "intent": "highly rated products (above 4.5)",
35
+ "manifest": "highly rated products (above a given number)",
36
+ "parameterized": {
37
+ "parameterized_sql_snippet": "products.rating > $1",
38
+ "parameterized_intent": "highly rated products (above $1)"
39
+ }
40
+ }
41
+ ```
42
+ * **Value Searches**: Specialized queries used when a value in the natural language query (e.g., "Lndn") does not perfectly match the stored value in the database ("London"). They employ mapping functions (like fuzzy trigram matching or semantic similarity) to find candidate values and their distance from the search term.
43
+ * *Full Structure Example* (Conceptual Fuzzy Match):
44
+ ```json
45
+ {
46
+ "concept_type": "City",
47
+ "query": "SELECT T.\"location\" AS value, 'users.location' AS columns, 'City' AS concept_type, fuzzy_distance(T.\"location\", $value) AS distance FROM \"users\" T WHERE fuzzy_match(T.\"location\", $value)",
48
+ "description": "Fuzzy match for city in location column"
49
+ }
50
+ ```
51
+
52
+ ## Prerequisites
53
+
54
+ Before you begin, ensure you have completed the following setup:
55
+
56
+ ### 1. Required Services & Access
57
+ * Enable the **Data Analytics API with Gemini**, **Gemini for Google Cloud API**, and **Dataplex Universal Catalog API** in your Google Cloud project.
58
+ * Ensure your IAM user or service account has the necessary roles for database access (appropriate for your database engine), `serviceusage.serviceUsageConsumer`, and `geminidataanalytics.queryDataUser`.
59
+ * Ensure the database instance has `executesql` permission enabled (Data API allowed).
60
+
61
+ ### 2. Gemini CLI
62
+ * Install the Gemini CLI. See [Get Started with Gemini CLI](https://geminicli.com/docs/get-started).
63
+ * Run `gemini --version` to ensure it's installed correctly.
64
+
65
+ ### 3. Google Cloud Authentication
66
+ * Configure Application Default Credentials (ADC) by running:
67
+ ```sh
68
+ gcloud auth application-default login
69
+ ```
70
+
71
+ ## Installation
72
+
73
+ To install the Context Engineering Agent via the Gemini CLI:
74
+
75
+ ```sh
76
+ gemini extensions install https://github.com/GoogleCloudPlatform/db-context-enrichment
77
+ ```
78
+
79
+ *Note: The extension requires a Gemini API key at installation or via environment variable `GEMINI_API_KEY`.*
80
+
81
+ ### Optional: VSCode Integration
82
+ For an enhanced editing and diffing experience when reviewing context changes:
83
+ 1. Install [VSCode](https://code.visualstudio.com/download).
84
+ 2. Install the **Gemini CLI Companion** extension from the VSCode Marketplace.
85
+ 3. Open your workspace folder in VSCode, open the integrated terminal, and run `gemini`. You can verify the IDE extension is active by running `/ide status`.
86
+
87
+ ## Workflows
88
+
89
+ The extension is designed to support the **Critical User Journeys (CUJs)** for context engineering, following an iterative optimization loop:
90
+
91
+ 1. **Bootstrap**: Generate an initial baseline context.
92
+ 2. **Evaluate**: Measure context effectiveness against a golden dataset.
93
+ 3. **Hill-Climbing**: Perform gap analysis on failures and generate automated fixes.
94
+ 4. **Iterate**: Apply the improved context and re-run evaluation to continuously improve quality.
95
+ 5. **Final Validation** (Optional): Verify mutations against a separated test set to ensure generalization and prevent overfitting.
96
+
97
+ ### Automated Iterative Optimization (Autoctx)
98
+
99
+ The extension automates this loop via the following commands. Start the Gemini CLI by running `gemini` in your workspace folder:
100
+
101
+ 1. **Initialize (`/autoctx:init`)**: Sets up your local workspace by creating an `autoctx/` directory. It checks for the presence of a valid `tools.yaml` configuration inside it. If missing, the agent will interactively prompt you for your database connection details and generate the file for you. It also creates the `state.md` file to track experiment progress and an `experiments/` directory, all within `autoctx/`.
102
+ 2. **Generate Dataset (`/autoctx:generate-dataset`)**: Rapidly creates or expands a baseline of evaluation questions (golden dataset). It asks you for sample queries or descriptions of what users might ask, and generates a JSON file with Natural Language Queries (NLQs) and Golden SQL statements.
103
+ 3. **Bootstrap (`/autoctx:bootstrap`)**: Generates an initial context set. It performs progressive schema discovery to understand your database structure and qualified tables. It then generates starting Templates and Facets based on the schema and any user-provided documentation or sample queries.
104
+ 4. **Evaluate (`/autoctx:evaluate`)**: Measures context effectiveness against your golden dataset. This step automatically generates all necessary Evalbench configuration files (`db_config.yaml`, `model_config.yaml`, `run_config.yaml`, `llmrater_config.yaml`) inside the experiment folder and runs the evaluation pipeline to produce accuracy scores and identify failure cases.
105
+ 5. **Hill-Climb (`/autoctx:hillclimb`)**: Performs gap analysis on failures identified in the evaluation step. It reads the failure cases, determines why the LLM failed to generate correct SQL, and proposes updates or new additions to the context set (Templates or Facets) to improve performance in the next iteration.
106
+
107
+ ### Targeted Manual Generation
108
+
109
+ These are more basic workflows for context engineering to manually author specific context elements:
110
+
111
+ * **Generate Templates (`/generate_targeted_templates`)**: Initiates a guided workflow where you provide a sample question and SQL, and the agent helps you parameterize and save it as a template.
112
+ * **Generate Facets (`/generate_targeted_facets`)**: Guides you to define a specific intent and the corresponding SQL snippet (e.g., filter condition) to save as a facet.
113
+ * **Generate Value Searches (`/generate_targeted_value_searches`)**: Helps you configure how the system searches for and matches specific values within a concept type (e.g., setting up exact match or trigram fuzzy search for product names).
114
+
115
+ ## Development and Testing
116
+
117
+ To develop a new feature and test it with the correct dependencies and full bundling (including Evalbench and Toolbox binaries), it is recommended to create a custom release in your **fork**.
118
+
119
+ ### 1. Integration Testing (Fork & Release Workflow)
120
+
121
+ 1. **Create a fork** of the repository on GitHub.
122
+ 2. **Set up the fork/upstream relationship** in your local environment:
123
+ ```sh
124
+ git clone https://github.com/YOUR-USERNAME/db-context-enrichment.git
125
+ git remote add upstream https://github.com/GoogleCloudPlatform/db-context-enrichment
126
+ ```
127
+ 3. **Develop changes** in a new branch in your local repo and push them to your fork.
128
+ 4. **Create a new release** for your fork on GitHub (e.g., using tag `0.0.1-test`).
129
+ 5. Wait for the release assets to be generated by GitHub Actions in your fork.
130
+ 6. **Install the custom release** via Gemini CLI:
131
+ ```sh
132
+ gemini extensions install https://github.com/YOUR-USERNAME/db-context-enrichment --ref 0.0.1-test
133
+ ```
134
+ *Note: Use `gemini extensions uninstall google-cloud-db-context-engineering` to remove previous installations if needed.*
135
+
136
+ ### 2. Official Release Pipeline
137
+ - Releases are versioned and prepared automatically by the Release Please GitHub App.
138
+ - When functional PRs are merged, Release Please opens/updates a pending Release PR (bumping the extension version and updating the changelog).
139
+ - **Merging the Release PR** signals Release Please to tag the commit and create an official GitHub Release.
140
+ - **The creation of the GitHub Release** triggers the `.github/workflows/release.yml` pipeline.
141
+ - The pipeline uses PyInstaller to build standalone binary executables for Linux (x64), macOS (arm64), and Windows (x64).
142
+ - The pipeline packages the binary, `LICENSE`, `GEMINI.md`, and dynamically updates `gemini-extension.json` into `.tar.gz` and `.zip` archives.
143
+ - These archives are automatically attached back to the GitHub release as downloadable assets.
144
+ - Users receive the update the next time they install or upgrade the extension via Gemini CLI (`gemini extensions update --all`).
@@ -0,0 +1,62 @@
1
+ [project]
2
+ name = "google-cloud-db-context-engineering"
3
+ version = "0.5.1"
4
+ description = "A FastMCP server for generating natural language to SQL templates from database schemas."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ # Pinned to exact versions because this project is distributed as a standalone application.
8
+ dependencies = [
9
+ "fastmcp==3.3.1",
10
+ "google-genai==1.46.0",
11
+ "toolbox-core==0.5.2",
12
+ "google-cloud-geminidataanalytics==0.11.0",
13
+ ]
14
+
15
+ [project.scripts]
16
+ google-cloud-db-context-engineering = "google.cloud.db_context_enrichment.main:mcp.run"
17
+
18
+ [project.optional-dependencies]
19
+ test = [
20
+ "pytest",
21
+ "pytest-asyncio"
22
+ ]
23
+
24
+ [tool.setuptools]
25
+ package-dir = {"" = "src"}
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+ include = ["google.cloud.db_context_enrichment*"]
30
+
31
+ [tool.pytest.ini_options]
32
+ pythonpath = "src"
33
+
34
+ [[tool.uv.index]]
35
+ url = "https://pypi.org/simple"
36
+ default = true
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pre-commit>=4.6.0",
41
+ "pyinstaller>=6.18.0",
42
+ "ruff>=0.15.12",
43
+ ]
44
+
45
+ [tool.db-context-engineering]
46
+ toolbox_version = "0.31.0"
47
+ evalbench_version = "1.7.1"
48
+
49
+ [tool.ruff]
50
+ line-length = 88
51
+ target-version = "py312"
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "UP"]
55
+ ignore = ["E501"]
56
+
57
+ [tool.ruff.lint.isort]
58
+ known-first-party = ["google.cloud.db_context_enrichment"]
59
+
60
+ [build-system]
61
+ requires = ["setuptools>=61.0"]
62
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ # Initialization script for bootstrap module
@@ -0,0 +1,74 @@
1
+ import json
2
+
3
+ from pydantic import ValidationError
4
+
5
+ from google.cloud.db_context_enrichment.common.context_mutator import (
6
+ Mutation,
7
+ mutate_context_set,
8
+ )
9
+ from google.cloud.db_context_enrichment.facet import facet_generator
10
+ from google.cloud.db_context_enrichment.model import context
11
+ from google.cloud.db_context_enrichment.template import template_generator
12
+
13
+
14
+ async def generate_context(
15
+ output_file_path: str,
16
+ sql_dialect: str,
17
+ template_inputs_json: str | None = None,
18
+ facet_inputs_json: str | None = None,
19
+ ) -> str:
20
+ """
21
+ Core logic for generating a single unified ContextSet from key information and saving it to a file.
22
+ """
23
+ final_templates = None
24
+ final_facets = None
25
+
26
+ if template_inputs_json:
27
+ res_str = await template_generator.generate_templates(
28
+ template_inputs_json, sql_dialect
29
+ )
30
+ if '"error":' in res_str:
31
+ raise RuntimeError(f"Error generating templates: {res_str}")
32
+ try:
33
+ res_dict = json.loads(res_str)
34
+ final_templates = [
35
+ context.Template(**t) for t in res_dict.get("templates", [])
36
+ ]
37
+ except (json.JSONDecodeError, ValidationError) as e:
38
+ raise ValueError(f"Error parsing generated templates: {e}") from e
39
+
40
+ if facet_inputs_json:
41
+ res_str = await facet_generator.generate_facets(facet_inputs_json, sql_dialect)
42
+ if '"error":' in res_str:
43
+ raise RuntimeError(f"Error generating facets: {res_str}")
44
+ try:
45
+ res_dict = json.loads(res_str)
46
+ final_facets = [context.Facet(**f) for f in res_dict.get("facets", [])]
47
+ except (json.JSONDecodeError, ValidationError) as e:
48
+ raise ValueError(f"Error parsing generated facets: {e}") from e
49
+
50
+ mutations: list[Mutation] = []
51
+
52
+ if final_templates:
53
+ for t in final_templates:
54
+ mutations.append(
55
+ Mutation(
56
+ operation="add",
57
+ type="template",
58
+ value=t.model_dump(exclude_none=True),
59
+ )
60
+ )
61
+
62
+ if final_facets:
63
+ for f in final_facets:
64
+ mutations.append(
65
+ Mutation(
66
+ operation="add", type="facet", value=f.model_dump(exclude_none=True)
67
+ )
68
+ )
69
+
70
+ if not mutations:
71
+ raise ValueError("No templates or facets were generated to save.")
72
+
73
+ mutate_context_set(output_file_path, mutations)
74
+ return output_file_path