← Blog

Claude skill prototype pollution in MCP skill utility libraries — SA-SKL-PROTOTYPE4

Prototype pollution vulnerabilities arise from utility library patterns that are so common in MCP skill codebases that developers rarely question them: deep merging with lodash, cloning with JSON.parse(JSON.stringify()), validation schema construction, and shallow copying with Object.assign(). SA-SKL-PROTOTYPE4 covers four specific patterns where these utilities allow an attacker to inject properties into Object.prototype, affecting all subsequently created plain objects in the Node.js process.

By SkillAudit  |  6 Nov 2026

What prototype pollution means for a running MCP skill process

JavaScript objects inherit from Object.prototype by default. When attacker-controlled data is merged into a plain object using a path like {"__proto__": {"isAdmin": true}}, some merge functions follow the __proto__ key and assign isAdmin directly to Object.prototype rather than to the target object's own properties. After this assignment, every subsequently created plain object — including authentication context objects, middleware-constructed request objects, and configuration snapshots — has .isAdmin === true as an inherited property. Because if (user.isAdmin) returns true even for a non-admin user (the property is inherited, not own), the pollution effectively grants every user admin privileges for the life of the process without restarting the Node.js instance.

MCP skills are particularly at risk because they process structured JSON tool call arguments — a natural attack surface for __proto__ injection — and because the fix (Ajv schema validation with additionalProperties: false + key filtering before deep operations) is easy to implement consistently once the attack surface is understood.

SA-SKL-PROTOTYPE4 in scope: PROTOTYPE4-001 (lodash _.merge() with __proto__ key — still present without the customizer guard even on lodash 4.17.21+), PROTOTYPE4-002 (JSON.parse(JSON.stringify()) round-trip does not sanitize pollution — it round-trips __proto__ as a string key assignment), PROTOTYPE4-003 (express-validator object-based schema with user-supplied field names), PROTOTYPE4-004 (Object.assign(target, req.body) copies __proto__ as an own string property that affects hasOwnProperty checks). Each pattern includes SkillAudit detection rules and correct fixes.

PROTOTYPE4-001 — lodash _.merge() with user-controlled JSON assigns to Object.prototype

lodash _.merge() performs a deep merge by recursively traversing key-value pairs and assigning properties. When the source object contains a __proto__ key — either directly in the JSON or via a nested traversal — lodash follows the prototype chain reference and assigns the value to Object.prototype. lodash 4.17.21 (the current release as of 2026) does not contain an automatic guard against this in _.merge() itself — the fix is to either use _.mergeWith() with a customizer that blocks the three dangerous keys, or to validate input with an Ajv schema that rejects these keys before the merge call. Using structuredClone() as the merge operation (not safe — see PROTOTYPE4-002) or switching to a null-prototype target object are alternative patterns.

// VULNERABLE — lodash _.merge() with user-controlled JSON
import _ from 'lodash';

export async function updateAuditConfig(
  baseConfig: object,
  userSuppliedPatch: unknown // comes from tool call arguments
): Promise<object> {
  // Attacker supplies: userSuppliedPatch = {"__proto__": {"isAdmin": true, "skipAuth": true}}
  // After this call, every plain object in the process has isAdmin === true (inherited)
  const merged = _.merge({}, baseConfig, userSuppliedPatch);
  return merged;
}
// FIXED — Option A: _.mergeWith() customizer blocks dangerous keys
import _ from 'lodash';

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

function safeCustomizer(
  _objValue: unknown,
  _srcValue: unknown,
  key: string
): undefined {
  if (DANGEROUS_KEYS.has(key)) return undefined; // Skip dangerous keys entirely
  return undefined; // undefined = use default lodash merge behavior for other keys
}

export async function updateAuditConfig(
  baseConfig: object,
  userSuppliedPatch: unknown
): Promise<object> {
  if (typeof userSuppliedPatch !== 'object' || userSuppliedPatch === null) {
    throw new Error('Patch must be a non-null object');
  }
  return _.mergeWith({}, baseConfig, userSuppliedPatch, safeCustomizer);
}

// FIXED — Option B: Ajv schema validation before merge (recommended for MCP tool args)
import Ajv from 'ajv';

const ajv = new Ajv({ allowUnionTypes: true });
const patchSchema = {
  type: 'object',
  additionalProperties: false, // Only explicitly defined keys are allowed
  properties: {
    maxScanDepth: { type: 'number', minimum: 1, maximum: 10 },
    enableExperimentalChecks: { type: 'boolean' },
    skipPatterns: { type: 'array', items: { type: 'string' } },
  },
};
const validatePatch = ajv.compile(patchSchema);

export async function updateAuditConfigSafe(
  baseConfig: object,
  userSuppliedPatch: unknown
): Promise<object> {
  if (!validatePatch(userSuppliedPatch)) {
    throw new Error('Invalid patch: ' + ajv.errorsText(validatePatch.errors));
  }
  // Safe to merge — schema validation has excluded __proto__ via additionalProperties: false
  return _.merge({}, baseConfig, userSuppliedPatch);
}
CRITICAL
SA-SKL-PROTOTYPE4-001 — _.merge(target, userInput) in lodash follows __proto__ keys and assigns properties to Object.prototype, poisoning all subsequent plain objects in the Node.js process; fix by using _.mergeWith() with a customizer that blocks __proto__, constructor, and prototype keys, or by validating input with an Ajv schema using additionalProperties: false before calling merge. Detection: SkillAudit flags tool handler functions that call _.merge() or _.mergeWith() with arguments that trace to tool call parameters without an Ajv schema validation or key-filtering customizer guard.

PROTOTYPE4-002 — JSON.parse(JSON.stringify()) round-trip does not sanitize prototype pollution

A common misconception is that JSON.parse(JSON.stringify(untrustedInput)) sanitizes against prototype pollution because the JSON serialization strips non-JSON types. This is incorrect. JSON.stringify({"__proto__": {"admin": true}}) produces the string "{\"__proto__\":{\"admin\":true}}" — the __proto__ key is preserved as a literal string key in the JSON output. When JSON.parse() processes this string, it creates an object with a string key literally named __proto__ as an own property — it does not assign to the prototype chain. This means the round-trip does not cause pollution via JSON.parse() itself. However, if the resulting object (which has __proto__ as an own property) is then passed to _.merge() or another deep-clone function, the pollution occurs at that step. The fix is to perform the pollution defense at the merge step, not at the JSON parse step — and to use structuredClone() for safe cloning (which does sanitize __proto__ keys).

// MISCONCEPTION — JSON round-trip is NOT sufficient sanitization before _.merge()
import _ from 'lodash';

export async function mergeUserConfig(
  baseConfig: object,
  rawUserConfig: string // Raw JSON string from tool call argument
): Promise<object> {
  // Developer believes JSON.parse sanitizes prototype pollution — this is WRONG
  // JSON.parse preserves __proto__ as a string key (own property) on the parsed object
  const parsed = JSON.parse(rawUserConfig);
  // parsed is { __proto__: { admin: true } } — with __proto__ as OWN property

  // When passed to _.merge(), the OWN __proto__ key IS followed and DOES pollute
  // The pollution happens in _.merge(), not in JSON.parse()
  const merged = _.merge({}, baseConfig, parsed); // POLLUTION OCCURS HERE
  return merged;
}
// FIXED — Option A: Use structuredClone() for cloning (safe against __proto__ own prop)
export async function mergeUserConfigSafe(
  baseConfig: object,
  rawUserConfig: string
): Promise<object> {
  let parsed: unknown;
  try {
    parsed = JSON.parse(rawUserConfig);
  } catch {
    throw new Error('Invalid JSON');
  }

  if (typeof parsed !== 'object' || parsed === null) {
    throw new Error('Config must be a JSON object');
  }

  // structuredClone() strips __proto__ as an own property — safe to use as merge input
  // But still use _.mergeWith() with the customizer for defense in depth
  const sanitized = structuredClone(parsed);

  return _.mergeWith({}, baseConfig, sanitized, (_, __, key) => {
    if (['__proto__', 'constructor', 'prototype'].includes(key)) return undefined;
  });
}

// FIXED — Option B: Explicit key filtering before any deep operation
function sanitizeKeys(obj: unknown, depth = 0): unknown {
  if (depth > 10) return {}; // Prevent stack overflow on deeply nested input
  if (typeof obj !== 'object' || obj === null) return obj;
  const result: Record<string, unknown> = Object.create(null); // Null-prototype target
  for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
    if (['__proto__', 'constructor', 'prototype'].includes(key)) continue;
    result[key] = sanitizeKeys(value, depth + 1);
  }
  return result;
}
CRITICAL
SA-SKL-PROTOTYPE4-002 — JSON.parse(JSON.stringify(input)) does not sanitize __proto__ keys — the round-trip preserves __proto__ as an own property on the parsed object, which then causes pollution when that object is passed to _.merge(); use structuredClone() (which does strip __proto__ own properties) or perform key filtering before any deep merge operation. Detection: SkillAudit flags code paths where the output of JSON.parse() flows into _.merge() or other deep-merge functions without an intervening key-filtering sanitizer.

PROTOTYPE4-003 — express-validator object schema with user-supplied field names

express-validator's checkSchema() function accepts an object where the keys are field paths to validate. If a skill endpoint constructs the validation schema dynamically from user-supplied field names — for example, to validate a custom configuration format that the user defines — an attacker can supply __proto__, constructor, or constructor.prototype as a field path. express-validator internally uses deep property access to apply the schema entry, potentially creating or modifying properties on the prototype chain of the schema-building target objects. The fix is to never construct validation schemas from user-supplied keys, and to validate the allowed field names against an explicit allowlist before building any dynamic schema.

// VULNERABLE — express-validator schema constructed from user-supplied field names
import { checkSchema } from 'express-validator';

app.post('/api/audits/custom', (req, res, next) => {
  const { fields } = req.body; // User-supplied: { "__proto__": { required: true } }

  // Building a validation schema dynamically from user input
  const schema = {};
  for (const [fieldName, rules] of Object.entries(fields)) {
    // fieldName = "__proto__" — schema entry for __proto__
    // This pollutes the schema object via prototype chain assignment in some versions
    schema[fieldName] = {
      in: ['body'],
      isString: { errorMessage: 'Must be a string' },
      ...rules, // Attacker controls the validation rules object too
    };
  }

  checkSchema(schema)(req, res, next);
});
// FIXED — allowlist field names before building dynamic schema
import { checkSchema } from 'express-validator';

// Define the allowed custom field names the user can validate
const ALLOWED_CUSTOM_FIELDS = new Set([
  'repositoryUrl', 'branchName', 'maxDepth', 'skipPattern', 'outputFormat'
]);

app.post('/api/audits/custom', (req, res, next) => {
  const { fields } = req.body;

  if (typeof fields !== 'object' || fields === null) {
    return res.status(400).json({ error: 'fields must be an object' });
  }

  const schema: Record<string, object> = {};

  for (const fieldName of Object.keys(fields)) {
    // Reject any field name not in the explicit allowlist
    if (!ALLOWED_CUSTOM_FIELDS.has(fieldName)) {
      return res.status(400).json({ error: `Unknown field: ${fieldName}` });
    }
    // Only use hardcoded validation rules per field — never spread user-supplied rules
    schema[fieldName] = getHardcodedValidationRules(fieldName);
  }

  checkSchema(schema)(req, res, next);
});

function getHardcodedValidationRules(fieldName: string): object {
  const rules: Record<string, object> = {
    repositoryUrl: { in: ['body'], isURL: true },
    branchName: { in: ['body'], isString: true, trim: true, matches: { options: /^[a-zA-Z0-9/_.-]{1,100}$/ } },
    maxDepth: { in: ['body'], isInt: { options: { min: 1, max: 10 } } },
    skipPattern: { in: ['body'], isString: true, isLength: { options: { max: 200 } } },
    outputFormat: { in: ['body'], isIn: { options: [['json', 'html', 'markdown']] } },
  };
  return rules[fieldName] ?? {};
}
HIGH
SA-SKL-PROTOTYPE4-003 — express-validator schema objects constructed from user-supplied field names allow injection of __proto__ or constructor.prototype as schema keys, potentially polluting the schema-building object's prototype chain; fix by validating field names against an explicit allowlist before building any dynamic schema and by using hardcoded validation rule objects rather than spreading user-supplied rule configurations. Detection: SkillAudit flags endpoints that call checkSchema() with a schema object where any key traces to request body or query parameter values.

PROTOTYPE4-004 — Object.assign(target, req.body) copies __proto__ as own property

Object.assign(target, source) copies enumerable own properties from the source to the target. When source is {"__proto__": {"isAdmin": true}} (as parsed by JSON.parse()), __proto__ is an own string property of the source (not an actual prototype reference). Object.assign() copies it as an own property assignment: it does not follow the prototype chain reference — instead it sets target.__proto__ = {"isAdmin": true}, which replaces the target object's prototype entirely with the attacker-supplied object. This means all prototype-inherited methods on target (like toString(), hasOwnProperty(), valueOf()) are now gone, replaced by whatever properties the attacker supplied. Code that calls target.hasOwnProperty(key) will now throw TypeError: target.hasOwnProperty is not a function — a denial-of-service vector even if the attacker cannot inject executable properties.

// VULNERABLE — Object.assign with req.body replaces target's prototype
app.post('/api/settings', express.json(), (req, res) => {
  const defaults = {
    maxAuditsPerDay: 10,
    notificationsEnabled: true,
    theme: 'dark',
  };

  // Attacker sends: { "__proto__": { "isAdmin": true }, "theme": "light" }
  // Object.assign copies __proto__ as an OWN property assignment
  // This replaces defaults.__proto__ with { isAdmin: true }
  // After this: defaults.hasOwnProperty('theme') throws TypeError
  const settings = Object.assign({}, defaults, req.body);

  // Downstream code: settings.hasOwnProperty('maxAuditsPerDay') → TypeError
  // Or: req.user.isAdmin may now inherit isAdmin if req.user shares the polluted prototype
  saveSettings(req.user.id, settings);
  res.json({ success: true });
});
// FIXED — Option A: Validate req.body schema before Object.assign
import Ajv from 'ajv';

const ajv = new Ajv();
const settingsSchema = {
  type: 'object',
  additionalProperties: false,
  properties: {
    theme: { type: 'string', enum: ['dark', 'light', 'system'] },
    notificationsEnabled: { type: 'boolean' },
  },
};
const validateSettings = ajv.compile(settingsSchema);

app.post('/api/settings', express.json(), (req, res) => {
  if (!validateSettings(req.body)) {
    return res.status(400).json({ errors: validateSettings.errors });
  }
  // Safe: schema validation excluded __proto__ via additionalProperties: false
  const settings = Object.assign({}, defaults, req.body);
  saveSettings(req.user.id, settings);
  res.json({ success: true });
});

// FIXED — Option B: Use Object.create(null) as target (null-prototype object)
// A null-prototype target has no __proto__ property to replace — assignment has no effect
app.post('/api/settings-safe', express.json(), (req, res) => {
  const target = Object.create(null); // No prototype — __proto__ assignment is a no-op
  const safeBody = req.body ?? {};

  // Explicitly copy only known keys — never use spread or Object.assign with full req.body
  if (typeof safeBody.theme === 'string' && ['dark','light','system'].includes(safeBody.theme)) {
    target.theme = safeBody.theme;
  }
  if (typeof safeBody.notificationsEnabled === 'boolean') {
    target.notificationsEnabled = safeBody.notificationsEnabled;
  }

  const settings = { ...defaults, ...target };
  saveSettings(req.user.id, settings);
  res.json({ success: true });
});
CRITICAL
SA-SKL-PROTOTYPE4-004 — Object.assign(target, req.body) where req.body contains a __proto__ key (as parsed by JSON.parse()) replaces the target's prototype with the attacker-supplied object, removing all inherited methods (hasOwnProperty, toString, valueOf) and causing TypeError in downstream code that calls these methods; fix by validating req.body with an Ajv schema using additionalProperties: false before any Object.assign() call, or by using a null-prototype target. Detection: SkillAudit flags tool handler endpoints that call Object.assign() where any source argument traces to req.body, req.query, or tool call parameters without schema validation.

Detection summary

ID Severity Pattern Fix
PROTOTYPE4-001 CRITICAL _.merge({}, userInput) with __proto__ key pollutes Object.prototype _.mergeWith() customizer blocking __proto__/constructor/prototype keys + Ajv schema
PROTOTYPE4-002 CRITICAL JSON.parse(JSON.stringify(input)) round-trip preserves __proto__ as own property; pollution occurs at _.merge() Use structuredClone() for cloning; apply key filtering before any deep merge
PROTOTYPE4-003 HIGH express-validator checkSchema() with user-supplied field names including __proto__ Allowlist field names before schema construction; use hardcoded validation rules per field
PROTOTYPE4-004 CRITICAL Object.assign(target, req.body) replaces target's prototype; hasOwnProperty throws TypeError Ajv schema with additionalProperties: false before assign; or null-prototype target

Related patterns: SA-SKL-PROTOTYPE2 covers advanced prototype pollution via AST-based transforms and middleware chains. SA-SKL-PROTOTYPE3 covers JSON merge-patch and lodash deep clone variant attacks. SA-SKL-DESERIALIZE covers eval and vm.runInNewContext sandbox escapes that often accompany prototype pollution in full RCE exploit chains.