@ubuligan/shared 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 jsznpm
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.
@@ -0,0 +1,65 @@
1
+ type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
2
+ interface Logger {
3
+ debug(msg: string, meta?: unknown): void;
4
+ info(msg: string, meta?: unknown): void;
5
+ warn(msg: string, meta?: unknown): void;
6
+ error(msg: string, meta?: unknown): void;
7
+ }
8
+ /**
9
+ * Minimal structured logger with no external dependency. In Node it writes to
10
+ * `process.stderr` (so it never corrupts stdio MCP protocol traffic); in the
11
+ * browser it falls back to `console`.
12
+ */
13
+ declare function createConsoleLogger(level?: LogLevel): Logger;
14
+ declare const noopLogger: Logger;
15
+
16
+ interface RetryOptions {
17
+ /** Max attempts including the first try. `1` disables retries. Default 3. */
18
+ retries?: number;
19
+ /** Base delay in ms for exponential backoff. Default 200. */
20
+ minDelayMs?: number;
21
+ /** Upper bound for a single backoff delay in ms. Default 5000. */
22
+ maxDelayMs?: number;
23
+ /** Decide whether an error is worth retrying. Default: retry everything. */
24
+ shouldRetry?: (error: unknown, attempt: number) => boolean;
25
+ }
26
+ /**
27
+ * Run `fn` with exponential backoff + full jitter. Used to wrap MCP requests so
28
+ * transient transport / network blips don't bubble up to callers.
29
+ */
30
+ declare function withRetry<T>(fn: () => Promise<T>, opts?: RetryOptions, logger?: Logger, label?: string): Promise<T>;
31
+
32
+ interface StdioTransportConfig {
33
+ type: "stdio";
34
+ /** Executable to spawn, e.g. "node". */
35
+ command: string;
36
+ /** Arguments passed to the command, e.g. ["dist/index.js"]. */
37
+ args?: string[];
38
+ /** Extra environment variables merged onto the spawned process env. */
39
+ env?: Record<string, string>;
40
+ /** Working directory for the spawned process. */
41
+ cwd?: string;
42
+ }
43
+ interface HttpTransportConfig {
44
+ type: "http";
45
+ /** Endpoint URL of the Streamable HTTP MCP server. */
46
+ url: string;
47
+ /** Static headers (merged after auth headers). */
48
+ headers?: Record<string, string>;
49
+ }
50
+ type TransportConfig = StdioTransportConfig | HttpTransportConfig;
51
+ /**
52
+ * Resolve dynamic auth into request headers. Either a static record or an async
53
+ * getter (e.g. to refresh a bearer token before each connection).
54
+ */
55
+ type AuthConfig = {
56
+ type: "bearer";
57
+ token: string | (() => string | Promise<string>);
58
+ } | {
59
+ type: "headers";
60
+ headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
61
+ };
62
+ /** Resolve an {@link AuthConfig} into concrete request headers. */
63
+ declare function resolveAuthHeaders(auth?: AuthConfig): Promise<Record<string, string>>;
64
+
65
+ export { type AuthConfig, type HttpTransportConfig, type LogLevel, type Logger, type RetryOptions, type StdioTransportConfig, type TransportConfig, createConsoleLogger, noopLogger, resolveAuthHeaders, withRetry };
package/dist/index.js ADDED
@@ -0,0 +1,90 @@
1
+ // src/logger.ts
2
+ var LEVEL_ORDER = {
3
+ debug: 10,
4
+ info: 20,
5
+ warn: 30,
6
+ error: 40
7
+ };
8
+ function createConsoleLogger(level = "info") {
9
+ const threshold = level === "silent" ? Infinity : LEVEL_ORDER[level];
10
+ const hasStderr = typeof process !== "undefined" && !!process.stderr?.write;
11
+ const emit = (lvl) => (msg, meta) => {
12
+ if (LEVEL_ORDER[lvl] < threshold) return;
13
+ const line = `[mcp-toolkit] ${lvl.toUpperCase()} ${msg}`;
14
+ if (hasStderr) {
15
+ process.stderr.write(meta !== void 0 ? `${line} ${safe(meta)}
16
+ ` : `${line}
17
+ `);
18
+ } else {
19
+ const fn = lvl === "debug" ? console.debug : lvl === "warn" ? console.warn : lvl === "error" ? console.error : console.info;
20
+ if (meta !== void 0) fn(line, meta);
21
+ else fn(line);
22
+ }
23
+ };
24
+ return {
25
+ debug: emit("debug"),
26
+ info: emit("info"),
27
+ warn: emit("warn"),
28
+ error: emit("error")
29
+ };
30
+ }
31
+ function safe(meta) {
32
+ try {
33
+ return typeof meta === "string" ? meta : JSON.stringify(meta);
34
+ } catch {
35
+ return String(meta);
36
+ }
37
+ }
38
+ var noopLogger = {
39
+ debug() {
40
+ },
41
+ info() {
42
+ },
43
+ warn() {
44
+ },
45
+ error() {
46
+ }
47
+ };
48
+
49
+ // src/retry.ts
50
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
51
+ async function withRetry(fn, opts = {}, logger, label = "request") {
52
+ const retries = Math.max(1, opts.retries ?? 3);
53
+ const minDelay = opts.minDelayMs ?? 200;
54
+ const maxDelay = opts.maxDelayMs ?? 5e3;
55
+ const shouldRetry = opts.shouldRetry ?? (() => true);
56
+ let lastError;
57
+ for (let attempt = 1; attempt <= retries; attempt++) {
58
+ try {
59
+ return await fn();
60
+ } catch (error) {
61
+ lastError = error;
62
+ if (attempt >= retries || !shouldRetry(error, attempt)) break;
63
+ const backoff = Math.min(maxDelay, minDelay * 2 ** (attempt - 1));
64
+ const delay = Math.round(Math.random() * backoff);
65
+ logger?.warn(`${label} failed (attempt ${attempt}/${retries}), retrying in ${delay}ms`, errMsg(error));
66
+ await sleep(delay);
67
+ }
68
+ }
69
+ throw lastError;
70
+ }
71
+ function errMsg(error) {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
74
+
75
+ // src/transport-types.ts
76
+ async function resolveAuthHeaders(auth) {
77
+ if (!auth) return {};
78
+ if (auth.type === "bearer") {
79
+ const token = typeof auth.token === "function" ? await auth.token() : auth.token;
80
+ return { Authorization: `Bearer ${token}` };
81
+ }
82
+ return typeof auth.headers === "function" ? await auth.headers() : auth.headers;
83
+ }
84
+ export {
85
+ createConsoleLogger,
86
+ noopLogger,
87
+ resolveAuthHeaders,
88
+ withRetry
89
+ };
90
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/logger.ts","../src/retry.ts","../src/transport-types.ts"],"sourcesContent":["export type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"silent\";\n\nexport interface Logger {\n debug(msg: string, meta?: unknown): void;\n info(msg: string, meta?: unknown): void;\n warn(msg: string, meta?: unknown): void;\n error(msg: string, meta?: unknown): void;\n}\n\nconst LEVEL_ORDER: Record<Exclude<LogLevel, \"silent\">, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n};\n\n/**\n * Minimal structured logger with no external dependency. In Node it writes to\n * `process.stderr` (so it never corrupts stdio MCP protocol traffic); in the\n * browser it falls back to `console`.\n */\nexport function createConsoleLogger(level: LogLevel = \"info\"): Logger {\n const threshold = level === \"silent\" ? Infinity : LEVEL_ORDER[level];\n const hasStderr = typeof process !== \"undefined\" && !!process.stderr?.write;\n\n const emit =\n (lvl: Exclude<LogLevel, \"silent\">) =>\n (msg: string, meta?: unknown): void => {\n if (LEVEL_ORDER[lvl] < threshold) return;\n const line = `[mcp-toolkit] ${lvl.toUpperCase()} ${msg}`;\n if (hasStderr) {\n process.stderr.write(meta !== undefined ? `${line} ${safe(meta)}\\n` : `${line}\\n`);\n } else {\n const fn = lvl === \"debug\" ? console.debug : lvl === \"warn\" ? console.warn : lvl === \"error\" ? console.error : console.info;\n if (meta !== undefined) fn(line, meta);\n else fn(line);\n }\n };\n\n return {\n debug: emit(\"debug\"),\n info: emit(\"info\"),\n warn: emit(\"warn\"),\n error: emit(\"error\"),\n };\n}\n\nfunction safe(meta: unknown): string {\n try {\n return typeof meta === \"string\" ? meta : JSON.stringify(meta);\n } catch {\n return String(meta);\n }\n}\n\nexport const noopLogger: Logger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n","import type { Logger } from \"./logger.js\";\n\nexport interface RetryOptions {\n /** Max attempts including the first try. `1` disables retries. Default 3. */\n retries?: number;\n /** Base delay in ms for exponential backoff. Default 200. */\n minDelayMs?: number;\n /** Upper bound for a single backoff delay in ms. Default 5000. */\n maxDelayMs?: number;\n /** Decide whether an error is worth retrying. Default: retry everything. */\n shouldRetry?: (error: unknown, attempt: number) => boolean;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Run `fn` with exponential backoff + full jitter. Used to wrap MCP requests so\n * transient transport / network blips don't bubble up to callers.\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n opts: RetryOptions = {},\n logger?: Logger,\n label = \"request\",\n): Promise<T> {\n const retries = Math.max(1, opts.retries ?? 3);\n const minDelay = opts.minDelayMs ?? 200;\n const maxDelay = opts.maxDelayMs ?? 5000;\n const shouldRetry = opts.shouldRetry ?? (() => true);\n\n let lastError: unknown;\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt >= retries || !shouldRetry(error, attempt)) break;\n const backoff = Math.min(maxDelay, minDelay * 2 ** (attempt - 1));\n const delay = Math.round(Math.random() * backoff);\n logger?.warn(`${label} failed (attempt ${attempt}/${retries}), retrying in ${delay}ms`, errMsg(error));\n await sleep(delay);\n }\n }\n throw lastError;\n}\n\nfunction errMsg(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","export interface StdioTransportConfig {\n type: \"stdio\";\n /** Executable to spawn, e.g. \"node\". */\n command: string;\n /** Arguments passed to the command, e.g. [\"dist/index.js\"]. */\n args?: string[];\n /** Extra environment variables merged onto the spawned process env. */\n env?: Record<string, string>;\n /** Working directory for the spawned process. */\n cwd?: string;\n}\n\nexport interface HttpTransportConfig {\n type: \"http\";\n /** Endpoint URL of the Streamable HTTP MCP server. */\n url: string;\n /** Static headers (merged after auth headers). */\n headers?: Record<string, string>;\n}\n\nexport type TransportConfig = StdioTransportConfig | HttpTransportConfig;\n\n/**\n * Resolve dynamic auth into request headers. Either a static record or an async\n * getter (e.g. to refresh a bearer token before each connection).\n */\nexport type AuthConfig =\n | { type: \"bearer\"; token: string | (() => string | Promise<string>) }\n | {\n type: \"headers\";\n headers:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n };\n\n/** Resolve an {@link AuthConfig} into concrete request headers. */\nexport async function resolveAuthHeaders(auth?: AuthConfig): Promise<Record<string, string>> {\n if (!auth) return {};\n if (auth.type === \"bearer\") {\n const token = typeof auth.token === \"function\" ? await auth.token() : auth.token;\n return { Authorization: `Bearer ${token}` };\n }\n return typeof auth.headers === \"function\" ? await auth.headers() : auth.headers;\n}\n"],"mappings":";AASA,IAAM,cAA2D;AAAA,EAC/D,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAOO,SAAS,oBAAoB,QAAkB,QAAgB;AACpE,QAAM,YAAY,UAAU,WAAW,WAAW,YAAY,KAAK;AACnE,QAAM,YAAY,OAAO,YAAY,eAAe,CAAC,CAAC,QAAQ,QAAQ;AAEtE,QAAM,OACJ,CAAC,QACD,CAAC,KAAa,SAAyB;AACrC,QAAI,YAAY,GAAG,IAAI,UAAW;AAClC,UAAM,OAAO,iBAAiB,IAAI,YAAY,CAAC,IAAI,GAAG;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AC,YAAY,OAAO,OAAO,EAAG;AACxD,YAAM,UAAU,KAAK,IAAI,UAAU,WAAW,MAAM,UAAU,EAAE;AAChE,YAAM,QAAQ,KAAK,MAAM,KAAK,OAAO,IAAI,OAAO;AAChD,cAAQ,KAAK,GAAG,KAAK,oBAAoB,OAAO,IAAI,OAAO,kBAAkB,KAAK,MAAM,OAAO,KAAK,CAAC;AACrG,YAAM,MAAM,KAAK;AAAA,IACnB;AAAA,EACF;AACA,QAAM;AACR;AAEA,SAAS,OAAO,OAAwB;AACtC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;ACZA,eAAsB,mBAAmB,MAAoD;AAC3F,MAAI,CAAC,KAAM,QAAO,CAAC;AACnB,MAAI,KAAK,SAAS,UAAU;AAC1B,UAAM,QAAQ,OAAO,KAAK,UAAU,aAAa,MAAM,KAAK,MAAM,IAAI,KAAK;AAC3E,WAAO,EAAE,eAAe,UAAU,KAAK,GAAG;AAAA,EAC5C;AACA,SAAO,OAAO,KAAK,YAAY,aAAa,MAAM,KAAK,QAAQ,IAAI,KAAK;AAC1E;","names":[]}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@ubuligan/shared",
3
+ "version": "0.1.0",
4
+ "description": "Shared, dependency-free types and utilities for the MCP Toolkit (logger, retry, transport types)",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "main": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "files": [
17
+ "dist",
18
+ "LICENSE"
19
+ ],
20
+ "devDependencies": {
21
+ "tsup": "^8.3.5",
22
+ "typescript": "^5.7.2"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "author": "jsznpm",
28
+ "homepage": "https://github.com/jsznpm/create-mcp-toolkit#readme",
29
+ "bugs": {
30
+ "url": "https://github.com/jsznpm/create-mcp-toolkit/issues"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/jsznpm/create-mcp-toolkit.git",
35
+ "directory": "packages/shared"
36
+ },
37
+ "keywords": [
38
+ "mcp",
39
+ "model-context-protocol",
40
+ "ai",
41
+ "llm",
42
+ "types",
43
+ "utils"
44
+ ],
45
+ "scripts": {
46
+ "build": "tsup",
47
+ "typecheck": "tsc --noEmit"
48
+ }
49
+ }