Skip to main content
Glama
OrygnsCode

opa-mcp-server

Upload or replace OPA policy

opa_put_policy

Upload or replace a Rego policy in OPA by specifying its ID and source text. Policy is sent as plain text and parsed server-side.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
idYesPolicy ID to create or replace.
sourceYesRego source.

Implementation Reference

  • The handler function for 'opa_put_policy'. It accepts id and source (Rego source) as input, sends a PUT request to the OPA server's /v1/policies/{id} endpoint with the source as text/plain, and returns a success envelope with { id, replaced: true } or maps the OPA client error on failure.
    server.registerTool(
      'opa_put_policy',
      {
        title: 'Upload or replace OPA policy',
        description:
          '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.',
        inputSchema: {
          id: z.string().min(1).describe('Policy ID to create or replace.'),
          source: z.string().min(1).describe('Rego source.'),
        },
      },
      async ({ id, source }) => {
        return withToolEnvelope<{ id: string; replaced: boolean }>(config, async () => {
          try {
            await opa.request({
              method: 'PUT',
              path: `/v1/policies/${encodeURIComponent(id)}`,
              rawBody: source,
              rawContentType: 'text/plain',
            });
            return ok({ id, replaced: true });
          } catch (e) {
            return mapOpaClientError(e);
          }
        });
      },
    );
  • Zod input schema for the tool: requires id (non-empty string) and source (non-empty string for Rego source code).
    inputSchema: {
      id: z.string().min(1).describe('Policy ID to create or replace.'),
      source: z.string().min(1).describe('Rego source.'),
    },
  • Registration chain: server.ts calls registerTools() -> registerServerManagementTools() -> registerPolicyTools() which registers 'opa_put_policy' via server.registerTool().
    import { registerDataTools } from './data.js';
    import { registerDecisionTools } from './decisions.js';
    import { registerPolicyTools } from './policies.js';
    import { registerStatusTools } from './status.js';
    
    export function registerServerManagementTools(server: McpServer, config: Config): void {
      registerPolicyTools(server, config);
      registerDataTools(server, config);
      registerDecisionTools(server, config);
      registerStatusTools(server, config);
    }
  • Top-level registration function that delegates to category-specific registrars including registerServerManagementTools.
    import { registerServerManagementTools } from './server-management/index.js';
    
    export function registerTools(server: McpServer, config: Config): void {
      registerAuthoringTools(server, config);
      registerEvaluationTools(server, config);
      registerBundleTools(server, config);
      registerServerManagementTools(server, config);
      registerHelperTools(server, config);
    }
  • The OpaClient.request() method used by the handler to make the PUT request. It handles rawBody (text/plain) for policy upload, authentication via Bearer token, and error mapping for unreachable/auth/HTTP errors.
    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;
    }
Behavior3/5

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

The description discloses that the tool replaces existing policies and that the input is raw text/plain for server-side parsing. However, with no annotations, it fails to mention error responses, authentication needs, or rate limits, which are relevant for a write 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?

The description is two sentences (26 words) with no filler. The first sentence states the core action, and the second adds relevant detail. Every word earns its place.

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?

Given the numerous sibling tools, the description is sufficient to distinguish this write operation from read-only ones. It lacks details on permissions and error handling but is mostly complete for the tool's simplicity.

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 coverage is 100%, so baseline is 3. The description adds value by explaining that the source is uploaded as raw text/plain and interpreted by OPA, clarifying the processing beyond the schema definition.

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 uploads a Rego policy under a given ID and replaces any existing policy. The verb 'Upload' and the resource 'Rego policy' are specific and distinguish it from reading, listing, or deleting policies, which are covered by sibling tools.

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

Usage Guidelines3/5

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

The description implies usage for creating or replacing policies but does not explicitly state when to use this tool versus alternatives like opa_get_policy or opa_delete_policy. No guidance on context or exclusions is provided.

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