{
  "markdown": "# OPA MCP Server\n\n[![CI](https://github.com/OrygnsCode/opa-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/OrygnsCode/opa-mcp-server/actions/workflows/ci.yml)\n[![CodeQL](https://github.com/OrygnsCode/opa-mcp-server/actions/workflows/codeql.yml/badge.svg)](https://github.com/OrygnsCode/opa-mcp-server/actions/workflows/codeql.yml)\n[![npm version](https://img.shields.io/npm/v/@orygn/opa-mcp.svg)](https://www.npmjs.com/package/@orygn/opa-mcp)\n[![Docker pulls](https://img.shields.io/docker/pulls/orygn/opa-mcp.svg)](https://hub.docker.com/r/orygn/opa-mcp)\n[![OPA Ecosystem](https://img.shields.io/badge/OPA-ecosystem-blue.svg)](https://www.openpolicyagent.org/ecosystem/entry/opa-mcp)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)\n[![Node.js](https://img.shields.io/node/v/@orygn/opa-mcp.svg)](./package.json)\n[![opa-mcp-server MCP server](https://glama.ai/mcp/servers/OrygnsCode/opa-mcp-server/badges/score.svg)](https://glama.ai/mcp/servers/OrygnsCode/opa-mcp-server)\n\nA [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server\nthat turns any MCP-compatible client (Claude Desktop, Claude Code, Cursor,\nVS Code, Windsurf, Zed, and others) into a first-class\n[Open Policy Agent](https://www.openpolicyagent.org/) and Rego authoring\nenvironment.\n\n```\n+--------------------+ MCP/stdio  +-----------------+ spawn/HTTP +---------------------+\n|  Claude · Cursor · |----------> | @orygn/opa-mcp  |----------> | opa · regal         |\n|   VS Code · ...    |<---------- |                 |<---------- | conftest · REST API  |\n+--------------------+  52 tools  +-----------------+            +---------------------+\n```\n\n> **Status:** v0.6.0. Tool surface, error codes, and\n> environment variables follow [SemVer](https://semver.org/) from\n> v0.1.0 forward.\n\n> **Upgrading to 0.6.0:** `rego_bench` reports `iterations`, `nsPerOp`,\n> `allocsPerOp` and `bytesPerOp`. The fields opa prints (`N`, `T`, `Bytes`,\n> `MemAllocs`, `MemBytes`, `Extra`) were top-level and now sit under `raw`\n> for a single run, so anything that read them from the top level has to\n> look there. With `count` above one, `raw` is omitted: every document is in\n> `runs`, and `fastest` indexes the one the top-level figures come from.\n\n> **Upgrading to 0.4.0:** subprocesses no longer inherit the server's\n> environment. A policy that read a variable through `opa.runtime().env`\n> will no longer see it; name the variable in `OPA_MCP_PASSTHROUGH_ENV` if\n> it is genuinely needed. See the security section for why.\n\n> **Upgrading to 0.3.0:** the bundled OPA is now 1.19, so Rego v0 policies\n> no longer parse (`if` is required before a rule body, `contains` before a\n> partial set). Run `rego_migrate_v1` to convert them. If you supply your own\n> binary via `OPA_BINARY` or `PATH`, nothing changes.\n\n---\n\n## Table of contents\n\n- [What you can do with it](#what-you-can-do-with-it)\n- [Why this MCP](#why-this-mcp)\n- [Install](#install)\n- [Configuration](#configuration)\n- [Tool reference](#tool-reference)\n- [Prompts](#prompts)\n- [Resources](#resources)\n- [Cookbook](#cookbook)\n- [Architecture](#architecture)\n- [Security](#security)\n- [Troubleshooting](#troubleshooting)\n- [Development](#development)\n- [Versioning & support](#versioning--support)\n- [License](#license)\n\n## What you can do with it\n\nOnce an MCP client is connected, an agent can:\n\n- **Author Rego.** Generate, format, and refactor policies. The server\n  runs the real `opa fmt` and `opa parse` so output is byte-identical to\n  what you'd get on the command line, and `regal` (optional) surfaces\n  idiomatic suggestions.\n- **Evaluate against data.** Run a query against a policy and an input\n  document. Optional `--explain`, `--profile`, and `--coverage` flags\n  surface execution traces, hot rules, and per-line coverage.\n- **Debug a deny.** `rego_explain_decision` walks the agent through every\n  rule that fired (and every one that didn't), so it can answer \"why was\n  this rejected\" without you reading the trace by hand.\n- **Manage policies on a running OPA.** List, get, put, delete policies on\n  an OPA server through its REST API. Works against a local\n  `opa run --server` or a production deployment with bearer-token auth.\n- **Build & sign bundles.** Package a directory of policies into a\n  deployable bundle, optionally signing it. Output is a regular `.tar.gz`\n  the agent can hand to your delivery system.\n- **Lint.** `rego_lint` runs Regal across a directory or a single file\n  and returns each finding with its category, level and location.\n\nA walk-through of a typical session lives in [Cookbook](#cookbook).\n\n## Why this MCP\n\nOPA already has a perfectly good CLI and REST API. So why an MCP wrapper?\n\n- **Schema-shaped tool surface.** An agent calling `rego_eval` gets a\n  validated input schema, a structured output envelope, and stable error\n  codes, instead of parsing free-form CLI text and inventing its own\n  failure taxonomy. That alone makes Rego usable to an agent the way a\n  language server makes a language usable to an IDE.\n- **Higher-level helpers.** `rego_explain_decision`,\n  `rego_generate_test_skeleton`, `rego_describe_policy`, and\n  `rego_suggest_fix` compose the lower-level primitives into the tasks\n  agents are actually asked to do. They don't exist in the OPA CLI.\n- **Curated knowledge.** The bundled MCP **resources** expose the OPA\n  built-in function catalog, the official Rego style guide (formatted for\n  LLMs), and a curated pattern library covering RBAC, ABAC, Kubernetes\n  admission, IaC gates, API authz, and rate limiting, so the agent has\n  authoritative context without needing to scrape it.\n- **Safety boundaries the agent can rely on.** Path allow-list,\n  subprocess timeouts, and response-size caps. Defaults are conservative;\n  running the server doesn't quietly grant the agent more reach than the\n  operator intended.\n\nIf you've ever watched an agent fight `opa eval`'s argument order, you'll\nrecognize the gap this fills.\n\n## Install\n\nThe server runs locally over stdio. Pick the install path that matches\nyour client.\n\n### Claude Desktop\n\nEdit `claude_desktop_config.json` directly (or copy from\n[`examples/claude-desktop.json`](./examples/claude-desktop.json)):\n\n```json\n{\n  \"mcpServers\": {\n    \"opa\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@orygn/opa-mcp\"],\n      \"env\": {\n        \"OPA_BINARY\": \"/usr/local/bin/opa\",\n        \"REGAL_BINARY\": \"/usr/local/bin/regal\",\n        \"OPA_URL\": \"http://localhost:8181\",\n        \"OPA_MCP_ALLOWED_PATHS\": \"/path/to/your/policies\"\n      }\n    }\n  }\n}\n```\n\n> Replace the `/usr/local/bin/...` paths with your real ones. See the\n> [first-time install gotcha](#-first-time-install-gotcha-read-this-if-you-used-npx-or-the-global-install)\n> below. Windows users substitute `C:\\\\path\\\\to\\\\opa.exe`.\n\nOr download `opa-mcp.mcpb` from the\n[latest release](https://github.com/OrygnsCode/opa-mcp-server/releases/latest)\nand double-click it.\n\nAlternatively, use the Smithery one-liner:\n\n```bash\nnpx -y @smithery/cli install @orygn/opa-mcp --client claude\n```\n\n### Claude Code (CLI)\n\nRegister the server for the current project with `claude mcp add`:\n\n```bash\nclaude mcp add \\\n  --env OPA_BINARY=/usr/local/bin/opa \\\n  --env REGAL_BINARY=/usr/local/bin/regal \\\n  --env OPA_MCP_ALLOWED_PATHS=/path/to/your/policies \\\n  opa -- npx -y @orygn/opa-mcp\n```\n\nThis writes the config into `.mcp.json` at your project root and is\npicked up automatically on every `claude` session in that directory.\nAdd `--scope user` to register it globally instead.\n\n> Replace the paths with your real absolute paths (same caveat as\n> Claude Desktop above). On Windows use `C:\\path\\to\\opa.exe` syntax.\n\n**Persistent context and auto-checks for policy repos.**\nIf you work in an OPA policy repo regularly, two extra files remove\nrepetitive setup from every session:\n\n- [`examples/CLAUDE.md`](./examples/CLAUDE.md) -- copy to your repo\n  root or `.claude/CLAUDE.md`. Claude Code loads it every session,\n  so the agent always knows which tools to use and what conventions apply.\n- [`examples/claude-code-hook.json`](./examples/claude-code-hook.json) --\n  merge the `hooks` block into `.claude/settings.json`. Runs `opa check`\n  automatically after any `.rego` file is written, so syntax errors\n  surface immediately without a manual tool call.\n\n### Cursor\n\nDrop [`examples/cursor.json`](./examples/cursor.json) into either\n`.cursor/mcp.json` (project-scoped) or `~/.cursor/mcp.json` (user-scoped).\n\n### VS Code (GitHub Copilot Chat)\n\nDrop [`examples/vscode.json`](./examples/vscode.json) into\n`.vscode/mcp.json`, or paste the `servers` block into your user\n`settings.json` under `mcp.servers`.\n\n### Windsurf, Zed, and others\n\nSee [`examples/`](./examples) for a full set of drop-in configs.\n\n### Manual install (any MCP client)\n\n```bash\nnpm install -g @orygn/opa-mcp\nopa-mcp --version\n```\n\nthen point your client at the `opa-mcp` binary.\n\n### Docker\n\n```bash\ndocker pull orygn/opa-mcp:latest\ndocker run --rm -i \\\n  -v /path/to/your/policies:/policies:ro \\\n  -e OPA_MCP_ALLOWED_PATHS=/policies \\\n  orygn/opa-mcp\n```\n\nThe image is multi-arch (`linux/amd64`, `linux/arm64`), bundles pinned\nversions of `opa` and `regal`, and runs as a non-root user. No host\ninstall of OPA or Regal is required.\n\n### ⚠ If every tool call returns `OPA_BINARY_NOT_FOUND`\n\nThe npm package carries its own `opa` for the five platforms it is built\nfor, so a client `PATH` without `opa` on it does not matter there. The MCPB\nhas no bundled copy, and on any other platform neither does npm: then the\nserver boots but every tool call returns `OPA_BINARY_NOT_FOUND`. Neither the\nnpm package nor the MCPB bundles `regal` or `conftest`, and the Docker image\nships `regal` but not `conftest`, so their tools need a `PATH` entry or an\nexplicit path either way.\n\n**Fix:** add `OPA_BINARY` and `REGAL_BINARY` env entries to your client\nconfig with the absolute path to each binary. The example configs under\n[`examples/`](./examples) ship with placeholder paths you replace.\nFind the real paths with:\n\n```bash\nwhich opa && which regal                                    # macOS / Linux\n```\n\n```powershell\nGet-Command opa, regal | Select-Object Source              # Windows\n```\n\nThis does not affect the **Docker** install path, which ships `opa` and\n`regal` in the image and bypasses `PATH` entirely. The **MCPB** bundle\ncarries neither, and unlike the npm install has no bundled fallback: set\n`OPA_BINARY` or put `opa` on `PATH`.\nSee [Troubleshooting](#troubleshooting) for full detail.\n\n## Configuration\n\nThe server reads its configuration from environment variables. Every\nvariable is optional; defaults are sensible for a local OPA on\n`http://localhost:8181`.\n\n| Variable                       | Default                      | Purpose                                                                                                                                                                                                                                                                                      |\n| ------------------------------ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `OPA_URL`                      | `http://localhost:8181`      | Base URL of an OPA REST endpoint, used by `opa_*` tools.                                                                                                                                                                                                                                     |\n| `OPA_TOKEN`                    | _(unset)_                    | Bearer token for OPA, if your instance requires auth. Treated as a secret. Never echoed in logs or tool responses.                                                                                                                                                                           |\n| `OPA_BINARY`                   | `opa` (on `PATH`)            | Path to the `opa` CLI, used by `rego_*` tools.                                                                                                                                                                                                                                               |\n| `REGAL_BINARY`                 | `regal` (on `PATH`)          | Path to the `regal` linter. Required by `rego_lint`, `rego_fix`, and `rego_security_audit`.                                                                                                                                                                                                  |\n| `CONFTEST_BINARY`              | `conftest` (on `PATH`)       | Path to the `conftest` binary. Only required by `conftest_*` tools. Returns `CONFTEST_NOT_FOUND` if absent.                                                                                                                                                                                  |\n| `OPA_MCP_ALLOWED_PATHS`        | _(unset)_                    | Comma- or semicolon-separated list of directories the server is allowed to read policies from. **When unset, file-based tools refuse to read from disk.**                                                                                                                                    |\n| `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.                                                                                                                                                                           |\n| `OPA_MCP_LOG_LEVEL`            | `info`                       | One of `debug`, `info`, `warn`, `error`.                                                                                                                                                                                                                                                     |\n| `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.                                                                                                                                                           |\n| `OPA_MCP_TIMEOUT_MS`           | `30000`                      | Hard timeout for any spawned subprocess (`opa`, `regal`). After this, the child gets `SIGTERM` and then `SIGKILL`.                                                                                                                                                                           |\n| `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`.                                                                                                                                                           |\n| `OPA_MCP_NO_TELEMETRY`         | _(unset)_                    | Set to `1` to disable the anonymous startup ping. The ping sends the server version, OS platform, and a random install ID. The install ID is stored at `~/.orygn/opa-mcp/install-id` and is generated once on first run. No policy content or file paths are ever sent.                      |\n| `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. |\n| `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.                     |\n| `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.    |\n\nPaths in `OPA_MCP_ALLOWED_PATHS` must be absolute, and a `*_BINARY` value is\neither a bare command name looked up on `PATH` or an absolute path; anything\nelse stops the server at startup. A binary that cannot be run is reported by\neach tool call with a structured error.\n\n## Tool reference\n\nEvery tool returns a JSON envelope:\n\n```json\n{ \"ok\": true, \"data\": { ... }, \"warnings\": [ ... ] }\n{ \"ok\": false, \"error\": { \"code\": \"INVALID_REGO\", \"message\": \"...\", \"hint\": \"...\", \"details\": { ... } } }\n```\n\nStable error codes: `INVALID_INPUT`, `INVALID_REGO`, `INVALID_BUNDLE`,\n`EVAL_ERROR`, `OPA_BINARY_NOT_FOUND`, `REGAL_NOT_FOUND`,\n`CONFTEST_NOT_FOUND`, `OPA_UNREACHABLE`, `OPA_AUTH_FAILED`,\n`POLICY_NOT_FOUND`, `DATA_NOT_FOUND`, `PATH_NOT_ALLOWED`, `PATH_NOT_FOUND`,\n`NO_TESTS_FOUND`, `COVERAGE_BELOW_THRESHOLD`, `OPA_VERSION_UNSUPPORTED`,\n`GITHUB_TOKEN_MISSING`, `GIST_CREATE_FAILED`, `OUTPUT_TOO_LARGE`, `SUBPROCESS_KILLED`, `OPA_URL_INVALID`, `TIMEOUT`,\n`CANCELLED`, `UNKNOWN_ERROR`.\n\n### Category A: Authoring & static analysis\n\nOperate on Rego source code without needing a running OPA server. Wrap\n`opa fmt`, `opa parse`, `opa check`, `opa inspect`, `opa capabilities`,\n`opa deps`, and `regal`.\n\n| Tool                | What it does                                                                                                                                                                                                                                                            |\n| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `rego_format`       | Format Rego source. Wraps `opa fmt`. Idempotent.                                                                                                                                                                                                                        |\n| `rego_check`        | Type-check and validate Rego. Wraps `opa check`.                                                                                                                                                                                                                        |\n| `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.**                                                                                                               |\n| `rego_parse_ast`    | Parse Rego to AST JSON. Wraps `opa parse`.                                                                                                                                                                                                                              |\n| `rego_inspect`      | Inspect a bundle or directory: packages, rules, annotations. Wraps `opa inspect`.                                                                                                                                                                                       |\n| `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                                                                                         |\n| `rego_deps`         | Static dependency analysis: rule-level data references and cross-package calls.                                                                                                                                                                                         |\n| `rego_migrate_v1`   | Migrate Rego v0 source to v1 syntax. Runs `opa fmt --rego-v1` then validates with `opa check --v1-compatible`. Returns `{ original, migrated, changed, valid, errors }`.                                                                                                |\n| `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. |\n\n#### Featured: `rego_format`\n\n```jsonc\n// Input\n{\n  \"source\": \"package x\\nallow if input.user==\\\"admin\\\"\"\n}\n\n// Output (ok)\n{\n  \"ok\": true,\n  \"data\": {\n    \"formatted\": \"package x\\n\\nallow if input.user == \\\"admin\\\"\\n\",\n    \"changed\": true\n  }\n}\n```\n\n#### Featured: `rego_check`\n\n```jsonc\n// Input\n{\n  \"source\": \"package x\\nallow if y\",\n  \"strict\": true\n}\n\n// Output (error path; the JSON diagnostics arrive on stderr from opa)\n{\n  \"ok\": true,\n  \"data\": {\n    \"valid\": false,\n    \"errors\": [\n      {\n        \"code\": \"rego_unsafe_var_error\",\n        \"message\": \"var y is unsafe\",\n        \"location\": { \"row\": 2, \"col\": 11 }\n      }\n    ]\n  }\n}\n```\n\n### Category B: Evaluation & testing\n\nRun a query against a policy and input. Wrap `opa eval`, `opa test`, and\n`opa bench`.\n\n| Tool                      | What it does                                                                                                                                                                                                                                 |\n| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `rego_eval`               | Evaluate a query against a policy and input. The bread-and-butter tool.                                                                                                                                                                      |\n| `rego_eval_with_explain`  | Evaluate with `--explain=full` and return a structured trace.                                                                                                                                                                                |\n| `rego_eval_with_profile`  | Evaluate with `--profile` and return per-rule timing and evaluation counts.                                                                                                                                                                  |\n| `rego_eval_with_coverage` | Evaluate with `--coverage` and return per-line coverage.                                                                                                                                                                                     |\n| `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. With `coverage` or `threshold` OPA emits a coverage report instead of per-test records. |\n| `rego_bench`              | Run `opa bench` and return statistical timing data.                                                                                                                                                                                          |\n| `rego_compile_query`      | Partially evaluate a query against a policy.                                                                                                                                                                                                 |\n| `opa_exec`                | Batch-evaluate a decision against multiple input files. Returns per-file results with `successCount` and `errorCount`.                                                                                                                       |\n| `rego_test_multiroot`     | Run `opa test` once per root and aggregate. Use when `opa test .` hits package conflicts. Totals include `totalErrored`.                                                                                                                     |\n\n#### Featured: `rego_eval`\n\n```jsonc\n// Input\n{\n  \"query\": \"data.rbac.allow\",\n  \"source\": \"package rbac\\nimport rego.v1\\nallow if input.role == \\\"admin\\\"\",\n  \"input\": { \"role\": \"admin\" }\n}\n\n// Output\n{\n  \"ok\": true,\n  \"data\": {\n    \"result\": [{ \"expressions\": [{ \"value\": true, \"text\": \"data.rbac.allow\", \"location\": { \"row\": 1, \"col\": 1 } }] }]\n  }\n}\n```\n\n### Category C: Bundle operations\n\nPackage, sign, and verify deployable bundles. Wrap `opa build`, `opa sign`, and `opa build --verification-key`.\n\n| Tool                | What it does                                                                                                                                                                                                                                                                                             |\n| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `opa_bundle_build`  | Build a `.tar.gz` bundle from a policy directory. Supports `optimize` and `revision`.                                                                                                                                                                                                                    |\n| `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`. A directory signature stays valid wherever the directory is placed under the same name. Returns the path, algorithm, and file count. |\n| `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.                                                                                     |\n\n### Category D: OPA server management\n\nTalk to a running OPA server over its REST API. Require `OPA_URL` to\npoint at a reachable server.\n\n| Tool                 | What it does                                                                                                                                                                |\n| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `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.                                           |\n| `opa_get_policy`     | Get a single policy by ID. Returns the Rego source; `includeAst` adds OPA's parsed AST.                                                                                     |\n| `opa_put_policy`     | Upload or replace a policy.                                                                                                                                                 |\n| `opa_delete_policy`  | Delete a policy by ID.                                                                                                                                                      |\n| `opa_get_data`       | Read a path from the data hierarchy.                                                                                                                                        |\n| `opa_put_data`       | Write to a path in the data hierarchy.                                                                                                                                      |\n| `opa_patch_data`     | Apply a JSON Patch to the data hierarchy.                                                                                                                                   |\n| `opa_delete_data`    | Delete a document from the data hierarchy.                                                                                                                                  |\n| `opa_query_decision` | POST to a `/v1/data/...` decision endpoint with input.                                                                                                                      |\n| `opa_compile_query`  | Partially evaluate a query against the running server.                                                                                                                      |\n| `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.    |\n| `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. |\n| `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.  |\n\n### Category E: Higher-level helpers\n\nThe differentiation surface. These compose lower-level primitives into\nthe tasks agents are actually asked to do.\n\n| Tool                          | What it does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |\n| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `rego_explain_decision`       | Turn an evaluation trace into a structured per-rule summary of what fired and what did not                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |\n| `rego_generate_test_skeleton` | Given a policy, generate a `_test.rego` skeleton covering each rule.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| `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`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |\n| `rego_suggest_fix`            | For a failed `rego_check` or `rego_lint`, propose fix suggestions with a confidence level.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |\n| `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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |\n| `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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |\n| `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. No running OPA required. Correct starting point for writing integration tests or configuring `opa check --schema`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |\n| `rego_fix`                    | Run `regal fix` to auto-apply mechanical fixes: `opa-fmt`, `use-rego-v1`, `use-assignment-operator`, `no-whitespace-comment`, and `directory-package-mismatch`. 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                 |\n| `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`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n| `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.                                                                                                                                                                                                                                                                                                                                                                                                                |\n| `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. |\n| `rego_explain_undefined`      | Explain why a Rego query is undefined. 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |\n| `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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |\n\n### Category F: Conftest (configuration policy testing)\n\nTest Kubernetes manifests, Terraform plans, Dockerfiles, Helm charts, and any\nYAML/JSON/HCL/TOML/INI against Rego policies using\n[conftest](https://www.conftest.dev/). Requires `conftest` on `PATH` or\n`CONFTEST_BINARY` set; all four tools return `CONFTEST_NOT_FOUND` otherwise.\n\n| Tool              | What it does                                                                                                                                                                                                                                                                                                                   |\n| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `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.                                                                                                    |\n| `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.                                                                                                                                                                               |\n| `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. |\n| `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.                                                                                      |\n\n#### Featured: `conftest_test` with inline config\n\n```jsonc\n// Input\n{\n  \"inlineConfig\": \"apiVersion: v1\\nkind: Pod\\nspec:\\n  containers:\\n  - name: app\\n    image: nginx:latest\",\n  \"inlinePolicy\": \"package main\\ndeny contains msg if { input.spec.containers[_].image == \\\"nginx:latest\\\"; msg := \\\"pin your image tag\\\" }\"\n}\n\n// Output\n{\n  \"ok\": true,\n  \"data\": {\n    \"passed\": false,\n    \"results\": [\n      {\n        \"filename\": \"<inline>\",\n        \"namespace\": \"main\",\n        \"successes\": 0,\n        \"failures\": [{ \"msg\": \"pin your image tag\" }],\n        \"warnings\": [],\n        \"skipped\": [],\n        \"exceptions\": []\n      }\n    ],\n    \"summary\": {\n      \"passed\": 0,\n      \"failed\": 1,\n      \"warnings\": 0,\n      \"skipped\": 0,\n      \"successes\": 0,\n      \"failures\": 1\n    }\n  }\n}\n```\n\n### Category G: Meta\n\n| Tool              | What it does                                                                                                                                                                                    |\n| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `mcp_server_info` | Return server name, version, resolved `opa`/`regal`/`conftest` versions, transport type, and Node.js version in one call. Useful for verifying which server instance the agent is connected to. |\n\n## Prompts\n\nThree [MCP prompts](https://modelcontextprotocol.io/specification/2025-11-25/server/prompts)\nship with the server. Clients surface them as slash commands or workflow\ntemplates.\n\n| Prompt                        | Purpose                                                                                                          |\n| ----------------------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `policy_authoring_assistant`  | Walks the agent through writing a new policy: ask about the decision surface, draft, review, format, lint, test. |\n| `policy_review_checklist`     | Review checklist for an existing policy: completeness, edge cases, performance, security pitfalls.               |\n| `decision_debugging_workflow` | Diagnostic flow when a decision is unexpected: gather input, run with explain, isolate the rule, propose a fix.  |\n\n## Resources\n\nThree [MCP resources](https://modelcontextprotocol.io/specification/2025-11-25/server/resources)\nexpose curated reference data the agent can read at any time.\n\n| Resource URI        | What's there                                                                                                                                                                                 |\n| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `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. |\n| `opa://style-guide` | Condensed Rego style guide, formatted for LLM consumption.                                                                                                                                   |\n| `opa://patterns`    | Curated common-pattern library: RBAC, ABAC, Kubernetes admission, IaC gates, API authz, rate limiting. Each pattern includes when-to-use, full Rego, a test, and common pitfalls.            |\n\n## Cookbook\n\nA few session shapes that the tool set was designed for.\n\n### \"Help me write a policy\"\n\n```\nYou: I need an authz policy: editors can read/write, viewers can only read,\n     admins can do anything.\n\nAgent: I'll draft it. (calls rego_format on a draft, then rego_check, then\n       rego_lint)\n\nAgent: Here's the policy. I've also generated a test file with cases for\n       each role. (calls rego_generate_test_skeleton, then rego_test)\n\nAgent: All 9 tests pass. Want me to save it to <path>?\n```\n\n### \"Why was this denied?\"\n\n```\nYou: This API call is being denied and I don't know why.\n     [pastes input.json]\n\nAgent: (calls rego_explain_decision against your local policy with that input)\n\nAgent: The deny comes from rule `forbid_anonymous_writes` at line 17.\n       Specifically, `input.user` is null and the request method is \"POST\".\n       The rule fires, which causes the default deny. To allow this, you'd\n       need either an authenticated user or a policy exception for this\n       endpoint.\n```\n\n### \"Push this policy to staging OPA\"\n\n```\nYou: Push policies/rbac.rego to the staging OPA server, but first lint and\n     test it.\n\nAgent: (rego_lint → 2 style warnings, no errors)\n       (rego_test on policies/ → all pass)\n       (opa_put_policy with id=\"rbac\" against $OPA_URL)\n       (opa_get_policy to verify)\n\nAgent: Done. Policy `rbac` is live on staging at $OPA_URL.\n```\n\n## Architecture\n\n```\n┌──────────────────────────────────── @orygn/opa-mcp ───────────────────────────────────┐\n│                                                                                       │\n│   src/server.ts ──── McpServer (stdio) ─── tool / prompt / resource registries        │\n│                          │                                                            │\n│                          ├── tools/authoring/         ─┐                              │\n│                          ├── tools/evaluation/        ─┤                              │\n│                          ├── tools/bundles/           ─┼─── lib/opa-cli.ts ──┐        │\n│                          ├── tools/server-management/ ─┤                     │        │\n│                          ├── tools/helpers/           ─┤                     │        │\n│                          ├── tools/conftest/          ─┤                     │        │\n│                          ├── tools/meta/              ─┘                     │        │\n│                          │                                                   ▼        │\n│                          │                              lib/subprocess.ts ──┴── opa   │\n│                          │                              lib/regal-cli.ts   ───── regal│\n│                          │                              lib/conftest-cli.ts ─ conftest│\n│                          │                              lib/opa-client.ts  ───── HTTP │\n│                          │                                                            │\n│                          └── lib/output.ts (envelope + truncation)                    │\n│                              lib/security.ts (path allow-list)                        │\n│                              lib/errors.ts (structured failures)                      │\n│                              lib/logger.ts (file-only, never stdout)                  │\n└───────────────────────────────────────────────────────────────────────────────────────┘\n```\n\nFour things worth knowing if you're going to operate this:\n\n1. **stdout is the protocol channel.** The server logs to a file via\n   `lib/logger.ts` and never writes to stdout. If you see stray stdout\n   bytes, the client disconnects; the MCP transport layer is strict.\n2. **No tool handler throws.** Every handler catches its own exceptions and\n   returns a structured `{ ok: false, error: ... }` envelope, so the agent\n   sees a stable error vocabulary, not a stack trace. An argument that fails\n   the tool's input schema never reaches the handler: the MCP layer rejects\n   it and returns a tool result with `isError: true` whose text begins\n   `MCP error -32602: Input validation error:`, rather than the envelope.\n   Decoding subprocess output happens inside an async callback, where a throw\n   would bypass those handlers entirely, so that path is bounded by bytes\n   rather than left to a `try`/`catch` that could not see it.\n\n3. **Subprocesses are bounded in time, size, and environment.**\n   `lib/subprocess.ts` runs the binaries with `shell: false`, a hard\n   timeout with `SIGTERM`-then-`SIGKILL` escalation, and a per-stream byte\n   cap. There is no path through the server where an agent can construct a\n   shell command. The timeout alone is not enough: `opa` buffers a result\n   in memory and writes it in one burst at exit, so a command that finishes\n   well inside the timeout can still deliver hundreds of megabytes.\n4. **Children do not inherit the server's environment.** `lib/child-env.ts`\n   builds an explicit allow-list instead. Rego can read its interpreter's\n   environment through `opa.runtime().env`, so anything passed down is\n   readable by any policy the server evaluates, the proxy variables on the\n   list included.\n\n## Security\n\nThis server is designed to run **locally**, started by an MCP client on\nthe user's own machine, communicating over stdio. It is not designed to\nbe exposed on the network.\n\n- File-based tools refuse to read anything outside `OPA_MCP_ALLOWED_PATHS`.\n  When that variable is unset, file tools return `PATH_NOT_ALLOWED`.\n- Subprocesses run with `shell: false`, a hard timeout, and a byte cap on\n  captured output.\n- **Evaluated policy cannot read the server's environment.** Rego exposes the\n  environment of the `opa` process through `opa.runtime().env`, so a child that\n  inherited `process.env` would hand `OPA_TOKEN`, `GITHUB_TOKEN`, and every\n  other variable to any policy it evaluated. Since `rego_eval` accepts inline\n  source, no filesystem access is needed to reach that, which puts it one\n  prompt injection away from any untrusted Rego an agent reads. Children get an\n  explicit allow-list instead (`lib/child-env.ts`). The list holds no cloud or\n  repository token, but it is not free of credentials: `HTTP_PROXY` and its\n  siblings are on it, and a proxy URL can embed a username and password.\n  They are there because dropping them breaks everyone behind a corporate\n  proxy. Name them in `OPA_MCP_BLOCK_ENV` to withhold them anyway.\n  `OPA_MCP_PASSTHROUGH_ENV` opts individual variables back in.\n- `OPA_TOKEN` is never echoed in tool responses or log entries, and is not\n  passed to any child process.\n- **Tools that evaluate Rego are annotated open-world and not read-only.**\n  `rego_eval` and its variants, `rego_test`, `rego_test_multiroot`,\n  `rego_bench`, `rego_compile_query`, `opa_exec`, the explain, diff and\n  coverage helpers, the conftest tools, and the Regal tools (`rego_lint`,\n  `rego_security_audit`, `rego_fix`, which run a project's custom rules) all\n  run Rego, and OPA's `http.send` lets a policy reach, and write to, any\n  network address. A client that gates on the hints will ask before running\n  one. `opa_query_decision` and `opa_compile_query` are the exception: the\n  remote OPA evaluates a policy it already holds, and their hints describe\n  what the call does to that server. No evaluating tool passes or accepts a\n  capabilities file, so `http.send` cannot be restricted for evaluation;\n  `rego_check` and `opa_bundle_build` accept one, which affects only checking\n  and building.\n- Releases are published with\n  [npm provenance](https://docs.npmjs.com/generating-provenance-statements);\n  the Docker image is built from the committed `Dockerfile`, with pinned\n  versions of `opa` and `regal` checked against their published digests.\n\nTo report a vulnerability, follow [SECURITY.md](./SECURITY.md). **Please\ndo not open a public issue for security problems.**\n\n## Troubleshooting\n\nCommon issues, fast fixes.\n\n**`OPA_BINARY_NOT_FOUND` (or `REGAL_NOT_FOUND` / `CONFTEST_NOT_FOUND`) even\nthough the binary is installed.** _(most common first-day issue, read this\nfirst)_\n\nMCP clients (notably **Claude Desktop on Windows and macOS**) launch the\nserver with a deliberately reduced `PATH` that omits user-local bin\ndirectories, even ones that work fine in your interactive shell. The\nbinary is on your machine; the spawned MCP server just can't see it.\n\nFind the absolute path to `opa`:\n\n```bash\n# macOS / Linux\nwhich opa\n# → /usr/local/bin/opa  (or /opt/homebrew/bin/opa, or ~/.local/bin/opa)\n```\n\n```powershell\n# Windows\nGet-Command opa | Select-Object -ExpandProperty Source\n# → C:\\Users\\you\\bin\\opa.exe  (or wherever)\n```\n\nThen set `OPA_BINARY` to that absolute path in your client's MCP `env`\nblock. The same cause and fix apply to the other binaries: if `rego_lint`\n/ `rego_security_audit` / `rego_fix` report `REGAL_NOT_FOUND`, or the\n`conftest_*` tools report `CONFTEST_NOT_FOUND`, set `REGAL_BINARY` /\n`CONFTEST_BINARY` to the absolute path the same way (find it with\n`which regal` / `which conftest`). Having the binary on your shell `PATH`\nis not enough -- the spawned server gets a reduced `PATH`. The\n[`examples/`](./examples) configs already include these env vars; just\nedit the placeholder paths.\n\nThis issue does **not** affect the Docker install path, which bundles\n`opa` and `regal` and bypasses `PATH` entirely. The MCPB bundle resolves\n`opa` from `OPA_BINARY` or `PATH`, so it can hit this.\n\n**The server starts, then the client says \"disconnected.\"**\n\nThe most likely cause is something in the process writing to stdout\nbesides MCP frames. If you've added a custom tool, check that no library\nit calls prints to stdout. The fixed-position safety net is\n`lib/logger.ts`. Use it, not `console.log`.\n\n**`PATH_NOT_ALLOWED` on a file under my project.**\n\n`OPA_MCP_ALLOWED_PATHS` is empty by default. Set it to the absolute\npath(s) you want the server to read from, comma-separated.\n\n**`OPA_UNREACHABLE` when calling `opa_*` tools.**\n\n`OPA_URL` (default `http://localhost:8181`) must point at a running OPA\nserver (`opa run --server ...`). Check with `curl $OPA_URL/health`.\n\n**`TIMEOUT` when calling `opa_*` tools.**\n\nThe request did not finish within `OPA_MCP_HTTP_TIMEOUT_MS` (default 15 s).\nEither OPA is up but slow, or nothing is answering at `OPA_URL` and the\nconnection attempt is being dropped rather than refused, which looks the\nsame from here. Check `OPA_URL` and the server's load, or raise the limit.\n\n**`directory-package-mismatch` violation when linting inline source.**\n\nSince v0.1.1, the server auto-disables this rule for inline-source calls.\nIf you see it, you are running an older version -- upgrade to v0.1.1 or\nlater. To get canonical signal on this rule, lint via `paths` against the\nreal on-disk file instead of passing `source` directly.\n\n**Where are the logs?**\n\nDefault location is `<OS-tmpdir>/orygn-opa-mcp.log`. That's typically\n`/tmp/orygn-opa-mcp.log` on Linux/macOS or `%TEMP%\\orygn-opa-mcp.log`\non Windows. Set `OPA_MCP_LOG_FILE` to override, and\n`OPA_MCP_LOG_LEVEL=debug` to widen the firehose.\n\n## Development\n\n```bash\ngit clone https://github.com/OrygnsCode/opa-mcp-server.git\ncd opa-mcp-server\nnpm install\nnpm run dev\n```\n\nCommon commands:\n\n```bash\nnpm run lint              # ESLint\nnpm run typecheck         # tsc --noEmit\nnpm test                  # unit tests (Vitest)\nnpm run test:coverage     # unit + coverage report\nnpm run test:integration  # against real opa + regal binaries\nnpm run build             # compile to dist/\n```\n\nCI runs lint, typecheck, build, and unit tests on every push and PR\nacross Ubuntu and Windows on Node 20, 22 and 24, plus macOS on Node 22. Integration\ntests run on Linu",
  "bytes": 60000,
  "sha": "b3d6d3f553e866d28207dc35e02402828320cc04635ba590da5e6a2fccf10679",
  "repo_slug": "orygnscode/opa-mcp-server",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_orygnscode_opa_mcp_a8aef0a1/readme"
}