saagar-mcp-kit 0.1.0 → 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.
- package/CHANGELOG.md +15 -0
- package/README.md +94 -16
- package/bin/mcp-kit-parity.mjs +15 -29
- package/bin/mcp-kit-sign.mjs +49 -57
- package/bin/mcp-kit-smoke +90 -52
- package/lib/http-probe.mjs +89 -32
- package/lib/internal/protocol.mjs +33 -0
- package/lib/signing.mjs +66 -12
- package/lib/stdio-probe.mjs +116 -92
- package/package.json +6 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
- **Breaking for callers that verified without a pin.** Supply an independently
|
|
6
|
+
trusted publisher key with `--trusted-pub` for `mcp-kit-sign verify` and
|
|
7
|
+
`verify-pinned`, or with `trustedPubPath` for `verifyManifest`.
|
|
8
|
+
- Verification rejects paths that alias the bundled public key, including
|
|
9
|
+
symlinks and hard links. It compares the bundled key with the publisher pin
|
|
10
|
+
before checking the manifest signature.
|
|
11
|
+
|
|
12
|
+
## 0.1.0
|
|
13
|
+
|
|
14
|
+
- Initial release with Ed25519 manifest signing, HTTP and stdio probes, version
|
|
15
|
+
parity checks, Worker helpers, and a Wrangler smoke harness.
|
package/README.md
CHANGED
|
@@ -5,11 +5,14 @@ scaffolding that every server previously carried as hand-forked scripts:
|
|
|
5
5
|
Ed25519 manifest signing, HTTP and stdio protocol probes, server.json version
|
|
6
6
|
parity, Worker CORS helpers, and a wrangler smoke harness.
|
|
7
7
|
|
|
8
|
-
Zero runtime dependencies. Node >=
|
|
9
|
-
|
|
8
|
+
Zero runtime dependencies. Node >= 22. To test a fresh clone, see **Testing**.
|
|
9
|
+
To use this checkout in a consumer project, install it as a **devDependency**
|
|
10
|
+
from that project (assuming the clone is at `../mcp-kit`). The npm registry's
|
|
11
|
+
0.1.0 release lacks the pinned verifier used below. Signing, probes, parity,
|
|
12
|
+
and smoke are development tools. Bundle the Worker helpers with your Worker.
|
|
10
13
|
|
|
11
14
|
```sh
|
|
12
|
-
npm install --save-dev
|
|
15
|
+
npm install --save-dev ../mcp-kit
|
|
13
16
|
```
|
|
14
17
|
|
|
15
18
|
## What's inside
|
|
@@ -29,30 +32,62 @@ kit's drivers.
|
|
|
29
32
|
|
|
30
33
|
## Usage
|
|
31
34
|
|
|
35
|
+
Run the CLI examples from the consumer project. Its npm scripts can use the bin
|
|
36
|
+
names directly. In a shell, run `export PATH="$PWD/node_modules/.bin:$PATH"` first.
|
|
37
|
+
|
|
32
38
|
### Signing
|
|
33
39
|
|
|
40
|
+
Start with your manifest at `.well-known/mcp.json`. For verification, provision
|
|
41
|
+
`publisher-pin.pub` through an independently authenticated channel.
|
|
42
|
+
|
|
34
43
|
```sh
|
|
35
44
|
mcp-kit-sign gen-key --manifest=.well-known/mcp.json # one-time keypair
|
|
36
45
|
mcp-kit-sign sign --manifest=.well-known/mcp.json # detached .sig + pubkey
|
|
37
|
-
mcp-kit-sign verify --manifest=.well-known/mcp.json
|
|
46
|
+
mcp-kit-sign verify --manifest=.well-known/mcp.json --trusted-pub=publisher-pin.pub
|
|
38
47
|
```
|
|
39
48
|
|
|
40
49
|
The manifest is signed as raw bytes (no canonicalization): serve the exact
|
|
41
50
|
bytes that were signed, and re-sign after any manifest change. The private key
|
|
42
51
|
defaults to `.signing/mcp-ed25519.key` (gitignore `.signing/`; never commit it).
|
|
43
|
-
|
|
44
|
-
|
|
52
|
+
Verification requires `--trusted-pub` to point to a publisher key obtained and
|
|
53
|
+
pinned independently of the manifest/signature bundle. The bundled public key
|
|
54
|
+
(by default `mcp-ed25519.pub` beside the manifest, overridable with `--pub`)
|
|
55
|
+
is checked against that pin; by itself it establishes integrity only, not who
|
|
56
|
+
published the bundle. Keep the pin in an independently trusted configuration
|
|
57
|
+
or deliver it through a separately authenticated channel.
|
|
58
|
+
|
|
59
|
+
This is a breaking verifier change: existing library or CLI callers without an
|
|
60
|
+
independently provisioned pin will fail closed. Update each caller with its
|
|
61
|
+
publisher's separately authenticated pin before using the new verifier.
|
|
62
|
+
Callers that need a machine-readable assurance should use
|
|
63
|
+
`mcp-kit-sign verify-pinned` with the same flags as `verify`. Its JSON result
|
|
64
|
+
includes the policy and verification status from that invocation.
|
|
65
|
+
|
|
66
|
+
### Probing a stateless JSON HTTP (Worker) server
|
|
67
|
+
|
|
68
|
+
The HTTP probe supports stateless JSON request/response only. Streamable HTTP
|
|
69
|
+
SSE responses, session headers, and initialized notifications are outside its scope.
|
|
70
|
+
The smoke harness passes the server URL to the probe via `--endpoint`.
|
|
71
|
+
Choose a search query that fits your server's corpus.
|
|
45
72
|
|
|
46
73
|
```js
|
|
47
74
|
// scripts/probe-mcp.mjs — the repo keeps only its domain expectations
|
|
75
|
+
import { parseArgs } from "node:util";
|
|
48
76
|
import { probeHttpServer, rpc, parseToolPayload } from "saagar-mcp-kit/http-probe";
|
|
49
77
|
|
|
78
|
+
const { values: { endpoint } } = parseArgs({ options: { endpoint: { type: "string" } } });
|
|
79
|
+
if (!endpoint) throw new Error("Pass --endpoint with the server URL");
|
|
80
|
+
const query = "portfolio";
|
|
81
|
+
|
|
50
82
|
const summary = await probeHttpServer(endpoint, {
|
|
51
83
|
serverName: "saagarpatel-portfolio",
|
|
52
84
|
tools: ["get_document", "get_profile", "list_corpus", "search" /* ... */],
|
|
85
|
+
timeoutMs: 5000, // optional; default 5000. Bounds each initialize / tools/list request.
|
|
53
86
|
});
|
|
54
87
|
// domain calls:
|
|
55
|
-
const search = await rpc(endpoint, 3, "tools/call", { name: "search", arguments: { query } }
|
|
88
|
+
const search = await rpc(endpoint, 3, "tools/call", { name: "search", arguments: { query } }, {
|
|
89
|
+
timeoutMs: 5000, // optional; default 5000. Aborts the request if the Worker hangs.
|
|
90
|
+
});
|
|
56
91
|
const payload = parseToolPayload(search.json.result, "search");
|
|
57
92
|
```
|
|
58
93
|
|
|
@@ -92,8 +127,8 @@ mcp-kit-parity # server.json vs package.json/pypr
|
|
|
92
127
|
mcp-kit-parity --server-json=server.json --package=pyproject.toml
|
|
93
128
|
```
|
|
94
129
|
|
|
95
|
-
The
|
|
96
|
-
|
|
130
|
+
The check compares `server.json`'s top-level version and each `packages[].version`
|
|
131
|
+
with the package manifest version. Run this in CI for every
|
|
97
132
|
franchise repo — npm and PyPI alike.
|
|
98
133
|
|
|
99
134
|
### Smoke harness
|
|
@@ -102,14 +137,23 @@ franchise repo — npm and PyPI alike.
|
|
|
102
137
|
mcp-kit-smoke -- node scripts/probe-mcp.mjs --endpoint "http://127.0.0.1:{port}/mcp"
|
|
103
138
|
```
|
|
104
139
|
|
|
105
|
-
Boots `wrangler dev` on a free port
|
|
106
|
-
`{port}`
|
|
140
|
+
Boots `wrangler dev` on a free port by default. Any HTTP status from `/mcp`
|
|
141
|
+
starts the probe. The harness substitutes `{port}` in its arguments, runs it,
|
|
142
|
+
and tears down.
|
|
107
143
|
|
|
108
144
|
## Adopting in a franchise repo
|
|
109
145
|
|
|
110
146
|
Three-step wiring (portfolio-mcp shown; operant-mcp is identical in shape):
|
|
111
147
|
|
|
112
|
-
1. `npm install --save-dev
|
|
148
|
+
1. Run `npm install --save-dev ../mcp-kit` locally and commit the consumer's
|
|
149
|
+
`package.json` and `package-lock.json`. On a clean CI runner, run these
|
|
150
|
+
commands from the consumer checkout to provision the same relative path
|
|
151
|
+
with a kit commit that includes the pinned verifier:
|
|
152
|
+
```sh
|
|
153
|
+
git clone --no-checkout https://github.com/saagpatel/mcp-kit.git ../mcp-kit
|
|
154
|
+
git -C ../mcp-kit checkout --detach 61051c941f8d7d8cd67194e73e008a20117ddf44
|
|
155
|
+
npm ci
|
|
156
|
+
```
|
|
113
157
|
2. Replace scripts in `package.json`:
|
|
114
158
|
```json
|
|
115
159
|
"sign": "mcp-kit-sign sign --manifest=../portfolio-index/.well-known/mcp.json",
|
|
@@ -120,9 +164,15 @@ Three-step wiring (portfolio-mcp shown; operant-mcp is identical in shape):
|
|
|
120
164
|
repo's expected-tools list, server name, and domain calls; delete
|
|
121
165
|
`scripts/sign-manifest.mjs` and `scripts/smoke-mcp.sh`.
|
|
122
166
|
|
|
123
|
-
Python franchise repos
|
|
124
|
-
|
|
125
|
-
|
|
167
|
+
For parity alone, Python franchise repos can invoke the bin without adding an
|
|
168
|
+
npm dependency to their project:
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
npm exec --package=saagar-mcp-kit -- mcp-kit-parity --server-json=server.json --package=pyproject.toml
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The TOML reader matches an unindented, double-quoted `version = "..."` line in
|
|
175
|
+
`[project]`. It compares the string literally and does not resolve dynamic versions.
|
|
126
176
|
|
|
127
177
|
## Roadmap (deliberately not in v0.1)
|
|
128
178
|
|
|
@@ -133,8 +183,36 @@ Python franchise repos (MCPAudit, mcp-trust, shadow-mcp, mcpforge) can adopt
|
|
|
133
183
|
|
|
134
184
|
## Testing
|
|
135
185
|
|
|
186
|
+
From the kit checkout, run these with the toolchain versions below.
|
|
187
|
+
|
|
136
188
|
```sh
|
|
137
|
-
|
|
189
|
+
make setup
|
|
190
|
+
make check
|
|
138
191
|
```
|
|
139
192
|
|
|
193
|
+
There is no build, lint, format, or type-check step. The smoke harness expects
|
|
194
|
+
Bash, Node.js, curl, and the consumer repository's local `./node_modules/.bin/wrangler`.
|
|
195
|
+
`PORT` can select a port. Readiness and probe execution share the
|
|
196
|
+
`SMOKE_TIMEOUT_SECS` timeout (default 120 seconds).
|
|
197
|
+
|
|
198
|
+
Node 18 support was removed; Node 22 is the minimum supported major version.
|
|
199
|
+
|
|
200
|
+
## Status
|
|
201
|
+
|
|
202
|
+
### Stack
|
|
203
|
+
|
|
204
|
+
Dependency-free Node.js ESM package. Node.js 22 and newer are supported; the
|
|
205
|
+
repository toolchain is pinned to Node.js 26.11.1 and npm 12.2.0.
|
|
206
|
+
|
|
207
|
+
### Known risks
|
|
208
|
+
|
|
209
|
+
The HTTP probe is intentionally stateless JSON and does not implement the full
|
|
210
|
+
Streamable HTTP session/SSE lifecycle. The smoke harness needs the consumer's
|
|
211
|
+
local Wrangler installation and has not been exercised against Cloudflare here.
|
|
212
|
+
|
|
213
|
+
### Next steps
|
|
214
|
+
|
|
215
|
+
Run `make check` locally and rely on the Node.js matrix and macOS CI jobs for
|
|
216
|
+
cross-platform coverage. Full Streamable HTTP support remains a separate design decision.
|
|
217
|
+
|
|
140
218
|
MIT.
|
package/bin/mcp-kit-parity.mjs
CHANGED
|
@@ -1,36 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
// mcp-kit-parity [--server-json=server.json] [--package=package.json|pyproject.toml]
|
|
5
|
-
//
|
|
6
|
-
// Exits 0 on parity, 1 on mismatch, 2 on usage/read errors. Run it in CI so a
|
|
7
|
-
// release can't ship a stale registry entry.
|
|
8
|
-
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
9
3
|
import { existsSync } from "node:fs";
|
|
10
4
|
import { resolve } from "node:path";
|
|
11
5
|
import { checkParity } from "../lib/parity.mjs";
|
|
12
6
|
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
);
|
|
24
|
-
|
|
7
|
+
const HELP = "Usage: mcp-kit-parity [--server-json=PATH] [--package=PATH]\n mcp-kit-parity --help";
|
|
8
|
+
let parsed;
|
|
9
|
+
try {
|
|
10
|
+
parsed = parseArgs({ args: process.argv.slice(2), options: {
|
|
11
|
+
help: { type: "boolean" }, "server-json": { type: "string" }, package: { type: "string" },
|
|
12
|
+
}, strict: true, allowPositionals: true });
|
|
13
|
+
} catch (error) { console.error(`${error.message}\n${HELP}`); process.exit(2); }
|
|
14
|
+
if (parsed.values.help) { console.log(HELP); process.exit(0); }
|
|
15
|
+
if (parsed.positionals.length) { console.error(`unexpected positional argument: ${parsed.positionals[0]}\n${HELP}`); process.exit(2); }
|
|
16
|
+
const serverJsonPath = resolve(parsed.values["server-json"] ?? "server.json");
|
|
17
|
+
const packagePath = resolve(parsed.values.package ?? (existsSync("package.json") ? "package.json" : "pyproject.toml"));
|
|
25
18
|
try {
|
|
26
19
|
const { ok, version, problems } = checkParity({ serverJsonPath, packagePath });
|
|
27
|
-
if (ok) {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
for (const p of problems) console.error(`parity FAIL: ${p}`);
|
|
32
|
-
process.exit(1);
|
|
33
|
-
} catch (err) {
|
|
34
|
-
console.error(err?.message ?? String(err));
|
|
35
|
-
process.exit(2);
|
|
36
|
-
}
|
|
20
|
+
if (ok) console.log(`version parity OK: ${version}`);
|
|
21
|
+
else { for (const problem of problems) console.error(`parity FAIL: ${problem}`); process.exitCode = 1; }
|
|
22
|
+
} catch (error) { console.error(error?.message ?? String(error)); process.exitCode = 2; }
|
package/bin/mcp-kit-sign.mjs
CHANGED
|
@@ -1,62 +1,54 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
// mcp-kit-sign gen-key --manifest=PATH [--key=PATH] [--pub=PATH]
|
|
5
|
-
// mcp-kit-sign sign --manifest=PATH [--key=PATH] [--pub=PATH] [--sig=PATH]
|
|
6
|
-
// mcp-kit-sign verify --manifest=PATH [--pub=PATH] [--sig=PATH]
|
|
7
|
-
//
|
|
8
|
-
// --manifest is required (no machine-shaped defaults). --key defaults to
|
|
9
|
-
// .signing/mcp-ed25519.key under the CWD; pub/sig default to sitting next to
|
|
10
|
-
// the manifest. The private key is NEVER committed.
|
|
11
|
-
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
12
3
|
import { resolve } from "node:path";
|
|
13
4
|
import { defaultPaths, generateKeypair, signManifest, verifyManifest } from "../lib/signing.mjs";
|
|
14
5
|
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
return args.find((a) => a.startsWith(pre))?.slice(pre.length) ?? def;
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
const manifestFlag = flag("manifest");
|
|
23
|
-
if (!manifestFlag) {
|
|
24
|
-
console.error("--manifest=PATH is required");
|
|
25
|
-
process.exit(2);
|
|
26
|
-
}
|
|
27
|
-
const manifestPath = resolve(manifestFlag);
|
|
28
|
-
const derived = defaultPaths(manifestPath);
|
|
29
|
-
const keyPath = resolve(flag("key", ".signing/mcp-ed25519.key"));
|
|
30
|
-
const pubPath = resolve(flag("pub", derived.pubPath));
|
|
31
|
-
const sigPath = resolve(flag("sig", derived.sigPath));
|
|
32
|
-
|
|
33
|
-
const commands = {
|
|
34
|
-
"gen-key": () => {
|
|
35
|
-
generateKeypair({ keyPath, pubPath });
|
|
36
|
-
console.log(`private key -> ${keyPath} (chmod 600 — NEVER commit)`);
|
|
37
|
-
console.log(`public key -> ${pubPath} (publish this next to the manifest)`);
|
|
38
|
-
},
|
|
39
|
-
sign: () => {
|
|
40
|
-
signManifest({ manifestPath, keyPath, sigPath, pubPath });
|
|
41
|
-
console.log(`signed ${manifestPath}`);
|
|
42
|
-
console.log(` -> ${sigPath} (base64 Ed25519, detached)`);
|
|
43
|
-
console.log(` -> ${pubPath} (public key)`);
|
|
44
|
-
},
|
|
45
|
-
verify: () => {
|
|
46
|
-
const ok = verifyManifest({ manifestPath, sigPath, pubPath });
|
|
47
|
-
console.log(ok ? "signature VALID" : "signature INVALID");
|
|
48
|
-
process.exit(ok ? 0 : 1);
|
|
49
|
-
},
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
const run = commands[cmd];
|
|
53
|
-
if (!run) {
|
|
54
|
-
console.error(`unknown command "${cmd}" — use: gen-key | sign | verify`);
|
|
55
|
-
process.exit(2);
|
|
56
|
-
}
|
|
6
|
+
const HELP = `Usage: mcp-kit-sign <gen-key|sign|verify|verify-pinned> --manifest=PATH [--key=PATH] [--pub=PATH] [--sig=PATH] [--trusted-pub=PATH]\n mcp-kit-sign --help`;
|
|
7
|
+
const commands = new Map();
|
|
8
|
+
const usageError = (message) => { console.error(`${message}\n${HELP}`); process.exit(2); };
|
|
9
|
+
let parsed;
|
|
57
10
|
try {
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
11
|
+
parsed = parseArgs({ args: process.argv.slice(2), options: {
|
|
12
|
+
help: { type: "boolean" }, manifest: { type: "string" }, key: { type: "string" },
|
|
13
|
+
pub: { type: "string" }, sig: { type: "string" }, "trusted-pub": { type: "string" },
|
|
14
|
+
}, strict: true, allowPositionals: true });
|
|
15
|
+
} catch (error) { usageError(error.message); }
|
|
16
|
+
if (parsed.values.help) { console.log(HELP); process.exit(0); }
|
|
17
|
+
if (parsed.positionals.length !== 1) usageError("exactly one command is required");
|
|
18
|
+
const [cmd] = parsed.positionals;
|
|
19
|
+
if (!new Set(["gen-key", "sign", "verify", "verify-pinned"]).has(cmd)) usageError(`unknown command "${cmd}"`);
|
|
20
|
+
if (!parsed.values.manifest) usageError("--manifest=PATH is required");
|
|
21
|
+
const manifestPath = resolve(parsed.values.manifest);
|
|
22
|
+
const derived = defaultPaths(manifestPath);
|
|
23
|
+
const keyPath = resolve(parsed.values.key ?? ".signing/mcp-ed25519.key");
|
|
24
|
+
const pubPath = resolve(parsed.values.pub ?? derived.pubPath);
|
|
25
|
+
const sigPath = resolve(parsed.values.sig ?? derived.sigPath);
|
|
26
|
+
const trustedPubPath = parsed.values["trusted-pub"] ? resolve(parsed.values["trusted-pub"]) : undefined;
|
|
27
|
+
commands.set("gen-key", () => {
|
|
28
|
+
generateKeypair({ keyPath, pubPath });
|
|
29
|
+
console.log(`private key -> ${keyPath} (mode 600 — NEVER commit)`);
|
|
30
|
+
console.log(`public key -> ${pubPath} (publish this next to the manifest)`);
|
|
31
|
+
});
|
|
32
|
+
commands.set("sign", () => {
|
|
33
|
+
signManifest({ manifestPath, keyPath, sigPath, pubPath });
|
|
34
|
+
console.log(`signed ${manifestPath}\n -> ${sigPath} (base64 Ed25519, detached)\n -> ${pubPath} (public key)`);
|
|
35
|
+
});
|
|
36
|
+
commands.set("verify", () => {
|
|
37
|
+
if (!trustedPubPath) usageError("verify requires --trusted-pub=PATH (obtained independently of the manifest bundle)");
|
|
38
|
+
const ok = verifyManifest({ manifestPath, sigPath, pubPath, trustedPubPath });
|
|
39
|
+
console.log(ok ? "signature VALID" : "signature INVALID");
|
|
40
|
+
if (!ok) process.exitCode = 1;
|
|
41
|
+
});
|
|
42
|
+
commands.set("verify-pinned", () => {
|
|
43
|
+
if (!trustedPubPath) usageError("verify-pinned requires --trusted-pub=PATH (obtained independently of the manifest bundle)");
|
|
44
|
+
const ok = verifyManifest({ manifestPath, sigPath, pubPath, trustedPubPath });
|
|
45
|
+
console.log(JSON.stringify({
|
|
46
|
+
tool: "mcp-kit-sign",
|
|
47
|
+
command: "verify-pinned",
|
|
48
|
+
policy: "verify-independent-publisher-pin-v1",
|
|
49
|
+
status: ok ? "verified" : "invalid",
|
|
50
|
+
}));
|
|
51
|
+
if (!ok) process.exitCode = 1;
|
|
52
|
+
});
|
|
53
|
+
try { commands.get(cmd)(); }
|
|
54
|
+
catch (error) { console.error(error?.message ?? String(error)); process.exitCode = 1; }
|
package/bin/mcp-kit-smoke
CHANGED
|
@@ -1,67 +1,105 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
|
-
#
|
|
3
|
-
|
|
4
|
-
# tear everything down. Generalized from the per-repo smoke-mcp.sh scripts.
|
|
5
|
-
#
|
|
6
|
-
# mcp-kit-smoke -- node scripts/probe-mcp.mjs --endpoint "http://127.0.0.1:{port}/mcp"
|
|
7
|
-
#
|
|
8
|
-
# Run from the repo that owns wrangler.jsonc. Exits non-zero if wrangler never
|
|
9
|
-
# becomes ready or the probe fails.
|
|
10
|
-
set -euo pipefail
|
|
2
|
+
# Run a consumer's probe against its local wrangler dev process.
|
|
3
|
+
set -Eeuo pipefail
|
|
11
4
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
fi
|
|
16
|
-
shift
|
|
17
|
-
|
|
18
|
-
LOG="$(mktemp -t wdev.XXXXXX)"
|
|
19
|
-
PORT="${PORT:-$(python3 - <<'PY'
|
|
20
|
-
import socket
|
|
21
|
-
|
|
22
|
-
with socket.socket() as s:
|
|
23
|
-
s.bind(("127.0.0.1", 0))
|
|
24
|
-
print(s.getsockname()[1])
|
|
25
|
-
PY
|
|
26
|
-
)}"
|
|
27
|
-
|
|
28
|
-
npx wrangler dev --port "$PORT" --ip 127.0.0.1 >"$LOG" 2>&1 &
|
|
29
|
-
WPID=$!
|
|
5
|
+
LOG=""
|
|
6
|
+
MANAGER_PID=""
|
|
7
|
+
PROBE_PID=""
|
|
30
8
|
cleanup() {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
9
|
+
local status=$?
|
|
10
|
+
trap - EXIT INT TERM
|
|
11
|
+
if [[ -n "$PROBE_PID" ]] && kill -0 "$PROBE_PID" 2>/dev/null; then
|
|
12
|
+
kill -TERM "$PROBE_PID" 2>/dev/null || true
|
|
13
|
+
wait "$PROBE_PID" 2>/dev/null || true
|
|
14
|
+
fi
|
|
15
|
+
if [[ -n "$MANAGER_PID" ]] && kill -0 "$MANAGER_PID" 2>/dev/null; then
|
|
16
|
+
kill -TERM "$MANAGER_PID" 2>/dev/null || true
|
|
17
|
+
wait "$MANAGER_PID" 2>/dev/null || true
|
|
18
|
+
fi
|
|
19
|
+
if [[ -n "$LOG" && -f "$LOG" ]]; then
|
|
20
|
+
echo "=== wrangler log ==="
|
|
21
|
+
cat "$LOG"
|
|
22
|
+
rm -f "$LOG"
|
|
23
|
+
fi
|
|
24
|
+
exit "$status"
|
|
36
25
|
}
|
|
37
26
|
trap cleanup EXIT
|
|
27
|
+
trap 'exit 130' INT
|
|
28
|
+
trap 'exit 143' TERM
|
|
38
29
|
|
|
30
|
+
HELP='Usage: mcp-kit-smoke [--help] -- <probe command with {port} placeholder>
|
|
31
|
+
Requires Node.js, curl, and the consumer repository local wrangler install.
|
|
32
|
+
PORT optionally selects the local port; SMOKE_TIMEOUT_SECS sets the total deadline (default 120).'
|
|
33
|
+
if [[ "${1:-}" == "--help" && "$#" -eq 1 ]]; then echo "$HELP"; exit 0; fi
|
|
34
|
+
if [[ "${1:-}" != "--" || "$#" -lt 2 ]]; then echo "$HELP" >&2; exit 2; fi
|
|
35
|
+
shift
|
|
36
|
+
|
|
37
|
+
deadline="${SMOKE_TIMEOUT_SECS:-120}"
|
|
38
|
+
if ! [[ "$deadline" =~ ^[1-9][0-9]*$ ]]; then echo "SMOKE_TIMEOUT_SECS must be a positive integer" >&2; exit 2; fi
|
|
39
|
+
wrangler="./node_modules/.bin/wrangler"
|
|
40
|
+
if [[ ! -x "$wrangler" ]]; then
|
|
41
|
+
echo "wrangler not found at $wrangler; install it in the consumer repo (for example: npm install --save-dev wrangler)" >&2
|
|
42
|
+
exit 127
|
|
43
|
+
fi
|
|
44
|
+
LOG="$(mktemp "${TMPDIR:-/tmp}/mcp-kit-smoke.XXXXXX")"
|
|
45
|
+
if [[ -z "${PORT:-}" ]]; then
|
|
46
|
+
PORT="$(node -e 'const net=require("node:net");const s=net.createServer();s.listen(0,"127.0.0.1",()=>{console.log(s.address().port);s.close()})')"
|
|
47
|
+
fi
|
|
48
|
+
if ! [[ "$PORT" =~ ^[0-9]+$ ]] || (( PORT < 1 || PORT > 65535 )); then echo "PORT must be a valid TCP port" >&2; exit 2; fi
|
|
49
|
+
|
|
50
|
+
# The small Node supervisor owns a detached process group, forwards termination,
|
|
51
|
+
# escalates after a grace period, and waits for the wrangler process to exit.
|
|
52
|
+
node -e '
|
|
53
|
+
const {spawn}=require("node:child_process");
|
|
54
|
+
const child=spawn(process.argv[1],["dev","--port",process.argv[2],"--ip","127.0.0.1"],{detached:true,stdio:"inherit"});
|
|
55
|
+
let stopping=false,spawnFailure=false;
|
|
56
|
+
child.on("error",e=>{console.error(e.message);spawnFailure=true});
|
|
57
|
+
child.on("close",(code,signal)=>{if(!stopping)process.exit(spawnFailure?127:(code??(signal?1:0)))});
|
|
58
|
+
const signal=signum=>{try{process.kill(-child.pid,signum)}catch{};try{child.kill(signum)}catch{}};
|
|
59
|
+
const stop=()=>{if(stopping)return;stopping=true;signal("SIGTERM");const timer=setTimeout(()=>signal("SIGKILL"),500);timer.unref();child.once("close",()=>{clearTimeout(timer);process.exit(0)})};
|
|
60
|
+
process.on("SIGTERM",stop);process.on("SIGINT",stop);
|
|
61
|
+
' "$wrangler" "$PORT" >"$LOG" 2>&1 &
|
|
62
|
+
MANAGER_PID=$!
|
|
63
|
+
# SECONDS counts whole seconds from a fractional start, so it can read one
|
|
64
|
+
# second high; compare with > so the deadline is never reached early.
|
|
65
|
+
SECONDS=0
|
|
39
66
|
ready=0
|
|
40
|
-
secs=0
|
|
41
67
|
code=000
|
|
42
|
-
|
|
43
|
-
code
|
|
44
|
-
[ -
|
|
45
|
-
if [ "$code" !=
|
|
46
|
-
|
|
47
|
-
secs=$i
|
|
48
|
-
break
|
|
49
|
-
fi
|
|
50
|
-
if ! kill -0 "$WPID" 2>/dev/null; then
|
|
51
|
-
echo "!! wrangler exited early"
|
|
52
|
-
break
|
|
53
|
-
fi
|
|
68
|
+
while (( SECONDS <= deadline )); do
|
|
69
|
+
code="$(curl --connect-timeout 1 --max-time 2 -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/mcp" 2>/dev/null || true)"
|
|
70
|
+
[[ -n "$code" ]] || code=000
|
|
71
|
+
if [[ "$code" != 000 ]]; then ready=1; break; fi
|
|
72
|
+
if ! kill -0 "$MANAGER_PID" 2>/dev/null; then echo "!! wrangler exited early" >&2; break; fi
|
|
54
73
|
sleep 1
|
|
55
74
|
done
|
|
56
|
-
echo "ready=$ready after ${
|
|
57
|
-
|
|
58
|
-
if
|
|
75
|
+
echo "ready=$ready after ${SECONDS}s (/mcp returned HTTP ${code} on port ${PORT})"
|
|
76
|
+
if [[ "$ready" != 1 ]]; then
|
|
77
|
+
if (( SECONDS > deadline )); then echo "smoke timed out after ${deadline}s" >&2; exit 124; fi
|
|
59
78
|
exit 1
|
|
60
79
|
fi
|
|
61
80
|
|
|
62
|
-
# Substitute {port} in every probe arg, then run the probe.
|
|
63
81
|
probe=()
|
|
64
|
-
for arg in "$@"; do
|
|
65
|
-
|
|
82
|
+
for arg in "$@"; do probe+=("${arg//\{port\}/$PORT}"); done
|
|
83
|
+
# The probe also gets an owned process group so interrupted or timed-out probes
|
|
84
|
+
# cannot leave grandchildren behind.
|
|
85
|
+
node -e '
|
|
86
|
+
const {spawn}=require("node:child_process");
|
|
87
|
+
const child=spawn(process.argv[1],process.argv.slice(2),{detached:true,stdio:"inherit"});
|
|
88
|
+
let stopping=false,spawnFailure=false;
|
|
89
|
+
child.on("error",e=>{console.error(e.message);spawnFailure=true});
|
|
90
|
+
child.on("close",(code,signal)=>{if(!stopping)process.exit(spawnFailure?127:(code??(signal?1:0)))});
|
|
91
|
+
const signal=signum=>{try{process.kill(-child.pid,signum)}catch{};try{child.kill(signum)}catch{}};
|
|
92
|
+
const stop=()=>{if(stopping)return;stopping=true;signal("SIGTERM");const timer=setTimeout(()=>signal("SIGKILL"),500);timer.unref();child.once("close",()=>{clearTimeout(timer);process.exit(0)})};
|
|
93
|
+
process.on("SIGTERM",stop);process.on("SIGINT",stop);
|
|
94
|
+
' "${probe[@]}" &
|
|
95
|
+
PROBE_PID=$!
|
|
96
|
+
while kill -0 "$PROBE_PID" 2>/dev/null; do
|
|
97
|
+
if (( SECONDS > deadline )); then echo "smoke timed out after ${deadline}s" >&2; exit 124; fi
|
|
98
|
+
sleep 0.1
|
|
66
99
|
done
|
|
67
|
-
|
|
100
|
+
set +e
|
|
101
|
+
wait "$PROBE_PID"
|
|
102
|
+
status=$?
|
|
103
|
+
set -e
|
|
104
|
+
PROBE_PID=""
|
|
105
|
+
exit "$status"
|
package/lib/http-probe.mjs
CHANGED
|
@@ -1,25 +1,67 @@
|
|
|
1
|
-
// Generic
|
|
1
|
+
// Generic stateless JSON HTTP probe driver: JSON-RPC transport plus the
|
|
2
2
|
// protocol-level assertions every baked-corpus server shares (initialize
|
|
3
3
|
// answers with the right server name; tools/list matches the expected set;
|
|
4
4
|
// every tool is annotated read-only). Domain-specific tool calls stay in each
|
|
5
5
|
// server's own probe script, built on `rpc` / `parseToolPayload`.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
7
|
+
import {
|
|
8
|
+
validateInitializeResult,
|
|
9
|
+
validateResponse,
|
|
10
|
+
validateToolCallResult,
|
|
11
|
+
validateToolsResult,
|
|
12
|
+
} from "./internal/protocol.mjs";
|
|
13
|
+
|
|
14
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* POST one JSON-RPC message; throws on HTTP, parse, JSON-RPC, or timeout errors.
|
|
18
|
+
*
|
|
19
|
+
* @param {string} endpoint stateless JSON MCP HTTP endpoint URL
|
|
20
|
+
* @param {number|string} id JSON-RPC id
|
|
21
|
+
* @param {string} method JSON-RPC method
|
|
22
|
+
* @param {object} [params] JSON-RPC params (omitted from the body when undefined)
|
|
23
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
24
|
+
* @param {number} [options.timeoutMs=5000] abort the request after this many ms
|
|
25
|
+
* @returns {Promise<{ status: number, contentType: string|null, allowOrigin: string|null, json: object }>}
|
|
26
|
+
*/
|
|
27
|
+
export async function rpc(endpoint, id, method, params, options) {
|
|
28
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
29
|
+
const controller = new AbortController();
|
|
30
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
31
|
+
let res;
|
|
32
|
+
let text;
|
|
33
|
+
let contentType;
|
|
34
|
+
try {
|
|
35
|
+
res = await fetch(endpoint, {
|
|
36
|
+
method: "POST",
|
|
37
|
+
headers: {
|
|
38
|
+
"Content-Type": "application/json",
|
|
39
|
+
Accept: "application/json, text/event-stream",
|
|
40
|
+
},
|
|
41
|
+
body: JSON.stringify({
|
|
42
|
+
jsonrpc: "2.0",
|
|
43
|
+
id,
|
|
44
|
+
method,
|
|
45
|
+
...(params === undefined ? {} : { params }),
|
|
46
|
+
}),
|
|
47
|
+
signal: controller.signal,
|
|
48
|
+
});
|
|
49
|
+
contentType = res.headers.get("content-type");
|
|
50
|
+
if (contentType?.toLowerCase().includes("text/event-stream")) {
|
|
51
|
+
await res.body?.cancel();
|
|
52
|
+
throw new Error(`${method} unsupported: stateless JSON probe`);
|
|
53
|
+
}
|
|
54
|
+
text = await res.text();
|
|
55
|
+
} catch (err) {
|
|
56
|
+
if (controller.signal.aborted) {
|
|
57
|
+
throw new Error(`${method} timed out after ${timeoutMs}ms contacting ${endpoint}`, {
|
|
58
|
+
cause: err,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
throw err;
|
|
62
|
+
} finally {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
}
|
|
23
65
|
let json;
|
|
24
66
|
try {
|
|
25
67
|
json = JSON.parse(text);
|
|
@@ -31,12 +73,13 @@ export async function rpc(endpoint, id, method, params) {
|
|
|
31
73
|
if (res.status !== 200) {
|
|
32
74
|
throw new Error(`${method} returned HTTP ${res.status}: ${text.slice(0, 300)}`);
|
|
33
75
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
76
|
+
const result = validateResponse(json, id, method);
|
|
77
|
+
if (method === "initialize") validateInitializeResult(result, method);
|
|
78
|
+
if (method === "tools/list") validateToolsResult(result, method);
|
|
79
|
+
if (method === "tools/call") validateToolCallResult(result, method);
|
|
37
80
|
return {
|
|
38
81
|
status: res.status,
|
|
39
|
-
contentType
|
|
82
|
+
contentType,
|
|
40
83
|
allowOrigin: res.headers.get("access-control-allow-origin"),
|
|
41
84
|
json,
|
|
42
85
|
};
|
|
@@ -58,9 +101,15 @@ function assertSame(actual, expected, label) {
|
|
|
58
101
|
/**
|
|
59
102
|
* Run the shared protocol probe: initialize + tools/list with assertions.
|
|
60
103
|
*
|
|
61
|
-
* @param endpoint
|
|
62
|
-
* @param
|
|
63
|
-
* @
|
|
104
|
+
* @param {string} endpoint stateless JSON MCP HTTP endpoint URL
|
|
105
|
+
* @param {object} expect
|
|
106
|
+
* @param {string} [expect.serverName]
|
|
107
|
+
* @param {string[]} [expect.tools]
|
|
108
|
+
* @param {boolean} [expect.requireReadOnly=true]
|
|
109
|
+
* @param {string} [expect.clientName]
|
|
110
|
+
* @param {string} [expect.protocolVersion]
|
|
111
|
+
* @param {number} [expect.timeoutMs=5000] per-request abort bound for initialize and tools/list
|
|
112
|
+
* @returns {Promise<{ endpoint: string, initialize: object, toolsList: object }>} summary for reporting
|
|
64
113
|
*/
|
|
65
114
|
export async function probeHttpServer(endpoint, expect) {
|
|
66
115
|
const {
|
|
@@ -69,13 +118,21 @@ export async function probeHttpServer(endpoint, expect) {
|
|
|
69
118
|
requireReadOnly = true,
|
|
70
119
|
clientName = "mcp-kit-probe",
|
|
71
120
|
protocolVersion = "2025-06-18",
|
|
121
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
72
122
|
} = expect;
|
|
123
|
+
const rpcOptions = { timeoutMs };
|
|
73
124
|
|
|
74
|
-
const initialize = await rpc(
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
125
|
+
const initialize = await rpc(
|
|
126
|
+
endpoint,
|
|
127
|
+
1,
|
|
128
|
+
"initialize",
|
|
129
|
+
{
|
|
130
|
+
protocolVersion,
|
|
131
|
+
capabilities: {},
|
|
132
|
+
clientInfo: { name: clientName, version: "1.0.0" },
|
|
133
|
+
},
|
|
134
|
+
rpcOptions,
|
|
135
|
+
);
|
|
79
136
|
if (serverName && initialize.json.result?.serverInfo?.name !== serverName) {
|
|
80
137
|
throw new Error(
|
|
81
138
|
`initialize returned server ${JSON.stringify(
|
|
@@ -84,8 +141,8 @@ export async function probeHttpServer(endpoint, expect) {
|
|
|
84
141
|
);
|
|
85
142
|
}
|
|
86
143
|
|
|
87
|
-
const toolsList = await rpc(endpoint, 2, "tools/list");
|
|
88
|
-
const tools = toolsList.json.result
|
|
144
|
+
const toolsList = await rpc(endpoint, 2, "tools/list", undefined, rpcOptions);
|
|
145
|
+
const tools = validateToolsResult(toolsList.json.result);
|
|
89
146
|
const toolNames = tools.map((tool) => tool.name).sort();
|
|
90
147
|
if (expectedTools) assertSame(toolNames, [...expectedTools].sort(), "tools/list");
|
|
91
148
|
if (requireReadOnly && !tools.every((tool) => tool.annotations?.readOnlyHint === true)) {
|
|
@@ -98,7 +155,7 @@ export async function probeHttpServer(endpoint, expect) {
|
|
|
98
155
|
status: initialize.status,
|
|
99
156
|
contentType: initialize.contentType,
|
|
100
157
|
allowOrigin: initialize.allowOrigin,
|
|
101
|
-
serverInfo: initialize.json.result
|
|
158
|
+
serverInfo: validateInitializeResult(initialize.json.result),
|
|
102
159
|
protocolVersion: initialize.json.result.protocolVersion,
|
|
103
160
|
},
|
|
104
161
|
toolsList: {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Validate a response envelope and correlate it with its request. */
|
|
2
|
+
export function validateResponse(message, id, method) {
|
|
3
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
|
4
|
+
throw new Error(`${method} returned an invalid JSON-RPC response`);
|
|
5
|
+
}
|
|
6
|
+
if (message.jsonrpc !== "2.0") throw new Error(`${method} returned an invalid JSON-RPC version`);
|
|
7
|
+
if (message.id !== id) {
|
|
8
|
+
throw new Error(`${method} response id mismatch: expected ${JSON.stringify(id)}, got ${JSON.stringify(message.id)}`);
|
|
9
|
+
}
|
|
10
|
+
if (message.error !== undefined) {
|
|
11
|
+
throw new Error(`${method} JSON-RPC error: ${JSON.stringify(message.error)}`);
|
|
12
|
+
}
|
|
13
|
+
return message.result;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function validateInitializeResult(result, method = "initialize") {
|
|
17
|
+
if (!result || typeof result.serverInfo !== "object" || result.serverInfo === null) {
|
|
18
|
+
throw new Error(`${method} result.serverInfo is required`);
|
|
19
|
+
}
|
|
20
|
+
return result.serverInfo;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function validateToolsResult(result, method = "tools/list") {
|
|
24
|
+
if (!result || !Array.isArray(result.tools)) {
|
|
25
|
+
throw new Error(`${method} result.tools must be an array`);
|
|
26
|
+
}
|
|
27
|
+
return result.tools;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function validateToolCallResult(result, method) {
|
|
31
|
+
if (result?.isError === true) throw new Error(`${method} returned isError:true`);
|
|
32
|
+
return result;
|
|
33
|
+
}
|
package/lib/signing.mjs
CHANGED
|
@@ -16,8 +16,39 @@ import {
|
|
|
16
16
|
sign as edSign,
|
|
17
17
|
verify as edVerify,
|
|
18
18
|
} from "node:crypto";
|
|
19
|
-
import {
|
|
20
|
-
import { dirname } from "node:path";
|
|
19
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync, unlinkSync } from "node:fs";
|
|
20
|
+
import { dirname, resolve } from "node:path";
|
|
21
|
+
|
|
22
|
+
function pathIdentity(path) {
|
|
23
|
+
const absolute = resolve(path);
|
|
24
|
+
try { return realpathSync(absolute); }
|
|
25
|
+
catch {
|
|
26
|
+
try { return resolve(realpathSync(dirname(absolute)), absolute.slice(dirname(absolute).length + 1)); }
|
|
27
|
+
catch { return absolute; }
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function samePathIdentity(left, right) {
|
|
32
|
+
if (pathIdentity(left) === pathIdentity(right)) return true;
|
|
33
|
+
try {
|
|
34
|
+
const leftStat = statSync(left, { bigint: true });
|
|
35
|
+
const rightStat = statSync(right, { bigint: true });
|
|
36
|
+
return leftStat.dev === rightStat.dev && leftStat.ino !== 0n && leftStat.ino === rightStat.ino;
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function refuseAliases(paths) {
|
|
43
|
+
const entries = Object.entries(paths).filter(([, path]) => path);
|
|
44
|
+
for (let i = 0; i < entries.length; i += 1) {
|
|
45
|
+
for (let j = i + 1; j < entries.length; j += 1) {
|
|
46
|
+
if (samePathIdentity(entries[i][1], entries[j][1])) {
|
|
47
|
+
throw new Error(`refusing aliased ${entries[i][0]} and ${entries[j][0]} paths`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
21
52
|
|
|
22
53
|
/** Derive the default pub/sig paths from the manifest location. */
|
|
23
54
|
export function defaultPaths(manifestPath) {
|
|
@@ -32,13 +63,15 @@ export function defaultPaths(manifestPath) {
|
|
|
32
63
|
* Returns the written paths.
|
|
33
64
|
*/
|
|
34
65
|
export function generateKeypair({ keyPath, pubPath }) {
|
|
35
|
-
|
|
36
|
-
throw new Error(`refusing to overwrite existing private key: ${keyPath}`);
|
|
37
|
-
}
|
|
66
|
+
refuseAliases({ privateKey: keyPath, publicKey: pubPath });
|
|
38
67
|
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
|
|
39
68
|
mkdirSync(dirname(keyPath), { recursive: true });
|
|
40
|
-
|
|
41
|
-
|
|
69
|
+
try {
|
|
70
|
+
writeFileSync(keyPath, privateKey.export({ type: "pkcs8", format: "pem" }), { flag: "wx", mode: 0o600 });
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.code === "EEXIST") throw new Error(`refusing to overwrite existing private key: ${keyPath}`);
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
42
75
|
mkdirSync(dirname(pubPath), { recursive: true });
|
|
43
76
|
writeFileSync(pubPath, publicKey.export({ type: "spki", format: "pem" }));
|
|
44
77
|
return { keyPath, pubPath };
|
|
@@ -49,18 +82,39 @@ export function generateKeypair({ keyPath, pubPath }) {
|
|
|
49
82
|
* public key next to it when missing. Returns the written paths.
|
|
50
83
|
*/
|
|
51
84
|
export function signManifest({ manifestPath, keyPath, sigPath, pubPath }) {
|
|
85
|
+
refuseAliases({ manifest: manifestPath, signature: sigPath, privateKey: keyPath, publicKey: pubPath });
|
|
52
86
|
const priv = createPrivateKey(readFileSync(keyPath));
|
|
87
|
+
const derivedPublic = createPublicKey(priv);
|
|
88
|
+
if (existsSync(pubPath)) {
|
|
89
|
+
const existingPublic = createPublicKey(readFileSync(pubPath));
|
|
90
|
+
if (!existingPublic.export({ type: "spki", format: "der" }).equals(derivedPublic.export({ type: "spki", format: "der" }))) {
|
|
91
|
+
throw new Error(`existing public key does not match private key: ${pubPath}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
53
94
|
const signature = edSign(null, readFileSync(manifestPath), priv); // Ed25519: algorithm = null
|
|
54
|
-
writeFileSync(
|
|
55
|
-
|
|
56
|
-
|
|
95
|
+
if (!existsSync(pubPath)) writeFileSync(pubPath, derivedPublic.export({ type: "spki", format: "pem" }), { flag: "wx" });
|
|
96
|
+
mkdirSync(dirname(sigPath), { recursive: true });
|
|
97
|
+
const tempPath = resolve(dirname(sigPath), `.${Date.now()}-${process.pid}-${Math.random().toString(16).slice(2)}.sig.tmp`);
|
|
98
|
+
try {
|
|
99
|
+
writeFileSync(tempPath, `${signature.toString("base64")}\n`, { flag: "wx", mode: 0o600 });
|
|
100
|
+
renameSync(tempPath, sigPath);
|
|
101
|
+
} finally {
|
|
102
|
+
if (existsSync(tempPath)) unlinkSync(tempPath);
|
|
57
103
|
}
|
|
58
104
|
return { sigPath, pubPath };
|
|
59
105
|
}
|
|
60
106
|
|
|
61
|
-
/** Verify
|
|
62
|
-
export function verifyManifest({ manifestPath, sigPath, pubPath }) {
|
|
107
|
+
/** Verify bytes and publisher identity against a public key obtained independently. */
|
|
108
|
+
export function verifyManifest({ manifestPath, sigPath, pubPath, trustedPubPath }) {
|
|
109
|
+
if (!trustedPubPath) throw new Error("trustedPubPath is required; a colocated public key is not a trust anchor");
|
|
110
|
+
if (samePathIdentity(pubPath, trustedPubPath)) {
|
|
111
|
+
throw new Error("trusted public key must not alias the public key from the manifest bundle");
|
|
112
|
+
}
|
|
63
113
|
const pub = createPublicKey(readFileSync(pubPath));
|
|
114
|
+
const trustedPub = createPublicKey(readFileSync(trustedPubPath));
|
|
115
|
+
if (!pub.export({ type: "spki", format: "der" }).equals(trustedPub.export({ type: "spki", format: "der" }))) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
64
118
|
const signature = Buffer.from(readFileSync(sigPath, "utf8").trim(), "base64");
|
|
65
119
|
return edVerify(null, readFileSync(manifestPath), pub, signature);
|
|
66
120
|
}
|
package/lib/stdio-probe.mjs
CHANGED
|
@@ -1,120 +1,144 @@
|
|
|
1
|
-
// Generic MCP stdio probe driver
|
|
2
|
-
// newline-delimited JSON-RPC (MCP stdio framing — one message per line, not
|
|
3
|
-
// LSP Content-Length headers), run initialize + tools/list with the shared
|
|
4
|
-
// protocol assertions, then any domain-specific tool calls.
|
|
5
|
-
|
|
1
|
+
// Generic MCP stdio probe driver using newline-delimited JSON-RPC.
|
|
6
2
|
import { spawn } from "node:child_process";
|
|
3
|
+
import { StringDecoder } from "node:string_decoder";
|
|
4
|
+
import {
|
|
5
|
+
validateInitializeResult,
|
|
6
|
+
validateResponse,
|
|
7
|
+
validateToolCallResult,
|
|
8
|
+
validateToolsResult,
|
|
9
|
+
} from "./internal/protocol.mjs";
|
|
7
10
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
let rest = buf;
|
|
11
|
-
let nl = rest.indexOf("\n");
|
|
12
|
-
while (nl >= 0) {
|
|
13
|
-
const line = rest.slice(0, nl).trim();
|
|
14
|
-
rest = rest.slice(nl + 1);
|
|
15
|
-
if (line) messages.push(JSON.parse(line));
|
|
16
|
-
nl = rest.indexOf("\n");
|
|
17
|
-
}
|
|
18
|
-
return { messages, rest };
|
|
19
|
-
}
|
|
11
|
+
const MAX_FRAME_BYTES = 1024 * 1024;
|
|
12
|
+
const SHUTDOWN_GRACE_MS = 300;
|
|
20
13
|
|
|
21
14
|
/**
|
|
22
15
|
* Probe a stdio MCP server end to end.
|
|
23
|
-
*
|
|
24
|
-
* @param
|
|
25
|
-
* @param
|
|
26
|
-
* @param expect { serverName, tools, requireReadOnly = true, calls = [], timeoutMs = 5000 }
|
|
27
|
-
* calls: [{ name, arguments }] — run in order after tools/list
|
|
28
|
-
* @returns { serverInfo, tools, callResults } — callResults aligned with `calls`
|
|
16
|
+
* @param {string} command executable to spawn
|
|
17
|
+
* @param {string[]} args executable arguments
|
|
18
|
+
* @param {object} expect expected server/tool details and timeoutMs
|
|
29
19
|
*/
|
|
30
20
|
export async function probeStdioServer(command, args, expect = {}) {
|
|
31
21
|
const {
|
|
32
|
-
serverName,
|
|
33
|
-
|
|
34
|
-
requireReadOnly = true,
|
|
35
|
-
calls = [],
|
|
36
|
-
timeoutMs = 5000,
|
|
37
|
-
protocolVersion = "2025-06-18",
|
|
38
|
-
clientName = "mcp-kit-probe",
|
|
22
|
+
serverName, tools: expectedTools, requireReadOnly = true, calls = [], timeoutMs = 5000,
|
|
23
|
+
protocolVersion = "2025-06-18", clientName = "mcp-kit-probe",
|
|
39
24
|
} = expect;
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
let
|
|
25
|
+
const proc = spawn(command, args, { stdio: ["pipe", "pipe", "inherit"], env: { ...process.env, ...(expect.env ?? {}) } });
|
|
26
|
+
const pending = new Map();
|
|
27
|
+
const decoder = new StringDecoder("utf8");
|
|
28
|
+
let buffer = "";
|
|
29
|
+
let terminalError;
|
|
30
|
+
let exiting = false;
|
|
31
|
+
let exitResolve;
|
|
32
|
+
const exited = new Promise((resolve) => { exitResolve = resolve; });
|
|
33
|
+
const failAll = (error) => {
|
|
34
|
+
if (!terminalError) terminalError = error;
|
|
35
|
+
for (const [id, request] of pending) {
|
|
36
|
+
clearTimeout(request.timer);
|
|
37
|
+
request.reject(terminalError);
|
|
38
|
+
pending.delete(id);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
proc.once("error", (error) => failAll(new Error(`failed to spawn ${command}: ${error.message}`, { cause: error })));
|
|
42
|
+
proc.once("exit", (code, signal) => {
|
|
43
|
+
exitResolve({ code, signal });
|
|
44
|
+
if (!exiting) failAll(new Error(`stdio server exited early (code ${code}, signal ${signal})`));
|
|
45
|
+
});
|
|
46
|
+
proc.stdin.on("error", (error) => failAll(new Error(`stdio server stdin write failed: ${error.message}`, { cause: error })));
|
|
44
47
|
proc.stdout.on("data", (chunk) => {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
if (terminalError) return;
|
|
49
|
+
buffer += decoder.write(chunk);
|
|
50
|
+
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES && !buffer.includes("\n")) {
|
|
51
|
+
failAll(new Error(`stdio server exceeded ${MAX_FRAME_BYTES} byte frame limit`));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
let newline;
|
|
55
|
+
while ((newline = buffer.indexOf("\n")) !== -1) {
|
|
56
|
+
const line = buffer.slice(0, newline).trim();
|
|
57
|
+
buffer = buffer.slice(newline + 1);
|
|
58
|
+
if (!line) continue;
|
|
59
|
+
if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
|
|
60
|
+
failAll(new Error(`stdio server exceeded ${MAX_FRAME_BYTES} byte frame limit`));
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
let message;
|
|
64
|
+
try { message = JSON.parse(line); }
|
|
65
|
+
catch (error) {
|
|
66
|
+
failAll(new Error(`stdio server returned malformed JSON: ${error.message}`, { cause: error }));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
// Server notifications have no id and are deliberately not matched to calls.
|
|
70
|
+
if (!message || !Object.hasOwn(message, "id")) continue;
|
|
71
|
+
const request = pending.get(message.id);
|
|
72
|
+
if (!request) {
|
|
73
|
+
const active = pending.values().next().value;
|
|
74
|
+
if (active) failAll(new Error(`${active.method} response id mismatch: expected ${JSON.stringify(active.id)}, got ${JSON.stringify(message.id)}`));
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
pending.delete(message.id);
|
|
78
|
+
clearTimeout(request.timer);
|
|
79
|
+
try { request.resolve(validateResponse(message, request.id, request.method)); }
|
|
80
|
+
catch (error) { request.reject(error); }
|
|
81
|
+
}
|
|
82
|
+
if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) failAll(new Error(`stdio server exceeded ${MAX_FRAME_BYTES} byte frame limit`));
|
|
49
83
|
});
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
84
|
+
proc.stdout.on("end", () => {
|
|
85
|
+
buffer += decoder.end();
|
|
86
|
+
if (buffer.trim()) failAll(new Error("stdio server closed with an incomplete JSON-RPC frame"));
|
|
87
|
+
});
|
|
88
|
+
const notify = (method) => {
|
|
89
|
+
if (terminalError) throw terminalError;
|
|
90
|
+
proc.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method })}\n`);
|
|
91
|
+
};
|
|
92
|
+
const request = (id, method, params) => {
|
|
93
|
+
if (terminalError) return Promise.reject(terminalError);
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
const timer = setTimeout(() => {
|
|
96
|
+
pending.delete(id);
|
|
97
|
+
reject(new Error(`${method} timed out after ${timeoutMs}ms waiting for stdio response`));
|
|
98
|
+
}, timeoutMs);
|
|
99
|
+
pending.set(id, { id, method, resolve, reject, timer });
|
|
100
|
+
proc.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) })}\n`, (error) => {
|
|
101
|
+
if (error && pending.has(id)) {
|
|
102
|
+
failAll(new Error(`${method} stdin write failed: ${error.message}`, { cause: error }));
|
|
62
103
|
}
|
|
63
|
-
}
|
|
104
|
+
});
|
|
64
105
|
});
|
|
65
|
-
|
|
106
|
+
};
|
|
66
107
|
try {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
id: 1,
|
|
70
|
-
method: "initialize",
|
|
71
|
-
params: {
|
|
72
|
-
protocolVersion,
|
|
73
|
-
capabilities: {},
|
|
74
|
-
clientInfo: { name: clientName, version: "1.0.0" },
|
|
75
|
-
},
|
|
108
|
+
const init = await request(1, "initialize", {
|
|
109
|
+
protocolVersion, capabilities: {}, clientInfo: { name: clientName, version: "1.0.0" },
|
|
76
110
|
});
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
throw new Error(
|
|
81
|
-
`initialize returned server ${JSON.stringify(serverInfo?.name)}, ` +
|
|
82
|
-
`expected ${JSON.stringify(serverName)}`,
|
|
83
|
-
);
|
|
111
|
+
const serverInfo = validateInitializeResult(init);
|
|
112
|
+
if (serverName && serverInfo.name !== serverName) {
|
|
113
|
+
throw new Error(`initialize returned server ${JSON.stringify(serverInfo.name)}, expected ${JSON.stringify(serverName)}`);
|
|
84
114
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
send({ jsonrpc: "2.0", id: 2, method: "tools/list" });
|
|
88
|
-
await waitFor(2);
|
|
89
|
-
const tools = received[1]?.result?.tools || [];
|
|
115
|
+
notify("notifications/initialized");
|
|
116
|
+
const tools = validateToolsResult(await request(2, "tools/list"));
|
|
90
117
|
const toolNames = tools.map((tool) => tool.name).sort();
|
|
91
|
-
if (expectedTools) {
|
|
92
|
-
|
|
93
|
-
if (JSON.stringify(toolNames) !== JSON.stringify(expected)) {
|
|
94
|
-
throw new Error(
|
|
95
|
-
`tools/list mismatch: expected ${JSON.stringify(expected)}, got ${JSON.stringify(toolNames)}`,
|
|
96
|
-
);
|
|
97
|
-
}
|
|
118
|
+
if (expectedTools && JSON.stringify(toolNames) !== JSON.stringify([...expectedTools].sort())) {
|
|
119
|
+
throw new Error(`tools/list mismatch: expected ${JSON.stringify([...expectedTools].sort())}, got ${JSON.stringify(toolNames)}`);
|
|
98
120
|
}
|
|
99
121
|
if (requireReadOnly && !tools.every((tool) => tool.annotations?.readOnlyHint === true)) {
|
|
100
122
|
throw new Error("not every tool is annotated readOnlyHint=true");
|
|
101
123
|
}
|
|
102
|
-
|
|
103
124
|
const callResults = [];
|
|
104
125
|
for (let i = 0; i < calls.length; i += 1) {
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
id,
|
|
109
|
-
method: "tools/call",
|
|
110
|
-
params: { name: calls[i].name, arguments: calls[i].arguments ?? {} },
|
|
111
|
-
});
|
|
112
|
-
await waitFor(3 + i);
|
|
113
|
-
callResults.push(received[2 + i]?.result);
|
|
126
|
+
const method = "tools/call";
|
|
127
|
+
const result = await request(3 + i, method, { name: calls[i].name, arguments: calls[i].arguments ?? {} });
|
|
128
|
+
callResults.push(validateToolCallResult(result, method));
|
|
114
129
|
}
|
|
115
|
-
|
|
116
130
|
return { serverInfo, tools, callResults };
|
|
117
131
|
} finally {
|
|
118
|
-
|
|
132
|
+
exiting = true;
|
|
133
|
+
try { proc.stdin.end(); } catch {}
|
|
134
|
+
if (proc.exitCode === null && proc.signalCode === null) {
|
|
135
|
+
proc.kill("SIGTERM");
|
|
136
|
+
let graceTimer;
|
|
137
|
+
const grace = new Promise((resolve) => { graceTimer = setTimeout(() => resolve(false), SHUTDOWN_GRACE_MS); });
|
|
138
|
+
const exitedGracefully = await Promise.race([exited.then(() => true), grace]);
|
|
139
|
+
clearTimeout(graceTimer);
|
|
140
|
+
if (!exitedGracefully && proc.exitCode === null && proc.signalCode === null) proc.kill("SIGKILL");
|
|
141
|
+
}
|
|
142
|
+
if (proc.exitCode === null && proc.signalCode === null) await exited;
|
|
119
143
|
}
|
|
120
144
|
}
|
package/package.json
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "saagar-mcp-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Shared toolbelt for baked-corpus MCP servers: Ed25519 manifest signing, HTTP/stdio protocol probes, server.json version parity, Worker CORS helpers, and a wrangler smoke harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Saagar Patel",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
|
-
"url": "https://github.com/saagpatel/mcp-kit"
|
|
10
|
+
"url": "git+https://github.com/saagpatel/mcp-kit.git"
|
|
11
11
|
},
|
|
12
12
|
"engines": {
|
|
13
|
-
"node": ">=
|
|
13
|
+
"node": ">=22"
|
|
14
14
|
},
|
|
15
|
+
"packageManager": "npm@12.2.0",
|
|
15
16
|
"files": [
|
|
16
17
|
"bin",
|
|
17
18
|
"lib",
|
|
19
|
+
"CHANGELOG.md",
|
|
18
20
|
"README.md",
|
|
19
21
|
"LICENSE"
|
|
20
22
|
],
|
|
@@ -31,6 +33,6 @@
|
|
|
31
33
|
"mcp-kit-smoke": "bin/mcp-kit-smoke"
|
|
32
34
|
},
|
|
33
35
|
"scripts": {
|
|
34
|
-
"test": "node --test
|
|
36
|
+
"test": "node --test test/*.test.mjs"
|
|
35
37
|
}
|
|
36
38
|
}
|