Skip to main content
Glama
OrygnsCode

opa-mcp-server

Read data from OPA

opa_get_data

Fetch data from OPA by specifying a path under the data hierarchy using dotted or slash notation.

Instructions

Read a path from OPA's data hierarchy. The path argument may be in dotted form (users.alice) or slash form (users/alice).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesData path under `data.`, e.g. "users" or "users/alice".

Implementation Reference

  • The async handler function for the opa_get_data tool. It sends a GET request to OPA's /v1/data/{path} endpoint, unwraps the 'result' field from the response, and returns it. Uses withToolEnvelope for error handling and mapOpaClientError for HTTP error mapping.
    async ({ path }) => {
      return withToolEnvelope<{ result: unknown }>(config, async () => {
        try {
          const data = await opa.request<{ result: unknown }>({
            method: 'GET',
            path: dataPath(path),
          });
          return ok({ result: data.result });
        } catch (e) {
          return mapOpaClientError(e);
        }
      });
    },
  • Tool registration including input schema validation for opa_get_data. The tool accepts a single 'path' parameter as a non-empty string describing the data path under 'data.'. Defined inline in server.registerTool call.
    server.registerTool(
      'opa_get_data',
      {
        title: 'Read data from OPA',
        description:
          "Read a path from OPA's data hierarchy. The `path` argument may be in dotted form (`users.alice`) or slash form (`users/alice`).",
        inputSchema: {
          path: z.string().min(1).describe('Data path under `data.`, e.g. "users" or "users/alice".'),
        },
      },
  • The registerDataTools function registers opa_get_data (along with opa_put_data and opa_patch_data) onto the MCP server. This is called from src/tools/server-management/index.ts via registerServerManagementTools.
    export function registerDataTools(server: McpServer, config: Config): void {
      const opa = new OpaClient(config);
    
      server.registerTool(
        'opa_get_data',
        {
          title: 'Read data from OPA',
          description:
            "Read a path from OPA's data hierarchy. The `path` argument may be in dotted form (`users.alice`) or slash form (`users/alice`).",
          inputSchema: {
            path: z.string().min(1).describe('Data path under `data.`, e.g. "users" or "users/alice".'),
          },
        },
        async ({ path }) => {
          return withToolEnvelope<{ result: unknown }>(config, async () => {
            try {
              const data = await opa.request<{ result: unknown }>({
                method: 'GET',
                path: dataPath(path),
              });
              return ok({ result: data.result });
            } catch (e) {
              return mapOpaClientError(e);
            }
          });
        },
      );
  • Helper function dataPath converts a user-supplied path (dotted or slash form) into a proper /v1/data/{path} URL for the OPA REST API. Used by the opa_get_data handler to construct the request path.
    function dataPath(path: string): string {
      // Strip leading "data." or "/" — server always prepends /v1/data/.
      const stripped = path.replace(/^data\./, '').replace(/^\/+/, '');
      // Convert dotted form to slash form: "users.alice" -> "users/alice".
      return `/v1/data/${stripped.replace(/\./g, '/')}`;
    }
  • The OpaClient class used by the handler to execute HTTP requests against the OPA server. The request method handles building the URL, setting headers (including Authorization), sending the request, and parsing JSON responses.
    export class OpaClient {
      constructor(private readonly config: Config) {}
    
      async request<T = unknown>(opts: RequestOptions): Promise<T> {
        const url = this.buildUrl(opts.path, opts.query);
    
        const headers: Record<string, string> = {
          Accept: 'application/json',
          ...(opts.headers ?? {}),
        };
        if (this.config.opaToken) {
          headers['Authorization'] = `Bearer ${this.config.opaToken}`;
        }
    
        let bodyToSend: string | undefined;
        if (opts.rawBody !== undefined) {
          if (opts.body !== undefined) {
            throw new Error('OpaClient.request: pass either `body` or `rawBody`, not both.');
          }
          bodyToSend = opts.rawBody;
          if (!headers['Content-Type']) {
            headers['Content-Type'] = opts.rawContentType ?? 'text/plain';
          }
        } else if (opts.body !== undefined) {
          bodyToSend = JSON.stringify(opts.body);
          if (!headers['Content-Type']) {
            headers['Content-Type'] = 'application/json';
          }
        }
    
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), this.config.httpTimeoutMs);
    
        const init: RequestInit = {
          method: opts.method,
          headers,
          signal: controller.signal,
        };
        if (bodyToSend !== undefined) {
          init.body = bodyToSend;
        }
    
        let response: Response;
        try {
          response = await fetch(url, init);
        } catch (e) {
          throw new OpaUnreachableError(this.config.opaUrl, e);
        } finally {
          clearTimeout(timer);
        }
    
        if (response.status === 401) {
          throw new OpaAuthError();
        }
    
        const contentType = response.headers.get('content-type') ?? '';
        const isJson = contentType.includes('application/json');
        const payload: unknown = isJson ? await response.json() : await response.text();
    
        if (!response.ok) {
          throw new OpaHttpError(response.status, payload);
        }
    
        return payload as T;
      }
    
      private buildUrl(path: string, query?: RequestOptions['query']): string {
        const base = this.config.opaUrl.replace(/\/+$/, '');
        const normalizedPath = path.startsWith('/') ? path : `/${path}`;
        const url = new URL(`${base}${normalizedPath}`);
        if (query) {
          for (const [key, value] of Object.entries(query)) {
            if (value !== undefined) url.searchParams.set(key, String(value));
          }
        }
        return url.toString();
      }
    }
Behavior3/5

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

No annotations provided. Description adds path format details but does not disclose behavioral traits like error behavior, idempotency, or safety. Minimal for a read operation.

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?

Two sentences: first clearly states purpose, second adds crucial format detail. No waste, concise and structured.

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

Completeness4/5

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

Adequate for a simple one-param tool. Lacks description of return value (expected JSON data) and error handling, but still sufficient for basic use.

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

Parameters4/5

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

Schema has 100% coverage describing path parameter. Description adds value by noting alternative path formats (dotted or slash), beyond schema's examples.

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?

Clearly states 'Read a path from OPA's data hierarchy', specifying verb and resource. Distinguishes from siblings like opa_get_policy (policy read) and opa_query_decision (decision query).

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?

Provides guidance on path format (dotted or slash) and implies usage for data reads. Lacks explicit when-to-use vs alternatives, but sibling names help disambiguate.

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