> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mnemom.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Risk Engine

> How to assess, gate, and monitor risk for individual agents and teams using the Mnemom Risk Engine

The risk engine provides real-time, context-aware risk scoring for AI agent actions. There is a TypeScript SDK ([`@mnemom/risk`](https://www.npmjs.com/package/@mnemom/risk)); there is no official Python SDK today, so Python examples below call the REST API directly with `httpx`.

## Quick start

### Individual assessment

Assess whether an agent should be allowed to perform a specific action:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { assessRisk } from '@mnemom/risk';

  const assessment = await assessRisk('agent-abc-123', {
    action_type: 'financial_transaction',
    risk_tolerance: 'conservative',
    amount: 50000,
    counterparty_id: 'vendor-xyz',
  }, { apiKey: process.env.MNEMOM_API_KEY });

  console.log(assessment.risk_level);      // 'low' | 'medium' | 'high' | 'critical'
  console.log(assessment.recommendation);  // 'approve' | 'review' | 'deny'
  console.log(assessment.risk_score);      // 0.0 – 1.0
  ```

  ```python Python theme={null}
  import httpx

  response = httpx.post(
      "https://api.mnemom.ai/v1/risk/assess",
      headers={"Authorization": f"Bearer {token}"},
      json={
          "agent_id": "agent-abc-123",
          "context": {
              "action_type": "financial_transaction",
              "risk_tolerance": "conservative",
              "amount": 50000,
              "counterparty_id": "vendor-xyz",
          },
      },
  )
  assessment = response.json()

  print(assessment["risk_level"])      # 'low' | 'medium' | 'high' | 'critical'
  print(assessment["recommendation"])  # 'approve' | 'review' | 'deny'
  ```
</CodeGroup>

### Team assessment

Assess whether a group of agents is safe to operate together:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { assessTeamRisk } from '@mnemom/risk';

  const teamAssessment = await assessTeamRisk(
    ['agent-a', 'agent-b', 'agent-c'],
    {
      action_type: 'multi_agent_coordination',
      risk_tolerance: 'moderate',
      team_task: 'customer-support-pipeline',
      coordination_mode: 'sequential',
    }
  );

  console.log(teamAssessment.team_risk_level);       // 'low' | 'medium' | 'high' | 'critical'
  console.log(teamAssessment.team_recommendation);   // 'approve_team' | 'approve_individuals_only' | 'deny'
  console.log(teamAssessment.shapley_values);        // { 'agent-a': 0.12, 'agent-b': -0.03, ... }
  console.log(teamAssessment.synergy_type);          // 'synergistic' | 'neutral' | 'anti-synergistic'

  // Team risk assessments contribute to the Team Trust Rating —
  // the Coherence History and Operational Record components are
  // computed from historical team risk assessment results.
  ```

  ```python Python theme={null}
  import httpx

  team = httpx.post(
      "https://api.mnemom.ai/v1/risk/assess/team",
      headers={"Authorization": f"Bearer {token}"},
      json={
          "agent_ids": ["agent-a", "agent-b", "agent-c"],
          "context": {
              "action_type": "multi_agent_coordination",
              "risk_tolerance": "moderate",
              "team_task": "customer-support-pipeline",
              "coordination_mode": "sequential",
          },
      },
  ).json()

  print(team["team_recommendation"])
  print(team["shapley_values"])
  ```
</CodeGroup>

### Which agents you can assess

You can assess any agent whose reputation is public or unlisted, including agents in other organizations — that counterparty check is what the engine is for. Both the individual and team endpoints refuse the rest:

| Case | Response |
| - | - |
| The agent's reputation is private and you are not a member of the org that governs it | `403 reputation_private` |
| The agent has been deleted | `404 agent_not_found` |
| You pass a `team_id` for a team in an org you don't belong to | `404` (the same answer as a team that doesn't exist) |
| Mnemom can't confirm your membership right now | `503 membership_unresolved` — retry |

## Risk gates

Risk gates wrap an assessment call with a pass/fail check against a maximum risk score and/or level, so you can embed a single boolean decision in your agent pipeline instead of interpreting a raw assessment.

### Individual gate

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createRiskGate, financialContext } from '@mnemom/risk';

  const gate = createRiskGate({
    maxRiskLevel: 'medium',  // deny anything above 'medium'
    maxRiskScore: 0.5,       // and/or deny above this raw score
    apiKey: process.env.MNEMOM_API_KEY,
  });

  const result = await gate.check('agent-abc-123', financialContext(1000));

  if (result.allowed) {
    // proceed with the action
  } else {
    // block the action -- there is no separate "review" outcome from the gate
    // itself; use result.assessment.recommendation for finer-grained triage
    console.log(result.reason);
  }
  ```

  ```python Python theme={null}
  import httpx

  RISK_LEVEL_ORDER = ["low", "medium", "high", "critical"]

  def check_risk_gate(agent_id, context, max_level="medium", token=None):
      resp = httpx.post(
          "https://api.mnemom.ai/v1/risk/assess",
          headers={"Authorization": f"Bearer {token}"},
          json={"agent_id": agent_id, "context": context},
      )
      assessment = resp.json()
      allowed = RISK_LEVEL_ORDER.index(assessment["risk_level"]) <= RISK_LEVEL_ORDER.index(max_level)
      return allowed, assessment

  allowed, assessment = check_risk_gate(
      "agent-abc-123",
      {"action_type": "data_access", "risk_tolerance": "moderate"},
      token=token,
  )
  if allowed:
      pass  # proceed
  else:
      print(assessment["recommendation"])  # 'review' or 'deny'
  ```
</CodeGroup>

### Team gate

The team gate has the same `{allowed, assessment, reason}` shape as the individual gate -- gate on `assessment.team_recommendation` for the finer-grained `approve_team` / `approve_individuals_only` / `deny` triage:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createTeamRiskGate } from '@mnemom/risk';

  const teamGate = createTeamRiskGate({
    maxRiskLevel: 'medium',
    apiKey: process.env.MNEMOM_API_KEY,
  });

  const result = await teamGate.check(
    ['agent-a', 'agent-b', 'agent-c'],
    { action_type: 'task_delegation', risk_tolerance: 'conservative' },
  );

  if (!result.allowed) {
    console.log(result.reason);
  } else {
    switch (result.assessment?.team_recommendation) {
      case 'approve_team':
        // full team operation allowed
        break;
      case 'approve_individuals_only':
        // dispatch agents individually, no joint operations
        break;
      case 'deny':
        // block everything
        break;
    }
  }
  ```

  ```python Python theme={null}
  import httpx

  team = httpx.post(
      "https://api.mnemom.ai/v1/risk/assess/team",
      headers={"Authorization": f"Bearer {token}"},
      json={
          "agent_ids": ["agent-a", "agent-b", "agent-c"],
          "context": {"action_type": "task_delegation", "risk_tolerance": "conservative"},
      },
  ).json()

  print(team["team_recommendation"])  # 'approve_team' | 'approve_individuals_only' | 'deny'
  ```
</CodeGroup>

## Context builders

`@mnemom/risk` exports convenience functions that build a `RiskContext` object for common action types:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { financialContext, delegationContext, dataAccessContext } from '@mnemom/risk';

  // Financial transaction with amount and counterparty
  const ctx1 = financialContext(50000, 'vendor-xyz');

  // Task delegation with a coordination mode
  const ctx2 = delegationContext('customer-support-pipeline', 'sequential');

  // Data access with use case
  const ctx3 = dataAccessContext('audit-report-generation');
  ```

  There is no dedicated Python SDK; build the equivalent context object as a plain dict, e.g.:

  ```python Python theme={null}
  ctx1 = {"action_type": "financial_transaction", "amount": 50000, "counterparty_id": "vendor-xyz"}

  ctx2 = {"action_type": "task_delegation", "team_task": "customer-support-pipeline", "coordination_mode": "sequential"}
  ctx3 = {"action_type": "data_access", "use_case": "audit-report-generation"}
  ```
</CodeGroup>

## Understanding the response

### Individual assessment response

```json theme={null}
{
  "assessment_id": "ra_01HXY...",
  "agent_id": "agent-abc-123",
  "risk_score": 0.2847,
  "risk_level": "medium",
  "recommendation": "approve",
  "confidence": 0.80,
  "contributing_factors": [
    {
      "component": "compliance",
      "label": "Compliance",
      "weight": 0.30,
      "raw_value": 720,
      "risk_contribution": 0.084,
      "explanation": "Compliance: score 720/1000, weight 0.30 → risk contribution 0.084"
    }
  ],
  "suggested_thresholds": {
    "low": 0.25,
    "medium": 0.50,
    "high": 0.75,
    "critical": 0.75
  },
  "explanation": "Risk assessment for financial_transaction (moderate tolerance): score 0.2847 (medium), recommendation: approve. Top contributing factors: Compliance, Integrity Ratio, Drift Stability.",
  "proof_id": "prf_01HXY...",
  "proof_status": "pending",
  "created_at": "2026-02-22T12:00:00Z"
}
```

Key fields:

| Field | Description |
| - | - |
| `risk_score` | 0–1 composite risk score |
| `risk_level` | Classification: low, medium, high, critical |
| `recommendation` | Action guidance: approve, review, deny |
| `confidence` | How reliable the score is (based on data availability) |
| `contributing_factors` | Breakdown of which reputation components drove the score |
| `proof_status` | ZK proof lifecycle: none, pending, proving, verified, failed |

### Team assessment response

The team response includes everything from individual assessments plus team-specific analytics:

| Field | Description |
| - | - |
| `team_risk_score` | 0–1 team composite risk |
| `team_coherence_score` | 0–1 inverse of team risk (higher is better) |
| `portfolio_risk` | Aggregate Quality pillar (tail-risk-weighted average) |
| `coherence_risk` | 1 - Coherence Quality pillar (pairwise compatibility) |
| `concentration_risk` | HHI of Shapley values (how concentrated contributions are) |
| `weakest_link_risk` | Maximum individual risk in the team |
| `shapley_values` | Per-agent marginal contribution to team coherence |
| `outliers` | Agents flagged as statistical outliers |
| `clusters` | Groups of agents with correlated risk |
| `value_divergences` | Values not shared across all team members |
| `synergy_type` | Whether the team is better or worse than its individuals |
| `individual_assessments` | Full individual assessment for each team member |

## Monitoring risk over time

Fetch risk assessment history for trend analysis:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { getRiskHistory } from '@mnemom/risk';

  // signature is (agentId, options?, limit = 20) -- limit is a positional arg, not part of options
  const history = await getRiskHistory('agent-abc-123', { apiKey: process.env.MNEMOM_API_KEY }, 50);

  for (const assessment of history) {
    console.log(`${assessment.created_at}: ${assessment.risk_score} (${assessment.risk_level})`);
  }
  ```

  ```python Python theme={null}
  import httpx

  history = httpx.get(
      "https://api.mnemom.ai/v1/risk/history/agent-abc-123",
      headers={"Authorization": f"Bearer {token}"},
      params={"limit": 50},
  ).json()

  for assessment in history["assessments"]:
      print(f"{assessment['created_at']}: {assessment['risk_score']} ({assessment['risk_level']})")
  ```
</CodeGroup>

The Risk Playground in the dashboard provides an interactive visualization of risk history with color-coded risk level bands.

## Verifying ZK proofs

Once a proof is generated, retrieve and verify it:

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { getAssessment } from '@mnemom/risk';

  const assessment = await getAssessment('ra_01HXY...');

  if (assessment.proof_status === 'verified') {
    console.log('Risk score is cryptographically proven correct');
    console.log('Proof ID:', assessment.proof_id);
  }
  ```

  ```python Python theme={null}
  import httpx

  assessment = httpx.get(
      "https://api.mnemom.ai/v1/risk/assessments/ra_01HXY...",
      headers={"Authorization": f"Bearer {token}"},
  ).json()

  if assessment["proof_status"] == "verified":
      print("Risk score is cryptographically proven correct")
  ```
</CodeGroup>

<Note>
  Proofs are generated asynchronously and are best-effort -- the risk score is returned immediately and is valid regardless of whether a proof ever completes. Poll `GET /v1/risk/proofs/:proof_id` to follow a proof through to `verified` or `failed`.
</Note>

## Choosing action types

Select the action type that best matches what the agent is about to do:

| Action Type | When to Use | Emphasizes |
| - | - | - |
| `financial_transaction` | Payments, transfers, purchases | Compliance, integrity |
| `data_access` | Reading sensitive data, exports | Integrity, compliance |
| `task_delegation` | Handing work to another agent | Coherence, integrity |
| `tool_invocation` | Calling external APIs or tools | Integrity, drift stability |
| `autonomous_operation` | Self-directed tasks without supervision | Integrity, compliance |
| `multi_agent_coordination` | Joint operations with other agents | Coherence, integrity |

## Choosing risk tolerance

| Tolerance | Use Case | Effect |
| - | - | - |
| `conservative` | Financial services, healthcare, compliance-critical | Tighter thresholds, flags risk earlier |
| `moderate` | General operations, standard business logic | Balanced thresholds (default) |
| `aggressive` | Internal dev tools, non-critical pipelines | Wider thresholds, allows more latitude |

<Warning>
  Risk tolerance affects classification thresholds, not the underlying score. An agent with a 0.20 risk score gets classified as `medium` under conservative tolerance (medium starts at 0.15) but `low` under moderate tolerance (low goes up to 0.25). The raw score is the same — the interpretation changes.
</Warning>

## Billing

Mnemom uses μ-based usage pricing (1 μ = \$0.01) with no fixed plan tiers -- risk assessments are metered events billed against your μ balance. See [Pricing](/pricing/overview) for current rates and what proof availability requires on your account.

## See also

* [Risk Assessment Concepts](/concepts/risk-assessment) — how the scoring model works
* [Reputation Scores](/concepts/reputation-scores) — the data that feeds risk assessments
* [Team Trust Rating](/concepts/team-reputation) — team reputation built from team risk assessments
* [Team Management](/guides/team-management) — creating and managing teams
* [Fleet Coherence](/concepts/fleet-coherence) — pairwise coherence data used for team risk
* [Security & Trust Model](/guides/security-trust-model) — the full cryptographic verification pipeline


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.