OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(mcp): exclude forbidden fields from artifact tool schemas (#1588)
Michael D'Angelo2fffe877adf4
diff --git a/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts b/plugins/codex-security/mcp-app/src/artifact-schema-loader.tsindex c4ea6bd32..46b254e80 100644--- a/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts+++ b/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts@@ -108,13 +108,50 @@ export function loadArtifactZodSchema(documentId: string,definition: string,): z.ZodType {- return z.fromJSONSchema(- bundleArtifactSchema(- documents,- documentId,- definition,- ) as z.core.JSONSchema.JSONSchema,- );+ const schema = bundleArtifactSchema(documents, documentId, definition);+ const validator = z.fromJSONSchema(schema as z.core.JSONSchema.JSONSchema);+ return validator.meta(modelFacingSchema(schema));+}++/** Keep forbidden fields out of native tool declarations without allowing them. */+function modelFacingSchema(schema: ArtifactSchemaObject): ArtifactSchemaObject {+ function visit(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(visit);+ if (!value || typeof value !== "object") return value;+ const object = Object.fromEntries(+ Object.entries(value).map(([key, child]) => [+ key,+ ["const", "enum", "default", "examples"].includes(key)+ ? child+ : visit(child),+ ]),+ );+ const properties = object.properties;+ if (+ !properties ||+ typeof properties !== "object" ||+ Array.isArray(properties)+ )+ return object;+ const forbidden = Object.entries(properties)+ .filter(([, property]) => property === false)+ .map(([name]) => name);+ if (forbidden.length === 0) return object;++ // Zod renders false properties as {not:{}}, which the native declaration+ // projects as optional unknown fields. Exclude their names instead. This+ // is equivalent JSON Schema; the original validator remains unchanged.+ object.properties = Object.fromEntries(+ Object.entries(properties).filter(([, property]) => property !== false),+ );+ const names = { not: { enum: forbidden } };+ object.propertyNames =+ object.propertyNames === undefined+ ? names+ : { allOf: [object.propertyNames, names] };+ return object;+ }+ return visit(schema) as ArtifactSchemaObject;}function readSchemaPointer(document: SchemaDocument, pointer: string): unknown {diff --git a/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts b/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.tsindex 81ab81bbb..ffb4392c9 100644--- a/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts+++ b/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts@@ -65,6 +65,12 @@ const modelOnlyMeta = {ui: { visibility: ["model"] as const },};+const semanticFindingGuidance =+ " Findings require severity:{level}, confidence:{level,rationale}, taxonomy:{category,cwe:[]}, locations:[{path,startLine,endLine?}], and provenance:{source}, alongside ruleId,title,summary,remediation. Use repository-relative paths. Each codeEvidence entry needs id,label,path,startLine,code,explanation. Omit host-owned findingId,occurrenceId,fingerprints and scope.includePaths/excludePaths.";++const semanticCoverageGuidance =+ ' Coverage shape: {completeness:"partial"|"complete"|"unknown",surfaces:[{label,disposition}],explicitExclusions:[{pattern,reason}],deferred:[{id?,reason}]}. Surface dispositions: reported,no_issue_found,rejected,not_applicable,needs_follow_up. Arrays may be empty. Omit host-owned coverage documentType,schemaVersion,scanId,mode,inventoryStrategy,includePaths,excludePaths,receiptRefs. Omit resolvedDeferred from complete:false checkpoints; on a terminal draft use it only for finished generic tasks, and resolve candidates with a finding carrying the saved candidate ID in provenance.candidateId or a rejected/not_applicable surface carrying candidateId.';+function signalFromRequestContext(requestContext: unknown,): AbortSignal | undefined {@@ -170,7 +176,9 @@ export function registerCompactArtifactTools(name: "record_codex_security_scan_draft",title: "Record Codex Security Scan Draft",description:- "Save the canonical threat model, findings and coverage as an unsealed draft. Use complete:false as soon as a model is available, even with empty findings and partial coverage, then for progress checkpoints; use complete:true for the final result. The host derives threatmodel.md. Keep unvalidated candidates in coverage.deferred. On terminal Standard or diff drafts, close generic review tasks with coverage.resolvedDeferred:[{id,reason}], copying IDs from the returned coverage. Update linked surfaces by their saved IDs.",+ "Save the canonical threat model, findings and coverage as an unsealed draft. Use complete:false as soon as a model is available, even with empty findings and partial coverage, then for progress checkpoints; use complete:true for the final result. The host derives threatmodel.md. Keep unvalidated candidates in coverage.deferred. On terminal Standard or diff drafts, close generic review tasks with coverage.resolvedDeferred:[{id,reason}], copying IDs from the returned coverage. Update linked surfaces by their saved IDs." ++ semanticFindingGuidance ++ semanticCoverageGuidance,inputSchema: scanDraftInputSchema,readOnly: false,handler: async (input, requestContext) => {@@ -267,7 +275,9 @@ export function registerCompactWorkerArtifactTools(name: "record_codex_security_scan_draft",title: "Record Codex Security Scan Draft",description:- "Save this Standard worker's semantic findings and coverage. Use complete:false for progress checkpoints, then complete:true for its final result; keep unvalidated candidates in coverage.deferred. On terminal drafts, close generic review tasks with coverage.resolvedDeferred:[{id,reason}], copying IDs from the returned coverage. Update linked surfaces by their saved IDs.",+ "Save this Standard worker's semantic findings and coverage. Use complete:false for progress checkpoints, then complete:true for its final result; keep unvalidated candidates in coverage.deferred. On terminal drafts, close generic review tasks with coverage.resolvedDeferred:[{id,reason}], copying IDs from the returned coverage. Update linked surfaces by their saved IDs." ++ semanticFindingGuidance ++ semanticCoverageGuidance,inputSchema: scanDraftInputSchema,readOnly: false,handler: async (value) =>@@ -304,7 +314,9 @@ export function registerCompactWorkerArtifactTools(registerCompactTool(server, {name: "record_codex_security_deep_reduction",title: "Record Codex Security Deep Reduction",- description: "Record the merged findings and context for this Deep scan.",+ description:+ "Record the merged findings and context for this Deep scan. Preserve every assigned provenance.sourceFindingIds reference; omit retained provenance.sourceFindings bodies." ++ semanticFindingGuidance,inputSchema: deepReductionInputSchema,readOnly: false,handler: async (value) => recordCodexSecurityDeepReduction(context, value),diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_schema_loader.ts b/plugins/codex-security/mcp-app/tests/test_artifact_schema_loader.tsnew file mode 100644index 000000000..1d87559a0--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_artifact_schema_loader.ts@@ -0,0 +1,102 @@+import assert from "node:assert/strict";+import { join } from "node:path";+import { Ajv2020 } from "ajv/dist/2020.js";+import { importSource } from "./import-module.ts";++const { bundleArtifactSchema, loadArtifactZodSchema } = await importSource(+ join(import.meta.dirname, "../src/artifact-schema-loader.ts"),+);++const document = {+ $id: "codex-security://schemas/advertisement-fixture.json",+ $defs: {+ input: {+ type: "object",+ properties: {+ scope: {+ type: "object",+ properties: {+ includePaths: false,+ summary: { type: "string", minLength: 1 },+ },+ propertyNames: { pattern: "^[a-zA-Z]+$" },+ additionalProperties: true,+ },+ findings: {+ type: "array",+ items: {+ type: "object",+ properties: {+ findingId: false,+ title: { type: "string", minLength: 1 },+ confirmed: { const: false },+ },+ required: ["title"],+ additionalProperties: true,+ },+ },+ },+ required: ["findings"],+ additionalProperties: false,+ examples: [+ {+ findings: [+ { title: "Fixture", extension: { properties: { kept: false } } },+ ],+ },+ ],+ },+ },+};++const original = bundleArtifactSchema([document], document.$id, "input");+const validator = loadArtifactZodSchema([document], document.$id, "input");+const advertised = validator.toJSONSchema({ io: "input" });+assert.equal(original.properties.scope.properties.includePaths, false);+assert.equal(+ document.$defs.input.properties.scope.properties.includePaths,+ false,+);+assert.equal(+ Object.hasOwn(advertised.properties.scope.properties, "includePaths"),+ false,+);+assert.equal(+ Object.hasOwn(advertised.properties.findings.items.properties, "findingId"),+ false,+);+assert.deepEqual(advertised.properties.scope.propertyNames, {+ allOf: [{ pattern: "^[a-zA-Z]+$" }, { not: { enum: ["includePaths"] } }],+});+assert.deepEqual(validator.meta().examples, document.$defs.input.examples);++const ajv = new Ajv2020({ strict: false });+const authoredValidation = ajv.compile(original);+const advertisedValidation = ajv.compile(advertised);+for (const [input, expected] of [+ [{ findings: [] }, true],+ [+ {+ findings: [{ title: "Fixture", confirmed: false, extra: "retained" }],+ scope: { summary: "Reviewed", extension: true },+ },+ true,+ ],+ [{ findings: [], scope: { includePaths: [] } }, false],+ [{ findings: [], scope: { includePaths: null } }, false],+ [{ findings: [{ title: "Fixture", findingId: "host-owned" }] }, false],+ [{ findings: [{ title: "Fixture", findingId: false }] }, false],+ [{ findings: [{ title: "Fixture", confirmed: true }] }, false],+ [{ findings: [{}] }, false],+ [{ findings: [], scope: { "invalid-key": true } }, false],+ [{ findings: [], extra: true }, false],+] as const) {+ const label = JSON.stringify(input);+ assert.equal(authoredValidation(input), expected, `authored: ${label}`);+ assert.equal(advertisedValidation(input), expected, `advertised: ${label}`);+ assert.equal(+ validator.safeParse(input).success,+ expected,+ `runtime: ${label}`,+ );+}diff --git a/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts b/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.tsindex 0a68a7e20..ac5fa20dc 100644--- a/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts+++ b/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts@@ -1247,6 +1247,8 @@ async function testParentToolList(bundle: string) {`${tool.name} must not accept a model-selected artifact destination.`,);}+ if (tool.name === "record_codex_security_scan_draft")+ assertSemanticInputProperties(tool.inputSchema);}const deepScanTool = tools.find(@@ -1338,6 +1340,7 @@ async function testDiscoveryWorkerToolList(bundle: string) {);const [tool] = tools;+ assertSemanticInputProperties(tool.inputSchema);assert.deepEqual(tool.inputSchema.required, ["scanId","findings",@@ -1364,6 +1367,24 @@ async function testDiscoveryWorkerToolList(bundle: string) {coverage: workerDraft([]).coverage,};+ for (const forbiddenInput of [+ { ...input, scope: { includePaths: ["src"] } },+ { ...input, coverage: { ...input.coverage, mode: "repository" } },+ {+ ...input,+ findings: [+ { ...finding("fixture", "src/fixture.py"), findingId: "host-owned" },+ ],+ },+ ]) {+ requireToolError(+ await client.callTool({ name: tool.name, arguments: forbiddenInput }),+ /Input validation error/,+ "Omitting forbidden properties from the advertised shape must preserve validation.",+ );+ }+ await assert.rejects(readFile(resultPath), { code: "ENOENT" });+requireToolError(await client.callTool({name: tool.name,@@ -1525,6 +1546,7 @@ async function testReducerWorkerToolList(bundle: string) {`${tool.name} must expose scanId only when submitting its complete reduction.`,);if (tool.name === "record_codex_security_deep_reduction") {+ assertSemanticInputProperties(tool.inputSchema);assert.deepEqual(tool.inputSchema.required, ["scanId", "findings"]);assert.equal(tool.inputSchema.additionalProperties, false);assert.equal(@@ -1654,6 +1676,46 @@ async function testReducerWorkerToolList(bundle: string) {}}+function assertSemanticInputProperties(schema: Record<string, unknown>) {+ const properties = schema.properties as Record<+ string,+ Record<string, unknown>+ >;+ const findingSchema = properties.findings.items as Record<string, unknown>;+ const groups: [Record<string, unknown>, string[]][] = [+ [properties.scope, ["includePaths", "excludePaths"]],+ [findingSchema, ["findingId", "occurrenceId", "fingerprints"]],+ ];+ if (properties.coverage)+ groups.push([+ properties.coverage,+ [+ "documentType",+ "schemaVersion",+ "scanId",+ "mode",+ "inventoryStrategy",+ "includePaths",+ "excludePaths",+ "receiptRefs",+ ],+ ]);+ for (const [object, forbidden] of groups) {+ const names = object.propertyNames as { not: { enum: string[] } };+ for (const key of forbidden) {+ assert.equal(+ Object.hasOwn(object.properties as object, key),+ false,+ `${key} must not be advertised as an optional unknown input`,+ );+ assert.ok(+ names.not.enum.includes(key),+ `${key} remains forbidden in tools/list`,+ );+ }+ }+}+async function startScan(call: ReturnType<typeof toolCaller>,ownerThread: string,