← Blog

Claude skill prototype pollution via JSON.parse and Object.assign security — SA-SKL-PROTOTYPE5

MCP skill config loading commonly relies on JSON.parse() combined with Object.assign() to merge user-supplied settings into a configuration object — a pattern that is vulnerable to prototype pollution when the parsed input contains the key __proto__. SA-SKL-PROTOTYPE5 covers four distinct paths through which this occurs: a direct Object.assign(config, JSON.parse(req.body.settings)) merge that writes to Object.prototype, a shared module-level config target that propagates pollution to every subsequently created plain object, a deep merge of yargs CLI arguments that lets an attacker pass --constructor.prototype.admin=true to poison the prototype chain, and a JSON schema validator configured with additionalProperties: true that passes a __proto__ key through to the validated object without stripping it.

By SkillAudit  |  7 Nov 2026

Why prototype pollution persists in MCP skill config loading

Prototype pollution is not a new class of vulnerability, but it remains prevalent in MCP skills because config loading code is written quickly, often by adapting boilerplate that predates the widespread awareness of the attack. The pattern Object.assign(target, JSON.parse(input)) looks innocuous — JSON.parse() produces a plain JavaScript object, and Object.assign() copies its enumerable own properties. What is easy to miss is that JSON.parse('{"__proto__":{"admin":true}}') in Node.js returns an object with a __proto__ own property (not an inherited one), and when Object.assign() encounters that key, it writes it to the target's __proto__ accessor — which modifies Object.prototype itself.

The consequence is global: after the merge, every plain object literal {} created anywhere in the process has .admin === true as an inherited property. If any authorization check elsewhere in the skill reads a property from a plain object and falls back to inherited properties for a truthy check, the attacker has bypassed that check without touching any other part of the codebase. SkillAudit's AST scanner identifies all four SA-SKL-PROTOTYPE5 patterns in a single pass and surfaces the exact merge call sites, schema definitions, and deep-merge library calls that require remediation.

SA-SKL-PROTOTYPE5 in scope: PROTOTYPE5-001 (JSON.parse() output merged into prototype-sensitive target via Object.assign() without key sanitization — __proto__ key pollutes Object.prototype), PROTOTYPE5-002 (Object.assign(sharedConfig, JSON.parse(input)) where the target is a shared module-level object — prototype pollution propagates to all plain objects created after the merge), PROTOTYPE5-003 (deep merge of yargs-parsed CLI argv into shared config via lodash.merge or deepmerge — --constructor.prototype.admin=true CLI arg poisons Object.prototype), PROTOTYPE5-004 (JSON schema validator with additionalProperties: true passes __proto__ key into validated output — validator approves the schema but does not strip the dangerous key). Each finding includes SkillAudit detection rules and correct Node.js fixes.

PROTOTYPE5-001 — JSON.parse output merged into prototype-sensitive target via Object.assign

The most direct form of this vulnerability occurs when an MCP skill accepts a JSON body — typically a user-supplied settings or configuration object — parses it with JSON.parse(), and immediately merges the result into an existing configuration object using Object.assign(config, parsedInput). Because JSON.parse() in V8/Node.js preserves the string key "__proto__" as an own property on the returned object (it does not interpret it as a prototype assignment during parsing), and because Object.assign() copies all enumerable own properties of the source including __proto__, the merge triggers the setter on the target's __proto__ accessor — which mutates Object.prototype for the entire process.

An attacker who controls the JSON body can send {"__proto__":{"admin":true}} and cause every subsequent plain object literal to inherit admin: true. If the skill checks if (user.admin) and user is a plain object without an explicit admin property, the check passes because the property is inherited from the polluted Object.prototype. The fix requires sanitizing the parsed object before the merge — using either an AJV schema to validate and strip unexpected keys, a JSON reviver function that rejects dangerous key names, or merging into an Object.create(null) target so there is no prototype chain to poison.

// VULNERABLE — JSON.parse() output merged directly via Object.assign without sanitization
// Attacker sends: POST /settings  body: {"settings":"{\"__proto__\":{\"admin\":true}}"}
import express from 'express';

const app = express();
app.use(express.json());

// Module-level config — shared across requests
const config: Record<string, unknown> = {
  rateLimit: 100,
  maxUploadBytes: 5_000_000,
  allowedOrigins: ['https://skillaudit.dev'],
};

app.post('/settings', (req, res) => {
  // VULNERABLE: JSON.parse() returns object with "__proto__" as an own property
  // Object.assign() copies that own property, triggering the __proto__ setter
  // Result: Object.prototype.admin === true for the entire process lifetime

  const userSettings = JSON.parse(req.body.settings); // userSettings.__proto__ = {admin:true}
  Object.assign(config, userSettings);                 // Object.prototype polluted!

  res.json({ ok: true });
});

// Somewhere else in the codebase — completely unrelated endpoint:
app.get('/audit/:id', async (req, res) => {
  const session = {}; // Plain object — inherits from polluted Object.prototype
  loadSession(req, session);

  // VULNERABLE: session.admin is undefined as own property
  // but inherited as true from polluted Object.prototype
  if (session.admin) {
    // Attacker reaches this branch for every request after the pollution
    const allAudits = await db.query('SELECT * FROM audits');
    return res.json(allAudits.rows);
  }
  // ... normal flow
});

// MCP tool handler also affected:
server.tool(
  'update_config',
  'Update skill configuration settings',
  { settings: z.string().describe('JSON string of config overrides') },
  async ({ settings }) => {
    // VULNERABLE: same pattern — merges __proto__ into config
    const parsed = JSON.parse(settings);  // {"__proto__": {"isAdmin": true}}
    Object.assign(config, parsed);        // Object.prototype.isAdmin === true now

    return { content: [{ type: 'text', text: 'Config updated' }] };
  }
);
// FIXED — three complementary defenses: reviver, schema validation, null-prototype target
import Ajv from 'ajv';
import express from 'express';

const app = express();
app.use(express.json());

// Defense 1: JSON.parse() with a reviver that rejects dangerous keys
// Reviver is called for every key-value pair during parsing — before the object is returned
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);

function safeReviver(key: string, value: unknown): unknown {
  if (DANGEROUS_KEYS.has(key)) {
    // Returning undefined causes JSON.parse to omit this key from the output
    // This is called for nested keys too — e.g. {"a":{"__proto__":{"x":1}}} is also blocked
    throw new SyntaxError(`Rejected dangerous key in JSON input: "${key}"`);
    // Alternatively, return undefined to silently drop the key:
    // return undefined;
  }
  return value;
}

// Defense 2: AJV schema that only allows the specific keys we expect
const ajv = new Ajv({ removeAdditional: 'all' }); // Strips any key not in the schema

const settingsSchema = {
  type: 'object',
  properties: {
    rateLimit:        { type: 'number', minimum: 1, maximum: 10_000 },
    maxUploadBytes:   { type: 'number', minimum: 1, maximum: 100_000_000 },
    allowedOrigins:   { type: 'array', items: { type: 'string', format: 'uri' }, maxItems: 20 },
  },
  additionalProperties: false, // Reject any key not listed above — including __proto__
  required: [],
};

const validateSettings = ajv.compile(settingsSchema);

// Defense 3: merge into Object.create(null) target, then copy only validated keys
const config: Record<string, unknown> = {
  rateLimit: 100,
  maxUploadBytes: 5_000_000,
  allowedOrigins: ['https://skillaudit.dev'],
};

const ALLOWED_CONFIG_KEYS = new Set(['rateLimit', 'maxUploadBytes', 'allowedOrigins']);

function safeUpdateConfig(rawJson: string): void {
  // Step 1: parse with reviver — throws on __proto__, constructor, prototype keys
  const parsed = JSON.parse(rawJson, safeReviver) as unknown;

  // Step 2: validate against strict schema — removeAdditional strips unknown keys
  if (!validateSettings(parsed)) {
    throw new Error(`Invalid settings: ${ajv.errorsText(validateSettings.errors)}`);
  }

  // Step 3: merge into null-prototype intermediate — no prototype chain to pollute
  // Object.create(null) has no __proto__, no constructor, no toString etc.
  const nullTarget = Object.create(null) as Record<string, unknown>;
  Object.assign(nullTarget, parsed);

  // Step 4: copy ONLY explicitly allowed keys to the real config
  for (const key of ALLOWED_CONFIG_KEYS) {
    if (Object.prototype.hasOwnProperty.call(nullTarget, key)) {
      config[key] = nullTarget[key];
    }
  }
}

// MCP tool handler — uses safe config update
server.tool(
  'update_config',
  'Update skill configuration settings',
  { settings: z.string().describe('JSON string of config overrides') },
  async ({ settings }) => {
    safeUpdateConfig(settings); // Throws for any dangerous input — never pollutes prototype
    return { content: [{ type: 'text', text: 'Config updated' }] };
  }
);

// Verify: prototype is clean after any input
// JSON.parse('{"__proto__":{"admin":true}}', safeReviver) — throws SyntaxError, never reaches Object.assign
// ({}). admin === undefined — Object.prototype remains clean
CRITICAL
SA-SKL-PROTOTYPE5-001 — An MCP skill calls Object.assign(config, JSON.parse(userInput)) without sanitizing the parsed object — an attacker sends a JSON body with key "__proto__" (e.g., {"__proto__":{"admin":true}}) which JSON.parse() returns as an object with __proto__ as an own property, and Object.assign() then writes through the __proto__ setter to Object.prototype, poisoning every subsequent plain object in the process; fix by parsing with a reviver that rejects dangerous keys, validating with an AJV schema using additionalProperties: false, and merging through an Object.create(null) intermediate target before copying only allowlisted keys to the real config. Detection: SkillAudit flags every Object.assign() call whose source is a JSON.parse() call operating on request body, query string, or other untrusted input without an intervening validation step.

PROTOTYPE5-002 — Object.assign into shared module-level config object

A subtle but high-severity variant occurs when the target of the Object.assign() merge is a module-level variable — an object that is shared across all requests and all instantiations of the skill. When an attacker successfully delivers a __proto__ key through this merge, the prototype pollution affects not just future objects created in the same request, but every object created anywhere in the process for the remainder of its lifetime. This includes objects created in unrelated modules, in middleware, in the MCP framework itself, and in any third-party library that instantiates plain objects.

The core problem is that the prototype chain of the merge target is irrelevant when the polluting key is __proto__ — it always writes to Object.prototype regardless of whether the target is a module-level variable or a local variable. The fix requires ensuring the merge target has no prototype chain at all by using Object.create(null), so that even if a __proto__ key reaches the Object.assign() call, it is set as an ordinary own property on a null-prototype object rather than triggering the Object.prototype.__proto__ setter.

// VULNERABLE — Object.assign into shared module-level config
// The module-level config is shared across ALL requests and ALL tool calls

// config.ts — module loaded once at startup
export const sharedConfig: Record<string, unknown> = {
  debug: false,
  maxRetries: 3,
  apiBaseUrl: 'https://api.skillaudit.dev',
  featureFlags: { betaUI: false, advancedAudit: false },
};

// skill.ts — MCP tool handler
import { sharedConfig } from './config.js';

server.tool(
  'configure_skill',
  'Apply user configuration overrides to this skill session',
  { overrides: z.string().describe('JSON config overrides from the calling agent') },
  async ({ overrides }) => {
    // VULNERABLE: sharedConfig is the module singleton shared across all requests
    // Merging user input directly into it poisons Object.prototype globally

    // Even if only one attacker request slips through, the pollution persists
    // for the entire process lifetime — affecting all subsequent callers

    const parsed = JSON.parse(overrides);
    // If overrides = '{"__proto__":{"isAdmin":true,"debug":true}}'
    // Then: Object.prototype.isAdmin === true  ← persists until process restart
    //       Object.prototype.debug  === true   ← every {} in the process inherits this
    Object.assign(sharedConfig, parsed);

    return { content: [{ type: 'text', text: 'Configuration applied' }] };
  }
);

// Downstream: unrelated module that checks permissions
// permissions.ts
export function checkPermission(user: { id: string }, action: string): boolean {
  const context = {}; // Plain object — will inherit polluted properties
  populateContext(user, context);

  // VULNERABLE: context.isAdmin is never set by populateContext for regular users
  // but after prototype pollution it is true for every plain object
  if ((context as Record<string, unknown>).isAdmin) {
    return true; // Attacker bypasses this check for all users!
  }
  return hasExplicitPermission(user.id, action);
}
// FIXED — null-prototype merge target; strict allowlist; per-request config isolation
import Ajv from 'ajv';

// Schema for allowed config keys
const ajv = new Ajv({ removeAdditional: 'all' });
const configOverrideSchema = {
  type: 'object',
  properties: {
    debug:       { type: 'boolean' },
    maxRetries:  { type: 'integer', minimum: 0, maximum: 10 },
    apiBaseUrl:  { type: 'string', pattern: '^https://' },
    featureFlags: {
      type: 'object',
      properties: {
        betaUI:        { type: 'boolean' },
        advancedAudit: { type: 'boolean' },
      },
      additionalProperties: false,
    },
  },
  additionalProperties: false,
};
const validateOverride = ajv.compile(configOverrideSchema);

// Module-level defaults — never mutated directly by user input
const DEFAULT_CONFIG = Object.freeze({
  debug: false,
  maxRetries: 3,
  apiBaseUrl: 'https://api.skillaudit.dev',
  featureFlags: Object.freeze({ betaUI: false, advancedAudit: false }),
});

type SkillConfig = typeof DEFAULT_CONFIG;

// Produce a per-request config: start from defaults, apply validated overrides
// No shared mutable state — each call gets its own isolated config copy
function buildRequestConfig(overridesJson: string): SkillConfig {
  // Step 1: parse into null-prototype object so __proto__ is just a string key,
  // not a prototype assignment — null-prototype objects have no __proto__ setter
  let raw: Record<string, unknown>;
  try {
    const parsed = JSON.parse(overridesJson) as unknown;
    if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
      throw new TypeError('Config overrides must be a JSON object');
    }
    // Assign to null-prototype target — __proto__ becomes a plain own key, not a setter
    raw = Object.assign(Object.create(null) as Record<string, unknown>, parsed);
  } catch (e) {
    throw new Error(`Invalid config JSON: ${(e as Error).message}`);
  }

  // Step 2: convert back to regular object for AJV (AJV needs prototype chain for iteration)
  // Safe: raw is a null-prototype object, so its keys are only own keys — no prototype pollution
  const forValidation: Record<string, unknown> = {};
  for (const key of Object.keys(raw)) {
    // Explicitly skip dangerous keys as a belt-and-suspenders guard
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
    forValidation[key] = raw[key];
  }

  // Step 3: validate — AJV's removeAdditional:'all' strips anything not in schema
  if (!validateOverride(forValidation)) {
    throw new Error(`Config validation failed: ${ajv.errorsText(validateOverride.errors)}`);
  }

  // Step 4: merge validated overrides onto a fresh copy of defaults
  // Object.freeze(DEFAULT_CONFIG) ensures the original is never mutated
  return {
    ...DEFAULT_CONFIG,
    ...forValidation,
    featureFlags: {
      ...DEFAULT_CONFIG.featureFlags,
      ...(forValidation.featureFlags as Record<string, boolean> | undefined ?? {}),
    },
  } as SkillConfig;
}

server.tool(
  'configure_skill',
  'Apply user configuration overrides to this skill session',
  { overrides: z.string().describe('JSON config overrides from the calling agent') },
  async ({ overrides }) => {
    // Returns a fresh per-request config — sharedConfig / DEFAULT_CONFIG never mutated
    const requestConfig = buildRequestConfig(overrides);

    // Use requestConfig for this request only — not stored back to any shared state
    return { content: [{ type: 'text', text: `Config applied: debug=${requestConfig.debug}` }] };
  }
);
HIGH
SA-SKL-PROTOTYPE5-002 — An MCP skill calls Object.assign(sharedConfig, JSON.parse(userInput)) where sharedConfig is a module-level singleton — a successful __proto__ injection pollutes Object.prototype for the entire process lifetime, affecting every plain object created in every module for all subsequent requests and callers; fix by using Object.create(null) as the merge target so the __proto__ accessor is absent, validating with additionalProperties: false, and building per-request config copies from frozen defaults rather than mutating shared state. Detection: SkillAudit flags Object.assign() calls whose target is a module-scope variable and whose source derives from untrusted JSON input, and flags the absence of Object.freeze() or immutability enforcement on shared config objects.

PROTOTYPE5-003 — Deep merge of yargs CLI argv into shared config via lodash.merge or deepmerge

MCP skills that expose a command-line interface often parse startup arguments with yargs and deep-merge them into the application configuration. The combination of yargs and deep merge libraries creates a prototype pollution path that is exploitable through CLI arguments alone — no HTTP request is needed. Yargs parses dot-notation keys from the command line into nested objects: a flag like --featureFlags.betaUI=true becomes { featureFlags: { betaUI: true } } in the parsed argv. The dangerous key path is --constructor.prototype.admin=true, which yargs parses into { constructor: { prototype: { admin: true } } }. When this is passed to lodash.merge(config, argv) or an unguarded deepmerge(config, argv), the recursive merge traverses the constructor.prototype path and assigns admin: true to Object.prototype.

Versions of lodash prior to 4.17.21 and deepmerge prior to its isMergeableObject patch did not guard against this path. Even with patched versions, the application code must reject the top-level keys __proto__, constructor, and prototype in the argv object before the merge, because the library patches only protect against certain traversal paths and may not cover all variants. For skills deployed in environments where CLI arguments come from an orchestrator or agent that could be compromised, this is a lateral movement vector.

// VULNERABLE — yargs argv deep-merged into shared config without key sanitization
// Attacker invokes skill with: node skill.js --constructor.prototype.admin=true
// Or via orchestrator: { "args": ["--constructor.prototype.admin=true"] }

import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import merge from 'lodash.merge';    // lodash < 4.17.21: vulnerable to prototype pollution
// import deepmerge from 'deepmerge'; // Also vulnerable without isMergeableObject guard

const argv = yargs(hideBin(process.argv))
  .option('debug',      { type: 'boolean', default: false })
  .option('maxRetries', { type: 'number',  default: 3     })
  .option('apiKey',     { type: 'string'                  })
  .argv as Record<string, unknown>;

// Shared module-level config
const config: Record<string, unknown> = {
  debug: false,
  maxRetries: 3,
  apiKey: process.env.API_KEY,
  featureFlags: { betaUI: false, advancedAudit: false },
};

// VULNERABLE: lodash.merge traverses nested objects recursively
// argv from yargs with --constructor.prototype.admin=true is:
//   { constructor: { prototype: { admin: true } }, _: [], '$0': 'skill.js' }
// merge() traverses config.constructor → Function.prototype → sets admin=true on Object.prototype
// After this: ({}).admin === true for all plain objects in the process
merge(config, argv);

// ALSO VULNERABLE: __proto__ path directly
// node skill.js --__proto__.isAdmin=true
// yargs parses: { __proto__: { isAdmin: true } }
// merge() triggers Object.prototype.__proto__ setter → Object.prototype.isAdmin = true

// MCP tool that checks admin:
server.tool(
  'admin_reset',
  'Reset all audit data (admin only)',
  { confirm: z.boolean() },
  async ({ confirm }) => {
    const ctx = {}; // Plain object — inherits from polluted Object.prototype
    if (!confirm) throw new Error('Confirmation required');

    // VULNERABLE: ctx.admin is true via prototype pollution — all users are "admin"
    if (!(ctx as Record<string, unknown>).admin) {
      throw new Error('Forbidden: admin only');
    }
    await db.query('TRUNCATE audits');
    return { content: [{ type: 'text', text: 'All audits deleted' }] };
  }
);
// FIXED — sanitize argv before merge; use patched lodash; guard deepmerge with isMergeableObject
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import merge from 'lodash.merge'; // Must be >= 4.17.21
// import deepmerge from 'deepmerge'; // See isMergeableObject guard below

// Dangerous top-level and nested keys that must never reach a deep merge
const PROTO_POLLUTION_KEYS = new Set(['__proto__', 'constructor', 'prototype']);

// Recursively strip prototype-polluting keys from an object produced by argv parsing
// This is a belt-and-suspenders defense on top of using patched library versions
function sanitizeArgv(obj: unknown, depth = 0): unknown {
  if (depth > 10) return obj; // Limit recursion depth — avoid DoS on deeply nested input
  if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) return obj;

  const result = Object.create(null) as Record<string, unknown>;
  for (const key of Object.keys(obj as Record<string, unknown>)) {
    if (PROTO_POLLUTION_KEYS.has(key)) {
      // Log the attempt — this is a likely attack or serious misconfiguration
      console.error(`[SECURITY] Rejected prototype-polluting key in argv: "${key}" — possible attack`);
      continue; // Skip the key entirely
    }
    result[key] = sanitizeArgv((obj as Record<string, unknown>)[key], depth + 1);
  }
  return result;
}

// Parse only the specific options we expect — strict option definitions prevent
// unexpected keys from reaching the merge (yargs .strict() rejects unknown options)
const rawArgv = yargs(hideBin(process.argv))
  .option('debug',      { type: 'boolean', default: false })
  .option('maxRetries', { type: 'number',  default: 3     })
  .option('apiKey',     { type: 'string'                  })
  .strict()   // Reject unknown options — --constructor.prototype.admin=true is an unknown option
  .argv as Record<string, unknown>;

// Sanitize even after strict() as a defense-in-depth layer
const safeArgv = sanitizeArgv(rawArgv) as Record<string, unknown>;

const config: Record<string, unknown> = {
  debug: false,
  maxRetries: 3,
  apiKey: process.env.API_KEY,
  featureFlags: { betaUI: false, advancedAudit: false },
};

// lodash.merge >= 4.17.21 blocks __proto__ and constructor.prototype paths internally
// Our sanitizeArgv() adds an independent layer that blocks them before merge
merge(config, safeArgv);

// Alternative: deepmerge with isMergeableObject guard
// import deepmerge from 'deepmerge';
// import { isPlainObject } from 'is-plain-object';
// const safeConfig = deepmerge(config, safeArgv, {
//   isMergeableObject: (val) => isPlainObject(val), // Only merge plain objects — not Function, etc.
// });

// Verify: Object.prototype is clean after merge
// Before fix: ({}).admin === true after --constructor.prototype.admin=true
// After fix:  ({}).admin === undefined — merge never reaches Object.prototype
HIGH
SA-SKL-PROTOTYPE5-003 — An MCP skill deep-merges yargs-parsed CLI argv into a shared config object via lodash.merge(config, argv) or an unguarded deepmerge(config, argv) without stripping prototype-polluting keys — an attacker or compromised orchestrator supplies --constructor.prototype.admin=true which yargs parses into { constructor: { prototype: { admin: true } } }, and the recursive merge traverses the path to set admin: true on Object.prototype; fix by calling yargs().strict() to reject unknown options, recursively stripping __proto__, constructor, and prototype keys from argv before merge, using lodash >= 4.17.21, and using deepmerge with an isMergeableObject guard that rejects non-plain-object values. Detection: SkillAudit flags lodash.merge() and deepmerge() calls whose source derives from yargs.argv or any process argument parsing without an intermediate sanitization step.

PROTOTYPE5-004 — JSON schema validator with additionalProperties:true passes __proto__ key into validated object

A common misconception is that validating untrusted JSON input with a schema validator such as AJV automatically eliminates prototype pollution risk. Schema validation does enforce type constraints, required properties, and format checks — but it does not strip keys by default. When the schema is configured with additionalProperties: true (or when additionalProperties is omitted, since the JSON Schema default is true), the validator passes all keys through to the validated output, including __proto__. The validator confirms that the value associated with __proto__ satisfies any applicable type constraints and returns the object with the __proto__ key present — it does not strip it.

If the validated output is then merged into another object (or used directly in contexts where inherited properties are checked), the __proto__ key remains and can still pollute the prototype chain. The fix requires two changes: set additionalProperties: false in every schema to cause AJV to error on unexpected keys, and enable AJV's removeAdditional: 'all' option to silently strip unexpected keys rather than erroring — either approach prevents __proto__ from reaching the merge. Additionally, after validation, always use an explicit key allowlist when copying properties from the validated object to any config or state object.

// VULNERABLE — AJV schema with additionalProperties:true (or omitted) passes __proto__
import Ajv from 'ajv';

const ajv = new Ajv();
// Note: no removeAdditional option — AJV will NOT strip extra keys

const toolInputSchema = {
  type: 'object',
  properties: {
    name:        { type: 'string', maxLength: 100 },
    description: { type: 'string', maxLength: 500 },
    settings:    {
      type: 'object',
      properties: {
        retries: { type: 'number' },
        timeout: { type: 'number' },
      },
      // VULNERABLE: additionalProperties omitted — defaults to true
      // __proto__ key is allowed through if its value satisfies 'object' type
    },
  },
  // VULNERABLE: additionalProperties omitted at top level too
  // { "name": "audit", "__proto__": { "isAdmin": true } } passes validation!
};

const validate = ajv.compile(toolInputSchema);

server.tool(
  'create_audit',
  'Create a new audit task',
  { input: z.string().describe('JSON input for the new audit') },
  async ({ input }) => {
    const parsed = JSON.parse(input) as unknown;

    if (!validate(parsed)) {
      throw new Error(`Invalid input: ${ajv.errorsText(validate.errors)}`);
    }

    // VULNERABLE: validate() returned true but parsed still contains __proto__
    // as an own property because additionalProperties was not false
    // The attacker sent: {"name":"x","__proto__":{"isAdmin":true}}
    // validate() says: valid (name is a string, __proto__ is an object — both allowed)
    // parsed.__proto__ = {isAdmin:true} ← own property, not yet in prototype chain

    const auditConfig: Record<string, unknown> = {};
    Object.assign(auditConfig, parsed); // Now triggers __proto__ setter!
    // Object.prototype.isAdmin === true from this point forward

    const audit = await db.createAudit(auditConfig);
    return { content: [{ type: 'text', text: JSON.stringify(audit) }] };
  }
);
// FIXED — additionalProperties:false; removeAdditional:'all'; explicit key copy
import Ajv from 'ajv';
import addFormats from 'ajv-formats';

// Key fix: removeAdditional:'all' tells AJV to strip any key not listed in properties
// This runs DURING validation — the validated output never contains extra keys
const ajv = new Ajv({
  removeAdditional: 'all', // Strip keys not in schema — including __proto__, constructor, etc.
  useDefaults: true,       // Apply default values from schema
  coerceTypes: false,      // Do not coerce types — prevents type confusion attacks
});
addFormats(ajv);

const toolInputSchema = {
  type: 'object',
  properties: {
    name: {
      type: 'string',
      minLength: 1,
      maxLength: 100,
      pattern: '^[a-zA-Z0-9 _-]+$', // Allowlist of safe characters — no special chars
    },
    description: {
      type: 'string',
      maxLength: 500,
    },
    settings: {
      type: 'object',
      properties: {
        retries: { type: 'integer', minimum: 0, maximum: 5, default: 3 },
        timeout: { type: 'integer', minimum: 100, maximum: 30_000, default: 5_000 },
      },
      additionalProperties: false, // FIXED: reject any key not in settings.properties
      // __proto__ inside settings is stripped by removeAdditional before it can be used
    },
  },
  additionalProperties: false, // FIXED: reject __proto__, constructor, etc. at top level
  required: ['name'],
};

const validate = ajv.compile(toolInputSchema);

// Explicit allowlist for safe copying — belt-and-suspenders after AJV already stripped extras
const ALLOWED_AUDIT_KEYS = new Set(['name', 'description', 'settings']);

function safeExtractAuditInput(validated: Record<string, unknown>): Record<string, unknown> {
  // After AJV with removeAdditional:'all', validated only contains keys from the schema
  // This explicit copy is an additional guard that documents intent
  const safe: Record<string, unknown> = {};
  for (const key of ALLOWED_AUDIT_KEYS) {
    if (Object.prototype.hasOwnProperty.call(validated, key)) {
      safe[key] = validated[key];
    }
  }
  return safe;
}

server.tool(
  'create_audit',
  'Create a new audit task',
  { input: z.string().describe('JSON input for the new audit') },
  async ({ input }) => {
    let parsed: unknown;
    try {
      // Parse with reviver as first layer — rejects __proto__ before AJV even sees it
      parsed = JSON.parse(input, (key, value) => {
        if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
          throw new SyntaxError(`Rejected dangerous key: "${key}"`);
        }
        return value;
      });
    } catch (e) {
      throw new Error(`Invalid JSON: ${(e as Error).message}`);
    }

    // AJV validation with removeAdditional:'all' — strips any surviving extra keys
    if (!validate(parsed)) {
      throw new Error(`Validation failed: ${ajv.errorsText(validate.errors)}`);
    }

    // After removeAdditional, parsed contains ONLY name, description, settings
    // Safe copy guards against any future schema drift that might re-allow extra keys
    const safeInput = safeExtractAuditInput(parsed as Record<string, unknown>);

    const audit = await db.createAudit(safeInput); // Only known-safe keys reach the DB layer
    return { content: [{ type: 'text', text: JSON.stringify(audit) }] };
  }
);

// Verify: AJV strips __proto__ before it reaches Object.assign
// Input: {"name":"test","__proto__":{"isAdmin":true}}
// After validate(): { name: "test" }  ← __proto__ stripped by removeAdditional
// Object.prototype.isAdmin === undefined — prototype clean
MEDIUM
SA-SKL-PROTOTYPE5-004 — An MCP skill validates user-supplied JSON with an AJV schema that omits additionalProperties: false or sets it to true and does not enable removeAdditional: 'all' — the validator passes a __proto__ key through to the validated output because the JSON Schema default allows additional properties, and if the validated object is subsequently merged into another object the __proto__ key pollutes Object.prototype; fix by setting additionalProperties: false on every schema object definition and initializing AJV with { removeAdditional: 'all' } so unexpected keys are stripped during validation before the output is used. Detection: SkillAudit flags AJV compile() calls for schemas where any type: 'object' definition omits additionalProperties: false, and flags AJV instantiation without removeAdditional: 'all' in skills that subsequently merge validated objects.

Detection summary

ID Severity Pattern Fix
PROTOTYPE5-001 CRITICAL Object.assign(config, JSON.parse(userInput)) without key sanitization — __proto__ key in JSON body pollutes Object.prototype globally Parse with reviver rejecting dangerous keys; AJV with additionalProperties: false; merge through Object.create(null) target
PROTOTYPE5-002 HIGH Object.assign(sharedConfig, JSON.parse(input)) into module-level singleton — pollution propagates to all plain objects for the entire process lifetime Use Object.create(null) as merge target; build per-request config copies from Object.freeze() defaults; never mutate shared module-level state from user input
PROTOTYPE5-003 HIGH lodash.merge(config, argv) or deepmerge(config, argv) without sanitizing yargs-parsed CLI args — --constructor.prototype.admin=true CLI arg poisons Object.prototype yargs.strict() to reject unknown options; strip __proto__/constructor/prototype keys from argv; lodash >= 4.17.21; deepmerge with isMergeableObject guard
PROTOTYPE5-004 MEDIUM AJV schema with additionalProperties omitted or true — __proto__ key passes schema validation and reaches downstream merge call additionalProperties: false on every type: 'object' definition; AJV { removeAdditional: 'all' }; explicit key allowlist after validation

Related patterns: SA-SKL-PROTOTYPE4 covers prototype pollution through MCP tool call parameter deserialization — including polluted defaults in tool parameter schemas and pollution via tool output merged into agent state. Prototype pollution to RCE in MCP skills walks through a full exploit chain from a lodash.merge prototype pollution to remote code execution via child_process.spawn — demonstrating why these findings must be treated as CRITICAL even when the initial impact appears limited to privilege escalation.