@m-d-b-code/mcp-kit 0.0.0-stage → 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 m-d-b-code
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 CHANGED
@@ -1,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # mcp-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/m-d-b-code/mcp-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/m-d-b-code/mcp-kit/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@m-d-b-code/mcp-kit)](https://www.npmjs.com/package/@m-d-b-code/mcp-kit)
5
+
6
+ The shared foundation of MCP servers that sit **behind a gateway**: servers nobody calls directly,
7
+ reached only by an aggregator that discovers their tools and exposes them to its own clients, over
8
+ an internal network. Everything each such server used to copy lives here:
9
+
10
+ - **HTTP transport**: `/mcp` behind a shared secret (`x-mcp-token` header, constant-time
11
+ comparison), `/health` without one for the container healthcheck, a bounded request body (64 KiB
12
+ by default), clean shutdown on `SIGTERM`. Stateless, JSON responses, one `McpServer` per request.
13
+ - **Protocol revisions**: whatever the installed SDK speaks (`2026-07-28` today), with 2025-era
14
+ clients still served statelessly unless `legacy: "reject"` makes the server modern-only.
15
+ - **Configuration** read from the environment: a clear error at startup, never a degraded mode.
16
+ - **Logging** to stderr, its level set by a variable of the project's choosing.
17
+ - **Job-run reporting**: a server's internal timer reports each run to the gateway, which can then
18
+ notice a timer that stopped.
19
+ - The **ESLint config**, **base tsconfig** and **CI workflow** these projects share.
20
+
21
+ It is deliberately opinionated: one transport shape, one auth scheme. If your server faces clients directly (OAuth, sessions, SSE streams), use the MCP SDK on its own.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ npm install @m-d-b-code/mcp-kit @modelcontextprotocol/server @modelcontextprotocol/node
27
+ ```
28
+
29
+ The MCP SDK is a peer dependency: one copy, at the version the project picks. Node.js 26 or later.
30
+
31
+ ## Server
32
+
33
+ ```ts
34
+ import { McpServer } from "@modelcontextprotocol/server";
35
+ import {
36
+ createBridgeServer,
37
+ isEntryPoint,
38
+ listen,
39
+ loggerFactory,
40
+ readListenConfig,
41
+ runMain,
42
+ } from "@m-d-b-code/mcp-kit";
43
+
44
+ const log = loggerFactory("DEMO_LOG_LEVEL")("http");
45
+
46
+ function buildServer(): McpServer {
47
+ const server = new McpServer({ name: "demo", version: "1.0.0" });
48
+ // server.registerTool(…)
49
+ return server;
50
+ }
51
+
52
+ async function main(): Promise<void> {
53
+ // DEMO_MCP_TOKEN (required, 32 characters or more), DEMO_MCP_PORT, DEMO_MCP_HOST
54
+ const config = readListenConfig(process.env, "DEMO", 8788);
55
+ const server = createBridgeServer({ token: config.token, buildServer, log });
56
+ await listen(server, config);
57
+ log.info(`listening on ${config.host}:${config.port}`);
58
+ }
59
+
60
+ if (isEntryPoint(import.meta.url)) await runMain(main, log);
61
+ ```
62
+
63
+ A `ConfigError` thrown by `main` becomes one log line and exit code 2. `readToken`,
64
+ `readInteger` and `readOptional` read the project's own variables. `listen` takes an
65
+ `onShutdown` callback to close stores and timers. `createBridgeServer` takes `maxBodyBytes` for
66
+ tools that receive whole documents as arguments, and `legacy: "reject"` to refuse 2025-era clients
67
+ when the gateway only speaks `PROTOCOL_VERSION`.
68
+
69
+ ## Gateway side
70
+
71
+ `@m-d-b-code/mcp-kit/protocol` has no dependency at all, not even the SDK. A gateway imports the
72
+ same header name as its servers, so the two ends cannot drift:
73
+
74
+ ```ts
75
+ import { TOKEN_HEADER } from "@m-d-b-code/mcp-kit/protocol";
76
+
77
+ const transport = new StreamableHTTPClientTransport(url, {
78
+ requestInit: { headers: { [TOKEN_HEADER]: secret } },
79
+ });
80
+ // "auto": the newest revision both sides speak, 2025 for a server that knows nothing newer.
81
+ // `{ pin: PROTOCOL_VERSION }` instead, against servers started with `legacy: "reject"`.
82
+ const client = new Client(info, { versionNegotiation: { mode: "auto" } });
83
+ ```
84
+
85
+ ## Job-run reporting
86
+
87
+ ```ts
88
+ import { jobReporter } from "@m-d-b-code/mcp-kit";
89
+
90
+ const report = jobReporter(); // JOBS_REPORT_URL + JOBS_REPORT_TOKEN, or nothing is sent
91
+ report("sync", { ok: true, detail: "12 rows", startedAt });
92
+ ```
93
+
94
+ Each run is sent as `POST <JOBS_REPORT_URL>/<job>` with the token in `x-mcp-token` and a
95
+ `JobRun` body (`{ ok, detail, startedAt }`). A failed report is only logged. The receiver
96
+ validates the body with `parseJobRun` from `/protocol`.
97
+
98
+ ## Tooling
99
+
100
+ `tsconfig.json` (compiles `src/` to `dist/`, paths resolved from the project):
101
+
102
+ ```json
103
+ { "extends": "@m-d-b-code/mcp-kit/tsconfig.json" }
104
+ ```
105
+
106
+ `eslint.config.js` (with `eslint`, `@eslint/js` and `typescript-eslint` as dev dependencies):
107
+
108
+ ```js
109
+ import { mcpProjectConfig } from "@m-d-b-code/mcp-kit/eslint";
110
+
111
+ export default mcpProjectConfig({ root: import.meta.dirname });
112
+ ```
113
+
114
+ `.github/workflows/ci.yml` (runs `npm ci` then `npm run check`):
115
+
116
+ ```yaml
117
+ jobs:
118
+ check:
119
+ uses: m-d-b-code/mcp-kit/.github/workflows/mcp-project.yml@<sha> # vX.Y.Z
120
+ ```
121
+
122
+ Optional inputs: `node-version`, and `commit-status` to also report the result as a commit
123
+ status (see the workflow file).
124
+
125
+ ## Versioning
126
+
127
+ Semantic versioning. While at `0.x`, a minor release may break; pin accordingly. Releases are
128
+ published from CI with npm trusted publishing and provenance: `npm version <level>`, then
129
+ `git push --follow-tags`. See [CHANGELOG.md](CHANGELOG.md).
130
+
131
+ ## Contributing
132
+
133
+ Issues and pull requests are welcome. `npm install` sets up the git hooks; `npm run check` runs
134
+ formatting, types, lint, tests and the build, as CI does. Commit subjects follow
135
+ [Conventional Commits](https://www.conventionalcommits.org/).
136
+
137
+ ## License
138
+
139
+ [MIT](LICENSE)
@@ -0,0 +1,17 @@
1
+ export declare const MIN_TOKEN_LENGTH = 32;
2
+ /** Trimmed value, `null` when absent or blank. */
3
+ export declare function readOptional(env: NodeJS.ProcessEnv, name: string): string | null;
4
+ export declare function readToken(env: NodeJS.ProcessEnv, name: string): string;
5
+ /** An integer within bounds; absent or blank gives `fallback`. */
6
+ export declare function readInteger(env: NodeJS.ProcessEnv, name: string, fallback: number, min: number, max: number): number;
7
+ export interface ListenConfig {
8
+ /** Shared secret expected in `x-mcp-token`; the gateway sends the same one. */
9
+ token: string;
10
+ host: string;
11
+ port: number;
12
+ }
13
+ /**
14
+ * `<PREFIX>_MCP_TOKEN` (required), `<PREFIX>_MCP_PORT` and `<PREFIX>_MCP_HOST`: the part of
15
+ * every project's configuration that the bridge dictates.
16
+ */
17
+ export declare function readListenConfig(env: NodeJS.ProcessEnv, prefix: string, defaultPort: number): ListenConfig;
package/dist/config.js ADDED
@@ -0,0 +1,38 @@
1
+ import { ConfigError } from "./errors.js";
2
+ export const MIN_TOKEN_LENGTH = 32;
3
+ /** Trimmed value, `null` when absent or blank. */
4
+ export function readOptional(env, name) {
5
+ return env[name]?.trim() || null;
6
+ }
7
+ // No default and no tokenless mode: a missing guard would otherwise never be noticed.
8
+ export function readToken(env, name) {
9
+ const token = readOptional(env, name);
10
+ if (!token)
11
+ throw new ConfigError(`${name} is missing from the environment.`);
12
+ if (token.length < MIN_TOKEN_LENGTH) {
13
+ throw new ConfigError(`${name} is shorter than ${MIN_TOKEN_LENGTH} characters.`);
14
+ }
15
+ return token;
16
+ }
17
+ /** An integer within bounds; absent or blank gives `fallback`. */
18
+ export function readInteger(env, name, fallback, min, max) {
19
+ const raw = readOptional(env, name) ?? String(fallback);
20
+ const value = Number(raw);
21
+ if (!Number.isInteger(value) || value < min || value > max) {
22
+ throw new ConfigError(`invalid ${name}: ${JSON.stringify(raw)}`);
23
+ }
24
+ return value;
25
+ }
26
+ /**
27
+ * `<PREFIX>_MCP_TOKEN` (required), `<PREFIX>_MCP_PORT` and `<PREFIX>_MCP_HOST`: the part of
28
+ * every project's configuration that the bridge dictates.
29
+ */
30
+ export function readListenConfig(env, prefix, defaultPort) {
31
+ return {
32
+ token: readToken(env, `${prefix}_MCP_TOKEN`),
33
+ // Inside a container the loopback is reachable by nobody else.
34
+ host: readOptional(env, `${prefix}_MCP_HOST`) ?? "0.0.0.0",
35
+ port: readInteger(env, `${prefix}_MCP_PORT`, defaultPort, 0, 65535),
36
+ };
37
+ }
38
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,9 @@
1
+ /** An error meant to be read as is by the model: returned as text with `isError`, never thrown up. */
2
+ export declare class ToolError extends Error {
3
+ name: string;
4
+ }
5
+ /** The environment cannot start the server: `runMain` turns it into one log line and exit code 2. */
6
+ export declare class ConfigError extends Error {
7
+ name: string;
8
+ }
9
+ export declare function errorMessage(value: unknown): string;
package/dist/errors.js ADDED
@@ -0,0 +1,14 @@
1
+ /** An error meant to be read as is by the model: returned as text with `isError`, never thrown up. */
2
+ export class ToolError extends Error {
3
+ name = "ToolError";
4
+ }
5
+ /** The environment cannot start the server: `runMain` turns it into one log line and exit code 2. */
6
+ export class ConfigError extends Error {
7
+ name = "ConfigError";
8
+ }
9
+ export function errorMessage(value) {
10
+ if (value instanceof Error)
11
+ return value.message;
12
+ return typeof value === "string" ? value : String(value);
13
+ }
14
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from "eslint/config";
2
+ export interface LintOptions {
3
+ /** The project's root, `import.meta.dirname` of its `eslint.config.js`. */
4
+ root: string;
5
+ /** The tsconfig that covers sources and tests alike. */
6
+ project?: string;
7
+ }
8
+ export declare function mcpProjectConfig({ root, project, }: LintOptions): ReturnType<typeof defineConfig>;
package/dist/eslint.js ADDED
@@ -0,0 +1,33 @@
1
+ // The lint every project shares. Spread it first, then add the project's own blocks:
2
+ // export default [...mcpProjectConfig({ root: import.meta.dirname }), { … }];
3
+ import js from "@eslint/js";
4
+ import { defineConfig } from "eslint/config";
5
+ import tseslint from "typescript-eslint";
6
+ export function mcpProjectConfig({ root, project = "./tsconfig.test.json", }) {
7
+ return defineConfig({ ignores: ["dist/**", "node_modules/**", "coverage/**"] }, js.configs.recommended, tseslint.configs.strictTypeChecked, {
8
+ languageOptions: { parserOptions: { project, tsconfigRootDir: root } },
9
+ rules: {
10
+ "@typescript-eslint/no-non-null-assertion": "off",
11
+ "@typescript-eslint/restrict-template-expressions": ["error", { allowNumber: true }],
12
+ "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
13
+ // Logs go through the kit's logger, on stderr.
14
+ "no-console": "error",
15
+ // `() => resolve()` returns nothing useful, nobody is misled.
16
+ "@typescript-eslint/no-confusing-void-expression": [
17
+ "error",
18
+ { ignoreArrowShorthand: true },
19
+ ],
20
+ eqeqeq: ["error", "smart"],
21
+ },
22
+ }, {
23
+ files: ["tests/**/*.ts"],
24
+ rules: {
25
+ "@typescript-eslint/require-await": "off",
26
+ // `expect.stringContaining()` is typed `any` by vitest.
27
+ "@typescript-eslint/no-unsafe-assignment": "off",
28
+ },
29
+ },
30
+ // A script run by hand prints its findings.
31
+ { files: ["scripts/**/*.ts"], rules: { "no-console": "off" } }, { files: ["**/*.js"], extends: [tseslint.configs.disableTypeChecked] });
32
+ }
33
+ //# sourceMappingURL=eslint.js.map
package/dist/http.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { type Server } from "node:http";
2
+ import { createMcpHandler } from "@modelcontextprotocol/server";
3
+ import { type Logger } from "./log.js";
4
+ /** Builds the `McpServer` answering one request: the transport is stateless. */
5
+ export type ServerFactory = Parameters<typeof createMcpHandler>[0];
6
+ export declare const DEFAULT_MAX_BODY_BYTES: number;
7
+ export interface BridgeServerOptions {
8
+ token: string;
9
+ buildServer: ServerFactory;
10
+ /** Raise it only for a tool that takes a document as argument. */
11
+ maxBodyBytes?: number;
12
+ /**
13
+ * 2025-era clients: `"stateless"` (the default) still serves them, one stateless exchange per
14
+ * request; `"reject"` answers them with the unsupported-version error, so that only
15
+ * `PROTOCOL_VERSION` is spoken.
16
+ */
17
+ legacy?: "stateless" | "reject";
18
+ log?: Logger;
19
+ }
20
+ export declare function sameSecret(presented: string, expected: string): boolean;
21
+ /**
22
+ * `/health` without a token, `/mcp` behind `x-mcp-token`, nothing else. `/health` says nothing
23
+ * about the project's upstreams: their outage must not get a healthy server restarted.
24
+ */
25
+ export declare function createBridgeServer({ token, buildServer, maxBodyBytes, legacy, log, }: BridgeServerOptions): Server;
26
+ export interface ListenOptions {
27
+ host: string;
28
+ port: number;
29
+ /** Run once the server has stopped accepting requests, before the process exits. */
30
+ onShutdown?: () => void;
31
+ }
32
+ /** Listens, and closes cleanly on SIGINT / SIGTERM (`docker stop`). */
33
+ export declare function listen(server: Server, { host, port, onShutdown }: ListenOptions): Promise<void>;
34
+ /** True when the module at `moduleUrl` (`import.meta.url`) is the one node was started on. */
35
+ export declare function isEntryPoint(moduleUrl: string): boolean;
36
+ /**
37
+ * Runs `main`; a `ConfigError` becomes one log line and exit code 2, so that a misconfigured
38
+ * container says why in `docker logs` instead of a stack trace.
39
+ */
40
+ export declare function runMain(main: () => Promise<void>, log?: Logger): Promise<void>;
package/dist/http.js ADDED
@@ -0,0 +1,120 @@
1
+ // The MCP server over HTTP, reached only by a gateway on an internal network.
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import { argv } from "node:process";
5
+ import { pathToFileURL } from "node:url";
6
+ import { toNodeHandler } from "@modelcontextprotocol/node";
7
+ import { createMcpHandler } from "@modelcontextprotocol/server";
8
+ import { ConfigError } from "./errors.js";
9
+ import { loggerFactory } from "./log.js";
10
+ import { HEALTH_PATH, MCP_PATH, TOKEN_HEADER } from "./protocol.js";
11
+ export const DEFAULT_MAX_BODY_BYTES = 64 * 1024;
12
+ const digest = (s) => createHash("sha256").update(s, "utf8").digest();
13
+ // Constant time on fixed-length digests: `===` leaks the length of the matching prefix.
14
+ export function sameSecret(presented, expected) {
15
+ return presented.length > 0 && timingSafeEqual(digest(presented), digest(expected));
16
+ }
17
+ function send(response, code, body) {
18
+ const payload = JSON.stringify(body);
19
+ response.writeHead(code, {
20
+ "content-type": "application/json; charset=utf-8",
21
+ "content-length": Buffer.byteLength(payload),
22
+ });
23
+ response.end(payload);
24
+ }
25
+ class BodyError extends Error {
26
+ status;
27
+ constructor(message, status) {
28
+ super(message);
29
+ this.status = status;
30
+ }
31
+ }
32
+ // Read here rather than by `toNodeHandler`, so that the bound is the project's and the refusal ours.
33
+ async function readBody(request, maxBytes) {
34
+ const chunks = [];
35
+ let size = 0;
36
+ for await (const chunk of request) {
37
+ size += chunk.length;
38
+ if (size > maxBytes)
39
+ throw new BodyError("Request body too large.", 413);
40
+ chunks.push(chunk);
41
+ }
42
+ if (size === 0)
43
+ return undefined;
44
+ try {
45
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
46
+ }
47
+ catch {
48
+ throw new BodyError("Unreadable request body (JSON expected).", 400);
49
+ }
50
+ }
51
+ /**
52
+ * `/health` without a token, `/mcp` behind `x-mcp-token`, nothing else. `/health` says nothing
53
+ * about the project's upstreams: their outage must not get a healthy server restarted.
54
+ */
55
+ export function createBridgeServer({ token, buildServer, maxBodyBytes = DEFAULT_MAX_BODY_BYTES, legacy = "stateless", log = loggerFactory()("http"), }) {
56
+ const onerror = (err) => log.error("MCP request failed", err);
57
+ const mcp = createMcpHandler(buildServer, { legacy, responseMode: "json", onerror });
58
+ const handler = toNodeHandler(mcp, { onerror });
59
+ const server = createServer((request, response) => {
60
+ const path = (request.url ?? "").split("?")[0];
61
+ if (path === HEALTH_PATH) {
62
+ send(response, 200, { status: "ok" });
63
+ return;
64
+ }
65
+ if (path !== MCP_PATH) {
66
+ send(response, 404, { error: "Unknown path." });
67
+ return;
68
+ }
69
+ const presented = request.headers[TOKEN_HEADER];
70
+ if (!sameSecret(typeof presented === "string" ? presented : "", token)) {
71
+ send(response, 401, { error: "Missing or invalid authentication header." });
72
+ return;
73
+ }
74
+ readBody(request, maxBodyBytes)
75
+ .then((body) => handler(request, response, body), (err) => {
76
+ if (!(err instanceof BodyError))
77
+ throw err;
78
+ send(response, err.status, { error: err.message });
79
+ })
80
+ .catch((err) => {
81
+ log.error("request failed", err);
82
+ if (!response.headersSent)
83
+ send(response, 500, { error: "Internal error." });
84
+ else
85
+ response.end();
86
+ });
87
+ });
88
+ server.on("close", () => void mcp.close());
89
+ return server;
90
+ }
91
+ /** Listens, and closes cleanly on SIGINT / SIGTERM (`docker stop`). */
92
+ export async function listen(server, { host, port, onShutdown }) {
93
+ for (const signal of ["SIGINT", "SIGTERM"]) {
94
+ process.once(signal, () => server.close(() => {
95
+ onShutdown?.();
96
+ process.exit(0);
97
+ }));
98
+ }
99
+ await new Promise((resolve) => server.listen(port, host, resolve));
100
+ }
101
+ /** True when the module at `moduleUrl` (`import.meta.url`) is the one node was started on. */
102
+ export function isEntryPoint(moduleUrl) {
103
+ return Boolean(argv[1]) && moduleUrl === pathToFileURL(argv[1] ?? "").href;
104
+ }
105
+ /**
106
+ * Runs `main`; a `ConfigError` becomes one log line and exit code 2, so that a misconfigured
107
+ * container says why in `docker logs` instead of a stack trace.
108
+ */
109
+ export async function runMain(main, log = loggerFactory()("http")) {
110
+ try {
111
+ await main();
112
+ }
113
+ catch (err) {
114
+ if (!(err instanceof ConfigError))
115
+ throw err;
116
+ log.error(`invalid configuration, server not started: ${err.message}`);
117
+ process.exit(2);
118
+ }
119
+ }
120
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1,6 @@
1
+ export * from "./config.js";
2
+ export * from "./errors.js";
3
+ export * from "./http.js";
4
+ export * from "./jobs.js";
5
+ export * from "./log.js";
6
+ export * from "./protocol.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./config.js";
2
+ export * from "./errors.js";
3
+ export * from "./http.js";
4
+ export * from "./jobs.js";
5
+ export * from "./log.js";
6
+ export * from "./protocol.js";
7
+ //# sourceMappingURL=index.js.map
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { type Logger } from "./log.js";
2
+ import { type JobRun } from "./protocol.js";
3
+ export type ReportRun = (job: string, run: JobRun) => void;
4
+ /**
5
+ * `JOBS_REPORT_URL` is the root each run appends its name to (`…/sync`), `JOBS_REPORT_TOKEN` the
6
+ * secret it expects. Both or neither: without them nobody listens and nothing is sent. A failed
7
+ * report is only logged — the next run will tell again.
8
+ */
9
+ export declare function jobReporter(env?: NodeJS.ProcessEnv, log?: Logger): ReportRun;
package/dist/jobs.js ADDED
@@ -0,0 +1,34 @@
1
+ // What the gateway learns of a server's own timer: it can then watch it like any cron, and notice
2
+ // when it stops — a stopped timer leaves no error behind, only an expected run that
3
+ // never comes.
4
+ import { errorMessage } from "./errors.js";
5
+ import { loggerFactory } from "./log.js";
6
+ import { TOKEN_HEADER } from "./protocol.js";
7
+ const REPORT_TIMEOUT_MS = 10_000;
8
+ /**
9
+ * `JOBS_REPORT_URL` is the root each run appends its name to (`…/sync`), `JOBS_REPORT_TOKEN` the
10
+ * secret it expects. Both or neither: without them nobody listens and nothing is sent. A failed
11
+ * report is only logged — the next run will tell again.
12
+ */
13
+ export function jobReporter(env = process.env, log = loggerFactory()("jobs")) {
14
+ const root = env.JOBS_REPORT_URL?.trim().replace(/\/+$/, "") ?? "";
15
+ const token = env.JOBS_REPORT_TOKEN?.trim() ?? "";
16
+ if (!root || !token) {
17
+ if (root || token) {
18
+ log.warn("JOBS_REPORT_URL and JOBS_REPORT_TOKEN go together: runs not reported");
19
+ }
20
+ return () => undefined;
21
+ }
22
+ return (job, run) => {
23
+ void fetch(`${root}/${encodeURIComponent(job)}`, {
24
+ method: "POST",
25
+ headers: { "content-type": "application/json", [TOKEN_HEADER]: token },
26
+ body: JSON.stringify(run),
27
+ signal: AbortSignal.timeout(REPORT_TIMEOUT_MS),
28
+ }).then((response) => {
29
+ if (!response.ok)
30
+ log.warn(`run of ${job} not reported: HTTP ${response.status}`);
31
+ }, (err) => log.warn(`run of ${job} not reported: ${errorMessage(err)}`));
32
+ };
33
+ }
34
+ //# sourceMappingURL=jobs.js.map
package/dist/log.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export type Level = "debug" | "info" | "warn" | "error";
2
+ export interface Logger {
3
+ debug(message: string, ...rest: unknown[]): void;
4
+ info(message: string, ...rest: unknown[]): void;
5
+ warn(message: string, ...rest: unknown[]): void;
6
+ error(message: string, ...rest: unknown[]): void;
7
+ }
8
+ /**
9
+ * `levelVariable` names the project's own variable (`DEALABS_LOG_LEVEL`…), read at every line so
10
+ * that a test can change it. An unknown level means `info`.
11
+ */
12
+ export declare function loggerFactory(levelVariable?: string, env?: NodeJS.ProcessEnv): (scope: string) => Logger;
package/dist/log.js ADDED
@@ -0,0 +1,21 @@
1
+ /* eslint-disable no-console */
2
+ // stderr only: stdout would be the protocol channel if a stdio transport is ever added.
3
+ const ORDER = { debug: 10, info: 20, warn: 30, error: 40 };
4
+ /**
5
+ * `levelVariable` names the project's own variable (`DEALABS_LOG_LEVEL`…), read at every line so
6
+ * that a test can change it. An unknown level means `info`.
7
+ */
8
+ export function loggerFactory(levelVariable, env = process.env) {
9
+ const threshold = () => {
10
+ const raw = ((levelVariable && env[levelVariable]) || "info").toLowerCase();
11
+ return ORDER[raw] ?? ORDER.info;
12
+ };
13
+ return (scope) => {
14
+ const emit = (level) => (message, ...rest) => {
15
+ if (ORDER[level] >= threshold())
16
+ console.error(`[${level}] ${scope}: ${message}`, ...rest);
17
+ };
18
+ return { debug: emit("debug"), info: emit("info"), warn: emit("warn"), error: emit("error") };
19
+ };
20
+ }
21
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1,23 @@
1
+ /** Header carrying the shared secret. Neutral name: a generic bridge has no business knowing the project's. */
2
+ export declare const TOKEN_HEADER = "x-mcp-token";
3
+ /** The modern protocol revision the kit is tested against; a gateway may pin it for strict servers. */
4
+ export declare const PROTOCOL_VERSION = "2026-07-28";
5
+ export declare const MCP_PATH = "/mcp";
6
+ /** Unauthenticated, for the container healthcheck. */
7
+ export declare const HEALTH_PATH = "/health";
8
+ /** One run of a project's own timer, as reported to the gateway (`POST <root>/<job>`). */
9
+ export interface JobRun {
10
+ ok: boolean;
11
+ /** One line: what the run did, or what failed. */
12
+ detail: string;
13
+ /** Epoch milliseconds. */
14
+ startedAt: number;
15
+ }
16
+ /** A start further back than this is taken for a clock error, and replaced by the receipt time. */
17
+ export declare const JOB_RUN_MAX_AGE_MS = 86400000;
18
+ /**
19
+ * The receiving side: `undefined` when `ok` is not a boolean (the only field a run cannot do
20
+ * without); otherwise the run, with a missing detail emptied and an implausible start replaced by
21
+ * `now`.
22
+ */
23
+ export declare function parseJobRun(body: unknown, now?: number): JobRun | undefined;
@@ -0,0 +1,30 @@
1
+ // What both ends of the bridge must agree on: the gateway (client) imports this module as well, so the
2
+ // two sides cannot drift apart. No dependency, not even on the MCP SDK.
3
+ /** Header carrying the shared secret. Neutral name: a generic bridge has no business knowing the project's. */
4
+ export const TOKEN_HEADER = "x-mcp-token";
5
+ /** The modern protocol revision the kit is tested against; a gateway may pin it for strict servers. */
6
+ export const PROTOCOL_VERSION = "2026-07-28";
7
+ export const MCP_PATH = "/mcp";
8
+ /** Unauthenticated, for the container healthcheck. */
9
+ export const HEALTH_PATH = "/health";
10
+ /** A start further back than this is taken for a clock error, and replaced by the receipt time. */
11
+ export const JOB_RUN_MAX_AGE_MS = 86_400_000;
12
+ /**
13
+ * The receiving side: `undefined` when `ok` is not a boolean (the only field a run cannot do
14
+ * without); otherwise the run, with a missing detail emptied and an implausible start replaced by
15
+ * `now`.
16
+ */
17
+ export function parseJobRun(body, now = Date.now()) {
18
+ if (typeof body !== "object" || body === null)
19
+ return undefined;
20
+ const { ok, detail, startedAt } = body;
21
+ if (typeof ok !== "boolean")
22
+ return undefined;
23
+ const plausible = typeof startedAt === "number" && startedAt <= now && startedAt > now - JOB_RUN_MAX_AGE_MS;
24
+ return {
25
+ ok,
26
+ detail: typeof detail === "string" ? detail : "",
27
+ startedAt: plausible ? startedAt : now,
28
+ };
29
+ }
30
+ //# sourceMappingURL=protocol.js.map
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@m-d-b-code/mcp-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Shared foundation for MCP servers behind a gateway: authenticated stateless HTTP transport, env config, logging and job-run reporting",
5
+ "keywords": [
6
+ "mcp",
7
+ "model-context-protocol",
8
+ "mcp-server",
9
+ "gateway",
10
+ "streamable-http"
11
+ ],
12
+ "homepage": "https://github.com/m-d-b-code/mcp-kit#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/m-d-b-code/mcp-kit/issues"
15
+ },
16
+ "license": "MIT",
17
+ "author": "m-d-b-code",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/m-d-b-code/mcp-kit.git"
21
+ },
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=26"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "!dist/**/*.map",
29
+ "tsconfig.base.json"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./protocol": {
37
+ "types": "./dist/protocol.d.ts",
38
+ "default": "./dist/protocol.js"
39
+ },
40
+ "./eslint": {
41
+ "types": "./dist/eslint.d.ts",
42
+ "default": "./dist/eslint.js"
43
+ },
44
+ "./tsconfig.json": "./tsconfig.base.json"
45
+ },
46
+ "scripts": {
47
+ "prepare": "git config core.hooksPath .githooks || exit 0",
48
+ "build": "rm -rf dist && tsc -p tsconfig.json",
49
+ "prepack": "npm run build",
50
+ "test": "vitest run",
51
+ "typecheck": "tsc -p tsconfig.test.json",
52
+ "lint": "eslint . --max-warnings 0",
53
+ "format": "prettier --write .",
54
+ "format:check": "prettier --check .",
55
+ "check": "npm run format:check && npm run typecheck && npm run lint && npm test && npm run build"
56
+ },
57
+ "peerDependencies": {
58
+ "@eslint/js": ">=10",
59
+ "@modelcontextprotocol/node": "^2.0.0",
60
+ "@modelcontextprotocol/server": "^2.0.0",
61
+ "eslint": ">=10",
62
+ "typescript-eslint": "^8.0.0"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@eslint/js": {
66
+ "optional": true
67
+ },
68
+ "eslint": {
69
+ "optional": true
70
+ },
71
+ "typescript-eslint": {
72
+ "optional": true
73
+ }
74
+ },
75
+ "devDependencies": {
76
+ "@eslint/js": "^10.0.1",
77
+ "@modelcontextprotocol/client": "^2.4.0",
78
+ "@modelcontextprotocol/node": "^2.1.2",
79
+ "@modelcontextprotocol/server": "^2.4.0",
80
+ "@types/node": "^26.5.1",
81
+ "eslint": "^10.10.0",
82
+ "prettier": "^3.9.6",
83
+ "typescript": "npm:@typescript/typescript6@^6.0.2",
84
+ "typescript-eslint": "^8.70.0",
85
+ "vitest": "^5.0.0"
86
+ },
87
+ "publishConfig": {
88
+ "access": "public"
89
+ }
90
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/tsconfig",
3
+ "compilerOptions": {
4
+ "target": "ES2023",
5
+ "lib": ["ES2023"],
6
+ "types": ["node"],
7
+ "module": "NodeNext",
8
+ "moduleResolution": "NodeNext",
9
+ "rootDir": "${configDir}/src",
10
+ "outDir": "${configDir}/dist",
11
+ "strict": true,
12
+ "noUncheckedIndexedAccess": true,
13
+ "noImplicitOverride": true,
14
+ "noImplicitReturns": true,
15
+ "erasableSyntaxOnly": true,
16
+ "verbatimModuleSyntax": true,
17
+ "sourceMap": true,
18
+ "skipLibCheck": true,
19
+ "forceConsistentCasingInFileNames": true
20
+ },
21
+ "include": ["${configDir}/src/**/*.ts"]
22
+ }