Manages dynamic MCP toolsets to prevent LLM overwhelm by enabling only relevant tools on demand via runtime control or static startup.
Also known as code-rabi/toolception
- Stars
- 6
- Tools
- 5
- Downloads, 30 days
- —
- Latest version
- —
- Last commit
- Nov 5, 2026
- License
- Apache-2.0
What is Toolception MCP?
Toolception manages dynamic MCP toolsets to prevent LLM overwhelm by enabling only relevant tools on demand via runtime control or static startup. It exposes 5 tools, such as enable_toolset, disable_toolset, list_toolsets.
Summary generated from the project's README
About Toolception MCP server
Managing large collections of tools for AI agents is what Toolception enables by grouping functions into manageable toolsets. Developers building complex MCP servers with dozens or hundreds of tools can use this library to prevent LLM confusion, token bloat, and name collisions. It allows for the selective exposure of tools, ensuring that an agent only sees the specific capabilities relevant to its current task.
Users can choose between two primary modes: DYNAMIC for runtime control or STATIC for predictable startup. In dynamic mode, clients use meta-tools like enable_toolset and disable_toolset to load tools on demand, which supports lazy loading and reduces prompt latency. Static mode preloads specific toolsets or all available sets at bootstrap. The library also supports permission-based access control via HTTP headers or server-side configuration maps, making it suitable for multi-tenant environments where different clients require isolated tool access. It requires Node.js 25.3.0 or later and integrates with the MCP TypeScript SDK and Zod 4 for schema validation.
What you can do with it
- 1Reduce LLM tool confusionAn agent can enable only the specific toolset needed for a task to avoid being overwhelmed by a massive catalog.
- 2Implement multi-tenant securityRestrict tool access so that different users or clients only see the specific toolsets they are authorized to use.
- 3Optimize prompt token usageMinimize latency and token consumption by only loading relevant tools instead of the entire library.
Written from the project's README. Every use case is checked against a quote from it.
How to install Toolception MCP
Formats verified 10 Nov 2026Add to CursorAdd to GooseInstall Toolception MCP in Claude Code
$ claude mcp add toolception -- npx -y toolceptionInstall Toolception MCP in Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"toolception": {
"command": "npx",
"args": [
"-y",
"toolception"
]
}
}
}Install Toolception MCP in VS Code
.vscode/mcp.json
{
"servers": {
"toolception": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"toolception"
]
}
}
}Install Toolception MCP in VS Code CLI
$ code --add-mcp '{"name":"toolception","type":"stdio","command":"npx","args":["-y","toolception"]}'Install Toolception MCP in Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"toolception": {
"command": "npx",
"args": [
"-y",
"toolception"
]
}
}
}Install Toolception MCP in Codex
$ codex mcp add toolception -- npx -y toolceptionInstall Toolception MCP in Codex config.toml
~/.codex/config.toml
[mcp_servers.toolception] command = "npx" args = ["-y", "toolception"]
Install Toolception MCP in Gemini CLI
$ gemini mcp add -s user toolception npx -- -y toolceptionInstall Toolception MCP in Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"toolception": {
"command": "npx",
"args": [
"-y",
"toolception"
]
}
}
}Toolception MCP tools 5
Detected from the READMEenable_toolsetdisable_toolsetlist_toolsetsdescribe_toolsetlist_tools
| enable_toolset | — | |
| disable_toolset | — | |
| list_toolsets | — | |
| describe_toolset | — | |
| list_tools | — |
Configuration
API_TOKENUSER_ID
| Name | Description | |
|---|---|---|
| API_TOKEN | — | |
| USER_ID | — |
Automated checks
Ran Nov 12, 2026Full report →Passed our automated checks. That is not a security audit: read the code and give the server the narrowest access it needs. How checks work
- Source repository linked and reachablePass
- Open source license (OSI)Pass
- Commit or release in the last yearPass
- Package name not close to a popular packagePass
- Remote endpoint uses HTTPSNot checked
- Destructive tools are labelledPass
- No hidden instructions to the modelPass
- No critical advisory in the package or its dependenciesNot checked
README
View on GitHubToolception – Dynamic MCP Tooling Library
Table of Contents
- When and why to use Toolception
- Starter guide
- Static startup
- Permission-based starter guide
- Permission configuration approaches
- Custom HTTP endpoints
- Per-session context
- API
- Permission-based client integration
- Permission-based security best practices
- Permission-based common patterns
- Client ID lifecycle
- Session ID lifecycle
- Tool types
- Startup modes
- License
When and why to use Toolception
Building MCP servers with dozens or hundreds of tools often harms LLM performance and developer experience:
- Too many tools overwhelm selection: Larger tool lists increase confusion and mis-selection rates.
- Token and schema bloat: Long tool catalogs inflate prompts and latency.
- Name collisions and ambiguity: Similar tool names across domains cause failures and fragile integrations.
- Operational overhead: Loading every tool up-front wastes resources; many tools are task-specific.
Toolception addresses this by grouping tools into toolsets and letting you expose only what’s needed, when it’s needed.
When to use Toolception
- Large or multi-domain catalogs: You have >20–50 tools or multiple domains (e.g., search, data, billing) and don’t want to expose them all at once.
- Task-specific workflows: You want the client/agent to enable only the tools relevant to the current task.
- Multi-tenant or policy needs: Different users/tenants require different tool access or limits.
- Per-session context: You need different context values (API tokens, user IDs) for each client session passed to module loaders.
- Permission-based access control: You need to enforce client-specific toolset permissions for security, compliance, or multi-tenant isolation. Each client should only see and access the toolsets they're authorized to use, with server-side or header-based permission enforcement.
- Collision-safe naming: You need predictable, namespaced tool names to avoid conflicts.
- Lazy loading: Some tools are heavy and should be loaded on demand.
Why Toolception helps
- Toolsets: Group related tools and expose minimal, coherent subsets per task.
- Dynamic mode (runtime control):
- Enable toolsets on demand via meta-tools (
enable_toolset,disable_toolset,list_toolsets,describe_toolset,list_tools). - Reduce prompt/tool surface area → better tool selection and lower latency.
- Lazy-load module-produced tools only when needed; pass shared
contextsafely to loaders. - Supports
tools.listChangednotifications so clients can react to updated tool lists.
- Enable toolsets on demand via meta-tools (
- Static mode (predictable startup):
- Preload known toolsets (or ALL) at startup for fixed pipelines and simpler environments.
- Keep only the required sets for your deployment footprint.
- Exposure policy:
- maxActiveToolsets: Cap concurrently active sets to prevent bloat.
- allowlist/denylist: Enforce which toolsets can be enabled.
- namespaceToolsWithSetKey: Default on; registers tools as
set.toolto avoid collisions and clarify intent.
- Operational safety:
- Central
ToolRegistryvalidates names and prevents collisions. ModuleLoadersare deterministic/idempotent for repeatable runs and caching.
- Central
Choosing a mode
- Prefer DYNAMIC when tool needs vary by task, you want tighter prompts, or you need runtime gating and lazy loading.
- Choose STATIC when your tool needs are stable and small, or when your client cannot (or should not) perform runtime enable/disable operations.
Typical flows
- Discovery-first (dynamic): Client calls
list_toolsets→ enables a set → calls namespaced tools (e.g.,core.ping). - Fixed pipeline (static): Server preloads named toolsets (or ALL) at startup; clients call
list_toolsand invoke as usual.
Starter guide
Step 1: Install
npm i toolception @modelcontextprotocol/server zod
Toolception 0.9 is built on MCP TypeScript SDK v2 (@modelcontextprotocol/server) and needs Zod 4 (zod ^4.6.7); Zod 3 schemas are rejected. Install the same versions toolception depends on, so your app and toolception share one copy of each. Toolception needs Node.js 25.3.0 or later.
Step 2: Import Toolception
import { createMcpServer } from "toolception";
Step 3: Define a toolset catalog
const catalog = {
quotes: { name: "Quotes", description: "Market quotes", modules: ["quotes"] },
};
Step 4: Define a tool
inputSchema should be a Zod 4 raw shape (or a Zod 4 object schema); toolception wraps a raw shape with z.object() before it calls McpServer.registerTool. A Zod 3 schema fails to enable its toolset with an E_VALIDATION error. A plain JSON Schema object (type: "object") also works: toolception registers it with the SDK's fromJsonSchema(), so clients see its properties and arguments are validated against it before your handler runs. A JSON Schema that does not compile (unknown type name, unresolved $ref, unsupported $schema dialect) fails the toolset's enable with an E_VALIDATION error that names the tool.
import { z } from "zod";
const quoteTool = {
name: "price",
description: "Return a fake price",
inputSchema: {
symbol: z.string(),
},
handler: async ({ symbol }: { symbol: string }) => ({
content: [{ type: "text", text: `${symbol}: 123.45` }],
}),
} as const;
Step 5: Provide module loaders
const moduleLoaders = {
quotes: async () => [quoteTool],
};
Step 6: (Optional) Configuration schema
const configSchema = {
$schema: "https://json-schema.org/draft/2020-12/schema",
type: "object",
properties: {
REQUIRED_PARAM: { type: "string", title: "Required Param" },
OPTIONAL_PARAM: { type: "string", title: "Optional Param" },
},
required: ["REQUIRED_PARAM"],
} as const;
Step 7: Create the MCP SDK server and start Toolception
import { McpServer } from "@modelcontextprotocol/server";
// You own the SDK server; pass a factory into Toolception (required in DYNAMIC mode)
const createServer = () =>
new McpServer({
name: "my-mcp-server",
version: "0.0.0",
}, { capabilities: { tools: { listChanged: true } } });
const { start, close } = await createMcpServer({
catalog,
moduleLoaders,
startup: { mode: "DYNAMIC" },
http: { port: 3000 },
createServer,
// configSchema, // uncomment to expose at /.well-known/mcp-config
});
await start();
Step 8: Graceful shutdown
process.on("SIGINT", async () => {
await close();
process.exit(0);
});
process.on("SIGTERM", async () => {
await close();
process.exit(0);
});
Static startup
Enable some or ALL toolsets at bootstrap. In STATIC mode every client gets its own server from createServer, with the startup toolsets already loaded:
import { McpServer } from "@modelcontextprotocol/server";
const staticCatalog = {
search: { name: "Search", description: "Search tools", modules: ["search"] },
quotes: { name: "Quotes", description: "Market quotes", modules: ["quotes"] },
};
// Load specific toolsets
createMcpServer({
catalog: staticCatalog,
startup: { mode: "STATIC", toolsets: ["search", "quotes"] },
http: { port: 3001 },
createServer: () =>
new McpServer({
name: "static-1",
version: "0.0.0",
}, { capabilities: { tools: { listChanged: false } } }),
});
// Load ALL toolsets
createMcpServer({
catalog: staticCatalog,
startup: { mode: "STATIC", toolsets: "ALL" },
http: { port: 3002 },
createServer: () =>
new McpServer({
name: "static-2",
version: "0.0.0",
}, { capabilities: { tools: { listChanged: false } } }),
});
Permission-based starter guide
Use createPermissionBasedMcpServer when you need to enforce client-specific toolset permissions. This is ideal for multi-tenant applications, security-sensitive environments, or when different clients should have different levels of access.
Step 1: Install
npm i toolception @modelcontextprotocol/server zod
Toolception 0.9 is built on MCP TypeScript SDK v2 (@modelcontextprotocol/server) and needs Zod 4 (zod ^4.6.7); Zod 3 schemas are rejected. Install the same versions toolception depends on, so your app and toolception share one copy of each.
Step 2: Import Toolception
import { createPermissionBasedMcpServer } from "toolception";
import { McpServer } from "@modelcontextprotocol/server";
Step 3: Define a toolset catalog
const catalog = {
admin: {
name: "Admin Tools",
description: "Administrative operations",
modules: ["admin"],
},
user: {
name: "User Tools",
description: "Standard user operations",
modules: ["user"],
},
};
Step 4: Define tools
const adminTool = {
name: "delete_user",
description: "Delete a user account",
inputSchema: {
userId: z.string().describe("User ID to delete"),
},
handler: async ({ userId }: { userId: string }) => ({
content: [{ type: "text", text: `User ${userId} deleted` }],
}),
} as const;
const userTool = {
name: "get_profile",
description: "Get user profile information",
inputSchema: {
userId: z.string().describe("User ID"),
},
handler: async ({ userId }: { userId: string }) => ({
content: [{ type: "text", text: `Profile for ${userId}: {...}` }],
}),
} as const;
Step 5: Provide module loaders
const moduleLoaders = {
admin: async () => [adminTool],
user: async () => [userTool],
};
Step 6: Choose permission approach
You have two options for managing permissions:
Header-Based Permissions:
- Use when you have an authentication gateway/proxy
- Permissions passed via HTTP headers
- Good for dynamic, frequently-changing permissions
- Requires external validation of headers
Config-Based Permissions:
- Use when you want server-side control
- Permissions defined in server configuration
- Better security (no client-provided permission data)
- Good for stable permission structures
Step 7: Create the permission-based MCP server
Option A: Header-Based Permissions
const createServer = () =>
new McpServer({
name: "permission-header-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: false } } });
const { start, close } = await createPermissionBasedMcpServer({
catalog,
moduleLoaders,
permissions: {
source: "headers",
headerName: "mcp-toolset-permissions", // optional, this is default
},
http: { port: 3000 },
createServer,
});
await start();
Option B: Config-Based Permissions (Static Map)
const createServer = () =>
new McpServer({
name: "permission-config-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: false } } });
const { start, close } = await createPermissionBasedMcpServer({
catalog,
moduleLoaders,
permissions: {
source: "config",
staticMap: {
"admin-client-id": ["admin", "user"],
"user-client-id": ["user"],
},
defaultPermissions: [], // unknown clients get no toolsets
},
http: { port: 3000 },
createServer,
});
await start();
Option C: Config-Based Permissions (Resolver Function)
const createServer = () =>
new McpServer({
name: "permission-resolver-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: false } } });
const { start, close } = await createPermissionBasedMcpServer({
catalog,
moduleLoaders,
permissions: {
source: "config",
resolver: (clientId: string) => {
// Your custom permission logic
if (clientId.startsWith("admin-")) {
return ["admin", "user"];
}
if (clientId.startsWith("user-")) {
return ["user"];
}
return [];
},
defaultPermissions: [],
},
http: { port: 3000 },
createServer,
});
await start();
Step 8: Graceful shutdown
process.on("SIGINT", async () => {
await close();
process.exit(0);
});
process.on("SIGTERM", async () => {
await close();
process.exit(0);
});
Permission configuration approaches
Header-Based Permissions Setup
Use header-based permissions when you have an authentication gateway or proxy that validates and sets permission headers. This approach is flexible for dynamic permissions but requires external header validation.
import { createPermissionBasedMcpServer } from "toolception";
import { McpServer } from "@modelcontextprotocol/server";
const createServer = () =>
new McpServer({
name: "permission-header-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: false } } });
const { start, close } = await createPermissionBasedMcpServer({
catalog: {
admin: {
name: "Admin",
description: "Admin tools",
modules: ["admin"],
},
user: {
name: "User",
description: "User tools",
modules: ["user"],
},
},
moduleLoaders: {
admin: async () => [
/* admin tools */
],
user: async () => [
/* user tools */
],
},
permissions: {
source: "headers",
headerName: "mcp-toolset-permissions", // optional, this is default
},
http: { port: 3000 },
createServer,
});
await start();
When to use:
- You have an authentication gateway/proxy that validates requests
- Permissions change frequently or are computed per-request
- You can ensure headers are cryptographically signed or validated
- Your auth system is external to the MCP server
Config-Based Permissions Setup (Static Map)
Use a static map when you have a fixed set of clients with known permissions. This provides server-side control and better security.
import { createPermissionBasedMcpServer } from "toolception";
import { McpServer } from "@modelcontextprotocol/server";
const createServer = () =>
new McpServer({
name: "permission-config-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: false } } });
const { start, close } = await createPermissionBasedMcpServer({
catalog: {
admin: {
name: "Admin",
description: "Admin tools",
modules: ["admin"],
},
user: {
name: "User",
description: "User tools",
modules: ["user"],
},
},
moduleLoaders: {
admin: async () => [
/* admin tools */
],
user: async () => [
/* user tools */
],
},
permissions: {
source: "config",
staticMap: {
"admin-client-id": ["admin", "user"],
"user-client-id": ["user"],
},
defaultPermissions: [], // clients not in map get no toolsets
},
http: { port: 3000 },
createServer,
});
await start();
When to use:
- You have a fixed set of known clients
- Permissions are relatively stable
- You want the highest security level
- You want to avoid trusting client-provided data
Config-Based Permissions Setup (Resolver Function)
Use a resolver function when you need custom logic to determine permissions, such as looking up from a database or applying complex rules.
import { createPermissionBasedMcpServer } from "toolception";
import { McpServer } from "@modelcontextprotocol/server";
const createServer = () =>
new McpServer({
name: "permission-resolver-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: false } } });
const { start, close } = await createPermissionBasedMcpServer({
catalog: {
admin: {
name: "Admin",
description: "Admin tools",
modules: ["admin"],
},
user: {
name: "User",
description: "User tools",
modules: ["user"],
},
},
moduleLoaders: {
admin: async () => [
/* admin tools */
],
user: async () => [
/* user tools */
],
},
permissions: {
source: "config",
resolver: (clientId: string) => {
// Custom logic - could check database, config file, etc.
if (clientId.startsWith("admin-")) {
return ["admin", "user"];
}
if (clientId.startsWith("user-")) {
return ["user"];
}
return [];
},
staticMap: {
// optional fallback
"special-client": ["admin"],
},
defaultPermissions: [],
},
http: { port: 3000 },
createServer,
});
await start();
When to use:
- You need custom permission logic
- Permissions are computed based on client ID patterns or attributes
- You want to integrate with existing permission systems
- You need fallback behavior with staticMap
Note: Resolver functions must be synchronous. If you need to fetch permissions from external sources, do so before server creation and cache the results.
Custom HTTP endpoints
Toolception supports custom HTTP endpoints alongside MCP protocol endpoints, enabling REST-like APIs with Zod validation and type inference.
Basic usage
import { createMcpServer, defineEndpoint } from "toolception";
import { z } from "zod";
const { start } = await createMcpServer({
// ... standard options
http: {
port: 3000,
customEndpoints: [
defineEndpoint({
method: "GET",
path: "/api/users",
querySchema: z.object({
limit: z.coerce.number().int().positive().default(10),
role: z.enum(["admin", "user"]).optional(),
}),
responseSchema: z.object({
users: z.array(z.object({ id: z.string(), name: z.string() })),
}),
handler: async (req) => {
// req.query is typed: { limit: number, role?: "admin" | "user" }
// req.clientId is available from mcp-client-id header
return { users: [{ id: "1", name: "Alice" }] };
},
}),
],
},
});
Validation schemas
- querySchema: Validates URL query parameters (use
z.coercefor type conversion) - bodySchema: Validates request body (POST/PUT/PATCH)
- paramsSchema: Validates path parameters (e.g.,
/users/:userId) - responseSchema: Validates handler response (prevents invalid data leakage)
Request context
Handlers receive a typed request object:
{
body: TBody, // Validated from bodySchema
query: TQuery, // Validated from querySchema
params: TParams, // Validated from paramsSchema
headers: Record<string, string | string[] | undefined>,
clientId: string, // From mcp-client-id header or auto-generated
}
Permission-aware endpoints
Use definePermissionAwareEndpoint in permission-based servers to access client permissions:
import { createPermissionBasedMcpServer, definePermissionAwareEndpoint } from "toolception";
const { start } = await createPermissionBasedMcpServer({
// ... permission config
http: {
customEndpoints: [
definePermissionAwareEndpoint({
method: "GET",
path: "/api/me",
responseSchema: z.object({
clientId: z.string(),
allowedToolsets: z.array(z.string()),
isAdmin: z.boolean(),
}),
handler: async (req) => {
// req.allowedToolsets and req.failedToolsets are available
return {
clientId: req.clientId,
allowedToolsets: req.allowedToolsets,
isAdmin: req.allowedToolsets.includes("admin-tools"),
};
},
}),
],
},
});
Error handling
Validation failures return standardized error responses:
- 400 VALIDATION_ERROR: Request validation failed (body, query, or params)
- 500 INTERNAL_ERROR: Handler threw an exception
- 500 RESPONSE_VALIDATION_ERROR: Response validation failed
Example error response:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed for query",
"details": [
{
"code": "invalid_type",
"path": ["limit"],
"message": "Expected number, received string"
}
]
}
}
Reserved paths
Custom endpoints cannot override built-in MCP paths:
/mcp- MCP JSON-RPC endpoint/healthz- Health check/tools- Tool listing/.well-known/mcp-config- Configuration schema
Complete example
See examples/custom-endpoints-demo.ts for a full working example with GET, POST, PUT, DELETE endpoints, pagination, and permission-aware handlers.
Per-session context
Use the sessionContext option to enable per-client context values extracted from query parameters. This is useful for multi-tenant scenarios where each client needs different configuration (API tokens, user IDs, etc.) passed to module loaders.
Basic usage
import { createMcpServer } from "toolception";
import { McpServer } from "@modelcontextprotocol/server";
const { start } = await createMcpServer({
catalog: { /* ... */ },
moduleLoaders: { /* ... */ },
context: { baseValue: 'shared' }, // Base context for all sessions
sessionContext: {
enabled: true,
queryParam: {
name: 'config',
encoding: 'base64',
allowedKeys: ['API_TOKEN', 'USER_ID'], // Security: always specify
},
merge: 'shallow',
},
createServer: () => new McpServer({
name: "my-server",
version: "1.0.0",
}, { capabilities: { tools: { listChanged: true } } }),
http: { port: 3000 },
});
await start();
Client connection
# Encode session config as base64
CONFIG=$(echo -n '{"API_TOKEN":"user-secret-token","USER_ID":"123"}' | base64)
# Connect with session config
curl -X POST "http://localhost:3000/mcp?config=$CONFIG" \
-H "mcp-client-id: my-client" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"initialize",...}'
Module loader receives merged context
const moduleLoaders = {
tenant: async (ctx: any) => {
// ctx = { baseValue: 'shared', API_TOKEN: 'user-secret-token', USER_ID: '123' }
return [/* tools using ctx.API_TOKEN */];
},
};
Custom context resolver
For advanced use cases, provide a custom resolver function:
sessionContext: {
enabled: true,
queryParam: { allowedKeys: ['tenant_id'] },
contextResolver: (request, baseContext, parsedConfig) => ({
...baseContext,
...parsedConfig,
clientId: request.clientId,
timestamp: Date.now(),
}),
}
Security considerations
- Always specify
allowedKeys: Without a whitelist, any key in the query config is accepted - Fail-secure: Invalid encoding silently falls back to base context
- No logging of values: Session config values are never logged
- Filtered silently: Disallowed keys are filtered without error messages
API
Toolception MCP questions
How do I add Toolception MCP to Claude Code?
Run claude mcp add toolception -- npx -y toolception in your terminal. Add --scope user to make it available in every project.
How do I add Toolception MCP to Cursor?
Open ~/.cursor/mcp.json and add the server under mcpServers, using the Cursor config shown in the install section above.
What tools does Toolception MCP provide?
It exposes 5 tools, including enable_toolset, disable_toolset, list_toolsets, describe_toolset, list_tools.
What is the difference between DYNAMIC and STATIC startup modes?
DYNAMIC mode allows enabling toolsets on demand via meta-tools for better prompt efficiency, while STATIC mode preloads specific or all toolsets at startup for stable environments.
Can I restrict tool access for different users?
Yes, using permission-based access control, you can enforce client-specific toolset permissions via HTTP headers or a server-side configuration map.
What version of Zod is required?
Toolception requires Zod 4 (specifically ^4.6.7); Zod 3 schemas are not supported and will result in validation errors.