> For the complete documentation index, see [llms.txt](https://docs.metamynd.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.metamynd.ai/sdks/agentsafe-guard-agent-side.md). Agents can also search and read this documentation through its [MCP server](https://docs.metamynd.ai/~gitbook/mcp).

# agentsafe-guard (agent-side)

The zero-dependency Node library an agent embeds to sign requests, call the gate, and wrap tools so they run only when the action is allowed.

`@metamynd/agentsafe-guard` is the zero-dependency Node library an AI agent embeds to speak MAGP. It signs requests, calls the gate, and wraps tool functions so they only run on a permit.

{% code overflow="wrap" %}

```
npm i @metamynd/agentsafe-guard
```

{% endcode %}

* **Runtime:** Node ≥ 18 (built-in `fetch` and Ed25519). ESM only (`"type": "module"`). No dependencies.
* **Exports:** `.` (the guard), `./policy-core` (the deterministic evaluator the gate runs), `./verify` (the verifier behind the `verify` CLI).
* **npm:** [@metamynd/agentsafe-guard](https://www.npmjs.com/package/@metamynd/agentsafe-guard) · source: [github.com/Metamynd/agentsafe-guard](https://github.com/Metamynd/agentsafe-guard)

#### Try it first: no account, no network

{% code overflow="wrap" %}

```
npx @metamynd/agentsafe-guard demo
```

{% endcode %}

Runs the policy engine in-process against a sample bundle and prints the verdict for a dozen tool calls (allow, observe, block, escalate, quarantine). It mints an ephemeral key, never opens a socket, and exits non-zero if any verdict disagrees with the policy, so it doubles as a smoke test of the installed package.

#### Governance as a build step: `verify`

{% code overflow="wrap" %}

```
npx @metamynd/agentsafe-guard verify
```

{% endcode %}

Asserts your agent **cannot** exceed its mandate and exits non-zero if it can. Put it in CI and a pull request that widens an agent's authority fails the build.

{% code overflow="wrap" %}

```
  ok   permits ordinary in-scope work  ok   refuses an action the mandate never granted   → block/NO_PERMISSION_FOR_ACTION  ok   refuses 501 against a cap of 500              → block/SOP_SPEND_CAP  n/a  no merchant allow-list in this mandate       EVERY merchant is permitted (the gate holds the first payment to each for review)
```

{% endcode %}

A control the mandate does not set is **reported, never passed**.

| Flag                                    | Effect                                                                                                                                                                                      |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--config <path>`                       | The agent config to check (default `./agent.metamynd.json`)                                                                                                                                 |
| `--require merchants,perTxn,cumulative` | Turns "not configured" into a build failure for the controls you list                                                                                                                       |
| `--context <file>`                      | A JSON file of request fields to evaluate with (needed when your rules require inputs such as `consent`; put a jurisdiction at the top level as `jurisdiction`, since it is a signed field) |
| `--json`                                | Machine-readable output                                                                                                                                                                     |

Evaluation is local and pure: no holds are minted, no nonces spent, no budget consumed. A run costs one GET. `AGENT_KEY`, `AGENT_DID` and `METAMYND_API` override `agent.metamynd.json`, so you can commit a key-less config and set the key as a CI secret.

The same check ships as a GitHub Action that writes a pass/fail table into the PR's checks summary:

{% code overflow="wrap" %}

```
- uses: Metamynd/agentsafe-guard/packages/agentsafe-guard@v0.5.3  with:    config: ./agent.metamynd.json    require: merchants,perTxn  env:    AGENT_KEY: ${{ secrets.AGENT_KEY }}
```

{% endcode %}

Inputs: `config` (default `./agent.metamynd.json`), `require`, `version` (the guard version to run, default `latest`), `working-directory`. Output: `ok`. Pin the action to a released tag, never `@main`.

#### Creating a guard

{% code overflow="wrap" %}

```
import { createGuard, createGuardFromConfig } from '@metamynd/agentsafe-guard';
// Preferred: load the portable config written by create-metamynd-agent or the dashboard.const guard = await createGuardFromConfig('./agent.metamynd.json');
// Or configure explicitly:const guardExplicit = createGuard({  api: process.env.AGENTSAFE_API,  agentDid: process.env.AGENT_DID,  agentKey: process.env.AGENT_KEY,   // held only by the agent});
```

{% endcode %}

`createGuardFromConfig(pathOrUrlOrObject, overrides)` accepts a file path, an `https://` URL or the config object itself. Any option below can be passed as an override.

| Option                            | Default                     | What it does                                                                                                                                                                                  |
| --------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api`, `agentDid`                 | from config                 | The gate's API base and the agent's DID (required)                                                                                                                                            |
| `agentKey`                        | from config                 | The agent's Ed25519 private key (hex)                                                                                                                                                         |
| `keyProvider`, `daemonSocketPath` | `staticKey`                 | `keyProvider: 'daemon'` signs through a local [agentsafe-signer](https://docs.metamynd.ai/sdks/agentsafe-signer) daemon so the key never enters this process                                  |
| `passphrase`                      | none                        | `createGuardFromConfig` only: decrypts a passphrase-encrypted managed key (`agentKeyEncrypted`) in memory                                                                                     |
| `mode`                            | `'local'`                   | `'local'` (local-first) or `'remote'` (every call goes to the gate). See [Enforcement mode](https://docs.metamynd.ai/sdks/agentsafe-guard-agent-side#enforcement-mode-local-first-by-default) |
| `sealValueActions`                | `true`                      | In local mode, an allowed value action is still sealed by the remote gate. `false` = pure offline (you give up the cumulative cap and evidence)                                               |
| `verifyOnChain`                   | `false`                     | Trust the cached bundle only if it is the latest one anchored on Hedera. See [below](https://docs.metamynd.ai/sdks/agentsafe-guard-agent-side#trustless-currency-check-verifyonchain)         |
| `bundleUrl`                       | `{api}/policy/bundle/{did}` | Where the signed policy bundle is fetched from                                                                                                                                                |
| `executionAdapter`                | live                        | Guard-wide execution adapter (dry-run, sandbox). `AGENTSAFE_EXECUTION_MODE=dry-run` sets it from the environment                                                                              |
| `signContext`                     | `false`                     | Also sign the GovernanceEnvelope hash, so a counterparty can prove the agent's key attested the context it sent                                                                               |

#### Wrapping a tool (the common case)

{% code overflow="wrap" %}

```
async function bookFlight(args) { /* …call the airline… */ return { pnr: 'ABC123' }; }
const gatedBookFlight = guard.guardTool(  'flight-purchase',              // the governed action = a scope in the agent's mandate  bookFlight,  (a) => ({    amount: a.amount,    currency: 'USD',    merchant: a.merchant,    // `resource` is a SIGNED field: what this call touches, checked against a mandate's    // resource-scope constraint the same way `merchant` is. Omit it if the action has none.    resource: a.resource,    // `jurisdiction` is SIGNED too (0.16.0): top-level, never in `context`, where the gate ignores it.    jurisdiction: a.jurisdiction,    context: { tool: 'book-flight', riskLevel: a.riskLevel },    // Optional: bind the complete payload the executor will receive (see Payload binding).    payload: { airline: a.merchant, amount: a.amount, passenger: a.passenger },  }),);
```

{% endcode %}

`guardTool` throws `GovernanceBlocked` (with `.governance` holding the decision) on any non-permitting disposition. Your tool function only runs on `allow` or `observe`; `observe` is permit-but-flag and logs a warning. The handler receives `(args, decision)`, so a value-bearing tool can pass `decision.authorizationId` on to the service that executes it.

{% hint style="warning" %} **Send a `riskLevel`.** A rule that judges risk escalates a request with a missing or unrecognised `riskLevel` (`CONTEXT_UNVERIFIABLE`) instead of treating it as low risk. `"HIGH"` and `" high "` are read as `high`. The mandate's owner can set a `riskTier` that the agent's claim can never lower. See [Context provenance & risk floors](https://docs.metamynd.ai/core-concepts/context-provenance-and-risk-floors). {% endhint %}

{% hint style="info" %} **No context means leaving it out, not `null`.** Omit `context`, or pass `{}`, when there is nothing to send. A rule that needed a field then escalates `CONTEXT_UNVERIFIABLE`. `context: null` is different: it goes out as `itinerary: null`, which fails the gate's request schema, so the request is refused `400` / `MALFORMED_REQUEST` before any rule runs. The same applies to a context that isn't an object. Both are safe refusals, with different reason codes. {% endhint %}

#### Calling the gate directly

{% code overflow="wrap" %}

```
const d = await guard.authorize({  action: 'flight-purchase', amount: 5000, currency: 'USD', merchant: 'skyward-air',  context: { riskLevel: 'high' },});if (d.decision === 'escalate') {  const outcome = await guard.escalationStatus(d.escalationId);}
```

{% endcode %}

`authorize()` never throws on a policy decision and fails **closed**: a network or gate failure returns `{ decision: 'block', reasonCode: 'GATE_UNREACHABLE' }` (or `SIGNER_UNREACHABLE` when a daemon key provider could not be reached). It never silently permits.

* `guard.authorize(...)` is always the explicit **remote** call.
* `guard.authorizeLocal(...)` is the explicit local-first call.
* `guard.check(...)` follows the configured `mode` (this is what `guardTool` uses).

All three return `{ decision, reasonCode, authorizationId, … }`.

#### Enforcement mode: local-first by default

The guard decides **locally by default**. `guardTool` and `check` evaluate the rule layer against the agent's cached signed policy bundle using the same `policy-core` the gate runs, so a block or escalate needs no network. An **allowed value action** (`amount > 0`) is still sealed by the remote gate, because the cumulative-spend cap, nonce/replay protection and anchored evidence must be server-side. If the bundle can't be fetched, the guard defers to the remote gate; a value action it can neither evaluate nor seal fails closed.

A block, escalate or non-value allow decided locally is reported to the gate as a best-effort, signed **local decision receipt**. It appears in the Activity Log and fleet decision mix, but it is not anchored evidence.

{% code overflow="wrap" %}

```
const guard   = await createGuardFromConfig('./agent.metamynd.json');                      // local-firstconst remote  = await createGuardFromConfig('./agent.metamynd.json', { mode: 'remote' });  // every call hits the gateconst offline = await createGuardFromConfig('./agent.metamynd.json', { mode: 'local', sealValueActions: false });
```

{% endcode %}

#### Payload binding

The signed authorize message covers the agent, action, amount, currency, merchant and resource. It does not cover a payee, an account number or a passenger list. Pass `payload` and the guard also signs an RFC 8785 canonical-JSON `sha256:` digest of the complete payload, bound to that one authorization:

{% code overflow="wrap" %}

```
await guard.authorize({  action: 'wire', amount: 250, currency: 'USD', merchant: 'skyward-air', context: { riskLevel: 'low' },  payload: { payee: { iban: 'NL91ABNA0417164300' }, reference: 'INV-1042' },});
```

{% endcode %}

* Pass the payload exactly as the executing service will receive it as JSON. From `guardTool`, have `mapArgs` return `payload`.
* The service that executes it (an [agentsafe-mcp-guard](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side) with `bindPayload`, or an [agentsafe-http-gateway](https://docs.metamynd.ai/sdks/agentsafe-http-gateway)) presents the digest of what it is about to run; a claim with a different payload is refused.
* It fails **closed**, never unbound: a payload JSON cannot carry (`NaN`, a function, a lone surrogate) blocks with `PAYLOAD_NOT_CANONICALIZABLE`; a key provider that cannot sign a binding blocks with `PAYLOAD_BINDING_UNSUPPORTED`.
* The gate echoes the digest it stored. A permit that does not echo it is refused with `PAYLOAD_BINDING_NOT_CONFIRMED` and the hold is released, so a proxy that strips the fields is a loud failure.
* A mandate issued with `requirePayloadBinding: true` makes the gate refuse an unbound authorization for that action (`PAYLOAD_BINDING_REQUIRED`).

**Late binding after a reviewer's MODIFY.** A modified action mints a hold with no digest. Bind the payload of the action that will actually run, then hand the executor a fresh signed request:

{% code overflow="wrap" %}

```
const status = await guard.escalationStatus(escalationId);            // approved, or modifiedconst bound = await guard.bindPayload({ authorizationId: status.authorizationId, action, payload });if (!bound.bound) throw new Error(`payload not bound: ${bound.reasonCode}`);const signed = { ...(await guard.buildSignedRequest({ action, ...modified, payload })), authorizationId: status.authorizationId };
```

{% endcode %}

`bindPayload` never throws for a gate answer. It returns `{ bound: true, payloadDigest }` or `{ bound: false, reasonCode }` (`PAYLOAD_ALREADY_BOUND`, `AUTHORIZATION_ALREADY_CLAIMED`, `PAYLOAD_BINDING_NOT_CONFIRMED`, …). The gate applies it only while the hold is live, unclaimed and unbound.

Version notes: payload binding needs guard ≥ 0.14.0; `bindPayload` and daemon-signed bindings need ≥ 0.15.0 (and `@metamynd/agentsafe-signer` ≥ 0.15.0). See [Payload binding](https://docs.metamynd.ai/core-concepts/payload-binding) and [Require payload binding](https://docs.metamynd.ai/guides/require-payload-binding).

#### Signed jurisdiction

Since 0.16.0, `authorize()`, `buildSignedRequest()`, `guardTool`'s `mapArgs` and `evaluateLocally`'s `request` take a top-level `jurisdiction` (ISO 3166-1 alpha-2):

{% code overflow="wrap" %}

```
await guard.authorize({ action: 'flight-purchase', amount: 150, merchant: 'skyward-air', jurisdiction: 'SG', context: { riskLevel: 'low' } });
```

{% endcode %}

* The value is trimmed, checked to be two ASCII letters, and upper-cased. Anything else is refused locally: `authorize()` returns `block` / `MALFORMED_REQUEST`, `buildSignedRequest()` throws, and nothing is sent.
* It is signed as the v2 message (`…|issuedAt|MAGP-AUTH-v2|<jurisdiction>`). Without it, the request is the v1 message byte for byte.
* A `jurisdiction` inside `context` is ignored by the gate and by `evaluateLocally`, and is never promoted to the signed field.
* **A registered payee's country wins.** If the owner registered the merchant with a country, that country is the effective jurisdiction, and a signed value that differs is refused `JURISDICTION_MISMATCH`.
* Refusals (all hard blocks, exported as `JURISDICTION_REASON_CODES`): `JURISDICTION_REQUIRED`, `JURISDICTION_NOT_ALLOWED`, `JURISDICTION_MISMATCH`. The local pre-check mirrors the first two. Only the gate can see the payee registry, so only the gate returns `JURISDICTION_MISMATCH`.
* With `keyProvider: 'daemon'`, the daemon must be `@metamynd/agentsafe-signer` ≥ 0.18.0. With an older daemon the request is refused `JURISDICTION_SIGNING_UNSUPPORTED` before it is sent.
* `normalizeJurisdiction(value)` is exported.

See [Restrict Jurisdictions](https://docs.metamynd.ai/guides/restrict-jurisdictions).

#### The context is signed (on by default since 0.17.0)

Every request carries `envelopeSignature`, the agent's signature over the envelope hash that covers `context` (sent as `itinerary`), `trace` and `materiality` (MAGP §8.3.13). The gate, and services on agentsafe-mcp-guard ≥ 0.17.0 / agentsafe-a2a-guard ≥ 0.12.0 / agentsafe-http-gateway ≥ 0.15.0, refuse a context altered after signing (`CONTEXT_SIGNATURE_INVALID`); older services ignore the field. Opt out with `createGuard({ ..., signContext: false })`. The context/trace/materiality are sent as their JSON and `trace` keeps only the keys the gate accepts. If the key provider cannot produce a verifying signature (a custom provider without `signEnvelope`; a signer daemon older than 0.19.0 for a request with no amount or currency) the request is refused `CONTEXT_SIGNING_UNSUPPORTED` before it is sent, never sent unsigned.

#### Trustless currency check (`verifyOnChain`)

Local evaluation trusts a bundle fetched over TLS. With `{ verifyOnChain: true }` the guard also confirms, from a **public Hedera mirror node with MetaMynd offline**, that its cached policy bundle is the **latest one anchored on the agent's own topic**. On each recompile MetaMynd publishes the SHA-256 of the compiled bundle's signature as a `policy-update` operation; the guard compares it with its bundle's `compiledSignature` (bundles are re-issued at serve time, so the anchored compile signature travels with them). A monotonic sequence number defeats a mirror that hides recent updates, and a rollback to an older signed bundle is detected.

If it can't confirm (mismatch, not yet anchored, mirror down), the guard **defers to the remote gate** rather than evaluate a bundle it can't prove is current.

{% code overflow="wrap" %}

```
const guard = await createGuardFromConfig('./agent.metamynd.json', { verifyOnChain: true });await guard.policyAnchor(); // → { sigDigest, seq } read from Hedera (or null)
```

{% endcode %}

See [Policy bundle pinning & freshness](https://docs.metamynd.ai/agent-protocol/policy-bundle-pinning-and-freshness).

#### Push invalidation (`watchPolicy`)

{% code overflow="wrap" %}

```
const stop = guard.watchPolicy((change) => console.log('rules changed', change));// … later: stop.close();
```

{% endcode %}

Subscribes to `GET /policy/events/:did` (Server-Sent Events, plain `fetch`). A rule change invalidates the cached bundle in about a second, and the next call re-fetches and re-verifies. It reconnects automatically; a dropped stream still leaves `maxStaleness` and the on-chain check as the floor.

#### Key custody

| Option                                       | Where the key lives                                                                                                                                                                                            |
| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agentKey` (default)                         | Raw hex key in this process                                                                                                                                                                                    |
| Passphrase-encrypted managed key             | `agent.metamynd.json` carries `agentKeyEncrypted` (`agentKey: null`). Decrypted in memory: `createGuardFromConfig(path, { passphrase })`. **Losing the passphrase is unrecoverable**; MetaMynd never stores it |
| `keyProvider: 'daemon'` + `daemonSocketPath` | A separate [agentsafe-signer](https://docs.metamynd.ai/sdks/agentsafe-signer) process. The key never enters this process                                                                                       |

{% code overflow="wrap" %}

```
const guard = createGuard({  api: 'https://metamynd.ai/api/v1',  agentDid: process.env.AGENT_DID,  keyProvider: 'daemon',  daemonSocketPath: './.agentsafe-signer/signer.sock',});
```

{% endcode %}

**Bring your own key (BYOK).** Provision the agent with your own public key so MetaMynd never sees the private key. The identity is issued unverified with a one-time `challenge`, and the gate blocks it (`AGENT_KEY_UNVERIFIED`) until you prove control:

{% code overflow="wrap" %}

```
const guard = await createGuardFromConfig('./agent.metamynd.json', { agentKey: myPrivateKey });await guard.verifyKey({ ref: config.identityId, challenge: config.challenge, token: ownerToken }); // one-time
```

{% endcode %}

`await guard.signChallenge(challenge)` returns just the hex signature if you'd rather submit verify-key yourself. `npm create metamynd-agent@latest -- --byok` does all of this for you.

{% hint style="info" %} Since 0.9.0, `buildSignedRequest`, `signChallenge` and `handshake().prove()` are `async`. Add `await`. {% endhint %}

#### Holds, capture and who settles

A permitted value action reserves a **hold** against the mandate's cap. Settlement is normally the job of the **service that executes** the action: it claims the hold and captures, releases or marks it unknown with [agentsafe-mcp-guard](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side) or [agentsafe-http-gateway](https://docs.metamynd.ai/sdks/agentsafe-http-gateway).

When the agent executes the action itself (no separate executor), it reconciles the hold:

{% code overflow="wrap" %}

```
await guard.capture(authorizationId, amountCharged, bookingRef, settlementTxHash);
```

{% endcode %}

* `capture` returns the gate's response and does not throw.
* Once a service has **claimed** the hold, the agent can capture it only at the **full authorized amount** and cannot void it; the gate refuses. Otherwise an agent could wait for a purchase to happen and then take its budget back. There is no `payTo` on the agent side.
* An unclaimed hold that is never captured lapses at its expiry (`POST /policy/mandate/authorize/:id/void` releases it early). A claimed hold stays committed until it is settled.

See [Holds, claims & exactly-once execution](https://docs.metamynd.ai/core-concepts/holds-claims-and-exactly-once-execution).

**Effect lifecycle methods.** `effectDispatching`, `effectDispatched`, `effectUnknown` and `effectStatus` report the external-effect lifecycle. `effectStatus(authorizationId)` is the public outcome lookup (`GET /policy/mandate/authorize/{id}/effect`). `effect/unknown` now accepts only the hold's **claimer** (its signature or claim token), its owner or an admin. `guard.effectUnknown()` is **deprecated** (agentsafe-guard 0.15.4): the agent is not the claimer, so the method now rejects locally with `EffectUnknownNotSupported` (`code: EFFECT_UNKNOWN_AGENT_UNSUPPORTED`) and never calls the gate. Report an ambiguous outcome from the executing service with `markAuthorizationUnknown`.

#### Payments (x402)

After `authorize` allows, the service returns a 402 bound to your `authorizationId`. `guard.preparePayment(requirements, authorizationId)` refuses an unbound 402 (`UnboundPayment`) or one whose authorization doesn't match yours (`AuthorizationMismatch`). Pay via x402, then the executing service settles. See [x402 Payment Binding](https://docs.metamynd.ai/agent-protocol/x402-payment-binding).

#### Evaluate locally (no network)

{% code overflow="wrap" %}

```
const verdict = guard.evaluateLocally({  standards: [{ standardKey: 'eu-ai-act', document: { molecules: [/* … */] } }],  sops:      [{ standardKey: 'sop:travel', document: { molecules: [/* … */] } }],  mandate:   { permission: [/* ODRL constraints … */] },  request:   { action: 'flight-purchase', amount: 600, merchant: 'amadeus', context: { riskLevel: 'low' } },});// → { decision: 'block', reasonCode: 'SOP_SPEND_CAP', authorizationId: null, remaining: null, proofRef: null }
```

{% endcode %}

Same verdict shape as the gate, computed purely locally. When resolving `mandate` from a fetched bundle for a specific action, an action with **no matching mandate** is refused (`NO_PERMISSION_FOR_ACTION` / `NO_MANDATE`) rather than falling through to an unrelated mandate. `guard.guardToolLocal(action, handler, mapArgs, { standards, sops, mandate })` wraps a tool against a local bundle and makes no network call at all, so it leaves no server-side trail. Signed fields (`amount`, `merchant`, `resource`) are always applied over the unsigned `context`, so a forged context key cannot shadow them.

#### Execution adapters (dry-run / sandbox)

An ExecutionAdapter sits between the verdict and the side effect, so the same governed decision can run live, as a dry run, or in a sandbox. A blocked or escalated action still throws before any adapter is consulted.

{% code overflow="wrap" %}

```
import { dryRunExecutionAdapter } from '@metamynd/agentsafe-guard';
const guard = createGuard({ api, agentDid, agentKey, executionAdapter: dryRunExecutionAdapter }); // or AGENTSAFE_EXECUTION_MODE=dry-runconst preview = guard.guardTool('flight-purchase', bookFlight, mapArgs, { executionAdapter: dryRunExecutionAdapter });await preview({ amount: 100 }); // → { dryRun: true, action, decision, authorizationId, args }; bookFlight never runs
// Custom: run the real handler with proceed(), or return something else to substitute it.const sandboxed = (ctx) => ctx.action === 'flight-purchase' ? sandboxBook(ctx.args) : ctx.proceed();
```

{% endcode %}

#### Mutual handshake with a service

{% code overflow="wrap" %}

```
const hs = guard.handshake();const { nonceA, message } = hs.hello();                                // → send HELLO to the serviceconst { sigA, handshakeId } = await hs.prove({ nonceA, challenge });   // verifies the service, → send PROVE
```

{% endcode %}

`prove()` throws `HandshakeFailed` if the service's CHALLENGE does not verify against the key in its DID. The service side is [agentsafe-mcp-guard](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side).

#### Escalation

{% code overflow="wrap" %}

```
const d = await guard.authorize({ action: 'flight-purchase', amount: 5000, context: { riskLevel: 'high' } });if (d.decision === 'escalate') {  const outcome = await guard.escalationStatus(d.escalationId);  // → { status: 'approved' | 'denied' | 'expired' | 'pending' | 'modified', authorizationId, reasonCode, … }}
```

{% endcode %}

An escalation is a hold, not a denial. Act only on `approved`. A `modified` outcome means a reviewer changed the action: it carries the follow-up escalation id and is never a go-ahead for the original request. See [Handle an Escalation](https://docs.metamynd.ai/guides/handle-an-escalation).

#### Evidence proofs

`await guard.proof(eventId)` fetches the Merkle inclusion proof for a decision's evidence record and **verifies it locally**. It returns `status: 'verified' | 'pending' | 'failed' | 'unreachable'`. `pending` means the batch is not anchored yet (anchoring is asynchronous); `failed` means a proof was returned and does not reconstruct the root. Confirming that the root is on Hedera is a separate check: see [magp-evidence](https://docs.metamynd.ai/sdks/protocol-building-blocks).

#### Full method surface

`createGuard()` returns:

{% code overflow="wrap" %}

```
authorize, authorizeLocal, check, loadBundle, policyAnchor, watchPolicy, mode,verifyOnChain, buildSignedRequest, bindPayload, capture, guardTool, evaluateLocally,guardToolLocal, handshake, preparePayment, escalationStatus, proof,effectDispatching, effectDispatched, effectUnknown, effectStatus,verifyKey, signChallenge, agentDid, executionAdapter
```

{% endcode %}

#### Refusal codes this package produces itself

| Code                               | When                                                                                                                                                                                                                                                                                            |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GATE_UNREACHABLE`                 | The gate could not be reached (fail closed)                                                                                                                                                                                                                                                     |
| `SIGNER_UNREACHABLE`               | The signer daemon could not be reached (fail closed)                                                                                                                                                                                                                                            |
| `GATE_HTTP_<status>`               | The gate answered with an unexpected HTTP status                                                                                                                                                                                                                                                |
| `PAYLOAD_NOT_CANONICALIZABLE`      | The payload cannot be represented as canonical JSON                                                                                                                                                                                                                                             |
| `PAYLOAD_BINDING_UNSUPPORTED`      | The key provider cannot sign a payload binding                                                                                                                                                                                                                                                  |
| `PAYLOAD_BINDING_NOT_CONFIRMED`    | The gate did not echo the payload digest; the hold is released                                                                                                                                                                                                                                  |
| `LOCAL_EVAL_ERROR`                 | `guardToolLocal` could not evaluate (fail closed)                                                                                                                                                                                                                                               |
| `MALFORMED_REQUEST`                | `bindPayload` called without `authorizationId`, `action` or `payload`; or a `jurisdiction` that is not two ASCII letters                                                                                                                                                                        |
| `JURISDICTION_SIGNING_UNSUPPORTED` | A `jurisdiction` was given but the signer daemon did not echo it (older than agentsafe-signer 0.18.0); nothing is sent                                                                                                                                                                          |
| `CONTEXT_SIGNING_UNSUPPORTED`      | The context is signed by default and the key provider cannot produce a signature the gate would verify (a custom provider without `signEnvelope`; a signer daemon older than 0.19.0 for a request with no amount or currency); nothing is sent. Upgrade the signer or pass `signContext: false` |

Every other reason code comes from the gate. See the [Reason Code Registry](https://docs.metamynd.ai/agent-protocol/reason-code-registry).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.metamynd.ai/sdks/agentsafe-guard-agent-side.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
