← Blog

Claude skill request timeout and resource exhaustion in MCP skill tool handlers — SA-SKL-TIMEOUT

Node.js's single-threaded event loop model means that any tool handler that blocks synchronously or holds open resources after a request terminates affects every other concurrent request in the same process. MCP skills running on shared infrastructure (the common case) are particularly exposed because a single attacker-controlled request can degrade service for all users. SA-SKL-TIMEOUT covers four resource exhaustion patterns: absent handler timeouts, unbounded request body size, streams not cleaned up on disconnect, and synchronous CPU blocking on each tool call.

By SkillAudit  |  6 Nov 2026

TIMEOUT-001 — No timeout on tool handler execution: event loop blocks indefinitely

MCP skill tool handlers that make external calls (to APIs, databases, or spawned processes) without a timeout will block indefinitely if the external service hangs or the attacker supplies input that causes a pathological computation (O(n²) regex backtracking, deep recursive descent parsers, exponential recursion). In a production Node.js process, all in-flight requests share the same event loop. A single handler that never resolves prevents the event loop from processing any other pending callbacks — effectively taking down the skill for all concurrent users. The fix is to use AbortSignal.timeout() (available from Node.js 17.3+) for all external calls and to track handler duration via AsyncLocalStorage to enforce a per-handler deadline independent of any individual operation.

// VULNERABLE — TIMEOUT-001: tool handler with no timeout — hangs indefinitely
app.post('/tools/analyze', requireAuth, async (req, res) => {
  const { repoUrl, branch } = req.body;

  // No timeout on the GitHub fetch — if GitHub is slow or repoUrl is a slow server,
  // this promise never resolves
  const repoData = await fetchGithubRepo(repoUrl, branch);

  // No timeout on the scan — if the user supplies a large file with a ReDoS pattern,
  // the regex engine runs forever
  const scanResults = await runSecurityScan(repoData);

  // Meanwhile, the event loop is blocked — all other requests in this process wait
  res.json({ results: scanResults });
});
// FIXED — TIMEOUT-001: AbortSignal.timeout() on all external calls
app.post('/tools/analyze', requireAuth, async (req, res) => {
  // Create a master abort signal for the entire handler — 30 second hard deadline
  const handlerSignal = AbortSignal.timeout(30_000);

  // Propagate the signal to all external calls
  const repoData = await fetchGithubRepo(req.body.repoUrl, req.body.branch, {
    signal: AbortSignal.any([handlerSignal, AbortSignal.timeout(10_000)]), // 10s for fetch
  });

  const scanResults = await runSecurityScan(repoData, {
    signal: AbortSignal.any([handlerSignal, AbortSignal.timeout(20_000)]), // 20s for scan
    // Worker thread for CPU-intensive scan to avoid blocking the event loop (see TIMEOUT-004)
  });

  if (handlerSignal.aborted) {
    return res.status(504).json({ error: 'Handler timeout — analysis took too long' });
  }

  res.json({ results: scanResults });
});

// For handlers that call fetch() (Node.js 18+):
// fetch(url, { signal: AbortSignal.timeout(10_000) })
// — automatically throws AbortError if the request takes longer than 10 seconds

// For handlers calling child_process.spawn():
const { spawn } = require('child_process');
const child = spawn('eslint', [filePath], { signal: AbortSignal.timeout(15_000) });
// — automatically kills the child process when the signal fires
HIGH
SA-SKL-TIMEOUT-001 — Tool handler route functions that make external calls or run user-input-dependent computations without timeout signals block the Node.js event loop indefinitely on pathological input or slow upstreams, causing service degradation for all concurrent users; fix by using AbortSignal.timeout() on all fetch(), spawn(), and async database calls within tool handlers. Detection: SkillAudit flags route handler functions that contain await fetch(), await db.*, or spawn() calls without a corresponding signal: option.

TIMEOUT-002 — Unbounded JSON body size: Express bodyParser limit does not cover streaming endpoints

Express's express.json() middleware applies a 100kb body size limit by default. However, this limit applies only to endpoints where the express.json() middleware is in the middleware chain. Streaming endpoints that read the request body directly via req.on('data', ...) or via other body parsing libraries (without an explicit size limit) have no limit. An attacker can send a 2GB JSON body to such an endpoint, consuming all available memory in the Node.js process and crashing it. Even on endpoints covered by express.json(), developers sometimes increase the limit to accommodate large uploads without realizing the DoS risk — a 50MB limit allows a single request to allocate 50MB of memory, and 20 concurrent requests allocate 1GB.

// VULNERABLE — TIMEOUT-002: missing body size limit on custom body reader
import express from 'express';

const app = express();

// express.json() with 100kb limit — applies only to this middleware
app.use(express.json({ limit: '100kb' }));

// VULNERABLE: custom streaming body reader with NO size limit
app.post('/tools/bulk-scan', (req, res) => {
  let body = '';

  req.on('data', (chunk) => {
    body += chunk; // Accumulates indefinitely — no size check
    // Attacker sends 2GB → process runs OOM → crash
  });

  req.on('end', async () => {
    const payload = JSON.parse(body);
    // ... process payload
  });
});

// ALSO VULNERABLE: express.json() with an excessive limit
app.use(express.json({ limit: '50mb' })); // 50MB per request → 20 concurrent = 1GB
// FIXED — TIMEOUT-002: enforce size limits on ALL body reading paths
import express from 'express';

const app = express();

// Set a reasonable limit on the shared json() middleware
app.use(express.json({ limit: '1mb' })); // 1MB is generous for API payloads

// FIXED: custom streaming body reader with enforced size limit
app.post('/tools/bulk-scan', (req, res) => {
  const MAX_BODY_SIZE = 1 * 1024 * 1024; // 1MB limit
  let body = '';
  let size = 0;

  req.on('data', (chunk) => {
    size += chunk.length;
    if (size > MAX_BODY_SIZE) {
      // Stop reading and reject — destroy the request stream
      req.destroy(new Error('Request body too large'));
      res.status(413).json({ error: 'Request body exceeds 1MB limit' });
      return;
    }
    body += chunk;
  });

  req.on('error', (err) => {
    if (!res.headersSent) {
      res.status(413).json({ error: 'Request body too large' });
    }
  });

  req.on('end', async () => {
    if (res.headersSent) return; // Already rejected due to size limit
    try {
      const payload = JSON.parse(body);
      // ... process payload
    } catch {
      res.status(400).json({ error: 'Invalid JSON' });
    }
  });
});
HIGH
SA-SKL-TIMEOUT-002 — Streaming request body readers that accumulate data via req.on('data') without a maximum size check allow attackers to send arbitrarily large bodies (2GB+), exhausting process memory and crashing the skill; fix by enforcing a byte counter in the data event handler and destroying the stream when the limit is exceeded, and setting a conservative limit on express.json() (≤1MB). Detection: SkillAudit flags route handlers containing req.on('data') without a corresponding byte-count guard and size rejection.

TIMEOUT-003 — Stream not destroyed on client disconnect: DB cursor reads all rows after client leaves

When a skill streams a large result set to a client (audit history, paginated scan results, log exports), the streaming pipeline typically involves a database cursor, a transform stream, and the response stream. If the client disconnects mid-stream (closes the browser tab, network interruption, timeout), the response stream receives a 'close' event — but the upstream database cursor continues reading rows until it reaches the end of the result set. For a query that would return 50,000 rows, closing after 100 rows means the database connection stays open and reads the remaining 49,900 rows from the DB, holding the DB connection and burning compute for the full scan. Under sustained disconnection attacks (10 clients connect and disconnect immediately on streaming endpoints), all DB connections in the pool are held by zombie cursors and no new connections are available.

// VULNERABLE — TIMEOUT-003: stream not destroyed on client disconnect
import { pipeline } from 'stream/promises';
import { createReadStream } from 'fs';

app.get('/tools/:id/logs', requireAuth, async (req, res) => {
  const cursor = db.auditLogs.findMany({
    where: { auditId: req.params.id },
    orderBy: { createdAt: 'asc' },
    // Returns up to 50,000 rows as a database cursor/stream
  });

  // Convert cursor to a Node.js readable stream
  const logStream = cursor.toStream(); // Hypothetical Prisma-like cursor to stream

  res.setHeader('Content-Type', 'application/x-ndjson');

  // VULNERABLE: if the client disconnects, res stream closes — but logStream continues
  // reading all 50k rows from the DB connection (which is never released)
  await pipeline(logStream, res);
});
// FIXED — TIMEOUT-003: destroy upstream on client disconnect
app.get('/tools/:id/logs', requireAuth, async (req, res) => {
  const cursor = db.auditLogs.findMany({
    where: { auditId: req.params.id },
    orderBy: { createdAt: 'asc' },
  });

  const logStream = cursor.toStream();

  res.setHeader('Content-Type', 'application/x-ndjson');

  // Destroy the DB cursor stream when the client disconnects
  req.on('close', () => {
    logStream.destroy(); // Closes the DB cursor — releases the connection immediately
  });

  // Also handle the case where the response finishes normally
  res.on('finish', () => {
    logStream.destroy();
  });

  logStream.on('error', (err) => {
    if (!err.message.includes('destroyed')) {
      // Log unexpected errors — 'destroyed' is expected on client disconnect
      console.error('Log stream error:', err);
    }
    if (!res.headersSent) res.status(500).end();
  });

  logStream.pipe(res);
});

// Alternative: use pipeline() with an AbortSignal tied to req 'close' event
import { pipeline } from 'stream/promises';

app.get('/tools/:id/logs', requireAuth, async (req, res) => {
  const ac = new AbortController();
  req.on('close', () => ac.abort()); // Abort pipeline when client disconnects

  const logStream = db.auditLogs.findMany({ where: { auditId: req.params.id } }).toStream();
  res.setHeader('Content-Type', 'application/x-ndjson');

  try {
    await pipeline(logStream, res, { signal: ac.signal });
  } catch (err) {
    if (err.name !== 'AbortError') console.error('Pipeline error:', err);
    // AbortError is expected on client disconnect — pipeline() cleans up all streams
  }
});
MEDIUM
SA-SKL-TIMEOUT-003 — Streaming route handlers that pipe a database cursor to the response without a req.on('close') cleanup handler leave the DB cursor reading until the end of the result set after client disconnects, holding DB connections in the pool and burning unnecessary compute; fix by calling logStream.destroy() in a req.on('close') handler, or using stream/promises pipeline() with an AbortSignal tied to the close event. Detection: SkillAudit flags route handlers that call stream.pipe(res) or pipeline(stream, res) without a req.on('close') handler that destroys the source stream.

TIMEOUT-004 — Synchronous CPU in async context: CPU-intensive regex blocks all concurrent requests

Node.js's event loop is cooperative — asynchronous operations yield control back to the event loop via await or setImmediate(), but synchronous CPU work (regex matching, tight loops, recursive descent parsing) holds the event loop thread until it completes. If a MCP skill's tool handler runs CPU-intensive regex over user-supplied input (e.g. scanning uploaded code for secret patterns, linting rules, or search over large log files) and that regex has exponential backtracking complexity on adversarial input (ReDoS), a single request with crafted input can hold the event loop for seconds to minutes. During that time, all other requests waiting in the event loop queue are paused — including requests from other users, health checks, and even TLS handshakes. The correct fix is to offload CPU-intensive work to Node.js Worker threads, which have their own event loop and do not share the main thread.

// VULNERABLE — TIMEOUT-004: synchronous CPU-intensive regex in main thread handler
app.post('/tools/secret-scan', requireAuth, async (req, res) => {
  const { code } = req.body;

  // These patterns run synchronously in the main event loop thread
  const patterns = [
    /(?:api[_-]?key|apikey)\s*[:=]\s*['"]?([a-z0-9]{20,})/gi,
    /(?:secret|password|passwd|pwd)\s*[:=]\s*['"]?(\S{8,})/gi,
    // ReDoS-vulnerable pattern — exponential backtracking on adversarial input:
    /(a+)+$/, // Catastrophic backtracking — do NOT use
  ];

  const matches = [];
  for (const pattern of patterns) {
    // regex.exec() is synchronous — holds the event loop for the entire scan duration
    let match;
    while ((match = pattern.exec(code)) !== null) {
      matches.push({ pattern: pattern.source, value: match[1] });
    }
  }
  // If 'code' is 500KB with adversarial content, this loop runs for 30+ seconds
  // All other requests in the process are paused for 30 seconds

  res.json({ matches });
});
// FIXED — TIMEOUT-004: offload CPU-intensive work to a Worker thread
// workers/secret-scanner.js (runs in its own thread with its own event loop)
import { parentPort, workerData } from 'worker_threads';

const SAFE_PATTERNS = [
  // Use linear-time patterns with possessive quantifiers or atomic groups
  // Test with https://redosdetector.com before deploying new patterns
  /(?:api[_-]?key|apikey)\s*[:=]\s*['"]?([a-zA-Z0-9_\-]{20,40})/gi,
  /(?:secret|password)\s*[:=]\s*['"]?([^\s'"]{8,32})/gi,
];

const matches = [];
const { code } = workerData;

// Limit input size in the worker too
if (code.length > 500_000) {
  parentPort.postMessage({ error: 'Code too large for scanning' });
  process.exit(0);
}

for (const pattern of SAFE_PATTERNS) {
  let match;
  while ((match = pattern.exec(code)) !== null) {
    matches.push({ value: match[1], index: match.index });
  }
}

parentPort.postMessage({ matches });

// main route handler (main thread):
import { Worker } from 'worker_threads';
import path from 'path';

function runSecretScan(code) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(path.resolve('./workers/secret-scanner.js'), {
      workerData: { code },
    });

    // Set a timeout for the worker — if it takes too long, terminate it
    const timeout = setTimeout(() => {
      worker.terminate();
      reject(new Error('Secret scan timeout'));
    }, 10_000); // 10 second limit

    worker.on('message', (result) => {
      clearTimeout(timeout);
      resolve(result);
    });

    worker.on('error', (err) => {
      clearTimeout(timeout);
      reject(err);
    });
  });
}

app.post('/tools/secret-scan', requireAuth, async (req, res) => {
  try {
    const result = await runSecretScan(req.body.code ?? '');
    if (result.error) return res.status(400).json({ error: result.error });
    res.json({ matches: result.matches });
  } catch (err) {
    res.status(504).json({ error: 'Scan timed out or failed' });
  }
});
HIGH
SA-SKL-TIMEOUT-004 — CPU-intensive regex or recursive parsing executed synchronously in Express route handlers holds the Node.js event loop — blocking all concurrent requests for the duration; fix by offloading CPU-bound work to Node.js Worker threads (which have isolated event loops) with a termination timeout, and validating regex patterns against ReDoS detection tools before deployment. Detection: SkillAudit flags route handlers containing synchronous regex operations (via RegExp.exec() or String.match()) on user-supplied input fields larger than 10KB without Worker thread delegation.

Detection summary

ID Severity Pattern Fix
TIMEOUT-001 HIGH External calls in tool handlers without AbortSignal — blocks event loop indefinitely AbortSignal.timeout(10_000) on all fetch(), spawn(), DB calls
TIMEOUT-002 HIGH Streaming body reader without size limit — 2GB body exhausts process memory Byte counter in req.on('data') + destroy at limit; express.json({ limit: '1mb' })
TIMEOUT-003 MEDIUM DB cursor stream not destroyed on client disconnect — connection held for full result set req.on('close', () => stream.destroy()) or AbortSignal pipeline
TIMEOUT-004 HIGH Synchronous CPU (regex, recursion) in main thread — blocks all concurrent requests Worker thread with termination timeout; ReDoS-safe patterns

Related patterns: SA-SKL-RATELIMIT4 covers distributed rate limit bypasses — the first layer of defense against sustained resource exhaustion attacks. SA-SKL-RATELIMIT (TIMEOUT) covers complete absence of rate limiting, the most basic form of DoS protection. SA-SKL-WEBWORKER covers SharedArrayBuffer and Worker thread security in MCP skill web UIs, which shares the Worker thread isolation model used in the TIMEOUT-004 fix.