Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

docs: import hosted Semgrep findings locally or in Cloud (#2576)

Michael D'Angelo55261a78e68c
diff --git a/docs/scanner-imports/examples/semgrep-hosted-mcp.mjs b/docs/scanner-imports/examples/semgrep-hosted-mcp.mjs
new file mode 100644
index 000000000..7d8b067a0
--- /dev/null
+++ b/docs/scanner-imports/examples/semgrep-hosted-mcp.mjs
@@ -0,0 +1,199 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { existsSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { join, posix } from "node:path";
+import { createInterface } from "node:readline/promises";
+import {
+ ExternalPublicationError,
+ prepareNormalizedExternalPublication,
+ prepareNormalizedLocalImport,
+} from "@openai/codex-security";
+
+const args = process.argv.slice(2);
+const save = args.at(-1) === "--save";
+if (save) args.pop();
+const [capture, target, cloudRepository] = args;
+const toCloud = target === "cloud";
+assert(
+ capture &&
+ target &&
+ args.length === (toCloud ? 3 : 2) &&
+ (!toCloud || cloudRepository.trim()),
+ "Usage: node semgrep-hosted-mcp.mjs CAPTURE.json {CHECKOUT | cloud REPOSITORY_URL_OR_ID} [--save]",
+);
+
+function requireScmUrl(value) {
+ const url = URL.parse(value);
+ assert(
+ ["https:", "http:"].includes(url?.protocol) &&
+ !url.username &&
+ !url.password &&
+ !/[?#]/u.test(value),
+ "Use an HTTP(S) source-control URL without credentials, query, or fragment.",
+ );
+}
+
+if (
+ toCloud &&
+ (URL.parse(cloudRepository)?.host ||
+ /^(?:[a-z][a-z\d+.-]*:\/|\/\/|[^@/\s]+@[^/:\s]+:)/iu.test(
+ cloudRepository.trim(),
+ ))
+) {
+ requireScmUrl(cloudRepository);
+}
+const { deploymentId, project, ref, findingIds, issues } = JSON.parse(
+ await readFile(capture, "utf8"),
+);
+requireScmUrl(project.url);
+assert(
+ Array.isArray(findingIds) && findingIds.length && Array.isArray(issues),
+ "Supply the requested findingIds and the original issues[] rows.",
+);
+assert(
+ [deploymentId, project.id, ...findingIds].every(
+ (id) => typeof id === "string" && id.trim(),
+ ) && ref?.startsWith("refs/"),
+ "Use string deployment, project and finding IDs, and a full Git ref.",
+);
+const missing = new Set(findingIds);
+assert.equal(
+ missing.size,
+ findingIds.length,
+ "The requested findingIds contain duplicate IDs.",
+);
+
+// Keep the original path in the row even when it cannot be used as a repository location.
+function locations({ filePath, line }) {
+ if (typeof filePath !== "string" || !filePath) return [];
+ const path = filePath.replaceAll("\\", "/");
+ const normalized = posix.normalize(path);
+ if (
+ path.includes("\0") ||
+ path.split("/").includes("..") ||
+ normalized.startsWith("/") ||
+ /^(?:[a-z][a-z\d+.-]*:|~[^/]*(?:\/|$)|[^/@]+@[^/]+:)/iu.test(normalized) ||
+ normalized === "." ||
+ normalized.endsWith("/") ||
+ path.endsWith("/.")
+ )
+ return [];
+ return [
+ { path: filePath, ...(Number.isSafeInteger(line) && line > 0 && { line }) },
+ ];
+}
+
+function text(value) {
+ return typeof value === "string" && value.trim() ? value : null;
+}
+
+const sourceProject = { id: project.id, name: project.name, url: project.url };
+const findings = issues.map((row) => {
+ const { issue } = row;
+ assert(
+ missing.delete(issue?.id),
+ `Unexpected or duplicate issue ID: ${JSON.stringify(issue?.id)}`,
+ );
+ assert(
+ issue.repository?.id === project.id &&
+ issue.ref === ref &&
+ issue.issueType === "ISSUE_TYPE_SAST",
+ `Issue ${JSON.stringify(issue.id)} does not match the selected project ID, ref and Code product.`,
+ );
+ const severity = issue.severity?.replace(/^SEVERITY_/u, "").toLowerCase();
+ const rule = text(issue.rulePath);
+ const message = text(issue.message);
+ const projectedLocations = locations(issue);
+ const start = projectedLocations[0]?.line;
+ return {
+ source_finding_id: issue.id,
+ evidence: {
+ title: rule ?? `Semgrep issue ${issue.id}`,
+ severity: ["critical", "high", "medium", "low"].includes(severity)
+ ? severity
+ : "unknown",
+ description: message,
+ branch: ref,
+ locations: projectedLocations,
+ details: {
+ kind: "sast",
+ repository: sourceProject,
+ ...(start &&
+ Number.isSafeInteger(issue.endLine) &&
+ issue.endLine >= start && { code: { end_line: issue.endLine } }),
+ rule: rule ? { id: rule } : null,
+ },
+ source_data: { deploymentId, project: sourceProject, row },
+ },
+ };
+});
+assert(
+ !missing.size,
+ `Missing requested issue IDs: ${JSON.stringify([...missing])}`,
+);
+
+const selection = { read: findings.length, findings, excluded: [] };
+const scope = JSON.stringify([
+ "semgrep-hosted-mcp",
+ deploymentId,
+ project.id,
+ ref,
+ "sast",
+]);
+const options = {
+ repository: toCloud ? cloudRepository : target,
+ provider: "semgrep",
+ sourceKey:
+ Buffer.byteLength(scope) <= 512
+ ? scope
+ : "semgrep-hosted-mcp:" +
+ createHash("sha256").update(scope).digest("hex"),
+};
+
+async function run() {
+ if (!toCloud) {
+ const local = await prepareNormalizedLocalImport(selection, options, {
+ sourceRepositories:
+ project.scmType === "SCM_TYPE_GITHUB_ENTERPRISE"
+ ? [{ url: project.url, platform: "github" }]
+ : [],
+ });
+ assert(
+ existsSync(join(local.preview.repository, ".git")) &&
+ local.matchesRepositoryRemote,
+ "Pass the Git worktree root with a configured remote for the selected project.",
+ );
+ return save
+ ? local.import()
+ : { sourceRepositoryUrl: project.url, ...local.preview };
+ }
+
+ const cloud = await prepareNormalizedExternalPublication(selection, options);
+ if (!save) return cloud.preview;
+ console.error(JSON.stringify(cloud.preview, null, 2));
+ const prompt = createInterface({
+ input: process.stdin,
+ output: process.stderr,
+ });
+ try {
+ const answer = await prompt.question(
+ "Publish this selection to the Cloud destination above? [y/N] ",
+ );
+ if (!/^y(es)?$/iu.test(answer.trim())) return { published: false };
+ } finally {
+ prompt.close();
+ }
+
+ try {
+ const result = await cloud.publish();
+ if (result.status !== "complete") process.exitCode = 1;
+ return result;
+ } catch (error) {
+ if (!(error instanceof ExternalPublicationError)) throw error;
+ process.exitCode = 1;
+ return error.result;
+ }
+}
+
+console.log(JSON.stringify(await run(), null, 2));
diff --git a/docs/scanner-imports/semgrep.md b/docs/scanner-imports/semgrep.md
index 42ca945f6..405b9cd91 100644
--- a/docs/scanner-imports/semgrep.md
+++ b/docs/scanner-imports/semgrep.md
@@ -3,12 +3,13 @@
Choose the route that matches your report or account. Each route uses a different
source of finding IDs.
-| Starting point | What to collect | Destination |
-| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
-| [CLI or CI report](#quick-start) | A Code-only JSON or self-contained SARIF 2.1.0 file, optionally gzipped. Native JSON keeps Semgrep severity and available snippets. | Local or Cloud |
-| [Guardian in Codex](#import-selected-guardian-findings) | Selected Code or Supply Chain findings through the connected Guardian account. | Local or Cloud |
-| [Selected Web API IDs](#existing-platform-findings) | Original project response and SAST findings pages for one full Git ref. Use the SDK to save a selection or [import it directly](#import-selected-semgrep-platform-sast-findings-with-the-sdk). | Local or Cloud |
-| [Whole Platform project](#collect-a-platform-project-and-branch) | All findings for one project, full ref and product using a Web API token. | Local or Cloud |
+| Starting point | What to collect | Destination |
+| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
+| [CLI or CI report](#quick-start) | A Code-only JSON or self-contained SARIF 2.1.0 file, optionally gzipped. Native JSON keeps Semgrep severity and available snippets. | Local or Cloud |
+| [Hosted AppSec Platform MCP](#import-selected-code-findings-from-the-hosted-mcp) | Selected rule-based Code (SAST) findings from a verified project and Git ref. | Local or Cloud |
+| [Guardian in Codex](#import-selected-guardian-findings) | Selected Code or Supply Chain findings through the connected Guardian account. | Local or Cloud |
+| [Selected Web API IDs](#existing-platform-findings) | Original project response and SAST findings pages for one full Git ref. Use the SDK to save a selection or [import it directly](#import-selected-semgrep-platform-sast-findings-with-the-sdk). | Local or Cloud |
+| [Whole Platform project](#collect-a-platform-project-and-branch) | All findings for one project, full ref and product using a Web API token. | Local or Cloud |
## Quick start
@@ -76,6 +77,109 @@ When calling `prepareNormalizedLocalImport` directly, pass the original SARIF
repository references in the third argument's `sourceRepositories`. Use
`{ url, platform: "github" }` for a verified custom GitHub host.
+## Import selected Code findings from the hosted MCP
+
+Use Semgrep’s hosted AppSec Platform MCP (beta) at `semgrep.dev` to import
+existing rule-based Code (SAST) findings. You can save the same capture to a
+local workbench. Workspaces with Semgrep import enabled in Codex Security
+Cloud can also publish to a private findings inbox or a connected repository.
+
+### Connect and capture
+
+Add the read-only server to Codex. Sign in to the Teams or Enterprise
+organization (including trials) that owns the project. If adding the server
+completes browser sign-in, skip the second command.
+
+```sh
+codex mcp add semgrep --url https://semgrep.dev/api/mcp/read-only
+codex mcp login semgrep
+```
+
+Reload MCP servers or start a new Codex session. Ask Codex to list open
+Code findings for your repository and full Git ref, then choose the IDs you
+want to import. For example, give Codex this request with your own values:
+
+> Use the hosted Semgrep MCP to capture rule-based Code findings `101` and
+> `103` from `https://github.com/example/project` on `refs/heads/main`.
+> Save the capture to `/path/to/private/capture.json` for the Codex Security
+> hosted MCP import example.
+
+For the capture, use `semgrep_account` to identify the organization and
+`ProjectsService_ListProjects` to match the project by its SCM URL. Its
+display name can differ from the repository path. Call
+`ProjectsService_GetProject` for that project and `IssuesService_ListIssues`
+with `body.issueTypes: ["ISSUE_TYPE_SAST"]` and the project ID, full ref
+and requested string IDs in `body.filter.repositoryIds`, `refs` and `ids`.
+Follow the cursor until every selected ID is accounted for. Save the
+original selected `structuredContent.issues` rows programmatically, including
+the nested `issue` and sibling fields. This captures list-level evidence.
+For snippets or dataflow traces, inspect the issue with `IssuesService_GetIssue`. The capture contains `deploymentId`
+(string), `ref`, `findingIds` (requested strings), `project` (from
+`structuredContent.project`) and `issues` (the selected rows).
+[Semgrep connection and authentication guide](https://docs.semgrep.dev/semgrep-appsec-platform/mcp)
+
+### Preview, save and verify
+
+Copy the [import example](examples/semgrep-hosted-mcp.mjs) and capture into
+a private directory outside the checkout. From that directory, install the
+SDK used by the example:
+
+```sh
+npm install @openai/[email protected]
+```
+
+**Local workbench.** In your own terminal, compare the intended remote's
+effective fetch URL (`git -C /path/to/checkout remote get-url origin`)
+with the capture’s `project.url`. A remote URL can contain credentials.
+Keep it out of the Codex transcript. For a custom transport helper, verify
+its configured target. Preview using the root of that worktree.
+
+```sh
+node semgrep-hosted-mcp.mjs capture.json /path/to/checkout
+```
+
+After checking the source URL, checkout and selected findings, save the
+same capture and read back the records.
+
+```sh
+node semgrep-hosted-mcp.mjs capture.json /path/to/checkout --save
+./node_modules/.bin/codex-security findings imported /path/to/checkout --format json
+```
+
+**Codex Security Cloud.** Your Cloud workspace must support the Semgrep
+provider separately from your Semgrep MCP access. The SDK also needs a
+file-backed ChatGPT sign-in. If you need one, run these commands from the
+private example directory and choose the intended account. Keep the same state directory for previews,
+saves and retries.
+
+```sh
+export CODEX_SECURITY_STATE_DIR="$PWD/cloud-state"
+mkdir -p -m 700 "$CODEX_SECURITY_STATE_DIR" "$CODEX_SECURITY_STATE_DIR/codex-home"
+CODEX_HOME="$CODEX_SECURITY_STATE_DIR/codex-home" codex login -c 'cli_auth_credentials_store="file"'
+```
+
+Pass `cloud` and the connected repository’s SCM URL. If several connectors
+share the URL, use the intended Cloud repository ID instead. Check the
+account, repository, selected findings and exclusions before confirming.
+
+```sh
+node semgrep-hosted-mcp.mjs capture.json cloud https://github.com/example/project
+```
+
+If the repository resolves but the preview reports HTTP 400 for the Semgrep
+source, check that Cloud import is enabled for Semgrep in that workspace.
+You can use the same capture locally while waiting for access. After a
+successful Cloud preview, save and review the receipt.
+
+```sh
+node semgrep-hosted-mcp.mjs capture.json cloud https://github.com/example/project --save
+```
+
+If the preview shows `privateImport`, check the completed private job and
+its counts. If it shows repository requests, check the receipts and verified
+count for the selected reports. Keep the capture and source key for retries.
+[Verify the Cloud import](README.md#verify-the-import) · [Resume an interrupted submission](schema-guide.md#retry-a-cloud-submission)
+
## Import selected Guardian findings
Sign in to
diff --git a/plugins/codex-security/skills/publish-findings/SKILL.md b/plugins/codex-security/skills/publish-findings/SKILL.md
index b141b2ec0..6dd28884e 100644
--- a/plugins/codex-security/skills/publish-findings/SKILL.md
+++ b/plugins/codex-security/skills/publish-findings/SKILL.md
@@ -96,11 +96,13 @@ Retain package versions, reported fixed versions, provenance and original eviden
## Semgrep Code
-Prefer native Code/SAST CLI or CI JSON for this reader; use self-contained SARIF 2.1.0 as a compatibility path. JSON retains the original severity better than SARIF. Use the selected Guardian workflow below for existing Code or Supply Chain findings. Select SAST rules or Code-only CI output; identifiable non-SAST records are excluded, but SARIF may omit the product metadata needed to distinguish Secrets.
+Prefer native Code/SAST CLI or CI JSON for this reader; use self-contained SARIF 2.1.0 as a compatibility path. JSON retains the original severity better than SARIF. Select SAST rules or Code-only CI output; identifiable non-SAST records are excluded, but SARIF may omit the product metadata needed to distinguish Secrets.
For a user-requested new scan, use the installed Semgrep CLI from the source repository root with the selected SAST rules: `semgrep scan --config /path/to/sast-rules.yaml --json-output /path/to/semgrep.json .`. Existing CI jobs can produce the same artifact using `--json-output`; authenticated `semgrep ci --code` follows the job's policy and baseline scope. Explain that this generates fresh scan findings, and do not substitute it for a request to retrieve existing Platform findings.
-For a selection of existing Code or Supply Chain findings in Codex, use the signed-in [Semgrep Guardian plugin](https://docs.semgrep.dev/semgrep-guardian/quickstart). Call its `get_semgrep_sast_findings` or `get_semgrep_supply_chain_findings` tool with the selected `deployment_name`, `repository_name` and full `ref`. Preserve any state and severity filters used for that selection. Reuse an existing successful tool result when its scope is explicit. If a selected ID is missing, report it and check the query scope and filters with the user. A project-wide fetch is a separate request.
+For selected rule-based Code findings from the hosted Semgrep AppSec Platform MCP, call `semgrep_account` and match the project's SCM URL to the requested repository. Fetch the project with `ProjectsService_GetProject` and the requested string issue IDs with `IssuesService_ListIssues`, scoped to the project ID, full ref and `ISSUE_TYPE_SAST`. Copy the original selected issue rows into a private capture with `deploymentId`, `project`, `ref`, `findingIds` and `issues`. Follow the [hosted MCP SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-code-findings-from-the-hosted-mcp) to preview and save to the verified local checkout or the explicitly selected Cloud destination. Verify the private inbox job or the connected repository’s receipts and readback, as shown in the preview.
+
+For a selection of existing Code or Supply Chain findings from Guardian, use the signed-in [Semgrep Guardian plugin](https://docs.semgrep.dev/semgrep-guardian/quickstart). Call its `get_semgrep_sast_findings` or `get_semgrep_supply_chain_findings` tool with the selected `deployment_name`, `repository_name` and full `ref`. Preserve any state and severity filters used for that selection. Reuse an existing successful tool result when its scope is explicit. If a selected ID is missing, report it and check the query scope and filters with the user. A project-wide fetch is a separate request.
Save a private JSON capture outside the checkout with `format: "semgrep-guardian-selection/v1"`, the verified `sourceRepositoryUrl`, the MCP `request` (tool `name` and `arguments`), the exact selected string `findingIds`, and `structuredContent: { findings: [...] }` containing the original selected tool rows. Match IDs exactly and keep the tool's repository, ref and evidence. Guardian returns a repository name, so verify its SCM URL for the local checkout or selected Cloud repository. Use the [Guardian preview command](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-guardian-findings) for the intended destination and confirm after reviewing the selection. Guardian handles sign-in for this workflow. Guardian and Web API IDs remain separate even when the strings match.