@szdatatalk/sqlward-mcp 0.0.0-stage → 0.3.3

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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 notices, patent notices,
102
+ trademark notices, and attribution notices from the Source
103
+ form of the Work, excluding those notices that do not pertain
104
+ to any part of 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 Derivative Works 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 notice 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
+ applicable law and appropriateness of using or redistributing the
151
+ Work and assume any risks associated with Your exercise of permissions
152
+ 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 Contributor be liable
158
+ for damages, including any direct, indirect, special, incidental, or
159
+ consequential damages of any kind, arising out of this License or out
160
+ of the use or inability to use the Work (including but not limited to
161
+ loss of data or data being rendered inaccurate or losses sustained by
162
+ You or third parties or a failure of the Work or any other software),
163
+ even if such Contributor has been advised of the possibility of such
164
+ 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, or indemnity
169
+ terms for Your component or your distribution. However, in accepting
170
+ such obligations, You may act only on Your own behalf and on Your
171
+ sole responsibility, and not on behalf of any other Contributor, and
172
+ only if You agree to indemnify, defend, and hold each Contributor
173
+ harmless for any liability incurred by, or claims asserted against,
174
+ such Contributor by reason of your accepting any such warranty or
175
+ 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 loss-free notice to 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 filename be included in the same "printed page" as the
187
+ copyright notice for easier identification within third-party
188
+ notices.
189
+
190
+ Copyright 2026 SqlWard Contributors
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.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ SqlWard
2
+ Copyright 2026 Suzhou DataTalk Information Technology Co., Ltd. (苏州数说信息科技有限公司)
3
+
4
+ This product includes SqlWard (https://github.com/shygoly/sqlward | https://www.npmjs.com/package/@szdatatalk/sqlward), developed by Suzhou DataTalk Information Technology Co., Ltd.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # `@szdatatalk/sqlward-mcp`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-compile `npx` **Model Context Protocol (MCP)** stdio server for **SqlWard** — offline Pure-Rust WebAssembly column-level SQL lineage (8 dialects), fail-closed M6 SQL security guardrails, and dbt blast-radius analysis.
4
+
5
+ > Zero SQL execution · Zero database credentials · Zero Python or Rust compilation required.
6
+
7
+ ## Quick Start (`npx`)
8
+
9
+ ```bash
10
+ npx -y @szdatatalk/sqlward-mcp
11
+ ```
12
+
13
+ ### Claude Code / Cursor / Windsurf / Antigravity MCP Config
14
+
15
+ ```json
16
+ {
17
+ "mcpServers": {
18
+ "sqlward": {
19
+ "command": "npx",
20
+ "args": ["-y", "@szdatatalk/sqlward-mcp"]
21
+ }
22
+ }
23
+ }
24
+ ```
25
+
26
+ ## Available Read-Only Tools
27
+
28
+ | Tool | Description |
29
+ | --- | --- |
30
+ | `sqlward_parse_column` | Extract deterministic column-level SQL lineage (`DIRECT`/`INDIRECT`) across 8 dialects (`postgres`, `mysql`, `doris`, `starrocks`, `oracle`, `spark`, `hive`, `tsql`). |
31
+ | `sqlward_evaluate_policy` | Fail-closed M6 SQL security guardrail (blocks writes, DDL, dynamic SQL, locking hints, disallowed functions, and direct/transitive PII column leaks). |
32
+ | `sqlward_column_impact` | Traverse upstream provenance or downstream impact for a `(table, column)` origin from SQL. |
33
+ | `sqlward_dbt_analyze` | Analyze dbt `manifest.json` + optional `catalog.json` / `run_results.json` offline with automatic slimming & batching. |
34
+ | `sqlward_dbt_diff` | Compute structural & column-level lineage diff between base and head dbt snapshots. |
35
+ | `sqlward_dbt_impact` | Compute bounded downstream/upstream blast-radius impact from a dbt node. |
36
+ | `sqlward_version_info` | Return runtime version, supported dialects, and input byte limits. |
37
+
38
+ ## License
39
+
40
+ Apache-2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { startStdioServer } from "../src/server.mjs";
3
+
4
+ startStdioServer().catch((err) => {
5
+ process.stderr.write(`sqlward-mcp fatal error: ${err?.message || err}\n`);
6
+ process.exit(1);
7
+ });
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@szdatatalk/sqlward-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.3",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/shygoly/sqlward.git",
8
+ "directory": "packages/mcp"
9
+ },
10
+ "homepage": "https://github.com/shygoly/sqlward#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/shygoly/sqlward/issues"
13
+ },
14
+ "description": "Zero-compile npx MCP stdio server for SqlWard: offline Pure-Rust WASM SQL lineage (8 dialects), M6 SQL security guardrails, and dbt blast-radius analysis.",
15
+ "type": "module",
16
+ "main": "./src/server.mjs",
17
+ "bin": {
18
+ "sqlward-mcp": "bin/sqlward-mcp.mjs"
19
+ },
20
+ "files": [
21
+ "bin/**",
22
+ "src/**",
23
+ "README.md",
24
+ "LICENSE",
25
+ "NOTICE"
26
+ ],
27
+ "keywords": [
28
+ "mcp",
29
+ "model-context-protocol",
30
+ "sqlward",
31
+ "szdatatalk",
32
+ "sql",
33
+ "lineage",
34
+ "dbt",
35
+ "security",
36
+ "guardrail",
37
+ "wasm"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "dependencies": {
43
+ "@szdatatalk/sqlward": "0.3.3"
44
+ },
45
+ "scripts": {
46
+ "test": "node --test test/mcp.test.mjs"
47
+ },
48
+ "engines": {
49
+ "node": ">=20"
50
+ }
51
+ }
package/src/server.mjs ADDED
@@ -0,0 +1,412 @@
1
+ /**
2
+ * Zero-dependency MCP stdio server wrapping `@szdatatalk/sqlward` (Pure-Rust WASM).
3
+ *
4
+ * Implements JSON-RPC 2.0 over newline-delimited stdio per Model Context Protocol
5
+ * (`2024-11-05` / `2025-03-26`). Never executes SQL and never connects to any database.
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import readline from "node:readline";
10
+ import { pathToFileURL } from "node:url";
11
+
12
+ const SERVER_NAME = "@szdatatalk/sqlward-mcp";
13
+ const SERVER_VERSION = "0.3.3";
14
+ const SUPPORTED_PROTOCOL_VERSION = "2024-11-05";
15
+
16
+ const READ_ONLY_ANNOTATIONS = {
17
+ readOnlyHint: true,
18
+ destructiveHint: false,
19
+ idempotentHint: true,
20
+ openWorldHint: false,
21
+ };
22
+
23
+ export const TOOL_SCHEMAS = [
24
+ {
25
+ name: "sqlward_parse_column",
26
+ description:
27
+ "Extract deterministic column-level SQL lineage (DIRECT/INDIRECT edges) offline across 8 dialects without executing SQL.",
28
+ annotations: READ_ONLY_ANNOTATIONS,
29
+ inputSchema: {
30
+ type: "object",
31
+ required: ["sql"],
32
+ properties: {
33
+ dialect: {
34
+ type: "string",
35
+ enum: ["postgres", "mysql", "doris", "starrocks", "oracle", "spark", "hive", "tsql"],
36
+ default: "postgres",
37
+ description: "SQL dialect to parse.",
38
+ },
39
+ sql: { type: "string", description: "SQL statement(s) to analyze offline." },
40
+ defaultSchema: { type: "string", description: "Optional default schema for unqualified table names." },
41
+ catalogSchema: {
42
+ type: "object",
43
+ description: "Optional map of table name -> array of column names for wildcard/SELECT * resolution.",
44
+ },
45
+ },
46
+ },
47
+ },
48
+ {
49
+ name: "sqlward_evaluate_policy",
50
+ description:
51
+ "Evaluate fail-closed M6 SQL security policy (blocks writes, DDL, dynamic SQL, locking hints, disallowed functions, and direct/transitive PII column leaks) offline.",
52
+ annotations: READ_ONLY_ANNOTATIONS,
53
+ inputSchema: {
54
+ type: "object",
55
+ required: ["sql"],
56
+ properties: {
57
+ dialect: {
58
+ type: "string",
59
+ enum: ["postgres", "mysql", "doris", "starrocks", "oracle", "spark", "hive", "tsql"],
60
+ default: "postgres",
61
+ },
62
+ sql: { type: "string", description: "SQL query to validate before execution." },
63
+ profile: {
64
+ type: "string",
65
+ enum: ["read-only", "analysis"],
66
+ default: "read-only",
67
+ description: "Built-in M6 policy profile when `snapshot` is omitted.",
68
+ },
69
+ snapshot: {
70
+ type: "object",
71
+ description: "Optional custom M6 PolicySnapshot JSON (relations, deniedLabels, enforceColumnAcl, columnGrants).",
72
+ },
73
+ principal: {
74
+ type: "object",
75
+ description: "Optional TrustedPrincipal ({ principalId, tenantId, roles }).",
76
+ },
77
+ },
78
+ },
79
+ },
80
+ {
81
+ name: "sqlward_column_impact",
82
+ description:
83
+ "Traverse upstream provenance or downstream blast-radius impact for a (table, column) origin from SQL offline.",
84
+ annotations: READ_ONLY_ANNOTATIONS,
85
+ inputSchema: {
86
+ type: "object",
87
+ required: ["sql", "table", "column"],
88
+ properties: {
89
+ dialect: {
90
+ type: "string",
91
+ enum: ["postgres", "mysql", "doris", "starrocks", "oracle", "spark", "hive", "tsql"],
92
+ default: "postgres",
93
+ },
94
+ sql: { type: "string", description: "SQL script to extract column lineage from." },
95
+ table: { type: "string", description: "Origin table name." },
96
+ column: { type: "string", description: "Origin column name." },
97
+ direction: {
98
+ type: "string",
99
+ enum: ["downstream", "upstream"],
100
+ default: "downstream",
101
+ },
102
+ },
103
+ },
104
+ },
105
+ {
106
+ name: "sqlward_dbt_analyze",
107
+ description:
108
+ "Analyze a dbt project offline from manifest.json (+ optional catalog.json / run_results.json) with automatic slimming & batching.",
109
+ annotations: READ_ONLY_ANNOTATIONS,
110
+ inputSchema: {
111
+ type: "object",
112
+ properties: {
113
+ manifestPath: { type: "string", description: "Local file path to dbt target/manifest.json." },
114
+ catalogPath: { type: "string", description: "Optional local file path to dbt target/catalog.json." },
115
+ runResultsPath: { type: "string", description: "Optional local file path to dbt target/run_results.json." },
116
+ manifest: { description: "Inline dbt manifest JSON object or string (alternative to manifestPath)." },
117
+ catalog: { description: "Optional inline dbt catalog JSON object or string." },
118
+ analyzeSql: { type: "boolean", default: true },
119
+ batchSize: { type: "integer", default: 50, minimum: 1, maximum: 500 },
120
+ },
121
+ },
122
+ },
123
+ {
124
+ name: "sqlward_dbt_diff",
125
+ description: "Compute structural and column-level lineage diff between base and head dbt snapshots.",
126
+ annotations: READ_ONLY_ANNOTATIONS,
127
+ inputSchema: {
128
+ type: "object",
129
+ required: ["base", "head"],
130
+ properties: {
131
+ base: { type: "object", description: "Base DbtProjectSnapshot returned by sqlward_dbt_analyze." },
132
+ head: { type: "object", description: "Head DbtProjectSnapshot returned by sqlward_dbt_analyze." },
133
+ },
134
+ },
135
+ },
136
+ {
137
+ name: "sqlward_dbt_impact",
138
+ description: "Compute bounded downstream/upstream blast-radius impact from a dbt node on a DbtProjectSnapshot.",
139
+ annotations: READ_ONLY_ANNOTATIONS,
140
+ inputSchema: {
141
+ type: "object",
142
+ required: ["snapshot", "originNode"],
143
+ properties: {
144
+ snapshot: { type: "object", description: "DbtProjectSnapshot returned by sqlward_dbt_analyze." },
145
+ originNode: { type: "string", description: "dbt unique_id (e.g. model.analytics.stg_orders)." },
146
+ direction: { type: "string", enum: ["downstream", "upstream", "both"], default: "downstream" },
147
+ maxHops: { type: "integer", default: 6, minimum: 1, maximum: 32 },
148
+ },
149
+ },
150
+ },
151
+ {
152
+ name: "sqlward_version_info",
153
+ description: "Inspect SqlWard WASM runtime version, supported SQL dialects, and input byte ceilings.",
154
+ annotations: READ_ONLY_ANNOTATIONS,
155
+ inputSchema: { type: "object", properties: {} },
156
+ },
157
+ ];
158
+
159
+ async function loadSqlWardModule(customModulePath) {
160
+ if (customModulePath) {
161
+ return import(pathToFileURL(path.resolve(customModulePath)).href);
162
+ }
163
+ return import("@szdatatalk/sqlward");
164
+ }
165
+
166
+ function readFileUtf8Checked(filePath, label) {
167
+ const abs = path.resolve(filePath);
168
+ if (!fs.existsSync(abs)) {
169
+ throw new Error(`${label} not found: ${path.basename(abs)}`);
170
+ }
171
+ return fs.readFileSync(abs, "utf8");
172
+ }
173
+
174
+ export async function createMcpHandler({ sqlwardModule, wasmPath } = {}) {
175
+ const sw = sqlwardModule || (await loadSqlWardModule(process.env.SQLWARD_MODULE_PATH));
176
+ const resolvedWasmPath = wasmPath || process.env.SQLWARD_WASM_PATH || sw.defaultWasmPath();
177
+ const wasm = await sw.instantiateWasm(resolvedWasmPath);
178
+
179
+ async function callTool(name, args = {}) {
180
+ switch (name) {
181
+ case "sqlward_version_info":
182
+ return wasm.versionInfo();
183
+
184
+ case "sqlward_parse_column": {
185
+ if (typeof args.sql !== "string" || !args.sql.trim()) {
186
+ throw new Error("`sql` must be a non-empty string");
187
+ }
188
+ return wasm.parseColumn({
189
+ dialect: args.dialect || "postgres",
190
+ sql: args.sql,
191
+ ...(args.defaultSchema ? { defaultSchema: args.defaultSchema } : {}),
192
+ ...(args.catalogSchema ? { catalogSchema: args.catalogSchema } : {}),
193
+ });
194
+ }
195
+
196
+ case "sqlward_evaluate_policy": {
197
+ if (typeof args.sql !== "string" || !args.sql.trim()) {
198
+ throw new Error("`sql` must be a non-empty string");
199
+ }
200
+ const snapshot = args.snapshot || {
201
+ policyId: "sqlward-mcp-default-v1",
202
+ policyVersion: "1.0.0",
203
+ profile: args.profile || "read-only",
204
+ relations: {},
205
+ };
206
+ const principal = args.principal || {
207
+ principalId: "mcp-agent",
208
+ tenantId: "default",
209
+ roles: ["developer"],
210
+ };
211
+ return wasm.evaluatePolicy({
212
+ dialect: args.dialect || "postgres",
213
+ sql: args.sql,
214
+ snapshot,
215
+ principal,
216
+ });
217
+ }
218
+
219
+ case "sqlward_column_impact": {
220
+ if (typeof args.sql !== "string" || !args.sql.trim()) {
221
+ throw new Error("`sql` must be a non-empty string");
222
+ }
223
+ if (typeof args.table !== "string" || !args.table.trim()) {
224
+ throw new Error("`table` must be a non-empty string");
225
+ }
226
+ if (typeof args.column !== "string" || !args.column.trim()) {
227
+ throw new Error("`column` must be a non-empty string");
228
+ }
229
+ const parsed = wasm.parseColumn({
230
+ dialect: args.dialect || "postgres",
231
+ sql: args.sql,
232
+ });
233
+ const edges = (parsed.statements || []).flatMap((s) => s.edges || []);
234
+ const direction = args.direction === "upstream" ? "upstream" : "downstream";
235
+ const impact =
236
+ direction === "upstream"
237
+ ? wasm.impactUpstream(edges, args.table, args.column)
238
+ : wasm.impactDownstream(edges, args.table, args.column);
239
+ return {
240
+ status: parsed.status,
241
+ direction,
242
+ origin: { table: args.table, column: args.column },
243
+ graphDigest: wasm.graphDigestFromEdges(edges),
244
+ impact,
245
+ };
246
+ }
247
+
248
+ case "sqlward_dbt_analyze": {
249
+ const manifest = args.manifestPath
250
+ ? readFileUtf8Checked(args.manifestPath, "manifestPath")
251
+ : args.manifest;
252
+ if (!manifest) {
253
+ throw new Error("Either `manifestPath` or `manifest` is required");
254
+ }
255
+ const catalog = args.catalogPath
256
+ ? readFileUtf8Checked(args.catalogPath, "catalogPath")
257
+ : args.catalog ?? null;
258
+ const runResults = args.runResultsPath
259
+ ? readFileUtf8Checked(args.runResultsPath, "runResultsPath")
260
+ : args.runResults ?? null;
261
+
262
+ return sw.analyzeDbtBatched(
263
+ {
264
+ manifest,
265
+ ...(catalog ? { catalog } : {}),
266
+ ...(runResults ? { run_results: runResults } : {}),
267
+ analyze_sql: args.analyzeSql !== false,
268
+ },
269
+ {
270
+ wasmPath: resolvedWasmPath,
271
+ batchSize: Number.isInteger(args.batchSize) ? args.batchSize : 50,
272
+ useWorker: true,
273
+ },
274
+ );
275
+ }
276
+
277
+ case "sqlward_dbt_diff": {
278
+ if (!args.base || !args.head) {
279
+ throw new Error("`base` and `head` dbt snapshots are required");
280
+ }
281
+ return wasm.diffDbt({ base: args.base, head: args.head });
282
+ }
283
+
284
+ case "sqlward_dbt_impact": {
285
+ if (!args.snapshot || typeof args.originNode !== "string") {
286
+ throw new Error("`snapshot` and `originNode` are required");
287
+ }
288
+ return wasm.impactDbt({
289
+ snapshot: args.snapshot,
290
+ origin_node: args.originNode,
291
+ direction: args.direction || "downstream",
292
+ max_hops: Number.isInteger(args.maxHops) ? args.maxHops : 6,
293
+ });
294
+ }
295
+
296
+ default:
297
+ throw new Error(`Unknown tool: ${name}`);
298
+ }
299
+ }
300
+
301
+ async function handleMessage(msg) {
302
+ if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0") {
303
+ return {
304
+ jsonrpc: "2.0",
305
+ id: msg?.id ?? null,
306
+ error: { code: -32600, message: "Invalid Request" },
307
+ };
308
+ }
309
+
310
+ const { id, method, params } = msg;
311
+
312
+ // Notifications (no id) require no response
313
+ if (method === "notifications/initialized" || method === "notifications/cancelled") {
314
+ return null;
315
+ }
316
+
317
+ if (method === "initialize") {
318
+ const requestedVersion =
319
+ typeof params?.protocolVersion === "string"
320
+ ? params.protocolVersion
321
+ : SUPPORTED_PROTOCOL_VERSION;
322
+ return {
323
+ jsonrpc: "2.0",
324
+ id,
325
+ result: {
326
+ protocolVersion: requestedVersion,
327
+ capabilities: { tools: { listChanged: false } },
328
+ serverInfo: {
329
+ name: SERVER_NAME,
330
+ version: SERVER_VERSION,
331
+ },
332
+ },
333
+ };
334
+ }
335
+
336
+ if (method === "ping") {
337
+ return { jsonrpc: "2.0", id, result: {} };
338
+ }
339
+
340
+ if (method === "tools/list") {
341
+ return {
342
+ jsonrpc: "2.0",
343
+ id,
344
+ result: { tools: TOOL_SCHEMAS },
345
+ };
346
+ }
347
+
348
+ if (method === "tools/call") {
349
+ const toolName = params?.name;
350
+ const toolArgs = params?.arguments || {};
351
+ try {
352
+ const result = await callTool(toolName, toolArgs);
353
+ return {
354
+ jsonrpc: "2.0",
355
+ id,
356
+ result: {
357
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
358
+ isError: false,
359
+ },
360
+ };
361
+ } catch (err) {
362
+ return {
363
+ jsonrpc: "2.0",
364
+ id,
365
+ result: {
366
+ content: [{ type: "text", text: String(err?.message || err) }],
367
+ isError: true,
368
+ },
369
+ };
370
+ }
371
+ }
372
+
373
+ if (id === undefined) return null;
374
+ return {
375
+ jsonrpc: "2.0",
376
+ id,
377
+ error: { code: -32601, message: `Method not found: ${method}` },
378
+ };
379
+ }
380
+
381
+ return { handleMessage, callTool };
382
+ }
383
+
384
+ export async function startStdioServer(options = {}) {
385
+ const handler = await createMcpHandler(options);
386
+ const rl = readline.createInterface({
387
+ input: process.stdin,
388
+ crlfDelay: Infinity,
389
+ });
390
+
391
+ rl.on("line", async (line) => {
392
+ const trimmed = line.trim();
393
+ if (!trimmed) return;
394
+ let msg;
395
+ try {
396
+ msg = JSON.parse(trimmed);
397
+ } catch {
398
+ process.stdout.write(
399
+ JSON.stringify({
400
+ jsonrpc: "2.0",
401
+ id: null,
402
+ error: { code: -32700, message: "Parse error" },
403
+ }) + "\n",
404
+ );
405
+ return;
406
+ }
407
+ const resp = await handler.handleMessage(msg);
408
+ if (resp !== null) {
409
+ process.stdout.write(JSON.stringify(resp) + "\n");
410
+ }
411
+ });
412
+ }