Codex CLI MCP Setup: GitHub, Permissions and Security

Codex CLI MCP setup

A useful Codex CLI MCP setup does more than connect to another tool. It defines which external systems Codex can reach, which actions the model can request, when a human must approve them and what happens if an MCP server behaves outside the CLI sandbox.

This guide covers Codex CLI installation, GitHub MCP configuration, config.toml, approval modes, tool allow lists, repository instructions and failed connection debugging. The emphasis is least privilege. Adding every available MCP server may look productive, but it gives the agent more overlapping tools to choose from and increases the number of systems that can read data or perform actions.

The safest starting point is one read-only server, a narrow set of tools and prompts for anything that writes, comments, pushes, merges or triggers a workflow. Developers still choosing an agent should compare the wider best AI coding tools before building a workflow around Codex-specific configuration.

Codex CLI MCP setup: the quick answer

DecisionSafer defaultReason
Configuration scopeUser-level for credentials and shared serversKeeps secrets and machine-specific commands out of repositories
First MCP connectionRead-only documentation or repository accessTests the transport and tool discovery without granting mutation rights
Tool exposureExplicit enabled_tools listReduces accidental tool selection and limits the available attack surface
Approval behaviourPrompt for writes, approve only known read toolsAvoids approval fatigue without making every action automatic
GitHub accessFine-grained token with selected repositoriesA compromised server cannot exceed the token’s own permissions
Repository rulesSmall, specific AGENTS.mdGives Codex durable workflow guidance but does not pretend instructions are a security boundary


Install or update Codex CLI before configuring MCP

Installation is the smallest part of this setup, but an old CLI can create misleading MCP errors when the server expects a newer transport or authentication flow. Use one supported installation route and verify the binary that your shell actually resolves.

macOS and Linux standalone installer

curl -fsSL https://chatgpt.com/codex/install.sh | sh

Windows PowerShell installer

powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"

npm installation

npm install -g @openai/codex

Then confirm the installation and run the built-in diagnostic summary:

codex --version
codex doctor --summary

Start Codex from a Git repository rather than a parent folder containing several unrelated projects. Run /status inside the terminal interface to confirm the working directory, sandbox and approval policy before adding external tools.

Decide which type of GitHub connection you actually need

“Codex CLI GitHub setup” can describe three different workflows. Confusing them leads to unnecessary access.

WorkflowWhat Codex can useDoes it need GitHub MCP?
Work on a cloned repositoryLocal files, local Git history and installed Git commandsNo
Read or manage remote issues, pull requests, Actions and repository dataGitHub API capabilities exposed as MCP toolsYes
Run hosted Codex reviews on GitHub pull requestsCodex cloud integration and repository permissionsNo local CLI MCP server is required

If the repository is already cloned and the job is to inspect code, edit files, run tests and create a local commit, do not add GitHub MCP merely because the project is hosted on GitHub. Add it only when the task needs remote platform data or actions that local Git cannot provide.

Add one MCP server and verify the connection path

Codex stores MCP server definitions in ~/.codex/config.toml. Trusted repositories can also contain .codex/config.toml, but user-level configuration is the cleaner home for personal credentials and machine-specific launch commands. The current options for STDIO, Streamable HTTP, timeouts, tool lists and approvals are documented in OpenAI’s Codex MCP documentation.

For a low-risk connection test, add a documentation server:

codex mcp add context7 -- npx -y @upstash/context7-mcp

Check the stored configuration and active session:

codex mcp list
codex

Inside Codex, run /mcp. Confirm that the server is enabled and exposes tools. Ask for a contained read operation before relying on it for a larger task. A server appearing in config.toml proves only that it was configured, not that its process started, authenticated or completed the MCP handshake.

Configure the GitHub MCP server without storing a token in TOML

The hosted GitHub MCP server uses Streamable HTTP. Keep the token in the environment and tell Codex which variable supplies it. Do not paste a personal access token into config.toml, AGENTS.md, a shell history entry or a repository .env file.

Set the variable in the shell that will launch Codex. For Bash or Zsh:

export GITHUB_PAT_TOKEN="your-token"

For PowerShell:

$env:GITHUB_PAT_TOKEN="your-token"

Add the remote server through the CLI:

codex mcp add github \
  --url https://api.githubcopilot.com/mcp/ \
  --bearer-token-env-var GITHUB_PAT_TOKEN

Or define it manually:

[mcp_servers.github]
url = "https://api.githubcopilot.com/mcp/"
bearer_token_env_var = "GITHUB_PAT_TOKEN"
enabled = true
required = false
startup_timeout_sec = 20
tool_timeout_sec = 60
default_tools_approval_mode = "writes"

required = false prevents a temporary GitHub outage from blocking every Codex session. Make a server required only when the task cannot proceed safely without it. The token itself should be fine-grained, limited to selected repositories, and granted only the permissions required by the exposed tools.

Use two allow lists, not one broad permission switch

A secure Codex MCP setup controls capability at two layers. The MCP server decides which tools it offers. Codex then decides which of those tools are enabled and how approval works. Restricting only one layer leaves unnecessary capability available at the other.

Start with read operations that support investigation and review:

[mcp_servers.github]
url = "https://api.githubcopilot.com/mcp/"
bearer_token_env_var = "GITHUB_PAT_TOKEN"
enabled_tools = [
  "get_file_contents",
  "search_code",
  "list_pull_requests",
  "pull_request_read"
]
default_tools_approval_mode = "prompt"

[mcp_servers.github.tools.get_file_contents]
approval_mode = "approve"

[mcp_servers.github.tools.search_code]
approval_mode = "approve"

[mcp_servers.github.tools.list_pull_requests]
approval_mode = "approve"

[mcp_servers.github.tools.pull_request_read]
approval_mode = "approve"

This configuration makes the named read tools available without repeated prompts while leaving any newly added or unlisted capability unavailable. Tool names can change between server releases, so verify the names shown by /mcp after an update rather than copying an old list indefinitely.

Tool categorySuggested policyWhy
Documentation searchapprove after verificationLow mutation risk, although queries may still disclose project context
Repository and pull request readsapprove or auto for selected repositoriesUseful for routine investigation with a read-scoped token
Create comments, issues or brancheswrites or promptPublic or team-visible side effects need review
Push files, merge pull requests or trigger Actionsprompt, or keep disabledThese actions can alter production code and deployment state
Infrastructure, secrets or deployment toolsSeparate server or profileCombining them with daily code tools widens the blast radius

The CLI sandbox does not automatically contain an MCP server

This is the security detail most basic setup guides miss. Codex sandbox settings constrain the commands Codex executes via its local command tools. An MCP server is a separate process or remote service with its own code, credentials and access. A write-capable MCP tool can therefore cause side effects that are not equivalent to those of a shell command running inside the workspace sandbox.

A read-only Codex session is not fully read-only if an enabled MCP server can still modify GitHub, a database, a browser session or another external system.

Use the sandbox and approval policy, but secure each MCP server independently:

  • Limit the credential before it reaches Codex.
  • Expose only the server toolsets required for the task.
  • Use enabled_tools to narrow the tools Codex can select.
  • Prompt before mutations, even when the local workspace allows writes.
  • Keep deployment and infrastructure servers disabled during ordinary coding sessions.
  • Revoke or rotate credentials when a local server, dependency or machine is no longer trusted.

For a locally hosted GitHub MCP server, Docker can add process isolation and the server’s own read-only mode:

[mcp_servers.github_local_readonly]
command = "docker"
args = [
  "run", "-i", "--rm",
  "-e", "GITHUB_PERSONAL_ACCESS_TOKEN",
  "-e", "GITHUB_READ_ONLY=1",
  "ghcr.io/github/github-mcp-server"
]
env_vars = ["GITHUB_PERSONAL_ACCESS_TOKEN"]
required = false
default_tools_approval_mode = "prompt"

Containerising the server limits some local process access. It does not reduce what the GitHub token can do, nor does it protect data sent to the remote GitHub API. Credential permissions remain the stronger control.

Use AGENTS.md for workflow rules, not access control

Codex loads AGENTS.md as durable repository guidance. It is useful for explaining build commands, review expectations, directories to avoid and how MCP tools should fit into the workflow. It is not an enforcement mechanism. A model can misinterpret an instruction, and a malicious repository file can attempt to redirect the agent’s behaviour.

# AGENTS.md

## Repository workflow

- Work on a new branch for every implementation task.
- Inspect the current diff before editing.
- Run the relevant tests and lint checks before reporting completion.
- Never push, merge or trigger a deployment.
- Use GitHub MCP for read operations only.
- Ask before posting an issue or pull request comment.
- Summarise every external action requested through MCP.
- Do not read or modify .env files, credential stores or production config.

Keep repository instructions concise enough to remain visible and specific enough to test. “Be careful with GitHub” is not useful. “Never merge, push or trigger Actions” gives Codex a clear behavioural boundary. Back that instruction with disabled tools and restricted credentials so a prompt failure cannot bypass policy.

More MCP servers can make Codex less predictable

Every MCP server adds tool descriptions to the agent’s available context. Several servers may expose similar ways to search files, read documentation, manage issues or control a browser. The model then has to choose not only whether to call a tool, but which overlapping tool is the right one.

The practical cost is not limited to security. Tool-heavy sessions can become slower, consume more context and produce inconsistent execution paths. An agent may use a remote repository search when local rg would be faster, or call a browser tool for information already present in the repository.

Use a simple tool budget:

  1. Start with Codex’s local file and command capabilities.
  2. Add one MCP server for context that does not exist locally.
  3. Enable only the tools required by a named workflow.
  4. Disable the server after the workflow ends if it is not part of daily development.
  5. Review the tool list after server updates.

A smaller tool surface often improves results because the intended path is obvious. MCP should remove manual integration work, not turn every Codex session into a general-purpose control plane.

Debug failed MCP connections in the right order

MCP errors are often described as a single problem, even though they occur at different stages: configuration loading, process launch, transport handshake, authentication, tool discovery, or tool execution. Diagnose the first failing stage rather than changing several settings at once.

SymptomLikely causeWhat to check
Server is absent from codex mcp listWrong config file, invalid TOML or disabled entryConfirm the active user, CODEX_HOME, table name and enabled value
Project server is ignoredRepository is not trustedUse user-level config for testing or trust the project after reviewing its files
Handshake closes during initialisationServer process exited, wrong transport or invalid STDIO outputRun the command directly, check dependency errors and ensure logs are not written to protocol stdout
Server starts slowly and times outFirst package download, Docker image pull or slow runtimePre-install dependencies or raise startup_timeout_sec modestly
HTTP server returns 401Token missing from the Codex launch environmentPrint the variable name without its value, restart Codex from the same shell and verify token expiry
Server connects but shows no toolsServer-side toolset restriction, Codex allow list or insufficient account accessInspect /mcp, remove stale tool names and test with the smallest known read tool
OAuth opens the wrong callback hostRemote shell, container or fixed redirect requirementSet the appropriate callback URL or port and register the complete redirect URI
Repeated prompts for safe read toolsDefault approval mode is too broadAdd per-tool approval rules and start a fresh session after editing config
Works in a terminal but not an IDEDifferent PATH or environment variablesUse absolute executable paths and confirm the IDE inherited the credential environment

Useful checks are:

codex mcp list
codex doctor --summary
codex

Then use /status and /mcp inside a fresh session. Restarting matters because configuration and tool discovery are not always cleanly rebuilt within a long-running conversation.

Test the denial paths before enabling write tools

A successful “list my repositories” prompt proves very little. A security test should confirm both what the setup rejects and what it permits.

TestExpected resultWhat it validates
Read a file from an allowed repositorySuccess without unnecessary promptsTransport, authentication and read tool policy
Read a private repository outside the token selectionDeniedCredential scope
Request an unlisted MCP toolUnavailableCodex enabled_tools policy
Ask Codex to create an issuePrompted or unavailableWrite approval policy
Ask Codex to merge a pull requestUnavailable in a read-only profileHigh-impact tool exclusion
Revoke the token and repeat a readClear authentication failureCredential dependency and error visibility
Stop the local MCP serverCodex still starts when required = falseFailure isolation

Once write tools are enabled, treat their output as you would any other code or repository change. Branch protections, deterministic checks and human review should remain in place. DIY AI’s guide to code review automation explains how tests, linters, security checks and approval gates should support agent-generated work.

Codex CLI MCP security checklist

  • Install a current Codex CLI release and run codex doctor --summary.
  • Launch Codex from the intended repository, not a broad parent directory.
  • Keep credentials out of TOML, repository files, prompts and shell history.
  • Use fine-grained tokens restricted to selected repositories.
  • Prefer read-only server modes where available.
  • Set enabled_tools instead of exposing every server capability.
  • Approve known read tools individually and prompt for writes.
  • Keep merge, deployment, workflow and secret-management tools disabled by default.
  • Treat MCP as a separate trust boundary from the Codex command sandbox.
  • Use AGENTS.md for workflow guidance, backed by enforced permissions.
  • Test denied repositories, disabled tools and revoked credentials.
  • Review MCP tools and token scopes after upgrades.

Codex CLI MCP FAQs

Does Codex CLI support MCP servers?

Yes. Codex CLI supports local STDIO servers and remote Streamable HTTP servers. Servers can be added with codex mcp add or configured in config.toml.

Where is the Codex CLI MCP config file?

User-level configuration normally lives at ~/.codex/config.toml. Trusted repositories can provide project-specific settings in .codex/config.toml. Keep personal credentials and machine-specific commands at user level.

Do I need MCP to use Codex CLI with a GitHub repository?

No. Codex can work with a locally cloned Git repository using local files and Git commands. GitHub MCP is needed for remote GitHub features such as issues, pull requests, Actions and API-backed repository data.

Does read-only sandbox mode make MCP read-only?

No. The local sandbox and an MCP server are separate trust boundaries. Restrict the MCP server’s own tools, credentials and approval policy rather than assuming the CLI sandbox controls every external action.

Should every MCP read tool be auto-approved?

No. Read operations can still disclose private repository content, issue data or customer information to an external service. Auto-approve only tools whose server, destination and credential scope have been reviewed.

How many MCP servers should Codex CLI use?

There is no useful target number. Use the smallest set that supplies context or actions unavailable locally. Disable overlapping or occasional servers so Codex has fewer ambiguous tools to choose from.

The best Codex MCP setup starts smaller than you expect

Install Codex, confirm the local repository workflow and add one read-only MCP server. Verify its launch path, authentication, tool list and denial behaviour. Only then add write tools one at a time.

A sound setup gives Codex only the integrations required for a predictable path from request to tool call to reviewed result. A narrow server, restricted credentials, and explicit approval policy will usually produce a safer and more reliable coding workflow than a large collection of powerful tools left permanently enabled.

You Might Also Like:

Best AI Coding Tools 2026

By: Steven Jones On:
Updated on: June 23, 2026
Claude Code is the best AI coding tool overall in 2026 because it leads the DIY AI dataset for repository…

Code Review Automation

By: Steven Jones On:
Updated on: June 5, 2026
Code review automation uses CI checks, review rules, security scans, test gates, static analysis and AI-assisted review to catch predictable…

Claude Code Best Practices

By: Steven Jones On:
The best Claude Code results come from treating it like a junior-to-mid engineer with fast hands, deep repository access and…
Steven Jones

Writer: Steven Jones

AI Tools Reviewer and Technical Analyst

Steven Jones is a technology analyst specialising in artificial intelligence, machine learning workflows, and emerging automation tools. At DIY AI, he focuses on clear, practical guidance for people comparing AI tools in the real world. His work covers text generation, image generation, video tools, data platforms, developer-focused AI products, and the automation workflows that connect them. Steven's reviews are built around hands-on testing, practical benchmarks, and transparent scoring rather than vendor claims. He looks closely at where each tool performs well, where it falls short, and what those trade-offs mean for creators, teams, and businesses trying to make sensible AI adoption decisions. He has a particular interest in safety, reliability, output quality, performance metrics, and dataset quality. When he is not reviewing the latest AI model updates, he experiments with prompt engineering techniques and contributes to DIY AI ongoing work on fair, explainable scoring frameworks for AI tools.

Contact

Leave a Comment On: Codex Cli Mcp

Your email address will not be published.