@codegiveness/mssql-mcp 0.2.0

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 (3) hide show
  1. package/bin/mssql-mcp +14 -0
  2. package/install.js +255 -0
  3. package/package.json +23 -0
package/bin/mssql-mcp ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ // Shim: replaced by the real binary during npm install (postinstall).
3
+ // If you see this message, the postinstall did not run or the download failed.
4
+ const { spawnSync } = require('child_process');
5
+ const path = require('path');
6
+ const fs = require('fs');
7
+ const binPath = path.join(__dirname, 'mssql-mcp');
8
+ if (fs.existsSync(binPath) && !fs.readFileSync(binPath, 'utf8').includes('Shim')) {
9
+ const result = spawnSync(binPath, process.argv.slice(2), { stdio: 'inherit' });
10
+ process.exit(result.status ?? 1);
11
+ } else {
12
+ console.error('mssql-mcp: binary not installed. Run "npm install" or use "dotnet tool install -g mssql-mcp" instead.');
13
+ process.exit(1);
14
+ }
package/install.js ADDED
@@ -0,0 +1,255 @@
1
+ // npm postinstall: download the prebuilt mssql-mcp binary for this platform,
2
+ // verify its SHA256 checksum, and replace the Node shim at bin/mssql-mcp with
3
+ // the real native executable.
4
+ //
5
+ // Contract (ADR-0014):
6
+ // - Fail loudly on ANY error (no network, 404, checksum mismatch, extraction
7
+ // failure, unsupported platform). Exit non-zero. No silent fallback to the
8
+ // Node shim — the shim is NOT a real server.
9
+ // - No retry logic in v1. The user retries manually.
10
+ // - Detect unsupported platform/arch BEFORE download; print supported RIDs.
11
+ // - Verify SHA256 after download; fail on mismatch.
12
+ // - Print final binary path on success.
13
+ //
14
+ // Fall-back command suggested in every error message:
15
+ // dotnet tool install -g mssql-mcp
16
+ 'use strict';
17
+
18
+ const crypto = require('crypto');
19
+ const fs = require('fs');
20
+ const https = require('https');
21
+ const os = require('os');
22
+ const path = require('path');
23
+ const { spawnSync } = require('child_process');
24
+
25
+ const REPO = 'codegiveness/mssql-mcp';
26
+ const BIN_DIR = path.join(__dirname, 'bin');
27
+ const BIN_PATH = path.join(BIN_DIR, 'mssql-mcp');
28
+
29
+ // (platform, arch) -> RID. win-x64 is framework-dependent per ADR-0002.
30
+ function ridFor(platform, arch) {
31
+ if (platform === 'linux' && arch === 'x64') return 'linux-x64';
32
+ if (platform === 'linux' && arch === 'arm64') return 'linux-arm64';
33
+ if (platform === 'darwin' && arch === 'x64') return 'osx-x64';
34
+ if (platform === 'darwin' && arch === 'arm64') return 'osx-arm64';
35
+ if (platform === 'win32' && arch === 'x64') return 'win-x64';
36
+ return null;
37
+ }
38
+
39
+ function archiveExt(rid) {
40
+ return rid === 'win-x64' ? '.zip' : '.tar.gz';
41
+ }
42
+
43
+ function die(message) {
44
+ console.error('mssql-mcp: ' + message);
45
+ console.error('');
46
+ console.error('Falling back is not automatic. You can install the .NET tool instead:');
47
+ console.error(' dotnet tool install -g mssql-mcp');
48
+ process.exit(1);
49
+ }
50
+
51
+ // Follow up to 3 HTTP redirects (GitHub releases redirect to S3/CDN).
52
+ // Hard depth limit prevents redirect loops from hanging or stack-overflowing.
53
+ const MAX_REDIRECTS = 3;
54
+
55
+ function fetchUrl(url, depth) {
56
+ if (depth === undefined) depth = 0;
57
+ return new Promise((resolve, reject) => {
58
+ if (depth > MAX_REDIRECTS) {
59
+ reject(new Error('too many redirects (>' + MAX_REDIRECTS + ') starting from ' + url));
60
+ return;
61
+ }
62
+ const req = https.get(url, (res) => {
63
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
64
+ res.resume();
65
+ fetchUrl(res.headers.location, depth + 1).then(resolve, reject);
66
+ return;
67
+ }
68
+ if (res.statusCode !== 200) {
69
+ res.resume();
70
+ reject(new Error('HTTP ' + res.statusCode + ' for ' + url));
71
+ return;
72
+ }
73
+ const chunks = [];
74
+ res.on('data', (c) => chunks.push(c));
75
+ res.on('end', () => resolve(Buffer.concat(chunks)));
76
+ });
77
+ req.on('error', reject);
78
+ req.setTimeout(60000, () => {
79
+ req.destroy(new Error('timeout downloading ' + url));
80
+ });
81
+ });
82
+ }
83
+
84
+ function sha256Hex(buf) {
85
+ return crypto.createHash('sha256').update(buf).digest('hex');
86
+ }
87
+
88
+ // Classify a download error from fetchUrl into an actionable reason string.
89
+ // Inspects the error message for HTTP status codes and the error code for
90
+ // network-level failures (ECONNRESET, ENOTFOUND, ECONNREFUSED).
91
+ function classifyDownloadError(err) {
92
+ if (err && err.message && /HTTP 404\b/.test(err.message)) return 'release not published yet';
93
+ if (err && (err.code === 'ECONNRESET' || err.code === 'ENOTFOUND' || err.code === 'ECONNREFUSED')) {
94
+ return 'network or proxy blocked';
95
+ }
96
+ if (err && err.message && /timeout/i.test(err.message)) return 'timed out';
97
+ return 'download failed';
98
+ }
99
+
100
+ // Parse a .sha256 sidecar file. Accepts "<hex> <filename>" or bare "<hex>".
101
+ function parseChecksumFile(text) {
102
+ const trimmed = text.trim();
103
+ if (/^[0-9a-fA-F]{64}$/.test(trimmed)) return trimmed.toLowerCase();
104
+ // "<hex> <filename>" form (sha256sum output).
105
+ const match = trimmed.match(/^([0-9a-fA-F]{64})\s+\*?\S/);
106
+ if (match) return match[1].toLowerCase();
107
+ // Last resort: first 64-hex-char run anywhere in the file.
108
+ const any = trimmed.match(/[0-9a-fA-F]{64}/);
109
+ if (any) return any[0].toLowerCase();
110
+ throw new Error('checksum file has no 64-hex SHA256 token');
111
+ }
112
+
113
+ function extractTarGz(archivePath, outDir) {
114
+ const r = spawnSync('tar', ['-xzf', archivePath, '-C', outDir], { stdio: 'inherit' });
115
+ if (r.status !== 0) {
116
+ throw new Error('tar exited with status ' + r.status);
117
+ }
118
+ }
119
+
120
+ function extractZip(archivePath, outDir) {
121
+ // Validate entry names before extraction to prevent path traversal (Zip Slip).
122
+ // `unzip -o` alone does not reject entries with ../ or absolute paths.
123
+ const list = spawnSync('unzip', ['-l', archivePath], { encoding: 'utf8' });
124
+ if (list.status !== 0) {
125
+ throw new Error('unzip -l failed with status ' + list.status);
126
+ }
127
+ const resolvedOut = path.resolve(outDir);
128
+ for (const line of list.stdout.split('\n')) {
129
+ const m = line.match(/^\s+\d+\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+(.+)$/);
130
+ if (!m) continue;
131
+ const entryPath = m[1].trim();
132
+ const resolvedEntry = path.resolve(outDir, entryPath);
133
+ if (!resolvedEntry.startsWith(resolvedOut + path.sep) && resolvedEntry !== resolvedOut) {
134
+ throw new Error('Refusing to extract zip entry outside target directory: ' + entryPath);
135
+ }
136
+ }
137
+
138
+ const r = spawnSync('unzip', ['-o', archivePath, '-d', outDir], { stdio: 'inherit' });
139
+ if (r.status !== 0) {
140
+ throw new Error('unzip exited with status ' + r.status + ' (is unzip installed?)');
141
+ }
142
+ }
143
+
144
+ async function main() {
145
+ const rid = ridFor(process.platform, process.arch);
146
+ if (!rid) {
147
+ console.error('mssql-mcp: unsupported platform/architecture.');
148
+ console.error(' detected: platform=' + process.platform + ', arch=' + process.arch);
149
+ console.error(' supported RIDs: linux-x64, linux-arm64, osx-x64, osx-arm64, win-x64');
150
+ die('cannot resolve a binary for this platform.');
151
+ return; // unreachable; die exits
152
+ }
153
+
154
+ // Resolve version from this package's package.json.
155
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
156
+ const version = pkg.version;
157
+ if (!version) {
158
+ die('package.json has no version field; cannot determine which release to download.');
159
+ return;
160
+ }
161
+ const tag = 'v' + version;
162
+
163
+ const ext = archiveExt(rid);
164
+ const basename = 'mssql-mcp-' + version + '-' + rid + ext;
165
+ const archiveUrl = 'https://github.com/' + REPO + '/releases/download/' + tag + '/' + basename;
166
+ const checksumUrl = archiveUrl + '.sha256';
167
+
168
+ console.log('mssql-mcp: installing v' + version + ' for ' + rid);
169
+ console.log('mssql-mcp: downloading ' + archiveUrl);
170
+
171
+ let archiveBuf;
172
+ try {
173
+ archiveBuf = await fetchUrl(archiveUrl);
174
+ } catch (e) {
175
+ die('download failed for archive [' + classifyDownloadError(e) + ']: ' + e.message + '\n URL: ' + archiveUrl);
176
+ return;
177
+ }
178
+
179
+ console.log('mssql-mcp: downloading ' + checksumUrl);
180
+ let checksumBuf;
181
+ try {
182
+ checksumBuf = await fetchUrl(checksumUrl);
183
+ } catch (e) {
184
+ die('download failed for checksum [' + classifyDownloadError(e) + ']: ' + e.message + '\n URL: ' + checksumUrl);
185
+ return;
186
+ }
187
+
188
+ const expected = parseChecksumFile(checksumBuf.toString('utf8'));
189
+ const actual = sha256Hex(archiveBuf);
190
+ if (expected !== actual) {
191
+ die(
192
+ 'SHA256 mismatch.\n' +
193
+ ' expected: ' + expected + '\n' +
194
+ ' actual: ' + actual + '\n' +
195
+ ' archive: ' + archiveUrl
196
+ );
197
+ return;
198
+ }
199
+ console.log('mssql-mcp: checksum verified (' + expected + ')');
200
+
201
+ // Stage the archive in a temp dir, extract, then move the binary into bin/.
202
+ if (!fs.existsSync(BIN_DIR)) fs.mkdirSync(BIN_DIR, { recursive: true });
203
+
204
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mssql-mcp-install-'));
205
+ try {
206
+ const archivePath = path.join(tmpRoot, basename);
207
+ fs.writeFileSync(archivePath, archiveBuf);
208
+
209
+ const extractDir = path.join(tmpRoot, 'extract');
210
+ fs.mkdirSync(extractDir, { recursive: true });
211
+ if (ext === '.zip') {
212
+ extractZip(archivePath, extractDir);
213
+ } else {
214
+ extractTarGz(archivePath, extractDir);
215
+ }
216
+
217
+ // Flat archive per sqz: binary at archive root, named `mssql-mcp` (Unix) or
218
+ // `mssql-mcp.exe` (Windows). Look for both to be defensive.
219
+ const candidates = [
220
+ path.join(extractDir, 'mssql-mcp'),
221
+ path.join(extractDir, 'mssql-mcp.exe'),
222
+ ].filter((p) => fs.existsSync(p));
223
+ if (candidates.length === 0) {
224
+ die('extraction produced no `mssql-mcp` binary. Archive: ' + archiveUrl);
225
+ return;
226
+ }
227
+ const extractedBin = candidates[0];
228
+
229
+ // Overwrite the shim with the real binary.
230
+ fs.copyFileSync(extractedBin, BIN_PATH);
231
+ if (process.platform !== 'win32') {
232
+ fs.chmodSync(BIN_PATH, 0o755);
233
+ }
234
+
235
+ console.log('mssql-mcp: installed binary to ' + BIN_PATH);
236
+ } finally {
237
+ // Best-effort cleanup; never fail the install over tempdir removal.
238
+ try {
239
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
240
+ } catch (_) {
241
+ // ignored
242
+ }
243
+ }
244
+ }
245
+
246
+ // Run main() only when invoked directly as `node install.js` (npm postinstall),
247
+ // not when required by the smoke test (npm/test.js).
248
+ if (require.main === module) {
249
+ main().catch((e) => {
250
+ die('unexpected error: ' + (e && e.stack ? e.stack : String(e)));
251
+ });
252
+ }
253
+
254
+ // Exposed for the smoke test in npm/test.js. Not part of the public API.
255
+ module.exports = { ridFor, archiveExt, parseChecksumFile, classifyDownloadError };
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@codegiveness/mssql-mcp",
3
+ "version": "0.2.0",
4
+ "description": "A Model Context Protocol (MCP) server for Microsoft SQL Server, built in C#/.NET 10",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/codegiveness/mssql-mcp"
9
+ },
10
+ "bin": {
11
+ "mssql-mcp": "bin/mssql-mcp"
12
+ },
13
+ "scripts": {
14
+ "postinstall": "node install.js"
15
+ },
16
+ "files": [
17
+ "bin/",
18
+ "install.js"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18"
22
+ }
23
+ }