Documentation / What is MastGuard

MastGuard Documentation

Everything you need to instrument, monitor, and govern your AI agents with confidence.

What is MastGuard

MastGuard is the governance and compliance layer for teams running AI agents in production. It captures every action your agents take, scores the risk in real time, blocks or pauses anything that crosses a policy line, and writes the whole story to an audit trail you can hand to a regulator. You get visibility into agent behavior, a Human in the Loop workflow for sensitive decisions, and one set of dashboards your engineering, security, and compliance teams can all share.

Who it is for. Healthcare teams shipping clinical assistants, fintech teams running trading and treasury agents, and enterprise software teams operating autonomous workflows where mistakes have a real cost.

What you get. Real time governance decisions on every agent action, dual approval Human in the Loop for high risk events, append only audit logs, signed webhooks, and policy enforcement that travels with your agents wherever they run.

Getting Started

Prerequisites

  • A work email you can verify.
  • An application or service that calls an AI model and you would like to govern.
  • Node.js 18 or newer if you are using the TypeScript SDK.

Create your account

Sign up at app.mastguard.io. You can sign in with email or with your Microsoft work account. Your first sign in automatically creates your organization. Every event, agent, and audit record is scoped to that organization.

Get your API key

Open the Developer page in the dashboard sidebar. Click Create API key, give it a name (for example production or staging), and copy the value. The key is shown once. Store it in a secret manager or in your platform's environment configuration.

Connect your first agent

An agent in MastGuard is anything that takes actions on behalf of a user or a system, identified by an agentId string that you choose. Install the SDK, send your first event, and the agent will appear in the dashboard within seconds.

After your first ingest call, the Overview page will show events flowing in, the Agents page will list your new agent with a risk category, and the Audit page will start recording every decision with a trace id.

Quickstart

Install the SDK:

npm install @auxdynamics/mastguard-sdk

Initialize the client and ingest your first event:

import { MastGuardClient } from "@auxdynamics/mastguard-sdk"

const client = new MastGuardClient({
  apiKey: process.env.MASTGUARD_API_KEY!,
})

const decision = await client.governance.ingest({
  agentId: "trade-agent-01",
  actionType: "PAYMENT_APPROVE",
  payload: { symbol: "AAPL", quantity: 100, amount_usd: 18500 },
})

if (decision.queued) {
  console.log("Event queued for async evaluation, trace:", decision.traceId)
} else if (decision.decision === "BLOCK") {
  throw new Error(`Blocked by governance, risk ${decision.riskScore}`)
} else if (decision.decision === "HITL") {
  console.log("Pending human review, trace:", decision.traceId)
} else {
  proceedWithAction()
}
HEADS UP
The SDK returns a queued flag. When events are evaluated asynchronously through the platform's event pipeline, queued is true and a decision arrives later through a webhook. Always check it before reading decision.

Core Concepts

Agent

An agent is any program, workflow, or assistant that takes actions you want to govern. You identify it with a string agentId that you pick. The same id used twice means the same agent. There is no separate registration step.

Ingest event

Every governed action is an ingest event. You send the agent id, an action type (one of the supported categories below), a payload describing what the agent wants to do, and optional context. MastGuard evaluates it and returns a decision.

Governance decision

Every event resolves to one of four decisions:

  • ALLOW. The action passed every policy and risk check.
  • ALERT. Allowed, but flagged for visibility and recorded with a higher risk score.
  • HITL. Routed to a human reviewer. The action should pause until approved.
  • BLOCK. Stopped by policy. The action must not proceed.

Human in the Loop (HITL)

When a decision is HITL, a task lands in the Review Queue in your dashboard. A reviewer opens the task, sees the original action, the risk score, the MAST failure modes detected, and the policies that triggered. They approve or reject with a written rationale. Sensitive workflows can require dual approval, where two reviewers must agree before the outcome is final.

Policy

A policy is a named rule that targets a set of action types and emits a decision when its conditions match. Policies have a priority and an active flag. You manage them on the Policies page in the dashboard.

Risk Score

Every event gets a numeric risk score and a category: LOW, MEDIUM, HIGH, or CRITICAL. The score reflects the action type, the detected failure modes, and the context. Use it to drive your own dashboards or trigger custom alerts through webhooks.

Provenance

Every event is stamped with a traceId. The trace id ties together the original ingest, the decision, any HITL task, every reviewer action, and the final audit record. Use it to follow a single action all the way through.

Audit Log

The audit log is append only. Every decision is written once and never modified. Each entry contains the trace id, the agent id, the action type, a payload hash, the final decision, the risk score, the failure modes detected, the policies evaluated, and the timestamp.

SDK Reference

The TypeScript SDK is published as @auxdynamics/mastguard-sdk. It is zero dependency, ships ESM and CJS builds, and works in Node.js 18+ as well as Edge runtimes such as Cloudflare Workers and Vercel Edge. Authentication uses the X-API-Key header, which the SDK sets for you.

Initialization

import { MastGuardClient } from "@auxdynamics/mastguard-sdk"

const client = new MastGuardClient({
  apiKey: process.env.MASTGUARD_API_KEY!,
  // baseUrl: "https://api.mastguard.io",
  // timeout: 30000,
  // retries: 3,
  // retryDelay: 1000,
})
NameTypeRequiredDescription
apiKeystringyesYour MastGuard API key, issued from the Developer page.
baseUrlstringnoDefaults to https://api.mastguard.io.
timeoutnumbernoPer request timeout in ms. Default 30000.
retriesnumbernoRetry attempts for 429, 5xx, and network errors. Default 3.
retryDelaynumbernoBase delay for exponential backoff in ms. Default 1000.
onError(err: Error) => voidnoHook fired on every error, including retried ones.
fetchtypeof fetchnoInject a custom fetch, mostly useful in tests.

Governance

client.governance.ingest(event)

Send an agent action for evaluation. Returns a governance decision.

NameTypeRequiredDescription
agentIdstringyesStable identifier for the agent.
actionTypeActionTypeValueyesOne of EMAIL_SEND, PAYMENT_APPROVE, RECORD_UPDATE, DOCUMENT_MODIFY, DATA_ACCESS, API_CALL, OTHER.
payloadRecord<string, unknown>yesThe data describing the proposed action.
contextRecord<string, unknown>noOptional context such as user id, session, or environment.

Returns:

{
  traceId: string
  decision: "ALLOW" | "ALERT" | "BLOCK" | "HITL"
  riskScore: number
  riskCategory: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL"
  mastFailures: Array<{ modeId; category; name; severity; confidence }>
  processingTimeMs: number
  mode: "sync" | "async"
  queued: boolean
}

client.governance.getDashboard()

Returns aggregated metrics for your organization: events today, events per minute, failures caught, HITL queue depth, compliance score, agents monitored.

client.governance.getAgents()

Returns the list of agents that have sent events, with last action type, total events, failures count, last seen timestamp, and risk category.

client.governance.getPolicies()

Returns the policies configured for your organization.

Agents

A small facade over governance for agent queries.

  • client.agents.list(). Same as governance.getAgents().
  • client.agents.get(agentId). Returns one agent or null.

HITL

  • client.hitl.getQueue({ status, page, limit }). Paginated list of HITL tasks.
  • client.hitl.getTask(taskId). Single task with full reviewer history.
  • client.hitl.approve(taskId, { rationale }). Approve with a justification (10 to 2000 characters). Returns the dual approval outcome.
  • client.hitl.reject(taskId, { rationale }). Reject with a justification.
  • client.hitl.getAuditLog({ agentId, actionType, decision, limit, cursor }). Searchable audit entries.

The approve and reject calls return:

{
  outcome: "PARTIALLY_APPROVED" | "APPROVED" | "REJECTED",
  task: HITLTask,
  decisionRecord: { id, taskId, reviewerId, decision, reason, decidedAt, ... }
}

Webhooks

  • client.webhooks.list(). All webhooks configured for the org.
  • client.webhooks.create({ name, url, eventTypes }). Returns the webhook plus a fullSecret shown only once.
  • client.webhooks.delete(webhookId). Removes the webhook.

Supported event types:

  • agent.decision.high_risk
  • agent.decision.blocked
  • hitl.task.created
  • hitl.task.approved
  • hitl.task.rejected
  • subscription.changed
  • api_key.created
  • api_key.revoked

Verify incoming webhook signatures with the static helper:

import { MastGuardWebhooks } from "@auxdynamics/mastguard-sdk"

const valid = await MastGuardWebhooks.verifySignature(
  rawBody,
  request.headers["x-mastguard-signature"]!,
  process.env.WEBHOOK_SIGNING_SECRET!,
)
if (!valid) return new Response("invalid signature", { status: 401 })

Billing

client.billing.getSubscription(). Returns plan, status, billing interval, current period end, and cancel at period end. Read only. Plan changes are made in the dashboard.

Errors

All errors extend MastGuardError. Catch the base class for blanket handling, or use instanceof for targeted responses.

NameTypeRequiredDescription
AuthenticationError401Missing or invalid API key.
AuthorizationError403API key does not have access to this resource.
NotFoundError404Resource does not exist.
ConflictError409Already in a terminal state, for example a task already approved.
ValidationError422Request body failed validation.
RateLimitError429Too many requests. Read retryAfterSeconds and retry.
ServerError5xxServer side issue. SDK retries automatically.
NetworkErrorn/aTransport failure before a response was received.
TimeoutErrorn/aRequest exceeded the configured timeout.

Dashboard Guide

The dashboard at app.mastguard.io is organized around the workflows your team runs every day.

Overview

The landing page for your organization. It shows the live state of your agents.

  • Total events today and events per minute.
  • Failures caught today.
  • HITL queue depth.
  • Compliance score and number of agents monitored.
  • Recent event stream and agent health list.

Agents

Every agent that has ever sent an event, ranked by activity and risk.

  • See last action type, total events, failures, and current risk category.
  • Drill into a single agent to view its event history.

Review Queue (HITL)

The work surface for human reviewers.

  • Filter pending tasks by approval status.
  • Open a task to see the original action, risk details, failure modes, and policy context.
  • Approve or reject with a written rationale (10 to 2000 characters).
  • Dual approval workflows show the first approver and require a second reviewer to confirm.

Audit Log

Searchable history of every decision.

  • Filter by agent, action type, or decision.
  • Open any entry to view the full trace, MAST failures, and policies evaluated.
  • Export filtered results for compliance review.

Policies

Define and manage the rules that drive governance decisions.

  • Create, edit, and toggle policies for specific action types.
  • Set priority to control evaluation order.

Monitoring

Time series charts of agent activity, decisions, and failure modes. Useful for spotting trends and unusual spikes.

Compliance

Generate compliance reports across the regulatory frameworks your organization is subject to. Reports are produced from the audit log and can be downloaded.

Developer

Manage everything technical for your integration.

  • Create and revoke API keys.
  • Create webhooks and view delivery history.
  • Copy the values you need for the SDK.

Settings

Organization, team, and account management.

  • Update your organization profile.
  • Invite teammates and assign roles.
  • Manage your own account and preferences.

Billing

Subscription, plan, and invoice history. Upgrade or change billing interval from this page.

Compliance and Policies

MastGuard ships compliance tooling for the regulated industries our customers operate in.

Supported frameworks

  • HIPAA. For healthcare teams handling protected health information.
  • GDPR. For teams operating in or serving the European Union.
  • EU AI Act. For high risk AI systems under the EU regulation.
  • SOX. For financial controls and reporting.
  • MiFID II. For investment services in the EU.

How policies are applied

Each ingest event is matched against the active policies that target its action type. Policies are evaluated in priority order. The first matching policy emits the decision. If no policy matches, the platform falls back to risk based defaults driven by detected MAST failure modes.

Generating a compliance report

Open the Compliance page in the dashboard, pick a framework and a date range, and generate a report. Reports are built from the immutable audit log and can be downloaded for your records or for your auditors.

Business Associate Agreements

If your organization handles PHI and needs a BAA, email info@auxdynamics.com and our team will work with you to get one in place.

Data retention

Audit records are append only and retained for the lifetime of your subscription. If you need custom retention windows for a specific framework, contact us and we will configure them for your organization.

Integrations

LLM providers

MastGuard is provider agnostic. You call your model the way you already do, and you send the proposed action to MastGuard before executing it. The SDK does not couple you to any specific provider.

REST API

  • Base URL: https://api.mastguard.io
  • Authentication: X-API-Key header.
  • All responses follow a consistent envelope with success, data, error, and meta fields.

Webhooks

Create endpoints from the Developer page or programmatically via the SDK. Every delivery is signed with HMAC SHA 256 in the X-MastGuard-Signature header (sha256=<hex>). Use MastGuardWebhooks.verifySignature to validate, or run the HMAC yourself.

Microsoft Entra ID (SSO)

Your team can sign in to the dashboard with their Microsoft work account. On the sign in screen choose Continue with Microsoft.

Troubleshooting

SDK call hangs or never returns

Cause. Network egress is blocked, the timeout is too low, or the base URL is wrong for your environment.

Fix. Confirm your machine can reach https://api.mastguard.io. Raise the timeout option if you are on a slow link. The SDK retries 429, 5xx, and network errors automatically, so transient failures should self heal.

Agent does not appear in the dashboard

Cause. No ingest events have been received for that agentId, or the events were sent with a key tied to a different organization.

Fix. Send a test ingest, then refresh the Agents page. Confirm the API key you are using belongs to the same organization you are viewing.

API key errors (401 AuthenticationError)

Cause. The key is missing, expired, revoked, or not being sent on the X-API-Key header.

Fix. Re issue a key from the Developer page, store it in your secret manager, and pass it into new MastGuardClient({ apiKey }). The header is set for you by the SDK.

HITL queue is not clearing

Cause. Tasks require a written rationale and, for dual approval flows, a second reviewer. Tasks also expire on their SLA.

Fix. Open the Review Queue, write a rationale of 10 to 2000 characters, and approve or reject. For dual approval tasks, ask a second reviewer to confirm. Expired tasks move out of the queue automatically.

Every decision is ALLOW

Cause. No policies are active for the action types you are sending, so events fall through to the safe default.

Fix. Open the Policies page, create policies that target the action types you care about, activate them, and confirm priorities. Send a test ingest and check the audit log to see which policies were evaluated.

Audit log shows no events

Cause. Your filters are excluding everything, or events are still in the async pipeline and have not yet resolved.

Fix. Clear the filters at the top of the Audit page. If you are using async ingest, wait a few seconds and refresh. Match by traceId if you have it.

RateLimitError (429)

Cause. You exceeded the per organization or per user request rate.

Fix. Honor the retryAfterSeconds property on the error. The SDK retries automatically by default, so most callers do not need to handle this unless you want custom backoff.

FAQs

Can I monitor multiple agents from one account?

Yes. One organization can govern any number of agents. Each agent is identified by the agentId string you pass on ingest. There is no per agent setup step.

What happens if MastGuard is unavailable?

The SDK retries transient failures with exponential backoff. You decide what your application does on a hard failure: fail open and let the action proceed, fail closed and block it, or queue and replay later. The SDK throws typed errors so you can branch on them.

Is my data stored or just evaluated?

Audit records are written for every decision so that you have a defensible trail. The audit record contains the agent id, action type, a hash of the payload, the decision, the risk score, the failure modes, and the policies evaluated. You control what you put in payload, so you can keep sensitive content out if you prefer.

How do I add team members?

Open Settings, choose your team, and invite by email. Roles control who can review HITL tasks, manage policies, and access billing.

Can I export audit logs?

Yes. Filter the Audit page and export the results. You can also pull audit entries programmatically through client.hitl.getAuditLog.

What is the difference between HITL and BLOCK?

HITL means the action is paused for a human to approve or reject. BLOCK is final: policy stopped the action and it must not proceed. HITL is for judgment calls. BLOCK is for known violations.

How do I delete an agent?

Agents are derived from your event history, so there is no destructive delete. If you stop sending events for an agentId, it stops appearing in active views. The historical audit trail is preserved for compliance.

Is there a free trial?

Yes. New organizations start on a trial with full access to the platform so you can evaluate it end to end. The Billing page shows your trial status and when it ends.

Can I trace a single agent action end to end?

Yes. Every event returns a traceId. Use it to look up the audit record, the HITL task (if any), reviewer history, and the final outcome.

Which action types are supported?

EMAIL_SEND, PAYMENT_APPROVE, RECORD_UPDATE, DOCUMENT_MODIFY, DATA_ACCESS, API_CALL, and OTHER. Use OTHER if your action does not map cleanly, and include the specifics in payload.

Do webhooks retry on failure?

Yes. Deliveries that do not get a 2xx response are retried with backoff. You can see delivery history from the Developer page.

How does dual approval work?

For high stakes flows, a task requires two distinct reviewers to approve before the outcome becomes APPROVED. The first approval moves the task to PARTIALLY_APPROVED. The second approval finalizes it. The same person cannot approve twice.

Does the SDK work in Edge runtimes?

Yes. The SDK works in Node.js 18+ and in Edge runtimes such as Cloudflare Workers and Vercel Edge.

Can I point the SDK at a custom URL?

Yes. Pass baseUrl when constructing the client.

How do I rotate an API key?

Create a new key on the Developer page, switch your application to it, then revoke the old key. Revocation takes effect immediately.

Contact and Support

We read every message. Whether you have a question about getting started, want to report a bug, or just want to share feedback, reach out anytime at info@auxdynamics.com.

Reporting a bug

Use a subject line in this format: [BUG] short description. Tell us how to reproduce it, what you expected to happen, and what actually happened. Include your SDK version, and your browser or runtime environment if it is relevant.

You can copy this template:

To: info@auxdynamics.com
Subject: [BUG] <short description>

SDK version:
Steps to reproduce:
1.
2.
3.

Expected behavior:

Actual behavior:

Environment:
- OS:
- Runtime (Node version, browser, etc.):
- MastGuard SDK version:
- Trace id (if any):
ONE MORE THING
If you are evaluating MastGuard for your team and want a guided walkthrough, ask for one in your email. We are happy to set up a call.