Skip to main content
Glama
OrygnsCode

opa-mcp-server

Explain Rego decision

rego_explain_decision

Evaluates a Rego query with full tracing to answer why a decision was made, returning a structured trace and per-rule summary.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesRego query to evaluate, e.g. "data.example.allow".
sourceNoInline Rego policy source. Mutually exclusive with `paths`.
pathsNoPolicy / data file or directory paths. Each must be inside an allowed root.
inputNoInline input document.
inputPathNoPath to a JSON input file. Mutually exclusive with `input`.
unknownsNoRefs to treat as unknown during partial evaluation.
partialNoRun partial evaluation rather than full evaluation.
strictBuiltinErrorsNoTreat builtin errors as fatal instead of returning undefined.

Implementation Reference

  • The main handler function `registerRegoExplainDecision` that registers the 'rego_explain_decision' tool on the MCP server. It runs a Rego query with `--explain=full`, parses the trace, summarizes per-rule events (entered/exited/failed), and returns a structured trace plus aggregated summary.
    export function registerRegoExplainDecision(server: McpServer, config: Config): void {
      const opa = new OpaCli(config);
    
      server.registerTool(
        'rego_explain_decision',
        {
          title: 'Explain Rego decision',
          description:
            '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.',
          inputSchema: SharedEvalInput,
        },
        async (args) => {
          return withToolEnvelope<RegoExplainDecisionOutput>(config, async () => {
            const evalEnvelope = await runEval(opa, config, args, { explain: 'full' });
            if (!evalEnvelope.ok) {
              // Re-issue the same error under this tool's output type.
              return err(evalEnvelope.error!.code, evalEnvelope.error!.message, {
                hint: evalEnvelope.error!.hint,
                details: evalEnvelope.error!.details,
              });
            }
            const data = evalEnvelope.data as RegoEvalOutput;
    
            const trace = (data.explanation ?? []) as TraceEvent[];
            const summary = summarizeTrace(trace);
    
            return ok<RegoExplainDecisionOutput>({
              result:
                data.result?.[0] !== undefined
                  ? (data.result as Array<{ expressions?: Array<{ value?: unknown }> }>)[0]
                      ?.expressions?.[0]?.value
                  : undefined,
              errors: data.errors,
              rulesFired: [...summary.rulesFired],
              rulesEvaluated: [...summary.rulesEvaluated],
              trace,
              summary: {
                totalEvents: summary.totalEvents,
                enterEvents: summary.enterEvents,
                exitEvents: summary.exitEvents,
                failEvents: summary.failEvents,
              },
            });
          });
        },
      );
    }
  • Output type `RegoExplainDecisionOutput` defining the shape of the tool's response: result, errors, rulesFired, rulesEvaluated, trace (raw events), and summary (total/enter/exit/fail event counts). The input schema is the shared `SharedEvalInput` from `_shared.ts`.
    export interface RegoExplainDecisionOutput {
      result: unknown;
      errors?: unknown[];
      rulesFired: string[];
      rulesEvaluated: string[];
      trace: TraceEvent[];
      summary: {
        totalEvents: number;
        enterEvents: number;
        exitEvents: number;
        failEvents: number;
      };
    }
  • The `summarizeTrace` helper function that iterates over trace events, counting enter/exit/fail operations and building sets of rule names that were evaluated vs. fired using regex matching on event messages.
    function summarizeTrace(trace: TraceEvent[] | undefined): RegoExplainDecisionOutput['summary'] & {
      rulesEvaluated: Set<string>;
      rulesFired: Set<string>;
    } {
      const rulesEvaluated = new Set<string>();
      const rulesFired = new Set<string>();
      let enterEvents = 0;
      let exitEvents = 0;
      let failEvents = 0;
      for (const event of trace ?? []) {
        if (event.op === 'enter') {
          enterEvents += 1;
          const ruleMatch = event.message ? /^(?:eval|enter)\s+(.+)$/i.exec(event.message) : null;
          if (ruleMatch?.[1]) rulesEvaluated.add(ruleMatch[1]);
        } else if (event.op === 'exit') {
          exitEvents += 1;
          const ruleMatch = event.message ? /^(?:exit|matched)\s+(.+)$/i.exec(event.message) : null;
          if (ruleMatch?.[1]) rulesFired.add(ruleMatch[1]);
        } else if (event.op === 'fail') {
          failEvents += 1;
        }
      }
      return {
        totalEvents: trace?.length ?? 0,
        enterEvents,
        exitEvents,
        failEvents,
        rulesEvaluated,
        rulesFired,
      };
    }
  • Registration of `registerRegoExplainDecision` within the helper tools module. Called from `registerHelperTools` which is invoked by the main `registerTools` entry point in `src/tools/index.ts` (line 42).
    import { registerRegoExplainDecision } from './explain-decision.js';
    import { registerRegoGenerateTestSkeleton } from './generate-test-skeleton.js';
    import { registerRegoSuggestFix } from './suggest-fix.js';
    
    export function registerHelperTools(server: McpServer, config: Config): void {
      registerRegoExplainDecision(server, config);
      registerRegoGenerateTestSkeleton(server, config);
      registerRegoDescribePolicy(server, config);
      registerRegoSuggestFix(server, config);
  • The `SharedEvalInput` Zod schema used as the input schema for rego_explain_decision. Defines shared input fields: query, source, paths, input, inputPath, unknowns, partial, strictBuiltinErrors.
    export const SharedEvalInput = {
      query: z.string().min(1).describe('Rego query to evaluate, e.g. "data.example.allow".'),
      source: z
        .string()
        .optional()
        .describe('Inline Rego policy source. Mutually exclusive with `paths`.'),
      paths: z
        .array(z.string())
        .optional()
        .describe('Policy / data file or directory paths. Each must be inside an allowed root.'),
      input: z.unknown().optional().describe('Inline input document.'),
      inputPath: z
        .string()
        .optional()
        .describe('Path to a JSON input file. Mutually exclusive with `input`.'),
      unknowns: z
        .array(z.string())
        .optional()
        .describe('Refs to treat as unknown during partial evaluation.'),
      partial: z.boolean().optional().describe('Run partial evaluation rather than full evaluation.'),
      strictBuiltinErrors: z
        .boolean()
        .optional()
        .describe('Treat builtin errors as fatal instead of returning undefined.'),
    };
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are present, so the description must carry the full burden. It states the tool returns a trace and summary but does not disclose if it is read-only, performance implications, error handling, or side effects. This is a significant gap for a tool with no annotation support.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences long, highly concise, and front-loaded with the core purpose. Every sentence adds value with no wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has 8 parameters but no output schema. The description does not detail the return format beyond 'structured trace plus summary', leaving agents to guess the exact fields. Common usage patterns (e.g., source vs paths) are not highlighted in the description, though the schema covers them.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema provides 100% coverage with parameter descriptions. The tool description adds no additional meaning beyond what the schema already specifies, so baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool evaluates a Rego query with full tracing, returning a structured trace and per-rule summary. This specific verb+resource+output combination differentiates it from sibling tools like rego_eval or rego_check.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly advises using this tool to answer 'why was this denied?', providing a clear use case. It implies alternatives exist for simple evaluation, but does not explicitly list when to avoid this tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/OrygnsCode/opa-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server