# OrygnsCode/opa-mcp-server [Health: Active]

**Category:** 💻 Developer Tools  
**Repository:** https://github.com/OrygnsCode/opa-mcp-server  
**GitHub Stars:** 9  
**npm Downloads (last month):** 1066  
**Views:** 3  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/orygnscode-opa-mcp-server

## Description
Open Policy Agent (OPA) and Rego policy toolkit. 32 tools spanning authoring (format, lint, check, deps), evaluation (eval, test, bench, coverage), and OPA REST control (policies, data, decisions, compile). Wraps the OPA CLI and the Regal linter, with AI-assisted helpers for explaining decisions, generating test skeletons, and suggesting fixes.

## Tools
Capabilities this server exposes over MCP:

- **rego_format** — Format Rego source code using `opa fmt`. Returns the formatted source and a `changed` flag indicating whether the input was already canonical. When the source uses string interpolation ($"..." or $`...` syntax) and OPA v1.12.0 or v1.12.1 is detected, the tool warns about or blocks formatting due to a known OPA bug that corrupts \{ escape sequences (fixed in OPA v1.12.2).
- **rego_check** — Type-check Rego with `opa check`. Returns `{ valid: true, errors: [] }` on success, or a list of structured diagnostics with file/line locations on failure. Provide either `source` for inline checking or `paths` for file/directory checking.
- **rego_check_schema** — Validate that a Rego policy's input.* field references are consistent with a JSON Schema using `opa check --schema`. Every field the policy reads from `input` must exist in the schema; mismatches surface as rego_type_error diagnostics with file/line locations. Returns `{ valid: true, errors: [] }` when all references match the schema, or `{ valid: false, errors: [...] }` with structured diagnostics when they do not. Accepts the schema inline (pass the `schema` output of `rego_infer_input_schema` directly as `inlineSchema`) or as a path to a JSON Schema file on disk, or to a schema directory when the policy declares `schemas:` annotations (`schemaPath`). Provide `source` for inline Rego or `paths` for file/directory checking.
- **rego_lint** — Lint Rego source with the Regal linter. Returns categorized violations (style, bugs, idiomatic, performance) with file/line locations. Requires `regal` on PATH or `REGAL_BINARY` set; returns REGAL_NOT_FOUND otherwise. When called with inline `source`, location-bound rules whose verdict depends on the on-disk path (`directory-package-mismatch`) are auto-disabled to avoid temp-file false positives, and `location.file` is reported as `<inline>` instead of the randomized temp path. Re-enable those rules via `enable` if your workflow actually needs them.
- **rego_parse_ast** — Parse Rego source to a JSON AST using `opa parse`. Returns the AST as a tree of nodes (package, imports, rules, expressions, terms). Use this when you need to introspect policy structure programmatically.
- **rego_inspect** — Inspect an OPA bundle, policy directory, or single Rego file with `opa inspect`. Returns manifest data, namespaces, rule annotations, and (if signed) signature metadata.
- **rego_capabilities** — Return OPA capabilities -- the available builtins, future keywords, features, and WASM ABI versions. With `current: true`, returns the running OPA's capabilities. With `version: "v1.19.0"`, returns those of a specific version. With neither, lists available named versions. By default (`names_only: true`), returns only builtin names and count to stay within response size limits. Pass `builtins: [...]` for the full type signatures and documentation of a few named builtins; `names_only: false` returns every full record, which needs OPA_MCP_MAX_RESPONSE_BYTES raised above its default.
- **rego_deps** — Static dependency analysis for a Rego reference. Given a target ref like "data.example.allow", returns the base document references (input/data leaves) and virtual document references (rules) it depends on, transitively.
- **rego_migrate_v1** — Migrate Rego v0 source to Rego v1 syntax in two phases: (1) `opa fmt --rego-v1` auto-fixes reserved keywords (`if`, `contains`, `every`, `in` in rule heads) and adds `import rego.v1`; (2) `opa check --v1-compatible` validates the migrated source and reports any remaining issues that cannot be auto-fixed (e.g. removed builtins, semantic conflicts). Returns the migrated source and a `changed` flag even when check finds remaining errors -- this lets you inspect what changed and fix the remainder manually. If the source cannot be parsed, or uses a built-in that v1 removed and so fails type checking in the first phase, returns `INVALID_REGO` with opa's own message.
- **rego_eval** — Evaluate a Rego query against a policy and an input document using `opa eval`. Returns the standard `{result: [...]}` shape. The bread-and-butter authoring tool.
- **rego_eval_with_explain** — Evaluate with `--explain=full` and return a structured trace alongside the result. Use this when an agent needs to see why a rule fired (or didn't) -- the trace is the basis for `rego_explain_decision`.
- **rego_eval_with_profile** — Evaluate with `--profile` and return per-rule timing and evaluation counts. Use this to find hot rules in slow policies.
- **rego_eval_with_coverage** — Evaluate with `--coverage` and return per-line coverage data. Useful for verifying that tests actually exercise the rules they're meant to.
- **rego_test** — Run Rego unit tests with `opa test`. Returns aggregate pass/fail/skip/error counts plus per-test records. `errored` counts tests OPA could not evaluate (a rule conflict, a raising built-in); such a test is neither a pass nor a failure, and a suite with any is not passing. Tests live in `*_test.rego` files; rule names beginning with `test_` are picked up automatically. Use `runPattern` to filter by name regex; when no tests match, the error hint includes the pattern you supplied. Use `threshold` to gate on minimum coverage (returns COVERAGE_BELOW_THRESHOLD on failure). Use `varValues: true` with `verbose: true` to include local variable bindings in the trace -- essential for debugging table-driven tests written with `every tc in cases { ... }` to identify which case caused a failure. When tests use the `test_x[case]` parameterized form, OPA reports the rule as a single test whatever the number of cases; `parameterizedGroups` maps the rule name to a record per case and `caseCounts` totals them, so a failing rule says which case failed. Use `ignorePatterns` to exclude generated or fixture files. Use `bundle: true` when testing bundle-structured policy directories. Use `timeout` to raise the per-test limit beyond OPA's default 5s. Note: enabling `coverage` or `threshold` switches OPA to coverage-report output mode -- per-test counts are unavailable but `coverage` and `coveragePct` fields are populated.
- **rego_test_multiroot** — Run `opa test` once per root and aggregate results. Solves the package-conflict problem that occurs when `opa test .` is run on a repo with multiple independent package namespaces (OPA issue #4724). Two modes: `explicit` (supply root list with optional per-root `include` paths for shared libraries) and `scan` (auto-discover leaf test roots using the leaf rule -- a directory is a root only if it directly contains `*_test.rego` files and none of its eligible subdirectories do, preventing OPA's automatic recursion from double-running tests). Use `sharedPaths` in scan mode to add shared library directories to every root's invocation without including them in discovery. Coverage and threshold work per-root; `overallCoveragePct` is the mean across roots that have coverage data.
- **rego_bench** — Benchmark a Rego query against a policy + input with `opa bench`. Returns statistical timing data: iterations, ns/op, and allocation counts. Use this to spot slow rules.
- **rego_compile_query** — Run partial evaluation on a query -- substitute known values and return the residual policy. Defaults `unknowns` to `["input"]` (treat input as unknown), so the residual encodes "given input X, this is what would have to be true." Use this for offline policy slicing or pre-computing decision sets.
- **opa_exec** — Evaluate a policy decision against one or more input files using `opa exec --format=json`. Unlike `rego_eval` (single input), `opa exec` processes every file independently and returns a per-file result -- ideal for CI pipelines that check many config files against a policy in one call. Supply `bundle` for bundle-based policies or `dataPaths` for raw policy files; these are mutually exclusive. Each file that fails evaluation appears in `results` with an `error` field rather than a `result` field. Set one of `fail`/`failDefined`/`failNonEmpty` to turn the call into a CI gate: the result then reports `failed: true` (instead of erroring) when the gate condition is met.
- **opa_bundle_build** — Build a deployable bundle from policy / data paths using `opa build`. Output is a `.tar.gz` archive with optional inline signing. Supports optimization, custom revision strings, and the WASM target.
- **opa_bundle_sign** — Sign a bundle directory with `opa sign`. A directory is signed in place: `.signatures.json` is written into it and files are recorded as `<directory name>/<file>`, so the signed directory verifies wherever it is placed as long as its name is unchanged, with `opa_bundle_verify` or with `opa build` or `opa run --bundle <name>` from its parent. An archive is refused: OPA reads the signature from inside it, so a signed archive comes from `opa_bundle_build` with `signingKey`. The key is a PEM private key (RSA or ECDSA); for HMAC algorithms pass a file holding the secret. Extra claims such as `keyid` and `scope` come from `claimsFile`. Returns the path written, the algorithm, and the number of files covered.
- **opa_bundle_verify** — Verify the signature of a signed bundle directory or `.tar.gz` archive with the public key. OPA has no standalone verify command, so this runs `opa build --verification-key` into a private temp file that is discarded. A directory is verified by name from its parent, matching how `opa_bundle_sign` signs it. OPA reads the key, checks the JWT in `.signatures.json`, compares the scope claim, then checks every file: Rego files by digest before parsing, data files and `.manifest` by parsed value, so an unparseable data file fails before its digest is compared. Failures return `INVALID_BUNDLE` with `details.reason` set to one of signature_invalid, scope_mismatch, file_modified, file_added, file_missing, file_unparseable, unsigned, signatures_malformed, not_a_bundle, bundle_load_error, or unknown when the message is not recognised; the raw output is in `details`. A key or algorithm OPA cannot use returns `INVALID_INPUT`. Pass `scope` exactly as the bundle was signed with. With a single key OPA does not check `verificationKeyId` against the signature keyid claim. `verified: true` is returned only when OPA loaded the bundle with its signature intact.
- **opa_list_policies** — List policies registered on the running OPA server. Returns the policy IDs and a count. Set `includeSource` for the Rego text of every policy, or `includeAst` for the parsed AST of every policy; both are off by default because either one pushes a list of any real size past the response cap.
- **opa_get_policy** — Fetch a single policy by ID from the running OPA server. Returns the Rego source; the parsed AST is omitted unless asked for, since it is roughly forty times the size of the source it came from. Use `rego_parse_ast` on the source when an AST is what's wanted.
- **opa_put_policy** — Upload a Rego policy under the given ID. Replaces any existing policy with that ID. The policy is uploaded as raw text/plain -- OPA parses it on the server side.
- **opa_delete_policy** — Delete a policy by ID from the running OPA server.
- **opa_get_data** — Read a path from OPA's data hierarchy. A `path` is read as dotted (`users.alice`) unless it contains a slash, in which case slash is the only separator (`users/alice`), so a key such as `example.com` is addressable as `hosts/example.com`. Pass `segments` instead when a key contains both.
- **opa_put_data** — Write or replace a value at the given data path. Body is sent as JSON. A `path` is read as dotted (`users.alice`) unless it contains a slash, in which case slash is the only separator (`users/alice`), so a key such as `example.com` is addressable as `hosts/example.com`. Pass `segments` instead when a key contains both.
- **opa_patch_data** — Apply a JSON Patch (RFC 6902) to the data document. Each operation is `{ op, path, value? }`. Omit both `path` and `segments` to patch the root of the data hierarchy, which is how a whole new top-level document is added.
- **opa_delete_data** — Remove a document from OPA's data store at the given path. A `path` is read as dotted (`users.alice`) unless it contains a slash, in which case slash is the only separator (`users/alice`), so a key such as `example.com` is addressable as `hosts/example.com`. Pass `segments` instead when a key contains both. OPA responds with 204 No Content on success; if no document exists at the path, OPA returns 404 which is mapped to `DATA_NOT_FOUND`. Root-path deletion (`/v1/data/` itself) is intentionally excluded -- supply at least one path segment.
- **opa_query_decision** — Evaluate a decision against the running OPA server. POSTs to the data path with `{input}` and returns whatever the rule produces. Use this to ask the server "given this input, what does data.X.allow say?"
- **opa_compile_query** — Send a query to the OPA server's `/v1/compile` endpoint for partial evaluation. Returns the residual query -- what remains after substituting in everything that's known.
- **opa_health** — Hit the OPA `/health` endpoint. A server that answers reports `{ healthy: true }` on 200 and `{ healthy: false }` with OPA's own reason otherwise, so an unactivated bundle is a health result rather than a tool error. `OPA_UNREACHABLE` means the server could not be reached at all. Supports `bundles` and `plugins` query flags to require those subsystems to also be healthy.
- **opa_status** — Return the running OPA server configuration via `GET /v1/config`. Returns the same underlying document as `opa_config` but presented under a `status` key as a convenience for agents that want to check "what is running" rather than "what was the server configured with". The response includes bundle settings, decision-log settings, and plugin configuration as OPA reported them at startup. Service header values are redacted, since OPA returns them verbatim and a header is the ordinary place to put an API key.
- **opa_config** — Return the running OPA server configuration from `GET /v1/config`. OPA drops the `credentials` block but returns `services.*.headers` verbatim, which is the ordinary place to put an API key or a bearer token, so those values are redacted here and the header names kept.
- **rego_explain_decision** — Evaluate a Rego query with full tracing and return a structured trace plus per-rule fired/not-fired summary. Use this when you need to answer "why was this denied?" -- the agent reads the structured trace and narrates the cause without re-implementing the trace parser.
- **rego_explain_undefined** — Diagnose why a fully-qualified Rego query (e.g. "data.authz.allow") produces no value, or falls back to its default. Combines a plain eval, a full-trace eval, and per-condition AST analysis to identify the exact body expression blocking each rule. Handles both runtime failures (trace-based) and indexer elimination (standalone condition eval). A rule written with `default allow := false` always has a value, so `queryResult` reports `default` for it and the same per-rule breakdown follows: the question "why is allow false" is the question this answers. Returns a structured breakdown of which conditions blocked each rule plus a human-readable summary.
- **rego_generate_test_skeleton** — Generate a `*_test.rego` skeleton from a policy. Parses the AST, finds each non-test rule, and emits one stub test per rule. Existing `test_*` and `todo_test_*` rules are skipped automatically -- only production rules get stubs, and a value rule whose head is computed gets a `todo_test_` stub, which `opa test` reports as skipped until its expected value is filled in and it is renamed `test_`. The AST is walked to infer which `input.*` fields the policy accesses; the inferred shape is used as the placeholder `with input as {...}` in each stub, so the developer only needs to fill in realistic values rather than guess the structure. With `tableStyle: true`, each stub uses an `every tc in cases { ... }` loop so you can add multiple input/expected pairs without duplicating assertion code. The `inferredInputShape` field in the response shows the detected shape for reference.
- **rego_describe_policy** — Parse a Rego policy and return a structured summary: package, imports, and rules. Each rule reports clauseCount (how many definitions share the name), isDefault (true if any clause is a default), hasArgs, bodyLength (total body expressions across all clauses), and inline annotations. Useful as the first step in any "what does this policy do" workflow.
- **rego_suggest_fix** — Map common Rego compile errors and Regal lint findings to mechanical fix suggestions. Pass diagnostics from `rego_check` or `rego_lint`. Returns one suggestion per input diagnostic; confidence is `high` for well-known patterns, `medium` for partial matches, `low` for everything else.
- **rego_coverage_gaps** — Run opa test --coverage and return a per-file breakdown of uncovered line ranges. Identifies which rules or branches are not yet exercised by tests. Files are sorted by coverage ascending so the worst-covered files appear first. Use threshold to limit the report to files below a target coverage percentage.
- **rego_security_audit** — Run regal lint restricted to its `bugs` category, the correctness rules whose defects most often turn into policy bypasses, plus any custom rules placed in a `security` category, across one or more policy directories. Returns findings grouped by severity (high/medium) with remediation guidance. Use this for a periodic fleet-wide sweep rather than per-file style review. Requires regal.
- **rego_infer_input_schema** — Statically analyse one or more Rego policies and return a JSON Schema (draft-07) object describing every input.* field the policies read. Uses opa parse for AST-level analysis -- no running OPA server required. Correct starting point for writing integration tests, configuring opa check --schema validation, or documenting a policy API. Accepts inline source, individual files, or directories (walked recursively for *.rego files).
- **rego_fix** — Run regal fix to automatically apply mechanical fixes for the five rules regal 0.30.0 supports: opa-fmt, use-rego-v1, use-assignment-operator, no-whitespace-comment, and directory-package-mismatch. Use dryRun: true to preview changes before modifying files. NOTE: directory-package-mismatch moves files to match their package path -- use disable: ["directory-package-mismatch"] to skip it. Files with uncommitted git changes require force: true. Requires regal.
- **rego_format_write** — Run `opa fmt --write` to canonically format one or more Rego files or directories in place. Use `dryRun: true` to preview which files would change without modifying them. Returns a list of files that were (or would be) reformatted. Unlike `rego_format` which returns formatted source as a string, this tool writes directly to disk. Supports `regoV1`, `v0Compatible`, and `v1Compatible` flags for version-specific formatting. If any file cannot be parsed, the operation is aborted and no files are written.
- **rego_policy_diff** — Evaluate the same query against two policies (or two versions of the same policy) and compare the results. Both evaluations run in parallel. Returns `equal: true/false`, the raw result from each side, and `changedPaths` -- the dot/bracket paths that differ. Useful for verifying that a refactor preserves behavior, or understanding exactly where two policies diverge. Each side takes either inline source (sourceA/sourceB) or a file/directory path (pathA/pathB). The same input and query are used for both evaluations.
- **rego_verify** — Formally verify a property about a Rego rule using SMT solving (Microsoft Z3). Unlike testing, this checks ALL possible inputs and either proves the property holds or returns a concrete counterexample input that falsifies it. Supports equality, comparison, startswith, endswith, contains, and simple regex.match patterns (prefix: ^lit.*, suffix: .*lit$, exact: ^lit$, contains: .*lit.*, wildcard: .*). Complex regex patterns (character classes, quantifiers, alternation) return INCONCLUSIVE. Also reports INCONCLUSIVE for negation-as-failure (not), comprehensions, partial set and object rules (deny contains msg), functions, else chains, and any operand it cannot encode. A body that reads an absent field is undefined rather than true, so always_true holds only if the rule is also true for an empty input: a rule requiring input.x will be answered with the counterexample {}.
- **rego_playground_share** — Share a Rego policy with teammates or create a reproducible example by publishing it as a GitHub Gist, secret unless `public: true` is passed, so only people holding the link can read it. Returns { gistUrl, rawPolicyUrl, id, public }: the gistUrl renders the policy with syntax highlighting on github.com; the rawPolicyUrl can be passed directly to OPA (`opa eval -d <rawPolicyUrl> <query>`) or used as a data source in Conftest. When query, input, or data are supplied, a metadata.json file is bundled into the Gist so recipients have the full evaluation context to reproduce results. Each call creates a new Gist -- use the returned id to reference it later. Requires GITHUB_TOKEN in the environment (GitHub personal access token with the "gist" scope); returns GITHUB_TOKEN_MISSING with setup instructions if unset.
- **conftest_test** — Evaluate configuration files (Kubernetes manifests, Terraform plans, Dockerfiles, Helm charts, or any YAML/JSON/HCL/TOML/INI) against Rego policies using `conftest test`. Returns per-file, per-namespace pass/fail/warn results so you can pinpoint exactly which policy rules fired. Requires `conftest` on PATH or `CONFTEST_BINARY` set; returns CONFTEST_NOT_FOUND otherwise. Provide config via `files` (disk paths) or `inlineConfig` (inline string). Provide policy via `policy` (disk path) or `inlinePolicy` (inline Rego source). Omit `policy` and `inlinePolicy` to use conftest's default `./policy` directory. Policies are executed by conftest and can call OPA built-ins such as http.send.
- **conftest_verify** — Run the `test_*` rules inside `*_test.rego` files within a conftest policy directory, verifying that the policies themselves are correct. Equivalent to `opa test` but using conftest's policy-loading machinery. Returns per-file pass/fail results, and NO_TESTS_FOUND when the directory holds no test rules. Requires `conftest` on PATH or `CONFTEST_BINARY` set; returns CONFTEST_NOT_FOUND otherwise.
- **conftest_pull** — Download Rego policies from an OCI registry or Git repository into a local directory using `conftest pull`. Use this to hydrate a local `policy/` directory before running `conftest_test`. Requires `conftest` on PATH or `CONFTEST_BINARY` set. The `policy` directory must be inside OPA_MCP_ALLOWED_PATHS. SECURITY: pulled policies are arbitrary Rego source that will be executed by `conftest_test`. Only pull from registries or repositories you own or explicitly trust -- malicious policy code can use OPA built-ins (http.send, opa.runtime) to exfiltrate data or make outbound network requests when the tests run.
- **conftest_push** — Package the local Rego policy directory as an OCI artifact and push it to a registry using `conftest push`. Registry credentials must be pre-configured in the host environment (docker login, ORAS keychain, etc.) -- this tool never handles credentials. The `policy` directory must be inside OPA_MCP_ALLOWED_PATHS. Requires `conftest` on PATH or `CONFTEST_BINARY` set.
- **mcp_server_info** — Return the name, version, and runtime details of this opa-mcp server instance. Use this when you need to confirm which version of opa-mcp is running, or to verify that the OPA, Regal, and Conftest binaries are reachable.

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `npx` (confidence: high):

```json
"mcpServers": {
  "opa-mcp-server": {
    "command": "npx",
    "args": ["-y","@orygn/opa-mcp"]
  }
}
```

## Documentation

## What OrygnsCode/opa-mcp-server does

OrygnsCode/opa-mcp-server connects MCP clients to Open Policy Agent (OPA), Rego policy files, the Regal linter, and a running OPA server. Its tools cover the policy lifecycle: formatting and type-checking source, validating input references against JSON Schema, inspecting syntax trees and bundles, analyzing dependencies, migrating Rego v0 to v1, evaluating decisions, running tests, measuring coverage and performance, and compiling partial queries.

It also handles bundle delivery and OPA administration. Policies can be built, signed, and verified; policies and data can be listed, retrieved, uploaded, changed, or deleted through OPA's REST API; and decisions can be evaluated against the server's data hierarchy.

## How it works

The server runs locally over MCP stdio. CLI-oriented tools invoke OPA commands such as `fmt`, `check`, `eval`, `test`, `bench`, `build`, `parse`, `inspect`, and `exec`. Regal is invoked for linting when its executable is available. REST-oriented tools send requests to a configured OPA HTTP endpoint.

Responses use structured JSON rather than requiring an agent to interpret terminal text. Depending on the operation, results include diagnostics with file and line locations, evaluation results, execution traces, coverage information, benchmark statistics, test counts, or bundle verification details. Evaluation variants expose full traces, rule profiles, or per-line coverage. Multi-root testing runs OPA separately for independent policy namespaces and aggregates the results.

## Setup and configuration

The package is available through npm as `@orygn/opa-mcp`; a typical client starts it with `npx -y @orygn/opa-mcp`. It can also be installed through the downloadable MCP bundle. The server requires Node.js 22 or later. Configure the OPA executable with `OPA_BINARY` when using a custom installation, and set `REGAL_BINARY` when Regal is not available on `PATH`. `OPA_URL` selects the OPA server used by REST tools, while `OPA_MCP_ALLOWED_PATHS` limits filesystem access to approved policy locations.

Claude Desktop and Claude Code examples use absolute executable and policy paths. The server can connect to a local `opa run --server` process or an OPA deployment using bearer-token authentication.

## Tools and capabilities

- Format, parse, type-check, lint, inspect, and migrate Rego source.
- Validate `input` references against inline or file-based JSON Schema.
- Evaluate, explain, profile, benchmark, and measure coverage for policy queries.
- Run filtered tests, coverage gates, parameterized cases, fixtures, and multi-root suites.
- Build, sign, and verify deployable OPA bundles.
- Execute decisions across multiple input files with CI-style failure gates.
- Manage OPA policies and data, then query decisions through the REST API.

## Limitations and notes

Regal-dependent linting returns an error when its executable cannot be found. Formatting Rego containing string interpolation is guarded when OPA 1.12.0 or 1.12.1 is detected because those versions can corrupt escaped sequences; OPA 1.12.2 fixes that issue. Response-size limits affect large capability, policy, AST, and coverage responses. OPA's root data document cannot be deleted through the delete-data tool, and signed archives must be produced through bundle building rather than signing an archive in place.

_Full upstream README: https://allmcps.com/mcp/orygnscode-opa-mcp-server/readme_

