Claude skill resource allocation security — SA-SKL-ALLOCATION
MCP skills that allocate arrays from count parameters, repeat strings from length fields, recurse over user-supplied JSON trees, or serialize arguments via JSON.stringify expose four resource exhaustion attack surfaces. Because all tools in a MCP server share one Node.js process, a single OOM kill or stack overflow from one tool call takes down the entire skill server for all users. SA-SKL-ALLOCATION covers all four patterns with attack payloads, memory and stack measurements, and correct Zod-based defenses.
Why resource exhaustion is uniquely dangerous for MCP skills
A conventional web server might survive a resource exhaustion attack against one endpoint because worker processes are isolated. MCP skill servers typically run as a single Node.js process serving all tools. When V8 runs out of heap memory or the call stack overflows, the entire process dies and every concurrent Claude session that depended on it receives an error. Because Claude’s tool call dispatch is model-driven, an attacker who can craft a prompt that triggers a vulnerable tool with an oversized argument can cause a platform-wide denial of service from a single session. The four SA-SKL-ALLOCATION patterns address this shared-process attack surface.
SA-SKL-ALLOCATION in scope: ALLOCATION-001 (unbounded array allocation), ALLOCATION-002 (string repeat DoS), ALLOCATION-003 (recursive tree without depth guard), ALLOCATION-004 (JSON.stringify circular reference). Each pattern includes SkillAudit detection rules and Zod-based remediation.
ALLOCATION-001 — Unbounded array allocation from attacker-controlled count parameter
MCP skills that create arrays sized by a user-supplied parameter allocate memory proportional to the input value. Without a cap, an attacker passes 1e9 (one billion) as the count, causing V8 to attempt an 8GB heap allocation. The process either OOMs immediately or V8’s heap limit kills it. All concurrent tool calls from other Claude sessions fail.
Vulnerable code
// generateAuditBatch.ts — array sized by attacker-controlled count parameter
import { z } from 'zod';
// Schema with no upper bound on count
const GenerateBatchArgs = z.object({
count: z.number().int().positive(), // no .max() — allows arbitrarily large values
templateId: z.string(),
});
export const generateAuditBatchTool = {
name: 'generate_audit_batch',
description: 'Generate a batch of audit job stubs for bulk processing',
inputSchema: { ... },
async execute(rawArgs: unknown) {
const { count, templateId } = GenerateBatchArgs.parse(rawArgs);
// VULNERABLE: allocates array of size `count` unconditionally
// args.count = 1_000_000_000 → V8 tries to allocate 8GB → OOM → process killed
const batch = new Array(count).fill(null).map((_, i) => ({
jobId: `${templateId}-${i}`,
status: 'pending',
}));
return { batch, total: batch.length };
},
};
Attack: OOM kill via oversized count parameter
// Attacker crafts a Claude prompt that triggers generate_audit_batch with count=1e9:
// "Please generate a batch of 1000000000 audit stubs using template 'test'"
//
// Claude calls: generate_audit_batch({ count: 1000000000, templateId: 'test' })
//
// In the tool handler:
// new Array(1_000_000_000).fill(null)
//
// V8 behavior:
// - Array with 1B elements of size ~8 bytes each = ~8GB allocation requested
// - If system has less than 8GB free heap, process OOM-killed by OS
// - If using --max-old-space-size=512 (common for small MCP containers), killed at 512MB
// - All concurrent Claude sessions using any tool on this server fail immediately
// Demonstration: measure actual allocation time and peak memory
// node -e "
// const before = process.memoryUsage().heapUsed;
// try {
// const arr = new Array(1_000_000_000).fill(null);
// console.log('allocated', arr.length, 'elements');
// } catch (e) {
// console.error('OOM:', e.message); // RangeError or FATAL ERROR Reached heap limit
// }
// "
// Output: FATAL ERROR: CALL_AND_RETRY_LAST Reached heap limit Allocation failed - JavaScript heap out of memory
Fix: Zod z.number().max() cap before allocation
// generateAuditBatch.ts — count capped at reasonable limit before allocation
import { z } from 'zod';
const MAX_BATCH_SIZE = 1000; // define and document the business-logic maximum
const GenerateBatchArgs = z.object({
// .max() enforces the cap at Zod parse time — before any allocation
count: z.number().int().positive().max(MAX_BATCH_SIZE, {
message: `Batch count cannot exceed ${MAX_BATCH_SIZE} items`,
}),
templateId: z.string().min(1).max(100).regex(/^[\w-]+$/),
});
export const generateAuditBatchTool = {
name: 'generate_audit_batch',
description: `Generate a batch of audit job stubs (max ${MAX_BATCH_SIZE} items)`,
inputSchema: {
type: 'object',
properties: {
count: {
type: 'number',
description: `Number of audit stubs to generate (1–${MAX_BATCH_SIZE})`,
},
templateId: { type: 'string' },
},
required: ['count', 'templateId'],
},
async execute(rawArgs: unknown) {
// Zod throws ZodError if count > MAX_BATCH_SIZE — no allocation attempted
const { count, templateId } = GenerateBatchArgs.parse(rawArgs);
// Safe: count is guaranteed <= 1000 by Zod validation above
const batch = Array.from({ length: count }, (_, i) => ({
jobId: `${templateId}-${i}`,
status: 'pending',
}));
return { batch, total: batch.length };
},
};
Document the cap in the tool description. Including the maximum in the tool’s description string (“max 1000 items”) helps Claude avoid generating out-of-range values in the first place, reducing error rate for legitimate users while the validation guard catches adversarial inputs.
new Array(1e9).fill(null) allocates ~8GB, crashing the Node.js process and terminating all concurrent Claude sessions using any tool on the server. Fix: add z.number().max(N) in the Zod schema before any array allocation; set N to the highest value that makes business-logic sense. Detection: SkillAudit AST rule flags new Array(x) or Array.from({ length: x }) patterns where x is derived from tool input arguments without a preceding .max() constraint in the Zod schema.ALLOCATION-002 — String repeat DoS via attacker-controlled length
Skills that construct padding strings, separator lines, or fill buffers using String.prototype.repeat() with a user-supplied length allocate memory proportional to the input. A length of 1e8 (100 million) creates a 100MB string in a single synchronous operation, blocking the event loop and potentially crashing the process.
Vulnerable code: string repeat with no length cap
// formatFindings.ts — separator line length from user argument, no cap
import { z } from 'zod';
const FormatArgs = z.object({
findings: z.array(z.string()),
separatorLength: z.number().int().positive(), // no .max()
});
export const formatFindingsTool = {
name: 'format_findings_report',
description: 'Format audit findings with a separator line of given length',
inputSchema: { ... },
async execute(rawArgs: unknown) {
const { findings, separatorLength } = FormatArgs.parse(rawArgs);
// VULNERABLE: 'separatorLength = 100_000_000' creates a 100MB string
// Synchronous operation — blocks the event loop for all other tool calls
// while the string is being allocated and filled
const separator = '─'.repeat(separatorLength); // each '─' is 3 bytes UTF-8
return { report: findings.join(`\n${separator}\n`) };
},
};
Attack: event loop blocking via oversized string repeat
// Attacker sends: { findings: ['test'], separatorLength: 100_000_000 }
//
// '─'.repeat(100_000_000) allocates:
// - 100 million characters × 3 bytes/char (UTF-8 encoding of ─) = 300MB
// - In V8's string rope implementation: synchronous, blocks main thread
// - During allocation: all other pending tool calls are queued, unserved
// - If heap limit is exceeded: FATAL ERROR, process killed
// - If heap limit is not exceeded: 300MB allocated, event loop stalled for ~2s
//
// Minimum DoS: even without OOM, 2s event loop stall disrupts all concurrent sessions
// V8 heap limit test:
// node --max-old-space-size=256 -e "'x'.repeat(1e8)"
// Output: FATAL ERROR: CALL_AND_RETRY_LAST Reached heap limit
Fix: z.number().max(N) on length inputs; never construct strings from user dimensions
// formatFindings.ts — separator length capped at business-logic maximum
import { z } from 'zod';
const MAX_SEPARATOR_LENGTH = 200; // display width of a reasonable terminal line
const FormatArgs = z.object({
findings: z.array(z.string().max(1000)).max(100), // cap both items and item length
separatorLength: z.number().int().min(1).max(MAX_SEPARATOR_LENGTH),
});
export const formatFindingsTool = {
name: 'format_findings_report',
description: `Format audit findings with a separator line (max ${MAX_SEPARATOR_LENGTH} chars)`,
inputSchema: { ... },
async execute(rawArgs: unknown) {
const { findings, separatorLength } = FormatArgs.parse(rawArgs);
// Safe: separatorLength <= 200 by Zod validation — 200 chars = 600 bytes maximum
const separator = '─'.repeat(separatorLength);
return { report: findings.join(`\n${separator}\n`) };
},
};
// General rule: never construct string/buffer sizes from raw user input.
// Always cap BEFORE the allocation call, not after.
// Cap arrays: z.array(...).max(N)
// Cap string lengths: z.string().max(N)
// Cap numeric dimensions: z.number().max(N)
String.prototype.repeat() called with an attacker-controlled length parameter allocates memory proportional to the input: 'x'.repeat(1e8) allocates ~100MB synchronously, blocking the Node.js event loop for all concurrent tool calls and potentially causing OOM kill. Fix: add z.number().max(N) in the Zod schema for any parameter that feeds into .repeat(), Buffer.alloc(), or similar size-based allocation. Detection: SkillAudit AST rule flags .repeat(x) or Buffer.alloc(x) where x is derived from tool input arguments without a preceding .max() constraint.ALLOCATION-003 — Recursive tree processing without depth guard causes stack overflow
MCP skills that accept nested JSON structures and process them recursively can be crashed via a deeply nested input. Node.js’s default call stack depth is approximately 10,000–15,000 frames. An attacker sends a JSON object nested 20,000 levels deep; the recursive function overflows the stack on the way down. Because JavaScript call stack overflows are synchronous fatal errors, they can terminate the entire process.
Vulnerable code: recursive tree traversal without depth limit
// analyzeCallGraph.ts — recursive tree visitor with no depth guard
import { z } from 'zod';
// Lazy recursive type — allows arbitrary nesting in Zod schema
const TreeNode: z.ZodType<any> = z.lazy(() =>
z.object({
name: z.string(),
children: z.array(TreeNode).optional(),
})
);
const AnalyzeArgs = z.object({
callTree: TreeNode,
});
// VULNERABLE: recurses without tracking depth
function extractCallChains(node: any, path: string[] = []): string[][] {
const current = [...path, node.name];
if (!node.children || node.children.length === 0) {
return [current];
}
// Recursive call — depth limited only by Node.js call stack (~10,000–15,000 frames)
return node.children.flatMap((child: any) => extractCallChains(child, current));
}
export const analyzeCallGraphTool = {
name: 'analyze_call_graph',
description: 'Analyze a function call graph tree for security patterns',
inputSchema: { ... },
async execute(rawArgs: unknown) {
const { callTree } = AnalyzeArgs.parse(rawArgs);
// If callTree is 20,000 levels deep, this throws RangeError: Maximum call stack size exceeded
const chains = extractCallChains(callTree);
return { callChains: chains };
},
};
Attack: deep nesting triggers stack overflow
#!/usr/bin/env python3
# Generate a deeply nested JSON tree that overflows Node.js's call stack
import json
def build_nested_tree(depth: int) -> dict:
node = {'name': f'fn_{depth}', 'children': []}
current = node
for i in range(depth - 1, 0, -1):
child = {'name': f'fn_{i}', 'children': []}
current['children'].append(child)
current = child
return node
# Node.js default stack: ~10,000–15,000 frames
# Nesting depth 20,000 overflows most configurations
tree = build_nested_tree(20_000)
payload = {
'name': 'analyze_call_graph',
'arguments': {'callTree': tree}
}
print(f'Tree depth: 20000, payload size: {len(json.dumps(payload)) / 1024:.0f} KB')
import requests
resp = requests.post(
'https://skillaudit.dev/mcp/tools/call',
json=payload,
headers={'Authorization': 'Bearer TOKEN', 'Content-Type': 'application/json'},
timeout=30,
)
print(f'Response: {resp.status_code}')
# If vulnerable: 500 Internal Server Error (process crashed and was restarted)
# or connection refused (process killed, not yet restarted)
Fix: depth counter with MAX_DEPTH guard before recursive call
// analyzeCallGraph.ts — recursion with explicit depth guard
import { z } from 'zod';
const MAX_DEPTH = 50; // maximum meaningful call chain depth; adjust per use case
// Zod schema with structural depth limit via refinement
const TreeNode: z.ZodType<any> = z.lazy(() =>
z.object({
name: z.string().max(200),
children: z.array(TreeNode).max(100).optional(), // cap breadth too
})
);
const AnalyzeArgs = z.object({
callTree: TreeNode,
});
// Recursive function with explicit depth tracking
function extractCallChains(
node: any,
path: string[] = [],
depth: number = 0
): string[][] {
// Guard: throw before recursing if depth limit reached
if (depth > MAX_DEPTH) {
throw Object.assign(
new Error(`Call tree exceeds maximum depth of ${MAX_DEPTH}`),
{ code: 'TREE_TOO_DEEP', status: 400 }
);
}
const current = [...path, node.name];
if (!node.children || node.children.length === 0) {
return [current];
}
return node.children.flatMap((child: any) =>
extractCallChains(child, current, depth + 1)
);
}
export const analyzeCallGraphTool = {
name: 'analyze_call_graph',
description: `Analyze a function call graph tree (max depth ${MAX_DEPTH})`,
inputSchema: { ... },
async execute(rawArgs: unknown) {
const { callTree } = AnalyzeArgs.parse(rawArgs);
try {
const chains = extractCallChains(callTree);
return { callChains: chains };
} catch (err: any) {
if (err.code === 'TREE_TOO_DEEP') {
return { error: err.message, callChains: [] };
}
throw err;
}
},
};
// Alternative: iterative traversal using an explicit stack (no call stack risk at all)
function extractCallChainsIterative(root: any): string[][] {
const result: string[][] = [];
const stack: { node: any; path: string[]; depth: number }[] = [
{ node: root, path: [], depth: 0 },
];
while (stack.length > 0) {
const { node, path, depth } = stack.pop()!;
if (depth > MAX_DEPTH) continue; // skip instead of throw for iterative version
const current = [...path, node.name];
if (!node.children || node.children.length === 0) {
result.push(current);
} else {
for (const child of node.children) {
stack.push({ node: child, path: current, depth: depth + 1 });
}
}
}
return result;
}
Iterative traversal eliminates stack overflow risk entirely. The recursive approach with a depth counter is simpler to read but still consumes stack frames. For deeply nested structures, the iterative approach using an explicit stack array is strictly safer — it uses heap memory (bounded by your existing allocation caps) rather than call stack frames.
RangeError: Maximum call stack size exceeded when the input exceeds ~10,000 nesting levels, potentially crashing the Node.js process and terminating all concurrent MCP tool calls. Fix: add an explicit depth parameter with a MAX_DEPTH guard that throws before recursing; or rewrite as iterative traversal with an explicit stack array. Detection: SkillAudit AST rule flags recursive function calls where the recursing argument originates from a tool input object field (node.children, obj.nested, etc.) without a depth parameter increment and limit check.ALLOCATION-004 — JSON.stringify on circular reference crashes or hangs
MCP skills that log arguments, build debug responses, or serialize error details using JSON.stringify() can be crashed if the argument contains a circular reference. JSON.stringify throws TypeError: Converting circular structure to JSON synchronously. If the error is caught and JSON.stringify is retried in a loop, the process hangs. Even a single uncaught throw in a logging path can bubble up and crash the tool call handler.
Vulnerable code: JSON.stringify on tool arguments without try/catch
// auditLogger.ts — logs raw args via JSON.stringify, no circular reference guard
import fs from 'fs';
export function logToolCall(toolName: string, args: unknown): void {
// VULNERABLE: JSON.stringify throws TypeError on circular references
// If args contains { a: { b: null } } where a.b is set to args.a (circular),
// this throws synchronously
const logLine = JSON.stringify({ tool: toolName, args, ts: Date.now() });
fs.appendFileSync('./audit.log', logLine + '\n');
}
// In the tool handler:
export async function execute(rawArgs: unknown) {
logToolCall('get_audit_findings', rawArgs); // throws if rawArgs is circular
// ...
}
Attack: circular reference injection causes TypeError crash
// Most MCP frameworks use JSON.parse to deserialize tool arguments from the wire,
// which can't create circular references (JSON is acyclic by definition).
// However, if a tool post-processes arguments or the skill server uses a custom
// deserializer that constructs JavaScript objects from templates, circular references
// can appear in the resulting args object.
// Example: an adversarial MCP message intercepted in transit (MITM or proxy injection):
// The MCP protocol uses JSON messages — but a skill's internal processing might
// reconstruct objects with shared references.
// Also applies to error logging:
export async function execute(rawArgs: unknown) {
try {
// ... tool logic
} catch (err: any) {
// VULNERABLE: err.cause or err.context may contain circular references
// (e.g., Node.js EventEmitter errors, Axios error objects with circular response refs)
console.error(JSON.stringify({ error: err.message, context: err })); // throws
// The uncaught TypeError from JSON.stringify propagates and crashes the handler
}
}
// Real-world circular reference example from Axios errors:
// err.response.request.socket.parser.incoming === err.response (circular)
// JSON.stringify(axiosError) → TypeError: Converting circular structure to JSON
Fix: try/catch on JSON.stringify; use safe-stringify for logging
// auditLogger.ts — safe serialization with circular reference handling
import safeStringify from 'fast-safe-stringify';
// Option A: use fast-safe-stringify package — handles circulars with '[Circular]' replacement
export function logToolCall(toolName: string, args: unknown): void {
// fast-safe-stringify never throws — circular references become '[Circular]'
const logLine = safeStringify({ tool: toolName, args, ts: Date.now() });
fs.appendFileSync('./audit.log', logLine + '\n');
}
// Option B: try/catch on JSON.stringify with structured fallback
export function safeJsonSerialize(value: unknown): string {
try {
return JSON.stringify(value);
} catch (err) {
if (err instanceof TypeError && err.message.includes('circular')) {
// Fallback: serialize a sanitized representation
return JSON.stringify({
__serialization_error: 'circular_reference',
type: typeof value,
keys: value !== null && typeof value === 'object' ? Object.keys(value) : [],
});
}
throw err; // rethrow unexpected errors
}
}
// Option C: custom replacer function that tracks seen objects
export function circularSafeStringify(value: unknown): string {
const seen = new WeakSet();
return JSON.stringify(value, (key, val) => {
if (typeof val === 'object' && val !== null) {
if (seen.has(val)) return '[Circular]';
seen.add(val);
}
return val;
});
}
// Recommended: use fast-safe-stringify for all logging paths;
// use the custom replacer approach for structured API responses where
// you want to control the '[Circular]' token format.
// Never retry JSON.stringify in a loop on failure — always fall through to the fallback.
Circular references in error objects are common and easily overlooked. Node.js built-in errors, Axios response errors, and many ORM error objects contain circular references in their cause, response, or context fields. Any code path that calls JSON.stringify(err) rather than JSON.stringify(err.message) is vulnerable. Apply fast-safe-stringify to all logging paths, not just tool argument serialization.
JSON.stringify() called on tool arguments or caught error objects without a circular reference guard throws TypeError: Converting circular structure to JSON when the input contains object cycles (common in Axios errors, Node.js EventEmitter errors, and ORM error objects). An uncaught throw in a logging or error-handling path crashes the tool call handler. Fix: replace JSON.stringify() with fast-safe-stringify in all logging paths; wrap manual JSON.stringify calls in try/catch with a structured fallback. Detection: SkillAudit flags JSON.stringify(x) calls where x is a caught error object (err, e, error variable names) or a raw tool input argument without a try/catch wrapper.SA-SKL-ALLOCATION summary findings
| Finding ID | Severity | Pattern | Root cause |
|---|---|---|---|
| SA-SKL-ALLOCATION-001 | HIGH | Unbounded array allocation from count parameter | new Array(args.count) without a Zod .max() cap allows 8GB+ allocation via count=1e9. Fix: z.number().max(N) before any size-based allocation. |
| SA-SKL-ALLOCATION-002 | HIGH | String repeat DoS via attacker-controlled length | 'x'.repeat(args.length) without a cap allocates 100MB+ synchronously, blocking the event loop. Fix: z.number().max(N) on any parameter feeding .repeat() or Buffer.alloc(). |
| SA-SKL-ALLOCATION-003 | HIGH | Recursive tree processing without depth guard | Recursive function processing user-supplied nested JSON overflows at ~10,000–15,000 depth. Fix: explicit depth counter with MAX_DEPTH guard; or iterative traversal with explicit stack array. |
| SA-SKL-ALLOCATION-004 | MEDIUM | JSON.stringify on circular reference crashes handler | JSON.stringify(err) or JSON.stringify(rawArgs) throws synchronously on circular objects. Fix: fast-safe-stringify in all logging paths; try/catch with structured fallback on manual calls. |
SkillAudit detects all four SA-SKL-ALLOCATION patterns through static analysis of array allocation patterns, string repeat calls, recursive function structures, and JSON serialization paths in your MCP skill’s source code. Run a full audit at skillaudit.dev.