Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

toolception

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

toolception - npm Package Compare versions

Comparing version
0.5.3
to
0.5.4
+298
-293
dist/index.js

@@ -1,9 +0,9 @@

var se = Object.defineProperty;
var te = Object.defineProperty;
var L = (r) => {
throw TypeError(r);
};
var te = (r, e, s) => e in r ? se(r, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : r[e] = s;
var d = (r, e, s) => te(r, typeof e != "symbol" ? e + "" : e, s), oe = (r, e, s) => e.has(r) || L("Cannot " + s);
var b = (r, e, s) => e.has(r) ? L("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, s);
var m = (r, e, s) => (oe(r, e, "access private method"), s);
var se = (r, e, t) => e in r ? te(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
var d = (r, e, t) => se(r, typeof e != "symbol" ? e + "" : e, t), oe = (r, e, t) => e.has(r) || L("Cannot " + t);
var b = (r, e, t) => e.has(r) ? L("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t);
var m = (r, e, t) => (oe(r, e, "access private method"), t);
import { z as y } from "zod";

@@ -14,3 +14,3 @@ import j from "fastify";

import { StreamableHTTPServerTransport as D } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { isInitializeRequest as z } from "@modelcontextprotocol/sdk/types.js";
import { isInitializeRequest as O } from "@modelcontextprotocol/sdk/types.js";
const R = {

@@ -32,9 +32,9 @@ dynamic: [

}
resolveMode(e, s) {
return this.isDynamicEnabled(s) ? "DYNAMIC" : this.getToolsetsString(s) ? "STATIC" : this.isDynamicEnabled(e) ? "DYNAMIC" : this.getToolsetsString(e) ? "STATIC" : null;
resolveMode(e, t) {
return this.isDynamicEnabled(t) ? "DYNAMIC" : this.getToolsetsString(t) ? "STATIC" : this.isDynamicEnabled(e) ? "DYNAMIC" : this.getToolsetsString(e) ? "STATIC" : null;
}
parseCommaSeparatedToolSets(e, s) {
parseCommaSeparatedToolSets(e, t) {
if (!e || typeof e != "string") return [];
const t = e.split(",").map((n) => n.trim()).filter((n) => n.length > 0), o = new Set(Object.keys(s)), i = [];
for (const n of t)
const s = e.split(",").map((n) => n.trim()).filter((n) => n.length > 0), o = new Set(Object.keys(t)), i = [];
for (const n of s)
o.has(n) ? i.push(n) : console.warn(

@@ -47,11 +47,11 @@ `Invalid toolset '${n}' ignored. Available: ${Array.from(

}
getModulesForToolSets(e, s) {
const t = /* @__PURE__ */ new Set();
getModulesForToolSets(e, t) {
const s = /* @__PURE__ */ new Set();
for (const o of e) {
const i = s[o];
i && (i.modules || []).forEach((n) => t.add(n));
const i = t[o];
i && (i.modules || []).forEach((n) => s.add(n));
}
return Array.from(t);
return Array.from(s);
}
validateToolsetName(e, s) {
validateToolsetName(e, t) {
if (!e || typeof e != "string")

@@ -61,15 +61,15 @@ return {

error: `Invalid toolset name provided. Must be a non-empty string. Available toolsets: ${Object.keys(
s
t
).join(", ")}`
};
const t = e.trim();
return t.length === 0 ? {
const s = e.trim();
return s.length === 0 ? {
isValid: !1,
error: `Empty toolset name provided. Available toolsets: ${Object.keys(
s
t
).join(", ")}`
} : s[t] ? { isValid: !0, sanitized: t } : {
} : t[s] ? { isValid: !0, sanitized: s } : {
isValid: !1,
error: `Toolset '${t}' not found. Available toolsets: ${Object.keys(
s
error: `Toolset '${s}' not found. Available toolsets: ${Object.keys(
t
).join(", ")}`

@@ -85,6 +85,6 @@ };

*/
validateToolsetModules(e, s) {
validateToolsetModules(e, t) {
try {
for (const o of e)
if (!s[o])
if (!t[o])
return {

@@ -94,7 +94,7 @@ isValid: !1,

};
return { isValid: !0, modules: this.getModulesForToolSets(e, s) };
} catch (t) {
return { isValid: !0, modules: this.getModulesForToolSets(e, t) };
} catch (s) {
return {
isValid: !1,
error: `Error resolving modules for ${e.join(", ")}: ${t instanceof Error ? t.message : "Unknown error"}`
error: `Error resolving modules for ${e.join(", ")}: ${s instanceof Error ? s.message : "Unknown error"}`
};

@@ -105,5 +105,5 @@ }

if (!e) return !1;
for (const s of this.keys.dynamic) {
const t = e[s];
if (t === !0 || typeof t == "string" && t.trim().toLowerCase() === "true")
for (const t of this.keys.dynamic) {
const s = e[t];
if (s === !0 || typeof s == "string" && s.trim().toLowerCase() === "true")
return !0;

@@ -115,6 +115,6 @@ }

if (e)
for (const s of this.keys.toolsets) {
const t = e[s];
if (typeof t == "string" && t.trim().length > 0)
return t;
for (const t of this.keys.toolsets) {
const s = e[t];
if (typeof s == "string" && s.trim().length > 0)
return s;
}

@@ -143,4 +143,4 @@ }

};
const s = e.trim();
return s.length === 0 ? {
const t = e.trim();
return t.length === 0 ? {
isValid: !1,

@@ -150,5 +150,5 @@ error: `Empty toolset name provided. Available toolsets: ${this.getAvailableToolsets().join(

)}`
} : this.catalog[s] ? { isValid: !0, sanitized: s } : {
} : this.catalog[t] ? { isValid: !0, sanitized: t } : {
isValid: !1,
error: `Toolset '${s}' not found. Available toolsets: ${this.getAvailableToolsets().join(
error: `Toolset '${t}' not found. Available toolsets: ${this.getAvailableToolsets().join(
", "

@@ -158,7 +158,7 @@ )}`

}
async resolveToolsForToolsets(e, s) {
const t = [];
async resolveToolsForToolsets(e, t) {
const s = [];
for (const o of e) {
const i = this.catalog[o];
if (i && (Array.isArray(i.tools) && i.tools.length > 0 && t.push(...i.tools), Array.isArray(i.modules) && i.modules.length > 0))
if (i && (Array.isArray(i.tools) && i.tools.length > 0 && s.push(...i.tools), Array.isArray(i.modules) && i.modules.length > 0))
for (const n of i.modules) {

@@ -168,4 +168,4 @@ const l = this.moduleLoaders[n];

try {
const a = await l(s);
Array.isArray(a) && a.length > 0 && t.push(...a);
const a = await l(t);
Array.isArray(a) && a.length > 0 && s.push(...a);
} catch (a) {

@@ -179,14 +179,14 @@ console.warn(

}
return t;
return s;
}
}
class N extends Error {
constructor(s, t, o, i) {
super(s);
constructor(t, s, o, i) {
super(t);
d(this, "code");
d(this, "details");
this.name = "ToolingError", this.code = t, this.details = o;
this.name = "ToolingError", this.code = s, this.details = o;
}
}
class O {
class z {
constructor(e = {}) {

@@ -200,4 +200,4 @@ d(this, "options");

}
getSafeName(e, s) {
return !this.options.namespaceWithToolset || s.startsWith(`${e}.`) ? s : `${e}.${s}`;
getSafeName(e, t) {
return !this.options.namespaceWithToolset || t.startsWith(`${e}.`) ? t : `${e}.${t}`;
}

@@ -215,10 +215,10 @@ has(e) {

}
addForToolset(e, s) {
this.add(s);
const t = this.toolsetToNames.get(e) ?? /* @__PURE__ */ new Set();
t.add(s), this.toolsetToNames.set(e, t);
addForToolset(e, t) {
this.add(t);
const s = this.toolsetToNames.get(e) ?? /* @__PURE__ */ new Set();
s.add(t), this.toolsetToNames.set(e, s);
}
mapAndValidate(e, s) {
return s.map((t) => {
const o = this.getSafeName(e, t.name);
mapAndValidate(e, t) {
return t.map((s) => {
const o = this.getSafeName(e, s.name);
if (this.has(o))

@@ -229,3 +229,3 @@ throw new N(

);
return { ...t, name: o };
return { ...s, name: o };
});

@@ -238,4 +238,4 @@ }

const e = {};
for (const [s, t] of this.toolsetToNames.entries())
e[s] = Array.from(t);
for (const [t, s] of this.toolsetToNames.entries())
e[t] = Array.from(s);
return e;

@@ -253,3 +253,3 @@ }

d(this, "activeToolsets", /* @__PURE__ */ new Set());
this.server = e.server, this.resolver = e.resolver, this.context = e.context, this.onToolsListChanged = e.onToolsListChanged, this.exposurePolicy = e.exposurePolicy, this.toolRegistry = e.toolRegistry ?? new O({ namespaceWithToolset: !0 });
this.server = e.server, this.resolver = e.resolver, this.context = e.context, this.onToolsListChanged = e.onToolsListChanged, this.exposurePolicy = e.exposurePolicy, this.toolRegistry = e.toolRegistry ?? new z({ namespaceWithToolset: !0 });
}

@@ -289,10 +289,10 @@ /**

*/
async enableToolset(e, s = !1) {
const t = this.resolver.validateToolsetName(e);
if (!t.isValid || !t.sanitized)
async enableToolset(e, t = !1) {
const s = this.resolver.validateToolsetName(e);
if (!s.isValid || !s.sanitized)
return {
success: !1,
message: t.error || "Unknown validation error"
message: s.error || "Unknown validation error"
};
const o = t.sanitized;
const o = s.sanitized;
if (this.activeToolsets.has(o))

@@ -320,3 +320,3 @@ return {

}
return this.activeToolsets.add(o), s || await this.notifyToolsChanged(), {
return this.activeToolsets.add(o), t || await this.notifyToolsChanged(), {
success: !0,

@@ -361,3 +361,3 @@ message: `Toolset '${o}' enabled successfully. Registered ${l?.length ?? 0} tools.`

*/
registerSingleTool(e, s) {
registerSingleTool(e, t) {
this.server.tool(

@@ -367,4 +367,4 @@ e.name,

e.inputSchema,
async (t) => await e.handler(t)
), this.toolRegistry.addForToolset(s, e.name);
async (s) => await e.handler(s)
), this.toolRegistry.addForToolset(t, e.name);
}

@@ -378,17 +378,17 @@ /**

async disableToolset(e) {
const s = this.resolver.validateToolsetName(e);
if (!s.isValid || !s.sanitized) {
const t = this.resolver.validateToolsetName(e);
if (!t.isValid || !t.sanitized) {
const o = Array.from(this.activeToolsets).join(", ") || "none";
return {
success: !1,
message: `${s.error || "Unknown validation error"} Active toolsets: ${o}`
message: `${t.error || "Unknown validation error"} Active toolsets: ${o}`
};
}
const t = s.sanitized;
return this.activeToolsets.has(t) ? (this.activeToolsets.delete(t), await this.notifyToolsChanged(), {
const s = t.sanitized;
return this.activeToolsets.has(s) ? (this.activeToolsets.delete(s), await this.notifyToolsChanged(), {
success: !0,
message: `Toolset '${t}' disabled successfully. Individual tools remain registered due to MCP limitations.`
message: `Toolset '${s}' disabled successfully. Individual tools remain registered due to MCP limitations.`
}) : {
success: !1,
message: `Toolset '${t}' is not currently active. Active toolsets: ${Array.from(this.activeToolsets).join(", ") || "none"}`
message: `Toolset '${s}' is not currently active. Active toolsets: ${Array.from(this.activeToolsets).join(", ") || "none"}`
};

@@ -414,9 +414,9 @@ }

async enableToolsets(e) {
const s = [];
const t = [];
for (const n of e)
try {
const l = await this.enableToolset(n, !0);
s.push({ name: n, ...l });
t.push({ name: n, ...l });
} catch (l) {
s.push({
t.push({
name: n,

@@ -428,4 +428,4 @@ success: !1,

}
const t = s.every((n) => n.success), o = s.some((n) => n.success), i = t ? "All toolsets enabled" : o ? "Some toolsets failed to enable" : "All toolsets failed to enable";
return o && await this.notifyToolsChanged(), { success: t, results: s, message: i };
const s = t.every((n) => n.success), o = t.some((n) => n.success), i = s ? "All toolsets enabled" : o ? "Some toolsets failed to enable" : "All toolsets failed to enable";
return o && await this.notifyToolsChanged(), { success: s, results: t, message: i };
}

@@ -441,7 +441,8 @@ /**

}
function ae(r, e, s) {
(s?.mode ?? "DYNAMIC") === "DYNAMIC" && (r.tool(
function ae(r, e, t) {
(t?.mode ?? "DYNAMIC") === "DYNAMIC" && (r.tool(
"enable_toolset",
"Enable a toolset by name",
{ name: y.string().describe("Toolset name") },
{ destructiveHint: !0, idempotentHint: !0 },
async (o) => {

@@ -457,2 +458,3 @@ const i = await e.enableToolset(o.name);

{ name: y.string().describe("Toolset name") },
{ destructiveHint: !0, idempotentHint: !0 },
async (o) => {

@@ -468,2 +470,3 @@ const i = await e.disableToolset(o.name);

{},
{ readOnlyHint: !0, idempotentHint: !0 },
async () => {

@@ -494,2 +497,3 @@ const o = e.getAvailableToolsets(), i = e.getStatus().toolsetToTools, n = o.map((l) => {

{ name: y.string().describe("Toolset name") },
{ readOnlyHint: !0, idempotentHint: !0 },
async (o) => {

@@ -525,2 +529,3 @@ const i = e.getToolsetDefinition(o.name), n = e.getStatus().toolsetToTools;

{},
{ readOnlyHint: !0, idempotentHint: !0 },
async () => {

@@ -546,8 +551,8 @@ const o = e.getStatus(), i = {

this.toolsetValidator = new re();
const s = e.startup ?? {}, t = this.resolveStartupConfig(s, e.catalog);
this.mode = t.mode, this.resolver = new ie({
const t = e.startup ?? {}, s = this.resolveStartupConfig(t, e.catalog);
this.mode = s.mode, this.resolver = new ie({
catalog: e.catalog,
moduleLoaders: e.moduleLoaders
});
const o = new O({
const o = new z({
namespaceWithToolset: e.exposurePolicy?.namespaceToolsWithSetKey ?? !0

@@ -563,3 +568,3 @@ });

}), e.registerMetaTools !== !1 && ae(e.server, this.manager, { mode: this.mode });
const i = t.toolsets;
const i = s.toolsets;
this.initPromise = this.initializeToolsets(i);

@@ -577,4 +582,4 @@ }

e === "ALL" ? await this.manager.enableToolsets(this.resolver.getAvailableToolsets()) : Array.isArray(e) && e.length > 0 && await this.manager.enableToolsets(e);
} catch (s) {
this.initError = s instanceof Error ? s : new Error(String(s)), console.error("Failed to initialize toolsets:", this.initError);
} catch (t) {
this.initError = t instanceof Error ? t : new Error(String(t)), console.error("Failed to initialize toolsets:", this.initError);
}

@@ -599,3 +604,3 @@ }

}
resolveStartupConfig(e, s) {
resolveStartupConfig(e, t) {
if (e.mode) {

@@ -607,8 +612,8 @@ if (e.mode === "DYNAMIC" && e.toolsets)

return { mode: "STATIC", toolsets: "ALL" };
const t = Array.isArray(e.toolsets) ? e.toolsets : [], o = [];
for (const i of t) {
const { isValid: n, sanitized: l, error: a } = this.toolsetValidator.validateToolsetName(i, s);
const s = Array.isArray(e.toolsets) ? e.toolsets : [], o = [];
for (const i of s) {
const { isValid: n, sanitized: l, error: a } = this.toolsetValidator.validateToolsetName(i, t);
n && l ? o.push(l) : a && console.warn(a);
}
if (t.length > 0 && o.length === 0)
if (s.length > 0 && o.length === 0)
throw new Error(

@@ -623,12 +628,12 @@ "STATIC mode requires valid toolsets or 'ALL'; none were valid"

if (Array.isArray(e.toolsets) && e.toolsets.length > 0) {
const t = [];
const s = [];
for (const o of e.toolsets) {
const { isValid: i, sanitized: n, error: l } = this.toolsetValidator.validateToolsetName(o, s);
i && n ? t.push(n) : l && console.warn(l);
const { isValid: i, sanitized: n, error: l } = this.toolsetValidator.validateToolsetName(o, t);
i && n ? s.push(n) : l && console.warn(l);
}
if (t.length === 0)
if (s.length === 0)
throw new Error(
"STATIC mode requires valid toolsets or 'ALL'; none were valid"
);
return { mode: "STATIC", toolsets: t };
return { mode: "STATIC", toolsets: s };
}

@@ -655,4 +660,4 @@ return { mode: "DYNAMIC" };

this.maxSize = e.maxSize ?? 1e3, this.ttlMs = e.ttlMs ?? 1e3 * 60 * 60, this.onEvict = e.onEvict;
const s = e.pruneIntervalMs ?? 1e3 * 60 * 10;
this.pruneInterval = setInterval(() => this.pruneExpired(), s);
const t = e.pruneIntervalMs ?? 1e3 * 60 * 10;
this.pruneInterval = setInterval(() => this.pruneExpired(), t);
}

@@ -669,9 +674,9 @@ getEntryCount() {

get(e) {
const s = this.storage.get(e);
return s ? Date.now() - s.lastAccessed > this.ttlMs ? (this.delete(e), null) : (s.lastAccessed = Date.now(), this.storage.delete(e), this.storage.set(e, s), s.resource) : null;
const t = this.storage.get(e);
return t ? Date.now() - t.lastAccessed > this.ttlMs ? (this.delete(e), null) : (t.lastAccessed = Date.now(), this.storage.delete(e), this.storage.set(e, t), t.resource) : null;
}
set(e, s) {
set(e, t) {
this.storage.size >= this.maxSize && this.evictLeastRecentlyUsed();
const t = { resource: s, lastAccessed: Date.now() };
this.storage.set(e, t);
const s = { resource: t, lastAccessed: Date.now() };
this.storage.set(e, s);
}

@@ -684,4 +689,4 @@ /**

delete(e) {
const s = this.storage.get(e);
s && (this.storage.delete(e), m(this, w, E).call(this, e, s.resource));
const t = this.storage.get(e);
t && (this.storage.delete(e), m(this, w, E).call(this, e, t.resource));
}

@@ -702,4 +707,4 @@ /**

this.storage.clear();
for (const [s, t] of e)
m(this, w, E).call(this, s, t.resource);
for (const [t, s] of e)
m(this, w, E).call(this, t, s.resource);
}

@@ -719,7 +724,7 @@ /**

pruneExpired() {
const e = Date.now(), s = [];
for (const [t, o] of this.storage.entries())
e - o.lastAccessed > this.ttlMs && s.push(t);
for (const t of s)
this.delete(t);
const e = Date.now(), t = [];
for (const [s, o] of this.storage.entries())
e - o.lastAccessed > this.ttlMs && t.push(s);
for (const s of t)
this.delete(s);
}

@@ -733,16 +738,16 @@ }

*/
E = function(e, s) {
E = function(e, t) {
if (this.onEvict)
try {
const t = this.onEvict(e, s);
t instanceof Promise && t.catch((o) => {
const s = this.onEvict(e, t);
s instanceof Promise && s.catch((o) => {
console.warn(`Error in cache eviction callback for key '${e}':`, o);
});
} catch (t) {
console.warn(`Error in cache eviction callback for key '${e}':`, t);
} catch (s) {
console.warn(`Error in cache eviction callback for key '${e}':`, s);
}
};
function F(r, e, s, t) {
function F(r, e, t, s) {
const o = ["/mcp", "/healthz", "/tools", "/.well-known/mcp-config"];
for (const i of s) {
for (const i of t) {
const n = `${e}${i.path}`;

@@ -758,3 +763,3 @@ if (o.some(

const a = i.method.toLowerCase();
r[a](n, async (c, h) => {
r[a](n, async (c, u) => {
try {

@@ -766,3 +771,3 @@ const f = c.headers["mcp-client-id"]?.trim(), v = f && f.length > 0 ? f : `anon-${T()}`;

if (!g.success)
return S(h, "body", g.error);
return S(u, "body", g.error);
x = g.data;

@@ -774,3 +779,3 @@ }

if (!g.success)
return S(h, "query", g.error);
return S(u, "query", g.error);
I = g.data;

@@ -782,3 +787,3 @@ }

if (!g.success)
return S(h, "params", g.error);
return S(u, "params", g.error);
M = g.data;

@@ -793,4 +798,4 @@ }

};
if (t?.contextExtractor) {
const g = await t.contextExtractor(c);
if (s?.contextExtractor) {
const g = await s.contextExtractor(c);
Object.assign(P, g);

@@ -804,3 +809,3 @@ }

g.error
), h.code(500), {
), u.code(500), {
error: {

@@ -817,3 +822,3 @@ code: "RESPONSE_VALIDATION_ERROR",

f
), h.code(500), {
), u.code(500), {
error: {

@@ -828,3 +833,3 @@ code: "INTERNAL_ERROR",

}
function S(r, e, s) {
function S(r, e, t) {
return r.code(400), {

@@ -834,3 +839,3 @@ error: {

message: `Validation failed for ${e}`,
details: s.errors
details: t.errors
}

@@ -840,3 +845,3 @@ };

class le {
constructor(e, s, t = {}, o) {
constructor(e, t, s = {}, o) {
d(this, "options");

@@ -849,14 +854,14 @@ d(this, "defaultManager");

d(this, "clientCache", new V({
onEvict: (e, s) => {
this.cleanupBundle(s);
onEvict: (e, t) => {
this.cleanupBundle(t);
}
}));
this.defaultManager = e, this.createBundle = s, this.options = {
host: t.host ?? "0.0.0.0",
port: t.port ?? 3e3,
basePath: t.basePath ?? "/",
cors: t.cors ?? !0,
logger: t.logger ?? !1,
app: t.app,
customEndpoints: t.customEndpoints
this.defaultManager = e, this.createBundle = t, this.options = {
host: s.host ?? "0.0.0.0",
port: s.port ?? 3e3,
basePath: s.basePath ?? "/",
cors: s.cors ?? !0,
logger: s.logger ?? !1,
app: s.app,
customEndpoints: s.customEndpoints
}, this.configSchema = o;

@@ -868,4 +873,4 @@ }

this.options.cors && await e.register(k, { origin: !0 });
const s = this.options.basePath.endsWith("/") ? this.options.basePath.slice(0, -1) : this.options.basePath;
e.get(`${s}/healthz`, async () => ({ ok: !0 })), e.get(`${s}/tools`, async () => this.defaultManager.getStatus()), e.get(`${s}/.well-known/mcp-config`, async (t, o) => (o.header("Content-Type", "application/schema+json; charset=utf-8"), this.configSchema ?? {
const t = this.options.basePath.endsWith("/") ? this.options.basePath.slice(0, -1) : this.options.basePath;
e.get(`${t}/healthz`, async () => ({ ok: !0 })), e.get(`${t}/tools`, async () => this.defaultManager.getStatus()), e.get(`${t}/.well-known/mcp-config`, async (s, o) => (o.header("Content-Type", "application/schema+json; charset=utf-8"), this.configSchema ?? {
$schema: "https://json-schema.org/draft/2020-12/schema",

@@ -880,5 +885,5 @@ title: "MCP Session Configuration",

})), e.post(
`${s}/mcp`,
async (t, o) => {
const i = t.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : `anon-${T()}`, l = !n.startsWith("anon-");
`${t}/mcp`,
async (s, o) => {
const i = s.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : `anon-${T()}`, l = !n.startsWith("anon-");
let a = l ? this.clientCache.get(n) : null;

@@ -893,16 +898,16 @@ if (!a) {

}
const c = t.headers["mcp-session-id"];
let h;
const c = s.headers["mcp-session-id"];
let u;
if (c && a.sessions.get(c))
h = a.sessions.get(c);
else if (!c && z(t.body)) {
u = a.sessions.get(c);
else if (!c && O(s.body)) {
const f = T();
h = new D({
u = new D({
sessionIdGenerator: () => f,
onsessioninitialized: (v) => {
a.sessions.set(v, h);
a.sessions.set(v, u);
}
});
try {
await a.server.connect(h);
await a.server.connect(u);
} catch {

@@ -915,4 +920,4 @@ return o.code(500), {

}
h.onclose = () => {
h?.sessionId && a.sessions.delete(h.sessionId);
u.onclose = () => {
u?.sessionId && a.sessions.delete(u.sessionId);
};

@@ -925,10 +930,10 @@ } else

};
return await h.handleRequest(
t.raw,
return await u.handleRequest(
s.raw,
o.raw,
t.body
s.body
), o;
}
), e.get(`${s}/mcp`, async (t, o) => {
const i = t.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "";
), e.get(`${t}/mcp`, async (s, o) => {
const i = s.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "";
if (!n)

@@ -939,11 +944,11 @@ return o.code(400), "Missing mcp-client-id";

return o.code(400), "Invalid or expired client";
const a = t.headers["mcp-session-id"];
const a = s.headers["mcp-session-id"];
if (!a)
return o.code(400), "Missing mcp-session-id";
const c = l.sessions.get(a);
return c ? (await c.handleRequest(t.raw, o.raw), o) : (o.code(400), "Invalid or expired session ID");
return c ? (await c.handleRequest(s.raw, o.raw), o) : (o.code(400), "Invalid or expired session ID");
}), e.delete(
`${s}/mcp`,
async (t, o) => {
const i = t.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "", l = t.headers["mcp-session-id"];
`${t}/mcp`,
async (s, o) => {
const i = s.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "", l = s.headers["mcp-session-id"];
if (!n || !l)

@@ -976,3 +981,3 @@ return o.code(400), {

}
), this.options.customEndpoints && this.options.customEndpoints.length > 0 && F(e, s, this.options.customEndpoints), this.options.app || await e.listen({ host: this.options.host, port: this.options.port }), this.app = e;
), this.options.customEndpoints && this.options.customEndpoints.length > 0 && F(e, t, this.options.customEndpoints), this.options.app || await e.listen({ host: this.options.host, port: this.options.port }), this.app = e;
}

@@ -993,9 +998,9 @@ /**

cleanupBundle(e) {
for (const [s, t] of e.sessions.entries())
for (const [t, s] of e.sessions.entries())
try {
typeof t.close == "function" && t.close().catch((o) => {
console.warn(`Error closing session ${s}:`, o);
typeof s.close == "function" && s.close().catch((o) => {
console.warn(`Error closing session ${t}:`, o);
});
} catch (o) {
console.warn(`Error closing session ${s}:`, o);
console.warn(`Error closing session ${t}:`, o);
}

@@ -1028,5 +1033,5 @@ e.sessions.clear();

throw new Error("createMcpServer: `createServer` (factory) is required");
const s = r.createServer(), t = (a) => typeof a?.server?.notification == "function", o = (a) => typeof a?.notifyToolsListChanged == "function", i = async (a) => {
const t = r.createServer(), s = (a) => typeof a?.server?.notification == "function", o = (a) => typeof a?.notifyToolsListChanged == "function", i = async (a) => {
try {
if (t(a)) {
if (s(a)) {
await a.server.notification({

@@ -1044,3 +1049,3 @@ method: "notifications/tools/list_changed"

}, n = new A({
server: s,
server: t,
catalog: r.catalog,

@@ -1050,3 +1055,3 @@ moduleLoaders: r.moduleLoaders,

context: r.context,
notifyToolsListChanged: async () => i(s),
notifyToolsListChanged: async () => i(t),
startup: r.startup,

@@ -1060,3 +1065,3 @@ registerMetaTools: r.registerMetaTools !== void 0 ? r.registerMetaTools : e === "DYNAMIC"

if (e === "STATIC")
return { server: s, orchestrator: n };
return { server: t, orchestrator: n };
const a = r.createServer(), c = new A({

@@ -1078,3 +1083,3 @@ server: a,

return {
server: s,
server: t,
start: async () => {

@@ -1089,5 +1094,5 @@ await l.start();

function de(r) {
he(r), ue(r), fe(r), me(r);
ue(r), he(r), fe(r), me(r);
}
function he(r) {
function ue(r) {
if (!r || typeof r != "object")

@@ -1098,3 +1103,3 @@ throw new Error(

}
function ue(r) {
function he(r) {
if (!r.source)

@@ -1131,4 +1136,4 @@ throw new Error('Permission source must be either "headers" or "config"');

function ge(r) {
for (const [e, s] of Object.entries(r))
if (!Array.isArray(s))
for (const [e, t] of Object.entries(r))
if (!Array.isArray(t))
throw new Error(

@@ -1138,3 +1143,3 @@ `staticMap value for client "${e}" must be an array of toolset names`

}
var p, _, B, H, Y, W;
var p, _, H, B, Y, W;
class pe {

@@ -1164,10 +1169,10 @@ /**

*/
resolvePermissions(e, s) {
resolvePermissions(e, t) {
if (this.cache.has(e))
return this.cache.get(e);
let t;
let s;
try {
this.config.source === "headers" ? t = m(this, p, _).call(this, s) : t = m(this, p, H).call(this, e), Array.isArray(t) || (console.warn(
this.config.source === "headers" ? s = m(this, p, _).call(this, t) : s = m(this, p, B).call(this, e), Array.isArray(s) || (console.warn(
`Permission resolution returned non-array for client ${e}, using empty permissions`
), t = []), t = t.filter(
), s = []), s = s.filter(
(o) => typeof o == "string" && o.trim().length > 0

@@ -1179,5 +1184,5 @@ );

o
), t = [];
), s = [];
}
return this.cache.set(e, t), t;
return this.cache.set(e, s), s;
}

@@ -1212,11 +1217,11 @@ /**

return [];
const s = m(this, p, B).call(this, e, this.normalizedHeaderName);
if (!s)
const t = m(this, p, H).call(this, e, this.normalizedHeaderName);
if (!t)
return [];
try {
return s.split(",").map((t) => t.trim()).filter((t) => t.length > 0);
} catch (t) {
return t.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
} catch (s) {
return console.warn(
`Failed to parse permission header '${this.normalizedHeaderName}':`,
t
s
), [];

@@ -1232,7 +1237,7 @@ }

*/
B = function(e, s) {
if (e[s] !== void 0)
return e[s];
for (const [t, o] of Object.entries(e))
if (t.toLowerCase() === s)
H = function(e, t) {
if (e[t] !== void 0)
return e[t];
for (const [s, o] of Object.entries(e))
if (s.toLowerCase() === t)
return o;

@@ -1247,12 +1252,12 @@ }, /**

*/
H = function(e) {
B = function(e) {
if (this.config.resolver) {
const s = m(this, p, Y).call(this, e);
if (s !== null)
return s;
const t = m(this, p, Y).call(this, e);
if (t !== null)
return t;
}
if (this.config.staticMap) {
const s = m(this, p, W).call(this, e);
if (s !== null)
return s;
const t = m(this, p, W).call(this, e);
if (t !== null)
return t;
}

@@ -1269,10 +1274,10 @@ return this.config.defaultPermissions || [];

try {
const s = this.config.resolver(e);
return Array.isArray(s) ? s : (console.warn(
const t = this.config.resolver(e);
return Array.isArray(t) ? t : (console.warn(
`Permission resolver returned non-array for client ${e}, using fallback`
), null);
} catch (s) {
const t = s instanceof Error ? s.message : String(s);
} catch (t) {
const s = t instanceof Error ? t.message : String(t);
return console.warn(
`Permission resolver declined client ${e} (${t}), trying fallback`
`Permission resolver declined client ${e} (${s}), trying fallback`
), null;

@@ -1288,20 +1293,20 @@ }

W = function(e) {
const s = this.config.staticMap[e];
return s !== void 0 ? Array.isArray(s) ? s : [] : null;
const t = this.config.staticMap[e];
return t !== void 0 ? Array.isArray(t) ? t : [] : null;
};
function ye(r, e) {
return async (s) => {
const t = e.resolvePermissions(
s.clientId,
s.headers
), o = r(t), i = o.orchestrator.getManager(), n = [], l = [];
if (t.length > 0) {
const a = await i.enableToolsets(t);
return async (t) => {
const s = e.resolvePermissions(
t.clientId,
t.headers
), o = r(s), i = o.orchestrator.getManager(), n = [], l = [];
if (s.length > 0) {
const a = await i.enableToolsets(s);
for (const c of a.results)
c.success ? n.push(c.name) : (l.push(c.name), console.warn(
`Failed to enable toolset '${c.name}' for client '${s.clientId}': ${c.message}`
`Failed to enable toolset '${c.name}' for client '${t.clientId}': ${c.message}`
));
if (n.length === 0 && l.length > 0)
throw new Error(
`All requested toolsets failed to enable for client '${s.clientId}'. Requested: [${t.join(", ")}]. Check that toolset names in permissions match the catalog.`
`All requested toolsets failed to enable for client '${t.clientId}'. Requested: [${s.join(", ")}]. Check that toolset names in permissions match the catalog.`
);

@@ -1317,3 +1322,3 @@ }

}
var u, U, q, J, G, K, Z, Q, X, C, ee;
var h, U, q, J, G, K, Z, Q, X, C, ee;
class ve {

@@ -1327,4 +1332,4 @@ /**

*/
constructor(e, s, t = {}, o) {
b(this, u);
constructor(e, t, s = {}, o) {
b(this, h);
d(this, "options");

@@ -1337,14 +1342,14 @@ d(this, "defaultManager");

d(this, "clientCache", new V({
onEvict: (e, s) => {
m(this, u, U).call(this, s);
onEvict: (e, t) => {
m(this, h, U).call(this, t);
}
}));
this.defaultManager = e, this.createPermissionAwareBundle = s, this.options = {
host: t.host ?? "0.0.0.0",
port: t.port ?? 3e3,
basePath: t.basePath ?? "/",
cors: t.cors ?? !0,
logger: t.logger ?? !1,
app: t.app,
customEndpoints: t.customEndpoints
this.defaultManager = e, this.createPermissionAwareBundle = t, this.options = {
host: s.host ?? "0.0.0.0",
port: s.port ?? 3e3,
basePath: s.basePath ?? "/",
cors: s.cors ?? !0,
logger: s.logger ?? !1,
app: s.app,
customEndpoints: s.customEndpoints
}, this.configSchema = o;

@@ -1360,6 +1365,6 @@ }

this.options.cors && await e.register(k, { origin: !0 });
const s = m(this, u, q).call(this, this.options.basePath);
m(this, u, J).call(this, e, s), m(this, u, G).call(this, e, s), m(this, u, K).call(this, e, s), m(this, u, Z).call(this, e, s), m(this, u, Q).call(this, e, s), m(this, u, X).call(this, e, s), this.options.customEndpoints && this.options.customEndpoints.length > 0 && F(e, s, this.options.customEndpoints, {
contextExtractor: async (t) => {
const o = m(this, u, C).call(this, t);
const t = m(this, h, q).call(this, this.options.basePath);
m(this, h, J).call(this, e, t), m(this, h, G).call(this, e, t), m(this, h, K).call(this, e, t), m(this, h, Z).call(this, e, t), m(this, h, Q).call(this, e, t), m(this, h, X).call(this, e, t), this.options.customEndpoints && this.options.customEndpoints.length > 0 && F(e, t, this.options.customEndpoints, {
contextExtractor: async (s) => {
const o = m(this, h, C).call(this, s);
try {

@@ -1390,3 +1395,3 @@ const i = await this.createPermissionAwareBundle(o);

}
u = new WeakSet(), /**
h = new WeakSet(), /**
* Cleans up resources associated with a client bundle.

@@ -1398,9 +1403,9 @@ * Closes all sessions within the bundle.

U = function(e) {
for (const [s, t] of e.sessions.entries())
for (const [t, s] of e.sessions.entries())
try {
typeof t.close == "function" && t.close().catch((o) => {
console.warn(`Error closing session ${s}:`, o);
typeof s.close == "function" && s.close().catch((o) => {
console.warn(`Error closing session ${t}:`, o);
});
} catch (o) {
console.warn(`Error closing session ${s}:`, o);
console.warn(`Error closing session ${t}:`, o);
}

@@ -1422,4 +1427,4 @@ e.sessions.clear();

*/
J = function(e, s) {
e.get(`${s}/healthz`, async () => ({ ok: !0 }));
J = function(e, t) {
e.get(`${t}/healthz`, async () => ({ ok: !0 }));
}, /**

@@ -1431,4 +1436,4 @@ * Registers the tools status endpoint.

*/
G = function(e, s) {
e.get(`${s}/tools`, async () => this.defaultManager.getStatus());
G = function(e, t) {
e.get(`${t}/tools`, async () => this.defaultManager.getStatus());
}, /**

@@ -1440,4 +1445,4 @@ * Registers the MCP configuration discovery endpoint.

*/
K = function(e, s) {
e.get(`${s}/.well-known/mcp-config`, async (t, o) => (o.header("Content-Type", "application/schema+json; charset=utf-8"), this.configSchema ?? {
K = function(e, t) {
e.get(`${t}/.well-known/mcp-config`, async (s, o) => (o.header("Content-Type", "application/schema+json; charset=utf-8"), this.configSchema ?? {
$schema: "https://json-schema.org/draft/2020-12/schema",

@@ -1459,36 +1464,36 @@ title: "MCP Session Configuration",

*/
Z = function(e, s) {
Z = function(e, t) {
e.post(
`${s}/mcp`,
async (t, o) => {
const i = m(this, u, C).call(this, t), n = !i.clientId.startsWith("anon-");
`${t}/mcp`,
async (s, o) => {
const i = m(this, h, C).call(this, s), n = !i.clientId.startsWith("anon-");
let l = n ? this.clientCache.get(i.clientId) : null;
if (!l)
try {
const h = await this.createPermissionAwareBundle(i);
h.failedToolsets.length > 0 && console.warn(
`Client ${i.clientId} had ${h.failedToolsets.length} toolsets fail to enable: [${h.failedToolsets.join(", ")}]. Successfully enabled: [${h.allowedToolsets.join(", ")}]`
const u = await this.createPermissionAwareBundle(i);
u.failedToolsets.length > 0 && console.warn(
`Client ${i.clientId} had ${u.failedToolsets.length} toolsets fail to enable: [${u.failedToolsets.join(", ")}]. Successfully enabled: [${u.allowedToolsets.join(", ")}]`
);
const f = h.sessions;
const f = u.sessions;
l = {
server: h.server,
orchestrator: h.orchestrator,
allowedToolsets: h.allowedToolsets,
failedToolsets: h.failedToolsets,
server: u.server,
orchestrator: u.orchestrator,
allowedToolsets: u.allowedToolsets,
failedToolsets: u.failedToolsets,
sessions: f instanceof Map ? f : /* @__PURE__ */ new Map()
}, n && this.clientCache.set(i.clientId, l);
} catch (h) {
} catch (u) {
return console.error(
`Failed to create permission-aware bundle for client ${i.clientId}:`,
h
), o.code(403), m(this, u, ee).call(this, "Access denied");
u
), o.code(403), m(this, h, ee).call(this, "Access denied");
}
const a = t.headers["mcp-session-id"];
const a = s.headers["mcp-session-id"];
let c;
if (a && l.sessions.get(a))
c = l.sessions.get(a);
else if (!a && z(t.body)) {
const h = T();
else if (!a && O(s.body)) {
const u = T();
c = new D({
sessionIdGenerator: () => h,
sessionIdGenerator: () => u,
onsessioninitialized: (f) => {

@@ -1517,5 +1522,5 @@ l.sessions.set(f, c);

return await c.handleRequest(
t.raw,
s.raw,
o.raw,
t.body
s.body
), o;

@@ -1530,5 +1535,5 @@ }

*/
Q = function(e, s) {
e.get(`${s}/mcp`, async (t, o) => {
const i = t.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "";
Q = function(e, t) {
e.get(`${t}/mcp`, async (s, o) => {
const i = s.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "";
if (!n)

@@ -1539,7 +1544,7 @@ return o.code(400), "Missing mcp-client-id";

return o.code(400), "Invalid or expired client";
const a = t.headers["mcp-session-id"];
const a = s.headers["mcp-session-id"];
if (!a)
return o.code(400), "Missing mcp-session-id";
const c = l.sessions.get(a);
return c ? (await c.handleRequest(t.raw, o.raw), o) : (o.code(400), "Invalid or expired session ID");
return c ? (await c.handleRequest(s.raw, o.raw), o) : (o.code(400), "Invalid or expired session ID");
});

@@ -1552,7 +1557,7 @@ }, /**

*/
X = function(e, s) {
X = function(e, t) {
e.delete(
`${s}/mcp`,
async (t, o) => {
const i = t.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "", l = t.headers["mcp-session-id"];
`${t}/mcp`,
async (s, o) => {
const i = s.headers["mcp-client-id"]?.trim(), n = i && i.length > 0 ? i : "", l = s.headers["mcp-session-id"];
if (!n || !l)

@@ -1594,6 +1599,6 @@ return o.code(400), {

C = function(e) {
const s = e.headers["mcp-client-id"]?.trim(), t = s && s.length > 0 ? s : `anon-${T()}`, o = {};
const t = e.headers["mcp-client-id"]?.trim(), s = t && t.length > 0 ? t : `anon-${T()}`, o = {};
for (const [i, n] of Object.entries(e.headers))
typeof n == "string" && (o[i] = n);
return { clientId: t, headers: o };
return { clientId: s, headers: o };
}, /**

@@ -1607,7 +1612,7 @@ * Creates a safe error response that doesn't expose unauthorized toolset information.

*/
ee = function(e = "Access denied", s = -32e3) {
ee = function(e = "Access denied", t = -32e3) {
return {
jsonrpc: "2.0",
error: {
code: s,
code: t,
message: e

@@ -1648,4 +1653,4 @@ },

r.exposurePolicy
), s = new pe(r.permissions), t = r.createServer(), o = new A({
server: t,
), t = new pe(r.permissions), s = r.createServer(), o = new A({
server: s,
catalog: r.catalog,

@@ -1676,3 +1681,3 @@ moduleLoaders: r.moduleLoaders,

},
s
t
), n = new ve(

@@ -1685,3 +1690,3 @@ o.getManager(),

return {
server: t,
server: s,
start: async () => {

@@ -1694,3 +1699,3 @@ await n.start();

} finally {
s.clearCache();
t.clearCache();
}

@@ -1697,0 +1702,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"registerMetaTools.d.ts","sourceRoot":"","sources":["../../src/meta/registerMetaTools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,SAAS,EACjB,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE;IAAE,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;CAAE,GACxC,IAAI,CA+GN"}
{"version":3,"file":"registerMetaTools.d.ts","sourceRoot":"","sources":["../../src/meta/registerMetaTools.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,SAAS,EACjB,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE;IAAE,IAAI,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;CAAE,GACxC,IAAI,CAoHN"}
{
"name": "toolception",
"version": "0.5.3",
"version": "0.5.4",
"private": false,

@@ -5,0 +5,0 @@ "type": "module",

Sorry, the diff of this file is too big to display