saagar-mcp-kit 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Saagar Patel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ # saagar-mcp-kit
2
+
3
+ Shared toolbelt for the baked-corpus MCP server franchise. One copy of the
4
+ scaffolding that every server previously carried as hand-forked scripts:
5
+ Ed25519 manifest signing, HTTP and stdio protocol probes, server.json version
6
+ parity, Worker CORS helpers, and a wrangler smoke harness.
7
+
8
+ Zero runtime dependencies. Node >= 18. Install as a **devDependency** — nothing
9
+ here ships in a server's runtime bundle.
10
+
11
+ ```sh
12
+ npm install --save-dev saagar-mcp-kit
13
+ ```
14
+
15
+ ## What's inside
16
+
17
+ | Surface | Import / bin | Replaces (per repo) |
18
+ |---|---|---|
19
+ | Ed25519 manifest signing | `mcp-kit-sign` CLI, `saagar-mcp-kit/signing` | `scripts/sign-manifest.mjs` |
20
+ | HTTP probe driver | `saagar-mcp-kit/http-probe` | the generic half of `scripts/probe-mcp.mjs` (HTTP flavor) |
21
+ | stdio probe driver | `saagar-mcp-kit/stdio-probe` | the generic half of `scripts/probe-mcp.mjs` (stdio flavor) |
22
+ | Worker CORS shell helpers | `saagar-mcp-kit/worker-shell` | the CORS block + 404/405/preflight responses in `src/index.ts` |
23
+ | Version parity check | `mcp-kit-parity` CLI, `saagar-mcp-kit/parity` | the per-repo server.json↔manifest parity test |
24
+ | wrangler smoke harness | `mcp-kit-smoke` CLI | `scripts/smoke-mcp.sh` |
25
+
26
+ Domain knowledge stays in each repo: expected tool lists, server names, and
27
+ domain tool-call assertions live in a thin per-repo probe script built on the
28
+ kit's drivers.
29
+
30
+ ## Usage
31
+
32
+ ### Signing
33
+
34
+ ```sh
35
+ mcp-kit-sign gen-key --manifest=.well-known/mcp.json # one-time keypair
36
+ mcp-kit-sign sign --manifest=.well-known/mcp.json # detached .sig + pubkey
37
+ mcp-kit-sign verify --manifest=.well-known/mcp.json # exit 0 valid / 1 invalid
38
+ ```
39
+
40
+ The manifest is signed as raw bytes (no canonicalization): serve the exact
41
+ bytes that were signed, and re-sign after any manifest change. The private key
42
+ defaults to `.signing/mcp-ed25519.key` (gitignore `.signing/`; never commit it).
43
+
44
+ ### Probing an HTTP (Worker) server
45
+
46
+ ```js
47
+ // scripts/probe-mcp.mjs — the repo keeps only its domain expectations
48
+ import { probeHttpServer, rpc, parseToolPayload } from "saagar-mcp-kit/http-probe";
49
+
50
+ const summary = await probeHttpServer(endpoint, {
51
+ serverName: "saagarpatel-portfolio",
52
+ tools: ["get_document", "get_profile", "list_corpus", "search" /* ... */],
53
+ });
54
+ // domain calls:
55
+ const search = await rpc(endpoint, 3, "tools/call", { name: "search", arguments: { query } });
56
+ const payload = parseToolPayload(search.json.result, "search");
57
+ ```
58
+
59
+ ### Probing a stdio server
60
+
61
+ ```js
62
+ import { probeStdioServer } from "saagar-mcp-kit/stdio-probe";
63
+
64
+ const { serverInfo, tools, callResults } = await probeStdioServer("node", ["dist/stdio.js"], {
65
+ serverName: "operant-mcp",
66
+ tools: ["compare_models", "get_case", "get_methodology", "get_results", "list_cases"],
67
+ calls: [{ name: "get_results", arguments: {} }],
68
+ });
69
+ ```
70
+
71
+ ### Worker CORS shell
72
+
73
+ ```ts
74
+ import {
75
+ preflightResponse,
76
+ notFoundResponse,
77
+ methodNotAllowedResponse,
78
+ withCors,
79
+ } from "saagar-mcp-kit/worker-shell";
80
+
81
+ if (request.method === "OPTIONS") return preflightResponse();
82
+ if (url.pathname !== "/mcp") return notFoundResponse("/mcp", { site });
83
+ if (request.method !== "POST") return methodNotAllowedResponse("/mcp");
84
+ // ...SDK transport wiring stays in the repo...
85
+ return withCors(await transport.handleRequest(request));
86
+ ```
87
+
88
+ ### Version parity (CI gate)
89
+
90
+ ```sh
91
+ mcp-kit-parity # server.json vs package.json/pyproject.toml
92
+ mcp-kit-parity --server-json=server.json --package=pyproject.toml
93
+ ```
94
+
95
+ The MCP registry is version-keyed: a release whose server.json lags its package
96
+ version silently serves a stale registry entry. Run this in CI for every
97
+ franchise repo — npm and PyPI alike.
98
+
99
+ ### Smoke harness
100
+
101
+ ```sh
102
+ mcp-kit-smoke -- node scripts/probe-mcp.mjs --endpoint "http://127.0.0.1:{port}/mcp"
103
+ ```
104
+
105
+ Boots `wrangler dev` on a free port, waits until `/mcp` answers, substitutes
106
+ `{port}` into the probe command, runs it, and tears down.
107
+
108
+ ## Adopting in a franchise repo
109
+
110
+ Three-step wiring (portfolio-mcp shown; operant-mcp is identical in shape):
111
+
112
+ 1. `npm install --save-dev saagar-mcp-kit`
113
+ 2. Replace scripts in `package.json`:
114
+ ```json
115
+ "sign": "mcp-kit-sign sign --manifest=../portfolio-index/.well-known/mcp.json",
116
+ "smoke": "mcp-kit-smoke -- node scripts/probe-mcp.mjs --endpoint http://127.0.0.1:{port}/mcp",
117
+ "parity": "mcp-kit-parity"
118
+ ```
119
+ 3. Rewrite `scripts/probe-mcp.mjs` to import the kit's driver and keep only the
120
+ repo's expected-tools list, server name, and domain calls; delete
121
+ `scripts/sign-manifest.mjs` and `scripts/smoke-mcp.sh`.
122
+
123
+ Python franchise repos (MCPAudit, mcp-trust, shadow-mcp, mcpforge) can adopt
124
+ `mcp-kit-parity` in CI without any npm dependency in the package itself:
125
+ `npx saagar-mcp-kit`'s bin or a pinned dev tool step.
126
+
127
+ ## Roadmap (deliberately not in v0.1)
128
+
129
+ - `mcp-kit-embed` — bake signed well-known files into TS string constants
130
+ (generalizing operant-mcp's `build-wellknown.mjs`).
131
+ - BM25 search module — only one franchise server uses it today; extraction
132
+ waits for a second consumer.
133
+
134
+ ## Testing
135
+
136
+ ```sh
137
+ npm test # node --test, no dependencies
138
+ ```
139
+
140
+ MIT.
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // server.json <-> package manifest version parity check.
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
+
9
+ import { existsSync } from "node:fs";
10
+ import { resolve } from "node:path";
11
+ import { checkParity } from "../lib/parity.mjs";
12
+
13
+ const args = process.argv.slice(2);
14
+ const flag = (name, def) => {
15
+ const pre = `--${name}=`;
16
+ return args.find((a) => a.startsWith(pre))?.slice(pre.length) ?? def;
17
+ };
18
+
19
+ const serverJsonPath = resolve(flag("server-json", "server.json"));
20
+ const packageFlag = flag("package");
21
+ const packagePath = resolve(
22
+ packageFlag ?? (existsSync("package.json") ? "package.json" : "pyproject.toml"),
23
+ );
24
+
25
+ try {
26
+ const { ok, version, problems } = checkParity({ serverJsonPath, packagePath });
27
+ if (ok) {
28
+ console.log(`version parity OK: ${version}`);
29
+ process.exit(0);
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
+ }
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ // Ed25519 manifest signing CLI.
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
+
12
+ import { resolve } from "node:path";
13
+ import { defaultPaths, generateKeypair, signManifest, verifyManifest } from "../lib/signing.mjs";
14
+
15
+ const args = process.argv.slice(2);
16
+ const cmd = args.find((a) => !a.startsWith("--")) ?? "verify";
17
+ const flag = (name, def) => {
18
+ const pre = `--${name}=`;
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
+ }
57
+ try {
58
+ run();
59
+ } catch (err) {
60
+ console.error(err?.message ?? String(err));
61
+ process.exit(1);
62
+ }
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env bash
2
+ # Local Workers-runtime smoke harness: boot `wrangler dev` on a free port, wait
3
+ # for it to answer, run the given probe command with {port} substituted, then
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
11
+
12
+ if [ "${1:-}" != "--" ] || [ "$#" -lt 2 ]; then
13
+ echo "usage: mcp-kit-smoke -- <probe command with {port} placeholder>" >&2
14
+ exit 2
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=$!
30
+ cleanup() {
31
+ kill "$WPID" 2>/dev/null || true
32
+ pkill -P "$WPID" 2>/dev/null || true
33
+ echo "=== wrangler log ==="
34
+ cat "$LOG"
35
+ rm -f "$LOG"
36
+ }
37
+ trap cleanup EXIT
38
+
39
+ ready=0
40
+ secs=0
41
+ code=000
42
+ for i in $(seq 1 120); do
43
+ code=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/mcp" 2>/dev/null || true)
44
+ [ -z "$code" ] && code=000
45
+ if [ "$code" != "000" ]; then
46
+ ready=1
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
54
+ sleep 1
55
+ done
56
+ echo "ready=$ready after ${secs}s (/mcp returned HTTP ${code} on port ${PORT})"
57
+
58
+ if [ "$ready" != "1" ]; then
59
+ exit 1
60
+ fi
61
+
62
+ # Substitute {port} in every probe arg, then run the probe.
63
+ probe=()
64
+ for arg in "$@"; do
65
+ probe+=("${arg//\{port\}/$PORT}")
66
+ done
67
+ "${probe[@]}"
@@ -0,0 +1,115 @@
1
+ // Generic MCP streamable-HTTP probe driver: JSON-RPC transport plus the
2
+ // protocol-level assertions every baked-corpus server shares (initialize
3
+ // answers with the right server name; tools/list matches the expected set;
4
+ // every tool is annotated read-only). Domain-specific tool calls stay in each
5
+ // server's own probe script, built on `rpc` / `parseToolPayload`.
6
+
7
+ /** POST one JSON-RPC message; throws on HTTP, parse, or JSON-RPC errors. */
8
+ export async function rpc(endpoint, id, method, params) {
9
+ const res = await fetch(endpoint, {
10
+ method: "POST",
11
+ headers: {
12
+ "Content-Type": "application/json",
13
+ Accept: "application/json, text/event-stream",
14
+ },
15
+ body: JSON.stringify({
16
+ jsonrpc: "2.0",
17
+ id,
18
+ method,
19
+ ...(params === undefined ? {} : { params }),
20
+ }),
21
+ });
22
+ const text = await res.text();
23
+ let json;
24
+ try {
25
+ json = JSON.parse(text);
26
+ } catch (err) {
27
+ throw new Error(`${method} returned non-JSON HTTP ${res.status}: ${text.slice(0, 300)}`, {
28
+ cause: err,
29
+ });
30
+ }
31
+ if (res.status !== 200) {
32
+ throw new Error(`${method} returned HTTP ${res.status}: ${text.slice(0, 300)}`);
33
+ }
34
+ if (json.error) {
35
+ throw new Error(`${method} JSON-RPC error: ${JSON.stringify(json.error)}`);
36
+ }
37
+ return {
38
+ status: res.status,
39
+ contentType: res.headers.get("content-type"),
40
+ allowOrigin: res.headers.get("access-control-allow-origin"),
41
+ json,
42
+ };
43
+ }
44
+
45
+ /** Extract and parse the JSON text payload of a tools/call result. */
46
+ export function parseToolPayload(result, label) {
47
+ const text = result?.content?.[0]?.text;
48
+ if (typeof text !== "string") throw new Error(`${label} returned no text payload`);
49
+ return JSON.parse(text);
50
+ }
51
+
52
+ function assertSame(actual, expected, label) {
53
+ const a = JSON.stringify(actual);
54
+ const e = JSON.stringify(expected);
55
+ if (a !== e) throw new Error(`${label} mismatch: expected ${e}, got ${a}`);
56
+ }
57
+
58
+ /**
59
+ * Run the shared protocol probe: initialize + tools/list with assertions.
60
+ *
61
+ * @param endpoint streamable-HTTP MCP endpoint URL
62
+ * @param expect { serverName, tools, requireReadOnly = true, clientName, protocolVersion }
63
+ * @returns { endpoint, initialize, toolsList } summary for reporting
64
+ */
65
+ export async function probeHttpServer(endpoint, expect) {
66
+ const {
67
+ serverName,
68
+ tools: expectedTools,
69
+ requireReadOnly = true,
70
+ clientName = "mcp-kit-probe",
71
+ protocolVersion = "2025-06-18",
72
+ } = expect;
73
+
74
+ const initialize = await rpc(endpoint, 1, "initialize", {
75
+ protocolVersion,
76
+ capabilities: {},
77
+ clientInfo: { name: clientName, version: "1.0.0" },
78
+ });
79
+ if (serverName && initialize.json.result?.serverInfo?.name !== serverName) {
80
+ throw new Error(
81
+ `initialize returned server ${JSON.stringify(
82
+ initialize.json.result?.serverInfo?.name,
83
+ )}, expected ${JSON.stringify(serverName)}`,
84
+ );
85
+ }
86
+
87
+ const toolsList = await rpc(endpoint, 2, "tools/list");
88
+ const tools = toolsList.json.result?.tools || [];
89
+ const toolNames = tools.map((tool) => tool.name).sort();
90
+ if (expectedTools) assertSame(toolNames, [...expectedTools].sort(), "tools/list");
91
+ if (requireReadOnly && !tools.every((tool) => tool.annotations?.readOnlyHint === true)) {
92
+ throw new Error("not every tool is annotated readOnlyHint=true");
93
+ }
94
+
95
+ return {
96
+ endpoint,
97
+ initialize: {
98
+ status: initialize.status,
99
+ contentType: initialize.contentType,
100
+ allowOrigin: initialize.allowOrigin,
101
+ serverInfo: initialize.json.result.serverInfo,
102
+ protocolVersion: initialize.json.result.protocolVersion,
103
+ },
104
+ toolsList: {
105
+ status: toolsList.status,
106
+ contentType: toolsList.contentType,
107
+ allowOrigin: toolsList.allowOrigin,
108
+ count: tools.length,
109
+ tools: tools.map((tool) => ({
110
+ name: tool.name,
111
+ readOnly: tool.annotations?.readOnlyHint === true,
112
+ })),
113
+ },
114
+ };
115
+ }
package/lib/parity.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // Language-neutral version-parity check between an MCP registry server.json and
2
+ // the package manifest it publishes from. The registry is version-keyed, so a
3
+ // release whose server.json lags its package version silently serves a stale
4
+ // registry entry — every franchise repo re-implements (or forgets) this test.
5
+ //
6
+ // Supports package.json (npm) and pyproject.toml (PEP 621). The TOML read is a
7
+ // deliberate line-match, not a parser, to stay dependency-free: it requires a
8
+ // plain `version = "x.y.z"` line in [project], which every franchise repo has.
9
+
10
+ import { readFileSync } from "node:fs";
11
+ import { basename } from "node:path";
12
+
13
+ function manifestVersion(packagePath) {
14
+ const raw = readFileSync(packagePath, "utf8");
15
+ if (basename(packagePath) === "package.json") {
16
+ const version = JSON.parse(raw).version;
17
+ if (typeof version !== "string") throw new Error(`${packagePath}: no "version" field`);
18
+ return version;
19
+ }
20
+ if (basename(packagePath) === "pyproject.toml") {
21
+ const project = raw.split(/^\[/m).find((s) => s.startsWith("project]"));
22
+ const m = (project ?? "").match(/^version\s*=\s*"([^"]+)"/m);
23
+ if (!m) throw new Error(`${packagePath}: no [project] version = "..." line`);
24
+ return m[1];
25
+ }
26
+ throw new Error(`unsupported manifest: ${packagePath} (need package.json or pyproject.toml)`);
27
+ }
28
+
29
+ /**
30
+ * Check server.json <-> package manifest version parity.
31
+ *
32
+ * @returns { ok, version, problems } — problems is a list of human-readable
33
+ * mismatch descriptions; ok is true when it is empty.
34
+ */
35
+ export function checkParity({ serverJsonPath, packagePath }) {
36
+ const server = JSON.parse(readFileSync(serverJsonPath, "utf8"));
37
+ const version = manifestVersion(packagePath);
38
+ const problems = [];
39
+
40
+ if (server.version !== version) {
41
+ problems.push(
42
+ `server.json version "${server.version}" != ${basename(packagePath)} version "${version}"`,
43
+ );
44
+ }
45
+ for (const [i, pkg] of (server.packages ?? []).entries()) {
46
+ if (pkg.version !== version) {
47
+ problems.push(
48
+ `server.json packages[${i}] (${pkg.identifier ?? "?"}) version ` +
49
+ `"${pkg.version}" != ${basename(packagePath)} version "${version}"`,
50
+ );
51
+ }
52
+ }
53
+ return { ok: problems.length === 0, version, problems };
54
+ }
@@ -0,0 +1,66 @@
1
+ // Ed25519 signing for public MCP discovery manifests (.well-known/mcp.json), so an
2
+ // agent or registry can verify a manifest authentically comes from its publisher.
3
+ // Zero deps (Node built-in crypto). Detached signature + published public key.
4
+ //
5
+ // The manifest is signed as RAW BYTES (no canonicalization), so the serving origin
6
+ // must serve the exact bytes that were signed — re-sign after any manifest change.
7
+ //
8
+ // The PRIVATE key must live outside the published tree (conventionally .signing/,
9
+ // gitignored) and is NEVER committed. The PUBLIC key and detached signature sit next
10
+ // to the manifest so verifiers can fetch all three.
11
+
12
+ import {
13
+ createPrivateKey,
14
+ createPublicKey,
15
+ generateKeyPairSync,
16
+ sign as edSign,
17
+ verify as edVerify,
18
+ } from "node:crypto";
19
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
20
+ import { dirname } from "node:path";
21
+
22
+ /** Derive the default pub/sig paths from the manifest location. */
23
+ export function defaultPaths(manifestPath) {
24
+ return {
25
+ pubPath: `${dirname(manifestPath)}/mcp-ed25519.pub`,
26
+ sigPath: `${manifestPath}.sig`,
27
+ };
28
+ }
29
+
30
+ /**
31
+ * Generate an Ed25519 keypair. Refuses to overwrite an existing private key.
32
+ * Returns the written paths.
33
+ */
34
+ export function generateKeypair({ keyPath, pubPath }) {
35
+ if (existsSync(keyPath)) {
36
+ throw new Error(`refusing to overwrite existing private key: ${keyPath}`);
37
+ }
38
+ const { publicKey, privateKey } = generateKeyPairSync("ed25519");
39
+ mkdirSync(dirname(keyPath), { recursive: true });
40
+ writeFileSync(keyPath, privateKey.export({ type: "pkcs8", format: "pem" }));
41
+ chmodSync(keyPath, 0o600);
42
+ mkdirSync(dirname(pubPath), { recursive: true });
43
+ writeFileSync(pubPath, publicKey.export({ type: "spki", format: "pem" }));
44
+ return { keyPath, pubPath };
45
+ }
46
+
47
+ /**
48
+ * Sign the manifest's raw bytes; write a detached base64 signature. Writes the
49
+ * public key next to it when missing. Returns the written paths.
50
+ */
51
+ export function signManifest({ manifestPath, keyPath, sigPath, pubPath }) {
52
+ const priv = createPrivateKey(readFileSync(keyPath));
53
+ const signature = edSign(null, readFileSync(manifestPath), priv); // Ed25519: algorithm = null
54
+ writeFileSync(sigPath, `${signature.toString("base64")}\n`);
55
+ if (!existsSync(pubPath)) {
56
+ writeFileSync(pubPath, createPublicKey(priv).export({ type: "spki", format: "pem" }));
57
+ }
58
+ return { sigPath, pubPath };
59
+ }
60
+
61
+ /** Verify the manifest's raw bytes against the detached signature. */
62
+ export function verifyManifest({ manifestPath, sigPath, pubPath }) {
63
+ const pub = createPublicKey(readFileSync(pubPath));
64
+ const signature = Buffer.from(readFileSync(sigPath, "utf8").trim(), "base64");
65
+ return edVerify(null, readFileSync(manifestPath), pub, signature);
66
+ }
@@ -0,0 +1,120 @@
1
+ // Generic MCP stdio probe driver: spawn a stdio MCP server, speak
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
+
6
+ import { spawn } from "node:child_process";
7
+
8
+ function parseLines(buf) {
9
+ const messages = [];
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
+ }
20
+
21
+ /**
22
+ * Probe a stdio MCP server end to end.
23
+ *
24
+ * @param command executable to spawn (e.g. "node")
25
+ * @param args argv (e.g. ["dist/stdio.js"])
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`
29
+ */
30
+ export async function probeStdioServer(command, args, expect = {}) {
31
+ const {
32
+ serverName,
33
+ tools: expectedTools,
34
+ requireReadOnly = true,
35
+ calls = [],
36
+ timeoutMs = 5000,
37
+ protocolVersion = "2025-06-18",
38
+ clientName = "mcp-kit-probe",
39
+ } = expect;
40
+
41
+ const proc = spawn(command, args, { stdio: ["pipe", "pipe", "inherit"] });
42
+ const received = [];
43
+ let buf = "";
44
+ proc.stdout.on("data", (chunk) => {
45
+ buf += chunk.toString("utf8");
46
+ const { messages, rest } = parseLines(buf);
47
+ buf = rest;
48
+ received.push(...messages);
49
+ });
50
+
51
+ const send = (msg) => proc.stdin.write(`${JSON.stringify(msg)}\n`);
52
+ const waitFor = (count) =>
53
+ new Promise((resolve, reject) => {
54
+ const start = Date.now();
55
+ const tick = setInterval(() => {
56
+ if (received.length >= count) {
57
+ clearInterval(tick);
58
+ resolve();
59
+ } else if (Date.now() - start > timeoutMs) {
60
+ clearInterval(tick);
61
+ reject(new Error(`timed out waiting for ${count} response(s), got ${received.length}`));
62
+ }
63
+ }, 10);
64
+ });
65
+
66
+ try {
67
+ send({
68
+ jsonrpc: "2.0",
69
+ id: 1,
70
+ method: "initialize",
71
+ params: {
72
+ protocolVersion,
73
+ capabilities: {},
74
+ clientInfo: { name: clientName, version: "1.0.0" },
75
+ },
76
+ });
77
+ await waitFor(1);
78
+ const serverInfo = received[0]?.result?.serverInfo;
79
+ if (serverName && serverInfo?.name !== serverName) {
80
+ throw new Error(
81
+ `initialize returned server ${JSON.stringify(serverInfo?.name)}, ` +
82
+ `expected ${JSON.stringify(serverName)}`,
83
+ );
84
+ }
85
+ send({ jsonrpc: "2.0", method: "notifications/initialized" });
86
+
87
+ send({ jsonrpc: "2.0", id: 2, method: "tools/list" });
88
+ await waitFor(2);
89
+ const tools = received[1]?.result?.tools || [];
90
+ const toolNames = tools.map((tool) => tool.name).sort();
91
+ if (expectedTools) {
92
+ const expected = [...expectedTools].sort();
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
+ }
98
+ }
99
+ if (requireReadOnly && !tools.every((tool) => tool.annotations?.readOnlyHint === true)) {
100
+ throw new Error("not every tool is annotated readOnlyHint=true");
101
+ }
102
+
103
+ const callResults = [];
104
+ for (let i = 0; i < calls.length; i += 1) {
105
+ const id = 3 + i;
106
+ send({
107
+ jsonrpc: "2.0",
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);
114
+ }
115
+
116
+ return { serverInfo, tools, callResults };
117
+ } finally {
118
+ proc.kill();
119
+ }
120
+ }
@@ -0,0 +1,40 @@
1
+ // Framework-free helpers for the Cloudflare Worker transport shell shared by
2
+ // baked-corpus MCP servers: the CORS contract and the three non-MCP response
3
+ // shapes. Uses only Web-standard Request/Response (Workers and Node >= 18),
4
+ // so the kit stays dependency-free. The SDK-coupled transport wiring
5
+ // (McpServer + WebStandardStreamableHTTPServerTransport) stays in each repo.
6
+
7
+ export const MCP_CORS = {
8
+ "Access-Control-Allow-Origin": "*",
9
+ "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
10
+ "Access-Control-Allow-Headers": "Content-Type, Mcp-Session-Id, MCP-Protocol-Version, Accept",
11
+ "Access-Control-Expose-Headers": "Mcp-Session-Id",
12
+ };
13
+
14
+ /** 204 CORS preflight. */
15
+ export function preflightResponse() {
16
+ return new Response(null, { status: 204, headers: MCP_CORS });
17
+ }
18
+
19
+ /** 404 for non-endpoint paths; `extra` merges into the JSON body (e.g. site). */
20
+ export function notFoundResponse(mcpEndpoint, extra = {}) {
21
+ return Response.json(
22
+ { error: "Not found", mcp_endpoint: mcpEndpoint, ...extra },
23
+ { status: 404, headers: MCP_CORS },
24
+ );
25
+ }
26
+
27
+ /** 405 for non-POST on the endpoint. */
28
+ export function methodNotAllowedResponse(mcpEndpoint, allowed = ["POST", "OPTIONS"]) {
29
+ return Response.json(
30
+ { error: "Method not allowed", mcp_endpoint: mcpEndpoint, allowed_methods: allowed },
31
+ { status: 405, headers: { ...MCP_CORS, Allow: allowed.join(", ") } },
32
+ );
33
+ }
34
+
35
+ /** Re-wrap a transport response with the CORS headers overlaid. */
36
+ export function withCors(res) {
37
+ const headers = new Headers(res.headers);
38
+ for (const [k, v] of Object.entries(MCP_CORS)) headers.set(k, v);
39
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
40
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "saagar-mcp-kit",
3
+ "version": "0.1.0",
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
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Saagar Patel",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/saagpatel/mcp-kit"
11
+ },
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "lib",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "exports": {
22
+ "./signing": "./lib/signing.mjs",
23
+ "./http-probe": "./lib/http-probe.mjs",
24
+ "./stdio-probe": "./lib/stdio-probe.mjs",
25
+ "./worker-shell": "./lib/worker-shell.mjs",
26
+ "./parity": "./lib/parity.mjs"
27
+ },
28
+ "bin": {
29
+ "mcp-kit-sign": "bin/mcp-kit-sign.mjs",
30
+ "mcp-kit-parity": "bin/mcp-kit-parity.mjs",
31
+ "mcp-kit-smoke": "bin/mcp-kit-smoke"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test 'test/*.test.mjs'"
35
+ }
36
+ }