OPA MCP Server
[CI]
[CodeQL]
[npm version]
[Docker pulls]
[OPA Ecosystem]
[License: MIT]
[Node.js]
[opa-mcp-server MCP server]
A Model Context Protocol (MCP) server
that turns any MCP-compatible client (Claude Desktop, Claude Code, Cursor,
VS Code, Windsurf, Zed, and others) into a first-class
Open Policy Agent and Rego authoring
environment.
Status: v0.9.1. Tool surface, error codes, and
environment variables follow SemVer from
v0.1.0 forward.
Upgrading to 0.9.0: a tool refuses an argument it does not declare,
and the error names it; it used to be dropped. A policy or query that does
not compile is INVALID_REGO in every tool that runs opa, where several
returned EVAL_ERROR. rego_explain_decision returns the trace as
readable lines, not OPA's raw events. conftest_test reports a run that
evaluated no rule as passed: false, and rego_generate_test_skeleton
writes todo_test_ stubs, which opa test skips until they are filled in.
Responses are compact JSON.
Upgrading to 0.8.0: opa_exec loads dataPaths as opa eval --data
does, so a directory that also holds test fixtures, or JSON and YAML that
is not data, can now fail to load; pass it as bundle to load it as
before. A policy that does not load is INVALID_REGO in opa_exec and
the conftest tools, where it was EVAL_ERROR and UNKNOWN_ERROR.
Upgrading to 0.7.0: Node.js 22 or later is required. The bundled OPA
is 1.21, which reads YAML against the 1.2 schema: bare yes, no, on
and off in data files are strings now, not booleans. If you supply your
own binary via OPA_BINARY or PATH, only the Node requirement applies.
Upgrading to 0.6.0: rego_bench reports iterations, nsPerOp,
allocsPerOp and bytesPerOp. The fields opa prints (N, T, Bytes,
MemAllocs, MemBytes, Extra) were top-level and now sit under raw
for a single run, so anything that read them from the top level has to
look there. With count above one, raw is omitted: every document is in
runs, and fastest indexes the one the top-level figures come from.
Upgrading to 0.4.0: subprocesses no longer inherit the server's
environment. A policy that read a variable through opa.runtime().env
will no longer see it; name the variable in OPA_MCP_PASSTHROUGH_ENV if
it is genuinely needed. See the security section for why.
Upgrading to 0.3.0: the bundled OPA is now 1.19, so Rego v0 policies
no longer parse (if is required before a rule body, contains before a
partial set). Run rego_migrate_v1 to convert them, or pass
v0Compatible: true to load one as it is. If you supply your own binary via
OPA_BINARY or PATH, nothing changes.
Table of contents
What you can do with it
Once an MCP client is connected, an agent can:
- Author Rego. Generate, format, and refactor policies. The server
runs the real
opa fmt and opa parse so output is byte-identical to
what you'd get on the command line, and regal (optional) surfaces
idiomatic suggestions.
- Evaluate against data. Run a query against a policy and an input
document. Optional
--explain, --profile, and --coverage flags
surface execution traces, hot rules, and per-line coverage.
- Debug a deny.
rego_explain_decision walks the agent through every
rule that fired (and every one that didn't), so it can answer "why was
this rejected" without you reading the trace by hand.
- Manage policies on a running OPA. List, get, put, delete policies on
an OPA server through its REST API. Works against a local
opa run --server or a production deployment with bearer-token auth.
- Build & sign bundles. Package a directory of policies into a
deployable bundle, optionally signing it. Output is a regular
.tar.gz
the agent can hand to your delivery system.
- Lint.
rego_lint runs Regal across a directory or a single file
and returns each finding with its category, level and location.
A walk-through of a typical session lives in Cookbook.
Why this MCP
OPA already has a perfectly good CLI and REST API. So why an MCP wrapper?
- Schema-shaped tool surface. An agent calling
rego_eval gets a
validated input schema, a structured output envelope, and stable error
codes, instead of parsing free-form CLI text and inventing its own
failure taxonomy. That alone makes Rego usable to an agent the way a
language server makes a language usable to an IDE.
- Higher-level helpers.
rego_explain_decision,
rego_generate_test_skeleton, rego_describe_policy, and
rego_suggest_fix compose the lower-level primitives into the tasks
agents are actually asked to do. They don't exist in the OPA CLI.
- Curated knowledge. The bundled MCP resources expose the OPA
built-in function catalog, the official Rego style guide (formatted for
LLMs), and a curated pattern library covering RBAC, ABAC, Kubernetes
admission, IaC gates, API authz, and rate limiting, so the agent has
authoritative context without needing to scrape it.
- Safety boundaries the agent can rely on. Path allow-list,
subprocess timeouts, and response-size caps. Defaults are conservative;
running the server doesn't quietly grant the agent more reach than the
operator intended.
If you've ever watched an agent fight opa eval's argument order, you'll
recognize the gap this fills.
Install
The server runs locally over stdio. Pick the install path that matches
your client.
Claude Desktop
Edit claude_desktop_config.json directly (or copy from
examples/claude-desktop.json):
Replace the /usr/local/bin/... paths with your real ones. See the
first-time install gotcha
below. Windows users substitute C:\\path\\to\\opa.exe.
Or download opa-mcp.mcpb from the
latest release
and double-click it.
Claude Code (CLI)
Register the server for the current project with claude mcp add:
This writes the config into .mcp.json at your project root and is
picked up automatically on every claude session in that directory.
Add --scope user to register it globally instead.
Replace the paths with your real absolute paths (same caveat as
Claude Desktop above). On Windows use C:\path\to\opa.exe syntax.
Persistent context and auto-checks for policy repos.
If you work in an OPA policy repo regularly, two extra files remove
repetitive setup from every session:
examples/CLAUDE.md -- copy to your repo
root or .claude/CLAUDE.md. Claude Code loads it every session,
so the agent always knows which tools to use and what conventions apply.
examples/claude-code-hook.json --
merge the hooks block into .claude/settings.json. Runs opa check
after Claude writes or edits a .rego file and hands any error back to
Claude, without a manual tool call.
Cursor
Drop examples/cursor.json into either
.cursor/mcp.json (project-scoped) or ~/.cursor/mcp.json (user-scoped).
VS Code (GitHub Copilot Chat)
Drop examples/vscode.json into
.vscode/mcp.json, or paste the servers block into your user
settings.json under mcp.servers.
Windsurf, Zed, and others
See examples/ for a full set of drop-in configs.
Manual install (any MCP client)
then point your client at the opa-mcp binary.
Docker
The image is multi-arch (linux/amd64, linux/arm64), bundles pinned
versions of opa and regal, and runs as a non-root user. No host
install of OPA or Regal is required.
⚠ If every tool call returns OPA_BINARY_NOT_FOUND
The npm package carries its own opa for the five platforms it is built
for, so a client PATH without opa on it does not matter there. The MCPB
has no bundled copy, and on any other platform neither does npm: then the
server boots but every tool call returns OPA_BINARY_NOT_FOUND. Neither the
npm package nor the MCPB bundles regal or conftest, and the Docker image
ships regal but not conftest, so their tools need a PATH entry or an
explicit path either way.
Fix: add OPA_BINARY and REGAL_BINARY env entries to your client
config with the absolute path to each binary. The example configs under
examples/ ship with placeholder paths you replace.
Find the real paths with:
This does not affect the Docker install path, which ships opa and
regal in the image and bypasses PATH entirely. The MCPB bundle
carries neither, and unlike the npm install has no bundled fallback: set
OPA_BINARY or put opa on PATH.
See Troubleshooting for full detail.
Configuration
The server reads its configuration from environment variables. Every
variable is optional; defaults are sensible for a local OPA on
http://localhost:8181.
Paths in OPA_MCP_ALLOWED_PATHS must be absolute, and a *_BINARY value is
either a bare command name looked up on PATH or an absolute path; anything
else stops the server at startup. A binary that cannot be run is reported by
each tool call with a structured error.
Tool reference
Every tool returns a JSON envelope:
Stable error codes: INVALID_INPUT, INVALID_REGO, INVALID_BUNDLE,
EVAL_ERROR, OPA_BINARY_NOT_FOUND, REGAL_NOT_FOUND,
CONFTEST_NOT_FOUND, OPA_UNREACHABLE, OPA_AUTH_FAILED,
POLICY_NOT_FOUND, DATA_NOT_FOUND, PATH_NOT_ALLOWED, PATH_NOT_FOUND,
NO_TESTS_FOUND, COVERAGE_BELOW_THRESHOLD, OPA_VERSION_UNSUPPORTED,
GITHUB_TOKEN_MISSING, GIST_CREATE_FAILED, OUTPUT_TOO_LARGE, SUBPROCESS_KILLED, OPA_URL_INVALID, TIMEOUT,
CANCELLED, UNKNOWN_ERROR. A rego_eval batch can also give an entry
NOT_EVALUATED: an input the call stopped before reaching, after another
timed out.
Category A: Authoring & static analysis
Operate on Rego source code without needing a running OPA server. Wrap
opa fmt, opa parse, opa check, opa inspect, opa capabilities,
opa deps, and regal.
Featured: rego_format
Featured: rego_check
Category B: Evaluation & testing
Run a query against a policy and input. Wrap opa eval, opa test, and
opa bench. Each of these tools takes v0Compatible to load a policy
written before OPA 1.0 without migrating it, and so does every other tool
that reads a policy through opa or conftest, from rego_check to
rego_verify and conftest_test. OPA then reads the query as v0 too, so
the future keywords are imported for it and in and every still work
there. rego_policy_diff takes it per side (v0CompatibleA,
v0CompatibleB), to compare a legacy policy with its migrated copy. The
exceptions are rego_deps, since opa deps has no such option, and the
Regal tools, which need none, since Regal reads either version.
Featured: rego_eval
Category C: Bundle operations
Package, sign, and verify deployable bundles. Wrap opa build, opa sign, and opa build --verification-key.
Category D: OPA server management
Talk to a running OPA server over its REST API. Require OPA_URL to
point at a reachable server.
Category E: Higher-level helpers
The differentiation surface. These compose lower-level primitives into
the tasks agents are actually asked to do.
Category F: Conftest (configuration policy testing)
Test Kubernetes manifests, Terraform plans, Dockerfiles, Helm charts, and any
YAML/JSON/HCL/TOML/INI against Rego policies using
conftest. Requires conftest on PATH or
CONFTEST_BINARY set; all four tools return CONFTEST_NOT_FOUND otherwise.
Featured: conftest_test with inline config
Category G: Meta
Prompts
Three MCP prompts
ship with the server. Clients surface them as slash commands or workflow
templates.
Resources
Three MCP resources
expose curated reference data the agent can read at any time.
Cookbook
A few session shapes that the tool set was designed for.
"Help me write a policy"
"Why was this denied?"
"Push this policy to staging OPA"
Architecture
Four things worth knowing if you're going to operate this:
-
stdout is the protocol channel. The server logs to a file via
lib/logger.ts and never writes to stdout. If you see stray stdout
bytes, the client disconnects; the MCP transport layer is strict.
-
No tool handler throws. Every handler catches its own exceptions and
returns a structured { ok: false, error: ... } envelope, so the agent
sees a stable error vocabulary, not a stack trace. An argument that fails
the tool's input schema never reaches the handler: the MCP layer rejects
it and returns a tool result with isError: true whose text begins
MCP error -32602: Input validation error:, rather than the envelope.
Decoding subprocess output happens inside an async callback, where a throw
would bypass those handlers entirely, so that path is bounded by bytes
rather than left to a try/catch that could not see it.
-
Subprocesses are bounded in time, size, and environment.
lib/subprocess.ts runs the binaries with shell: false, a hard
timeout with SIGTERM-then-SIGKILL escalation, and a per-stream byte
cap. There is no path through the server where an agent can construct a
shell command. The timeout alone is not enough: opa buffers a result
in memory and writes it in one burst at exit, so a command that finishes
well inside the timeout can still deliver hundreds of megabytes.
-
Children do not inherit the server's environment. lib/child-env.ts
builds an explicit allow-list instead. Rego can read its interpreter's
environment through opa.runtime().env, so anything passed down is
readable by any policy the server evaluates, the proxy variables on the
list included.
Security
This server is designed to run locally, started by an MCP client on
the user's own machine, communicating over stdio. It is not designed to
be exposed on the network.
- File-based tools refuse to read anything outside
OPA_MCP_ALLOWED_PATHS.
When that variable is unset, file tools return PATH_NOT_ALLOWED.
- Subprocesses run with
shell: false, a hard timeout, and a byte cap on
captured output.
- Evaluated policy cannot read the server's environment. Rego exposes the
environment of the
opa process through opa.runtime().env, so a child that
inherited process.env would hand OPA_TOKEN, GITHUB_TOKEN, and every
other variable to any policy it evaluated. Since rego_eval accepts inline
source, no filesystem access is needed to reach that, which puts it one
prompt injection away from any untrusted Rego an agent reads. Children get an
explicit allow-list instead (lib/child-env.ts). The list holds no cloud or
repository token, but it is not free of credentials: HTTP_PROXY and its
siblings are on it, and a proxy URL can embed a username and password.
They are there because dropping them breaks everyone behind a corporate
proxy. Name them in OPA_MCP_BLOCK_ENV to withhold them anyway.
OPA_MCP_PASSTHROUGH_ENV opts individual variables back in.
OPA_TOKEN is never echoed in tool responses or log entries, and is not
passed to any child process.
- Tools that evaluate Rego are annotated open-world and not read-only.
rego_eval and its variants, rego_test, rego_test_multiroot,
rego_bench, rego_compile_query, opa_exec, rego_migrate_v1 (when
given inputs), the explain, diff and coverage helpers, the conftest
tools, and the Regal tools (rego_lint,
rego_security_audit, rego_fix, which run a project's custom rules) all
run Rego, and OPA's http.send lets a policy reach, and write to, any
network address. A client that gates on the hints will ask before running
one. opa_query_decision and opa_compile_query are the exception: the
remote OPA evaluates a policy it already holds, and their hints describe
what the call does to that server. No evaluating tool passes or accepts a
capabilities file, so http.send cannot be restricted for evaluation;
rego_check and opa_bundle_build accept one, which affects only checking
and building.
- Releases are published with
npm provenance;
the Docker image is built from the committed
Dockerfile, with pinned
versions of opa and regal checked against their published digests.
To report a vulnerability, follow SECURITY.md. Please
do not open a public issue for security problems.
Troubleshooting
Common issues, fast fixes.
OPA_BINARY_NOT_FOUND (or REGAL_NOT_FOUND / CONFTEST_NOT_FOUND) even
though the binary is installed. (most common first-day issue, read this
first)
MCP clients (notably Claude Desktop on Windows and macOS) launch the
server with a deliberately reduced PATH that omits user-local bin
directories, even ones that work fine in your interactive shell. The
binary is on your machine; the spawned MCP server just can't see it.
Find the absolute path to opa:
Then set OPA_BINARY to that absolute path in your client's MCP env
block. The same cause and fix apply to the other binaries: if rego_lint
/ rego_security_audit / rego_fix report REGAL_NOT_FOUND, or the
conftest_* tools report CONFTEST_NOT_FOUND, set REGAL_BINARY /
CONFTEST_BINARY to the absolute path the same way (find it with
which regal / which conftest). Having the binary on your shell PATH
is not enough -- the spawned server gets a reduced PATH. The
examples/ configs already include these env vars; just
edit the placeholder paths.
This issue does not affect the Docker install path, which bundles
opa and regal and bypasses PATH entirely. The MCPB bundle resolves
opa from OPA_BINARY or PATH, so it can hit this.
The server starts, then the client says "disconnected."
The most likely cause is something in the process writing to stdout
besides MCP frames. If you've added a custom tool, check that no library
it calls prints to stdout. The fixed-position safety net is
lib/logger.ts. Use it, not console.log.
PATH_NOT_ALLOWED on a file under my project.
OPA_MCP_ALLOWED_PATHS is empty by default. Set it to the absolute
path(s) you want the server to read from, comma-separated.
OPA_UNREACHABLE when calling opa_* tools.
OPA_URL (default http://localhost:8181) must point at a running OPA
server (opa run --server ...). Check with curl $OPA_URL/health.
TIMEOUT when calling opa_* tools.
The request did not finish within OPA_MCP_HTTP_TIMEOUT_MS (default 15 s).
Either OPA is up but slow, or nothing is answering at OPA_URL and the
connection attempt is being dropped rather than refused, which looks the
same from here. Check OPA_URL and the server's load, or raise the limit.
directory-package-mismatch violation when linting inline source.
Since v0.1.1, the server auto-disables this rule for inline-source calls.
If you see it, you are running an older version -- upgrade to v0.1.1 or
later. To get canonical signal on this rule, lint via paths against the
real on-disk file instead of passing source directly.
Where are the logs?
Default location is <OS-tmpdir>/orygn-opa-mcp.log. That's typically
/tmp/orygn-opa-mcp.log on Linux/macOS or %TEMP%\orygn-opa-mcp.log
on Windows. Set OPA_MCP_LOG_FILE to override, and
OPA_MCP_LOG_LEVEL=debug to widen the firehose.
Development
Common commands:
CI runs lint, typecheck, build, and unit tests on every push and PR
across Ubuntu and Windows on Node 22, 24 and 26, plus macOS on Node 22. Integration
tests run on Linux, and on Windows as a non-required check, against pinned
opa, regal and conftest releases.
For the full contributor workflow (adding tools, naming conventions,
logging discipline, release process), see CONTRIBUTING.md.
Versioning & support
This project follows Semantic Versioning. The public
surface for SemVer purposes is the set of registered tools, prompts, and
resources, their input/output schemas, the recognized environment
variables, and the CLI entry point.
Breaking changes will be:
- announced in CHANGELOG.md under a new major version,
- preceded by at least one minor release with a deprecation warning,
- accompanied by a migration note in the release announcement.
Pinned versions of the upstream toolchain (opa and regal) are treated
as part of the build, not as a dependency the operator manages. The
Dockerfile and CI use the same pin; bumps go through
Dependabot or a manual PR.
License
MIT © Orygn LLC
@orygn/opa-mcp is an independent project. It is not affiliated with,
endorsed by, or sponsored by the Open Policy Agent project, the Cloud
Native Computing Foundation, Styra, or Anthropic. "Open Policy Agent"
and "Rego" are trademarks of their respective owners. "Model Context
Protocol" is a trademark of Anthropic, PBC.
Listed in the OPA Ecosystem.