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.
+--------------------+ MCP/stdio +-----------------+ spawn/HTTP +---------------------+
| Claude · Cursor · |----------> | @orygn/opa-mcp |----------> | opa · regal |
| VS Code · ... |<---------- | |<---------- | conftest · REST API |
+--------------------+ 52 tools +-----------------+ +---------------------+
Claude Code tests a pod policy against the real OPA, finds the pods it lets through, and fixes it (1 min video). Setup in Claude Code, step by step: 2 min walkthrough.
Status: v0.12.0. Tool surface, error codes, and environment variables follow SemVer from v0.1.0 forward.
Upgrading to 0.12.0: the bundled OPA is 1.23.0, which roots a bundle directory at the folder holding its
.manifest, so a directory signed by an earlier OPA has to be signed again.opa_bundle_buildnow names each module by its path from the folder above the paths given: a module that was/home/alice/policies/authz.regoispolicies/authz.rego. Those names are the policy ids a server shows, so rebuild a bundle to drop the old path. Conftest policies that callparse_config_fileare refused unlessOPA_MCP_CONFTEST_FILE_READSis set, and a folder with a link inside it that leads outside the allowed folders is refused.rego_compile_queryandopa_compile_queryrefuse aninputwhileinputitself is unknown, the default, since OPA ignores it then; name the unknown fields instead. A tool that cannot write its output returnsPATH_NOT_WRITABLEwhere it returnedINVALID_REGO,INVALID_BUNDLEorUNKNOWN_ERROR.
Upgrading from an earlier version? What changed in each release, and what you may have to act on, is in the CHANGELOG.
opa-mcp sends an anonymous daily report of the tools used, their error codes and the versions in use, never policies, inputs or paths.
OPA_MCP_TELEMETRY=offorDO_NOT_TRACK=1turns it off; docs/privacy.md lists every field.
- What you can do with it
- Why this MCP
- Install
- Configuration
- Tool reference
- Prompts
- Resources
- Cookbook
- Architecture
- Security
- Troubleshooting
- Development
- Versioning & support
- License
Once an MCP client is connected, an agent can:
- Author Rego. Generate, format, and refactor policies. The server
runs the real
opa fmtandopa parseso output is byte-identical to what you'd get on the command line, andregal(optional) surfaces idiomatic suggestions. - Evaluate against data. Run a query against a policy and an input
document. Optional
--explain,--profile, and--coverageflags surface execution traces, hot rules, and per-line coverage. - Debug a deny.
rego_explain_decisionwalks 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 --serveror 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.gzthe agent can hand to your delivery system. - Lint.
rego_lintruns 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.
OPA already has a perfectly good CLI and REST API. So why an MCP wrapper?
- Schema-shaped tool surface. An agent calling
rego_evalgets 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, andrego_suggest_fixcompose 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, rate limiting and AI agent tool calls, 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.
The server runs locally over stdio. Pick the install path that matches your client.
Edit claude_desktop_config.json directly (or copy from
examples/claude-desktop.json):
{
"mcpServers": {
"opa": {
"command": "npx",
"args": ["-y", "@orygn/opa-mcp"],
"env": {
"OPA_MCP_ALLOWED_PATHS": "/path/to/your/policies"
}
}
}
}
OPA_MCP_ALLOWED_PATHSis the directory (or comma-separated list) that holds your policies; on Windows write it asC:\\path\\to\\policies. OPA itself is bundled. The lint and Conftest tools also needregalandconftest: addREGAL_BINARYandCONFTEST_BINARYwith their absolute paths (see Configuration).
Or download opa-mcp.mcpb from the
latest release
and install it in Claude Desktop: Settings > Desktop app > Extensions >
Manage > Advanced settings > Install extension, or drop the file on that
Extensions page. The extension does not include OPA: set OPA Binary Path
in its settings, or have opa on PATH.
From your project folder, register the server with claude mcp add:
claude mcp add opa --scope project -- npx -y @orygn/opa-mcpThe walkthrough video shows the whole setup.
Or install the plugin, which runs the same server in every project, and in Claude Desktop's Cowork too:
/plugin install opa-mcp --marketplace OrygnsCode/opa-mcp-server
The plugin pins one opa-mcp release; claude plugin update opa-mcp@orygn
moves it to the newest. It reads the same environment variables, set for
example in the env block of ~/.claude/settings.json.
plugin/README.md has the details.
Claude Code shares the folders you work in with the server as MCP roots:
the folder it started in, plus any added with --add-dir or /add-dir.
With OPA_MCP_ALLOWED_PATHS unset, those are the folders the file tools
may use, and the list follows the session as folders are added. --scope project writes .mcp.json in the project, so Claude Code in the terminal
and the editor extensions both pick it up, and since it holds no path it
works for anyone who clones the repository. Use --scope user instead to
have it in every project.
To pick the folders yourself, add
--env OPA_MCP_ALLOWED_PATHS=/path/to/your/policiesafter the server name (on Windows,C:\path\to\policies). When set, it is used instead of the client's roots.--envtakes every argument up to the next option, so the name has to come first. On Windows, run the command in Command Prompt: Windows PowerShell drops the--andclaudethen rejects-y. Without--scope, Claude Code keeps the server private to you under the folder's path, and on Windows the VS Code extension can miss it when the drive letter's case differs. Add--env REGAL_BINARY=...and--env CONFTEST_BINARY=...for the lint and Conftest tools, as for Claude Desktop above.
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 thehooksblock into.claude/settings.json. Runsopa checkafter Claude writes or edits a.regofile and hands any error back to Claude, without a manual tool call.
Drop examples/cursor.json into either
.cursor/mcp.json (project-scoped) or ~/.cursor/mcp.json (user-scoped).
Drop examples/vscode.json into
.vscode/mcp.json, or paste the servers block into your user
settings.json under mcp.servers.
See examples/ for a full set of drop-in configs.
npm install -g @orygn/opa-mcp
opa-mcp --versionthen point your client at the opa-mcp binary.
docker pull orygn/opa-mcp:latest
docker run --rm -i \
-v /path/to/your/policies:/policies:ro \
-e OPA_MCP_ALLOWED_PATHS=/policies \
orygn/opa-mcpThe image is multi-arch (linux/amd64, linux/arm64), bundles pinned
versions of opa, regal and conftest, and runs as a non-root user.
No host install of OPA, Regal or Conftest is required.
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, so their tools need
a PATH entry or an explicit path there.
Fix: add OPA_BINARY and REGAL_BINARY env entries to your client
config with the absolute path to each binary. Find the real paths with:
which opa && which regal # macOS / LinuxGet-Command opa, regal | Select-Object Source # WindowsThis does not affect the Docker install path, which ships opa,
regal and conftest 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.
The server reads its configuration from environment variables. Every
variable is optional; defaults are sensible for a local OPA on
http://localhost:8181.
| Variable | Default | Purpose |
|---|---|---|
OPA_URL |
http://localhost:8181 |
Base URL of an OPA REST endpoint, used by opa_* tools. |
OPA_TOKEN |
(unset) | Bearer token for OPA, if your instance requires auth. Treated as a secret. Never echoed in logs or tool responses. |
OPA_BINARY |
opa (on PATH) |
Path to the opa CLI, used by rego_* tools. Unset: opa on PATH, else the bundled copy. |
REGAL_BINARY |
regal (on PATH) |
Path to the regal linter. Required by rego_lint, rego_fix, and rego_security_audit. |
CONFTEST_BINARY |
conftest (on PATH) |
Path to the conftest binary. Only required by conftest_* tools. Returns CONFTEST_NOT_FOUND if absent. |
OPA_MCP_ALLOWED_PATHS |
(unset) | Comma- or semicolon-separated list of directories the server is allowed to read policies from. When unset, file tools use the folders the client shares as MCP roots (Claude Code does); with neither, they refuse to read from disk. |
OPA_MCP_LOG_FILE |
<tmpdir>/orygn-opa-mcp.log |
Path the server appends logs to. The server never writes to stdout; that channel is reserved for the MCP protocol. |
OPA_MCP_LOG_LEVEL |
info |
One of debug, info, warn, error. |
OPA_MCP_MAX_RESPONSE_BYTES |
100000 |
Hard cap on a single tool response. Larger payloads are truncated with a __truncated: true marker. Values below 512 are refused. |
OPA_MCP_TIMEOUT_MS |
30000 |
Hard timeout for any spawned subprocess (opa, regal). After this, the child gets SIGTERM and then SIGKILL. |
OPA_MCP_HTTP_TIMEOUT_MS |
15000 |
Timeout for each request to the OPA REST API, from the connection attempt to the last byte of the response; reported as TIMEOUT. |
OPA_MCP_TELEMETRY |
on |
off turns off the anonymous daily usage report: tool names, error codes and versions, never policies, inputs or paths. log writes it to the log instead of sending it. DO_NOT_TRACK=1 also turns it off. What it holds. |
OPA_MCP_NO_CLIENT_ROOTS |
(unset) | Set to 1 to ignore the client's MCP roots, so file tools stay off unless OPA_MCP_ALLOWED_PATHS is set. |
OPA_MCP_MAX_SUBPROCESS_BYTES |
33554432 (32 MiB) |
Maximum bytes captured from a subprocess's stdout and stderr, counted separately. On overflow the stream is clamped, the child is stopped, and the tool returns OUTPUT_TOO_LARGE. Distinct from OPA_MCP_MAX_RESPONSE_BYTES, which trims the reply after the output is already in memory. |
OPA_MCP_PASSTHROUGH_ENV |
(unset) | Comma-separated variable names to pass through to opa, regal and conftest. Everything else is withheld. Anything named here is readable by any policy the server evaluates, via opa.runtime().env, so use it only for values that are safe in that position. |
OPA_MCP_BLOCK_ENV |
(unset) | Comma-separated variable names to withhold from opa, regal and conftest even when they are on the built-in allow-list. Applied last, so it also overrides OPA_MCP_PASSTHROUGH_ENV. Use it to drop the proxy variables, which can carry credentials, at the cost of proxy support. |
OPA_MCP_CONFTEST_FILE_READS |
(unset) | Set to 1 to let conftest policies call parse_config_file and parse_combined_config_files. They read the file named relative to the policy, and .. reaches outside the allowed folders, so conftest_test and conftest_verify refuse a policy that calls them unless this is set. |
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.
Every tool returns a JSON envelope:
{ "ok": true, "data": { ... }, "warnings": [ ... ] }
{ "ok": false, "error": { "code": "INVALID_REGO", "message": "...", "hint": "...", "details": { ... } } }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,
PATH_NOT_WRITABLE, 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.
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.
| Tool | What it does |
|---|---|
rego_format |
Format Rego source. Wraps opa fmt. Idempotent. |
rego_check |
Type-check and validate Rego. Wraps opa check. |
rego_lint |
Run Regal across a file or directory. Returns each violation with its category, level and location. Requires regal on PATH or REGAL_BINARY set. |
rego_parse_ast |
Parse Rego to AST JSON. Wraps opa parse. |
rego_inspect |
Inspect a bundle or directory: packages, rules, annotations. Wraps opa inspect. |
rego_capabilities |
List the built-ins and features the resolved opa binary understands (OPA_BINARY, then PATH, then the bundled copy); builtins names up to 100 to return full records for |
rego_deps |
Static dependency analysis: rule-level data references and cross-package calls. |
rego_migrate_v1 |
Migrate Rego v0 source to v1. Renames a rule v1 reserves the name of (contains, every, if, in) and replaces the built-ins v1 removed, with exact equivalents, before opa fmt --rego-v1 converts the syntax and opa check validates it. Given inputs, evaluates the original as v0 and the result as v1 on each and reports any rule that differs, plus any queries, which is how functions are compared. Returns { original, migrated, changed, valid, errors, rewrites, notes, equivalence }. dataPaths loads the data the policy reads for that comparison. |
rego_check_schema |
Check Rego against a JSON Schema. Validates that every input.* field the policy reads exists in the schema using opa check --schema. Accepts an inline schema, a path to a JSON Schema file, or a schema directory when the policy declares schemas: annotations. |
// Input
{
"source": "package x\nallow if y",
"strict": true
}
// Output (error path; the JSON diagnostics arrive on stderr from opa)
{
"ok": true,
"data": {
"valid": false,
"errors": [
{
"code": "rego_unsafe_var_error",
"message": "var y is unsafe",
"location": { "row": 2, "col": 11 }
}
]
}
}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.
| Tool | What it does |
|---|---|
rego_eval |
Evaluate a query against a policy and input. The bread-and-butter tool. inputs evaluates the query against up to 50 input documents in one call and reports each; with no policy, a query alone tries out a built-in or an expression. Each result says whether the query was defined, and print() output comes back in printed. |
rego_eval_with_explain |
Evaluate with --explain=full and return OPA's raw trace events. rego_explain_decision renders the same trace as readable lines. |
rego_eval_with_profile |
Evaluate with --profile and return per-rule timing and evaluation counts. |
rego_eval_with_coverage |
Evaluate with --coverage and return per-line coverage. |
rego_test |
Run Rego unit tests with opa test. Returns pass, fail, skip and error counts plus per-test records; errored counts tests OPA could not evaluate. coverage or threshold also adds the coverage report, unless a test fails or errors. allPassed is true only when at least one test ran and none failed, errored or was skipped. |
rego_bench |
Run opa bench and return statistical timing data. |
rego_compile_query |
Partially evaluate a query against a policy. To substitute an input, name only the unknown fields in unknowns; with input itself unknown, the default, OPA ignores it and the call is refused. |
opa_exec |
Batch-evaluate a decision against multiple input files. Returns per-file results with successCount and errorCount. dataPaths load as opa eval --data loads them; bundle takes a bundle. |
rego_test_multiroot |
Run opa test once per root and aggregate. Use when opa test . hits package conflicts. Totals include totalErrored; allPassed is true only when every root passed every test. |
// Input
{
"query": "data.rbac.allow",
"source": "package rbac\nimport rego.v1\nallow if input.role == \"admin\"",
"input": { "role": "admin" }
}
// Output
{
"ok": true,
"data": {
"result": [{ "expressions": [{ "value": true, "text": "data.rbac.allow", "location": { "row": 1, "col": 1 } }] }]
}
}Package, sign, and verify deployable bundles. Wrap opa build, opa sign, and opa build --verification-key.
| Tool | What it does |
|---|---|
opa_bundle_build |
Build a .tar.gz bundle from a policy directory. Supports optimize and revision. |
opa_bundle_sign |
Sign a bundle directory in place with a private key; an archive is refused, since OPA reads the signature from inside it, and comes signed from opa_bundle_build. Signed by OPA 1.23 or later, the directory can be moved or renamed; signed by an earlier OPA, it must keep its name. A signature verifies only under an OPA on the same side of 1.23. Returns the path, algorithm, and file count. |
opa_bundle_verify |
Verify a signed bundle with a public key through opa build --verification-key. Failures name the reason: wrong key, scope, modified, added, missing or unparseable file, unsigned, or a bundle that does not load. |
Talk to a running OPA server over its REST API. Require OPA_URL to
point at a reachable server.
| Tool | What it does |
|---|---|
opa_list_policies |
List the policy IDs registered on the server, with a count. includeSource and includeAst add the Rego text or the parsed AST. |
opa_get_policy |
Get a single policy by ID. Returns the Rego source; includeAst adds OPA's parsed AST. |
opa_put_policy |
Upload or replace a policy; replaced says whether one existed. A policy that does not compile returns INVALID_REGO with OPA's errors and is not stored. |
opa_delete_policy |
Delete a policy by ID. |
opa_get_data |
Read a path from the data hierarchy. |
opa_put_data |
Write to a path in the data hierarchy. |
opa_patch_data |
Apply a JSON Patch to the data hierarchy. |
opa_delete_data |
Delete a document from the data hierarchy. |
opa_query_decision |
POST to a /v1/data/... decision endpoint with input. defined: false means the path produced no value, which is not the same as false. |
opa_compile_query |
Partially evaluate a query against the running server, or with target turn a filter rule into a SQL WHERE clause, a UCAST tree or a Lucene query. |
opa_health |
Liveness / readiness check. A server that answers reports healthy: true or healthy: false with OPA's reason; OPA_UNREACHABLE means it could not be reached at all. |
opa_status |
The same GET /v1/config document as opa_config, under a status key. Bundle and decision-log status (/v1/status) is not exposed. Service header values are redacted. |
opa_config |
Server configuration from GET /v1/config. OPA drops the credentials block but returns service headers verbatim, so header values are redacted here and the names kept. |
The differentiation surface. These compose lower-level primitives into the tasks agents are actually asked to do.
| Tool | What it does |
|---|---|
rego_explain_decision |
Evaluate with full tracing and return the rules entered and fired, plus the trace as readable lines. The Fail lines name the condition that stopped a rule. |
rego_generate_test_skeleton |
Given a policy, generate a _test.rego skeleton with one stub per rule. Stubs are todo_test_ rules, which opa test reports as skipped until they are filled in and renamed test_. |
rego_describe_policy |
Summarize a policy's package, imports and per-rule structure from its AST. For the input references a policy reads, use rego_infer_input_schema |
rego_suggest_fix |
Pass errors from rego_check or violations from rego_lint unchanged; returns a fix suggestion per diagnostic with a confidence level, and the rule's documentation link where there is one. |
rego_coverage_gaps |
Run opa test --coverage and return per-file uncovered line ranges, sorted worst first. Use threshold to focus on files below a target percentage. |
rego_security_audit |
Run regal lint restricted to its bugs category, plus any custom rules in a security category, across a directory. Returns severity-grouped findings with remediation guidance. Modules that do not parse are listed in unparseable and the rest are audited. |
rego_infer_input_schema |
Statically analyse a policy (or directory of policies) with opa parse and return a JSON Schema describing every input.* field the policy reads. Follows loop variables, rules and function parameters bound to part of the input, so some c in input.containers then c.image gives input.containers[].image. A type is set only where the policy shows it. No running OPA required. A starting point for test inputs or a rego_check_schema schema; review it first. |
rego_fix |
Run regal fix to auto-apply mechanical fixes. Regal 0.42 and later fix opa-fmt, use-rego-v1, use-assignment-operator, no-whitespace-comment, directory-package-mismatch, non-raw-regex-pattern, prefer-equals-comparison, redundant-existence-check and constant-condition; older releases fix a subset. Use dryRun: true to preview changes first. Returns a per-file breakdown of which rules were applied and, for directory-package-mismatch, the new path the file was moved to. |
rego_format_write |
Run opa fmt --write to canonically format one or more Rego files or directories in place. Use dryRun: true to list which files would change without modifying them. Validates all files parse successfully before writing any. Supports regoV1, v0Compatible, and v1Compatible flags. Only requires opa. |
rego_policy_diff |
Evaluate the same query against two policies in parallel and compare the results. Returns equal: true/false, the raw value from each side (resultA/resultB), and changedPaths -- dot/bracket JSON paths that differ. Each side takes inline source or a file/directory path. Useful for verifying refactor equivalence or mapping divergence between two policy versions. inputs compares the two on up to 50 input documents in one call and returns batch, one entry per input, with differing counting the inputs on which they disagree. |
rego_verify |
Formally verify a property about a Rego rule using SMT solving (Microsoft Z3 via WASM). Unlike testing, this checks ALL possible inputs mathematically and either proves the property holds or returns a concrete counterexample. The kind field takes always_true, never_true or satisfiable. Handles equality, comparison, string built-ins (startswith, endswith, contains, regex.match), multi-clause rules, rule defaults, non-boolean head values, and cross-rule inlining. Reports INCONCLUSIVE rather than guessing for negation-as-failure, comprehensions, partial set and object rules, functions, else chains, and complex regex. A body reading an absent field is undefined rather than true, so always_true requires the rule to hold for an empty input too. |
rego_explain_undefined |
Explain why a Rego query is undefined, fell back to its default, or (for a set such as deny) holds no element. Combines a plain eval, a full-trace eval, and per-condition AST analysis to identify the exact body expression blocking each rule. Returns a structured breakdown of which conditions blocked each rule plus a human-readable summary. |
rego_playground_share |
Publish a policy (and optional input) as a secret GitHub Gist (pass public: true to list it) and return the link, for sharing a reproduction. Requires GITHUB_TOKEN with the gist scope; returns GITHUB_TOKEN_MISSING otherwise. |
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.
| Tool | What it does |
|---|---|
conftest_test |
Evaluate config files or an inline document against Rego policies with conftest test. Per-file, per-namespace results with arrays always present, and a summary that counts files by name. Parser names are a closed set. A run that evaluated no rule (wrong namespace, or no deny/violation/warn rules) is reported as passed: false with nothingEvaluated: true, where conftest itself exits 0. |
conftest_verify |
Run the test_* rules in a conftest policy directory with conftest verify. Reports per-rule results and NO_TESTS_FOUND when there are none. |
conftest_pull |
Pull a policy bundle from an OCI registry or Git repo into a local directory with conftest pull. The target directory need not exist; conftest creates it, and empties it first, so do not point it at one holding anything else. Omitting policy uses the conftest default, which must itself sit inside an allowed root. |
conftest_push |
Package a local policy directory as an OCI artifact and push to a registry with conftest push. Registry credentials come from the host environment (docker login, ORAS keychain, etc.) -- credentials are never passed through tools. |
// Input
{
"inlineConfig": "apiVersion: v1\nkind: Pod\nspec:\n containers:\n - name: app\n image: nginx:latest",
"inlinePolicy": "package main\ndeny contains msg if { input.spec.containers[_].image == \"nginx:latest\"; msg := \"pin your image tag\" }"
}
// Output
{
"ok": true,
"data": {
"passed": false,
"results": [
{
"filename": "<inline>",
"namespace": "main",
"successes": 0,
"failures": [{ "msg": "pin your image tag" }],
"warnings": [],
"skipped": [],
"exceptions": []
}
],
"summary": {
"passed": 0,
"failed": 1,
"warnings": 0,
"skipped": 0,
"successes": 0,
"failures": 1
}
}
}| Tool | What it does |
|---|---|
mcp_server_info |
Return server name, version, resolved opa/regal/conftest versions, transport type, Node.js version, and the allowed paths with where they came from. Useful for verifying which server instance the agent is connected to. |
Three MCP prompts ship with the server. Clients surface them as slash commands or workflow templates.
| Prompt | Purpose |
|---|---|
policy_authoring_assistant |
Walks the agent through writing a new policy: ask about the decision surface, draft, review, format, lint, test. |
policy_review_checklist |
Review checklist for an existing policy: completeness, edge cases, performance, security pitfalls. |
decision_debugging_workflow |
Diagnostic flow when a decision is unexpected: gather input, run with explain, isolate the rule, propose a fix. |
Three MCP resources expose curated reference data the agent can read at any time.
| Resource URI | What's there |
|---|---|
opa://builtins |
Categorized OPA built-in function reference, derived at read time from opa capabilities --current. Security-sensitive functions (http.send, crypto.x509.*, opa.runtime) are flagged. |
opa://style-guide |
Condensed Rego style guide, formatted for LLM consumption. |
opa://patterns |
Curated common-pattern library: RBAC, ABAC, Kubernetes admission, IaC gates, API authz, rate limiting, AI agent tool calls. Each pattern includes when-to-use, full Rego, a test, and common pitfalls. |
A few session shapes that the tool set was designed for.
You: I need an authz policy: editors can read/write, viewers can only read,
admins can do anything.
Agent: I'll draft it. (calls rego_format on a draft, then rego_check, then
rego_lint)
Agent: (calls rego_eval with an `inputs` batch: each role, no role at all,
a role that is not a string, an unknown method)
Agent: Here's the policy. A request with no role, or a role that is not a
string, is denied. I kept those probes as tests next to one case per
role. (calls rego_generate_test_skeleton, fills in the stubs, then
rego_test)
Agent: All 9 tests pass. Want me to save it to <path>?
You: This API call is being denied and I don't know why.
[pastes input.json]
Agent: (calls rego_explain_decision against your local policy with that input)
Agent: The deny comes from rule `forbid_anonymous_writes` at line 17.
Specifically, `input.user` is null and the request method is "POST".
The rule fires, which causes the default deny. To allow this, you'd
need either an authenticated user or a policy exception for this
endpoint.
You: Push policies/rbac.rego to the staging OPA server, but first lint and
test it.
Agent: (rego_lint → 2 style warnings, no errors)
(rego_test on policies/ → all pass)
(opa_put_policy with id="rbac" against $OPA_URL)
(opa_get_policy to verify)
Agent: Done. Policy `rbac` is live on staging at $OPA_URL.
┌──────────────────────────────────── @orygn/opa-mcp ───────────────────────────────────┐
│ │
│ src/server.ts ──── McpServer (stdio) ─── tool / prompt / resource registries │
│ │ │
│ ├── tools/authoring/ ─┐ │
│ ├── tools/evaluation/ ─┤ │
│ ├── tools/bundles/ ─┼─── lib/opa-cli.ts ──┐ │
│ ├── tools/server-management/ ─┤ │ │
│ ├── tools/helpers/ ─┤ │ │
│ ├── tools/conftest/ ─┤ │ │
│ ├── tools/meta/ ─┘ │ │
│ │ ▼ │
│ │ lib/subprocess.ts ──┴── opa │
│ │ lib/regal-cli.ts ───── regal│
│ │ lib/conftest-cli.ts ─ conftest│
│ │ lib/opa-client.ts ───── HTTP │
│ │ │
│ └── lib/output.ts (envelope + truncation) │
│ lib/security.ts (path allow-list) │
│ lib/errors.ts (structured failures) │
│ lib/logger.ts (file-only, never stdout) │
└───────────────────────────────────────────────────────────────────────────────────────┘
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.tsand 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 withisError: truewhose text beginsMCP 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 atry/catchthat could not see it. -
Subprocesses are bounded in time, size, and environment.
lib/subprocess.tsruns the binaries withshell: false, a hard timeout withSIGTERM-then-SIGKILLescalation, 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:opabuffers 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.tsbuilds an explicit allow-list instead. Rego can read its interpreter's environment throughopa.runtime().env, so anything passed down is readable by any policy the server evaluates, the proxy variables on the list included.
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 or write anything outside
OPA_MCP_ALLOWED_PATHSor, when it is unset, outside the folders the client shares as MCP roots. With neither, file tools returnPATH_NOT_ALLOWED. If the client's roots cannot be read, file tools are disabled rather than left on the previous list. A folder is refused when a link anywhere inside it leads outside those folders, sinceopa,regalandconftestfollow links when they walk it, and on Windows a path whose parts end in a dot or a space, or name a data stream, is refused because Windows opens something other than the path checked. - Conftest policies cannot read files by name. conftest's
parse_config_fileandparse_combined_config_filesread a file named relative to the policy, and..reaches any file on the drive, so a policy that calls them is refused unlessOPA_MCP_CONFTEST_FILE_READSis set. - 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
opaprocess throughopa.runtime().env, so a child that inheritedprocess.envwould handOPA_TOKEN,GITHUB_TOKEN, and every other variable to any policy it evaluated. Sincerego_evalaccepts 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_PROXYand 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 inOPA_MCP_BLOCK_ENVto withhold them anyway.OPA_MCP_PASSTHROUGH_ENVopts individual variables back in. OPA_TOKENis 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_evaland its variants,rego_test,rego_test_multiroot,rego_bench,rego_compile_query,opa_exec,rego_migrate_v1(when giveninputs), 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'shttp.sendlets a policy reach, and write to, any network address. A client that gates on the hints will ask before running one.opa_query_decisionandopa_compile_queryare 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, sohttp.sendcannot be restricted for evaluation;rego_checkandopa_bundle_buildaccept 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 ofopaandregalchecked against their published digests.
To report a vulnerability, follow SECURITY.md. Please do not open a public issue for security problems.
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:
# macOS / Linux
which opa
# → /usr/local/bin/opa (or /opt/homebrew/bin/opa, or ~/.local/bin/opa)# Windows
Get-Command opa | Select-Object -ExpandProperty Source
# → C:\Users\you\bin\opa.exe (or wherever)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.
Without OPA_MCP_ALLOWED_PATHS, the server allows only the folders the
client shares as MCP roots, and not every client shares them.
mcp_server_info lists the allowed paths and where they came from. Set
OPA_MCP_ALLOWED_PATHS 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.
git clone https://github.com/OrygnsCode/opa-mcp-server.git
cd opa-mcp-server
npm install
npm run devCommon commands:
npm run lint # ESLint
npm run typecheck # tsc --noEmit
npm test # unit tests (Vitest)
npm run test:coverage # unit + coverage report
npm run test:integration # against real opa + regal binaries
npm run build # compile to dist/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.
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.
@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.
