> 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-mcp-guard-service-side.md). Agents can also search and read this documentation through its [MCP server](https://docs.metamynd.ai/~gitbook/mcp).

# agentsafe-mcp-guard (service-side)

`@metamynd/agentsafe-mcp-guard` is the library an MCP server, or any service that executes governed calls, embeds to **independently re-verify** an agent's signed request against the agent's own published policy. It never trusts the agent's own guard. It also claims the agent's hold for single execution and settles it afterwards, which is what makes the service a trustless enforcement point rather than a hopeful one.

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

* **Runtime:** Node ≥ 18. No dependencies (built-in Ed25519 and `fetch`).
* **Exports:** `.` (main), `./policy` (bundle signing/verification), `./policy-core` (the evaluator), `./did` (key-in-DID verification), `./x402` (payment binding helpers).
* **npm:** [@metamynd/agentsafe-mcp-guard](https://www.npmjs.com/package/@metamynd/agentsafe-mcp-guard)

#### Minimal working example

```js
import express from 'express';
import { createMcpGuard } from '@metamynd/agentsafe-mcp-guard';

const guard = createMcpGuard({
  serviceDid: process.env.SERVICE_DID,        // did:key or did:hedera: the key must be inside the DID
  serviceKey: process.env.SERVICE_KEY,        // the service's own Ed25519 key
  issuerApi: 'https://metamynd.ai/api/v1',
  policyPublicKey: process.env.MAGP_POLICY_PUBLIC_KEY, // pinned, from GET /magp/policy/pubkey
  requireAuthorization: true,                 // claim the hold before executing (off by default)
});

async function rawBookFlight(signed, args) { /* real booking, real credentials */ }

const bookFlight = guard.guardIncomingTool('flight-purchase', rawBookFlight, {
  bindPayload: true,            // the args executed must be the payload the agent signed
  requirePayloadBinding: true,  // refuse an authorization the agent did not bind
  settle: true,                 // capture on return; a throw is parked as UNKNOWN
});

const app = express();
app.use(express.json());

app.post('/magp/handshake', async (req, res) => {
  try {
    if (req.body.type === 'HELLO') return res.json(await guard.handshakeChallenge(req.body));
    if (req.body.type === 'PROVE') return res.json(guard.handshakeVerify(req.body));
    res.status(400).json({ error: 'unknown handshake message' });
  } catch (e) {
    res.status(401).json({ error: e.message });
  }
});

app.post('/tools/book-flight', async (req, res) => {
  try {
    res.json(await bookFlight(req.body.signed, req.body.args));
  } catch (e) {
    if (e.name === 'GovernanceBlocked') return res.status(403).json({ error: e.governance });
    throw e;
  }
});
```

{% hint style="warning" %}
**`handshakeChallenge` is `async`** (since 0.5.0). `res.json(guard.handshakeChallenge(...))` without `await` serialises a Promise. `handshakeVerify` is synchronous and throws `HandshakeFailed` on a bad signature.
{% endhint %}

#### `createMcpGuard` options

| Option                            | Default    | What it does                                                                                                                                                                                                                                             |
| --------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `serviceDid`                      | required   | This service's DID. A `did:key` or `did:hedera` plus a key makes claims and settlements **signed** as this identity (see [Service identity](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side#service-identity-and-trusted-counterparties)) |
| `serviceKey`                      | none       | The service's Ed25519 private key (hex). Needed for the handshake and for signed claims                                                                                                                                                                  |
| `keyProvider`, `daemonSocketPath` | none       | `keyProvider: 'daemon'` gets handshake signatures from a service-role [agentsafe-signer](https://docs.metamynd.ai/sdks/agentsafe-signer) daemon                                                                                                          |
| `issuerApi`                       | none       | Where bundles are fetched and holds are claimed and settled (`https://metamynd.ai/api/v1`)                                                                                                                                                               |
| `fetchBundle`                     | none       | Your own `(agentDid) => bundle` source instead of `issuerApi`                                                                                                                                                                                            |
| `policyPublicKey`                 | none       | MetaMynd's policy-signing key. Pin it: see [Pin the policy key](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side#pin-the-policy-key)                                                                                                       |
| `allowUnverifiedBundle`           | `false`    | Local development only: lets an unpinned guard on plain `http://` serve value calls                                                                                                                                                                      |
| `requireAuthorization`            | `false`    | Claim the agent's hold at the issuer before executing a permitted call. Turn it on for anything that moves value                                                                                                                                         |
| `settlementStore`                 | in-process | Durable anti-reuse for `settle()` across instances: `{ reserve, release, finalize }`                                                                                                                                                                     |
| `verifyCapability`                | none       | `(signed) => { ok, reasonCode }`: verify a commitment-bound capability (see [magp-zk](https://docs.metamynd.ai/sdks/magp-zk-zk-module))                                                                                                                  |
| `requireCapability`               | `false`    | With `verifyCapability`, a permit with no capability is blocked (`CAPABILITY_REQUIRED`)                                                                                                                                                                  |

#### Methods

`createMcpGuard()` returns:

```
handshakeChallenge, handshakeVerify, verifyRequest, guardIncomingTool,
requirePayment, settle, claimAuthorization, lookupOutcome,
captureAuthorization, releaseAuthorization, markAuthorizationUnknown, serviceDid
```

| Method                                                                                                               | Returns                                                                                                                                                         | Notes                                                                                                                          |
| -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `await handshakeChallenge(hello)`                                                                                    | `{ handshakeId, toDid, nonceB, sigB, protoVersion }`                                                                                                            | HELLO → CHALLENGE. Needs `serviceKey` or a key provider                                                                        |
| `handshakeVerify({ handshakeId, sigA })`                                                                             | `{ channelId, remoteDid }`                                                                                                                                      | PROVE → READY. Single-use; throws `HandshakeFailed`                                                                            |
| `await verifyRequest(signed, { trustedContext?, payloadDigest?, requirePayloadBinding? })`                           | `{ decision, reasonCode }`                                                                                                                                      | The independent re-check. With `requireAuthorization`, a permit also carries non-enumerable `claimToken` and `authorizationId` |
| `guardIncomingTool(action, handler, opts?)`                                                                          | `async (signed, ...args) => result`                                                                                                                             | Runs `handler(signed, ...args)` only on a permit; otherwise throws `GovernanceBlocked`                                         |
| `await claimAuthorization({ authorizationId, payloadDigest? })`                                                      | `{ claimed, agentDid, action, amount, currency, merchant, payloadDigest, claimToken, counterpartyAuthenticated, replayed }` or `{ claimed: false, reasonCode }` | Used for you by `requireAuthorization`                                                                                         |
| `await lookupOutcome({ authorizationId })`                                                                           | `{ ok, outcome, nothingExecuted, retrySafe, … }`                                                                                                                | Public outcome lookup                                                                                                          |
| `await captureAuthorization({ authorizationId, claimToken, amountCharged, bookingRef?, settlementTxHash?, payTo? })` | `{ ok, reasonCode?, settlementEvidence, amountCharged, authorizedAmount, … }`                                                                                   | Settle what you executed                                                                                                       |
| `await releaseAuthorization({ authorizationId, claimToken, reason? })`                                               | `{ ok, reasonCode? }`                                                                                                                                           | Only for provable non-execution                                                                                                |
| `await markAuthorizationUnknown({ authorizationId, reason?, claimToken })`                                           | `{ ok, reasonCode? }`                                                                                                                                           | For a timeout, a 5xx or a lost response                                                                                        |
| `requirePayment(p)` / `await settle(...)`                                                                            | see [Payments](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side#payments-x402)                                                                    | x402 binding                                                                                                                   |

The settlement helpers never throw. They return `{ ok, reasonCode }`, and a successful call also spreads the issuer's response onto the result (`result.settlementEvidence`), keeping it at `result.data` too.

#### What `verifyRequest` checks

1. Required fields are present (`MALFORMED_REQUEST` otherwise; never a best-effort check of a partial request).
2. The Ed25519 signature over the canonical message, against the key embedded in the agent's DID (`SIGNATURE_INVALID`). Since 0.16.0 the v2 message is rebuilt when the request carries a top-level `jurisdiction`, and v1 when it doesn't. The guard never tries the other, so a jurisdiction stripped, changed or added in transit fails.
3. Payload binding, when the agent signed a digest or you asked for one (see [Payload binding](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side#payload-binding)).
4. Freshness: `issuedAt` may lag by the freshness window but lead by no more than 30 seconds (`REQUEST_EXPIRED`).
5. The agent's policy bundle: fetched, subject-checked (`BUNDLE_SUBJECT_MISMATCH`) and, with `policyPublicKey`, signature- and staleness-checked.
6. Containment (`AGENT_SUSPENDED` / `AGENT_QUARANTINED`) and the operating-mode floor.
7. Standards → SOPs → mandate, with the same `policy-core` the gate runs. Signed fields are applied last, so a forged context key can't shadow them. An action the mandate **never granted** is refused (`NO_PERMISSION_FOR_ACTION` / `NO_MANDATE`); the re-check never falls through to an implicit permit.
8. With `requireAuthorization`, on a permit only: claim the hold and compare it with what is being executed.

Any unexpected error returns `{ decision: 'block', reasonCode: 'GUARD_ERROR' }`.

#### `guardIncomingTool` options

| Option                  | Default | What it does                                                                                                                                                                                                                                                                                                       |
| ----------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `bindPayload`           | `false` | `true` digests the single argument after `signed`, refuses locally if it differs from the digest the agent signed (`PAYLOAD_NOT_BOUND`), and states the digest in the claim. The handler receives the same JSON snapshot that was digested. A function `(signed, ...args) => value` chooses what to digest instead |
| `requirePayloadBinding` | `false` | Also refuse an authorization the agent did not bind (`PAYLOAD_BINDING_REQUIRED`). Needs `bindPayload` (the guard throws at wrap time otherwise)                                                                                                                                                                    |
| `trustedContext`        | none    | Risk this service derives from the real call, never from the agent: an object or `(signed, ...args) => object`. Applied over the agent's claim and labelled `gateway_derived`; the agent can raise its risk above it but never lower it. A deriver that throws or yields nothing usable fails the call closed      |
| `settle`                | `false` | With `requireAuthorization`: a handler that returns is captured at the authorized amount; one that throws is marked **UNKNOWN** (never released, because a throw doesn't prove nothing ran)                                                                                                                        |

The wrapped tool's own `action` is authoritative. A guard that wraps many tools can't be tricked into running an expensive tool's handler with a cheap tool's valid signature.

Without `requireAuthorization`, every permitted value call logs a warning: replay, cumulative spend, rate limits, circuit breakers and spend-anomaly checks are stateful and were not re-verified against the issuer.

#### Pin the policy key

The bundle is what `verifyRequest` enforces, so whoever can change it in flight can change the rules. Fetch `GET /magp/policy/pubkey` once, out of band, and bake it into your config:

```js
const guard = createMcpGuard({ serviceDid, issuerApi: 'https://metamynd.ai/api/v1', policyPublicKey: '<hex from /magp/policy/pubkey>' });
```

| Situation                                    | Result                                                                 |
| -------------------------------------------- | ---------------------------------------------------------------------- |
| Pinned, bundle signature invalid             | `POLICY_BUNDLE_SIGNATURE_INVALID` (any call)                           |
| Pinned, bundle unsigned                      | `POLICY_BUNDLE_UNSIGNED` (every call, amount 0 included, since 0.18.1) |
| Pinned, bundle older than its `maxStaleness` | `POLICY_BUNDLE_STALE` (every call, amount 0 included, since 0.18.1)    |
| **Not pinned**, issuer on plain `http://`    | `POLICY_BUNDLE_UNVERIFIED` for value-bearing calls (since 0.12.0)      |
| Not pinned, issuer on `https://`             | Warns at startup and trusts TLS                                        |
| `allowUnverifiedBundle: true`                | Restores the pre-0.12.0 behaviour. Development only                    |
| Custom `fetchBundle`                         | Your own source; not affected                                          |

MetaMynd re-issues compiled bundles at serve time (a fresh `issuedAt`, re-signed, with `compiledAt` and `compiledSignature` carried), so `maxStaleness` bounds the age of the copy you received. See [Pin the policy key](https://docs.metamynd.ai/guides/pin-the-policy-key) and [Policy bundle pinning & freshness](https://docs.metamynd.ai/agent-protocol/policy-bundle-pinning-and-freshness).

#### Claims and exactly-once execution (`requireAuthorization`)

Re-evaluating policy per request proves the request is well formed and in policy. It does not stop a captured, still-fresh request from being replayed, and it can't enforce the mandate's total budget across many separately legal calls. `requireAuthorization: true` closes both by forcing the exact request back through the stateful gate.

* On a permit, the guard **claims** the hold named by `signed.authorizationId` (`AUTHORIZED → DISPATCHING`). That transition is legal exactly once, so a replay or a race fails with **`AUTHORIZATION_ALREADY_CLAIMED`**.
* The claimed hold's own `agentDid`, `action`, `amount`, `currency` and `merchant` are compared with the call being executed: `AUTHORIZATION_AGENT_MISMATCH`, `AUTHORIZATION_ACTION_MISMATCH`, `AUTHORIZATION_AMOUNT_MISMATCH`, `AUTHORIZATION_CURRENCY_MISMATCH`, `AUTHORIZATION_MERCHANT_MISMATCH`.
* A revoked mandate's hold is refused `AUTHORIZATION_VOIDED`; an expired one `AUTHORIZATION_EXPIRED`.
* Every claim carries a fresh, secret `Idempotency-Key` and is retried **once** if its response is lost (no response, a 5xx, or `EFFECT_TRANSITION_CONTENDED`). If the first attempt had landed, the issuer returns your original grant and the result has `replayed: true`. A definite answer is never retried.
* The `authorizationId` must come from a real `authorize()` on the agent side (an agent-side `guardTool` already seals value actions remotely, so its `decision.authorizationId` is available to thread through).
* A **claimed hold stays committed** to the mandate's cap until it is settled. It does not lapse at the 15-minute hold TTL.

**The claim token.** An anonymous claim returns a claim token as `decision.claimToken`. It is **non-enumerable**, so an echoed, logged, spread or `JSON.stringify`-ed verdict does not carry it to the agent, the one party that must not have it. Keep it server-side: once a hold is claimed, only the claimer can settle it below its amount, void it or mark it unknown.

**Before any retry, look it up.**

```js
const out = await guard.lookupOutcome({ authorizationId });
// out.outcome: not_started | expired | in_flight | settled | not_executed | unknown | reversing | reversed | reversal_failed
if (out.ok && out.retrySafe) { /* re-authorize and retry */ }
```

`retrySafe` is true only for `expired` and `not_executed`. A `not_started` hold is `nothingExecuted` but not retry-safe: it can still be claimed until its window closes, so void it first. Never retry an `unknown` or `in_flight` outcome blindly.

#### Settling what you claimed

| Upstream result                                    | Call                                                                                                           | Budget                           |
| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| Executed                                           | `captureAuthorization({ authorizationId, claimToken, amountCharged, bookingRef?, settlementTxHash?, payTo? })` | Spent                            |
| Provably did **not** execute (a clean refusal)     | `releaseAuthorization({ authorizationId, claimToken, reason })`                                                | Returned                         |
| Ambiguous (a timeout, a 5xx, a dropped connection) | `markAuthorizationUnknown({ authorizationId, reason, claimToken })`                                            | Stays committed until reconciled |

```js
const decision = await guard.verifyRequest(signed);
// … execute …
const r = await guard.captureAuthorization({
  authorizationId: decision.authorizationId,
  claimToken: decision.claimToken,
  amountCharged: 120,
  payTo: '0.0.5005',          // the account you paid: needed when settling BELOW the authorized amount
});
if (!r.ok) console.warn('capture refused', r.reasonCode);
```

* **`payTo`** (0.12.2): a Hedera account id or an EVM address. If the owner lists that merchant's payee accounts, a lowered capture without a listed `payTo` is refused `PAYEE_NOT_REGISTERED`, and the settlement observer only counts a credit to the account you name. `payTo` is not a signed field.
* **Release only what provably did not happen.** A refused release (the owner forced the hold into reconciliation, `HOLD_UNDER_RECONCILIATION`, or it was claimed) is an HTTP 409; the helper still returns `{ ok: false, reasonCode }`.
* `markAuthorizationUnknown` needs the claim token of an anonymous claim; a signed claim needs none.
* Failing to settle can only over-count spend, never under-count it.

See [Settlement & settlement evidence](https://docs.metamynd.ai/agent-protocol/settlement-and-settlement-evidence) and [Settle a claimed hold](https://docs.metamynd.ai/guides/settle-a-claimed-hold).

#### Payload binding

When the agent signed a payload digest (`agentsafe-guard` `payload`, Python `payload=`), `bindPayload: true` makes the claim state the digest of what **this service** is about to execute. The issuer compares it with the digest the agent signed and refuses a difference, leaving the hold claimable by a correct executor.

| Code                          | Meaning                                                                                           |
| ----------------------------- | ------------------------------------------------------------------------------------------------- |
| `PAYLOAD_NOT_BOUND`           | The executed arguments differ from the signed digest (refused locally, nothing claimed)           |
| `PAYLOAD_BINDING_REQUIRED`    | The agent bound nothing and `requirePayloadBinding` is on                                         |
| `PAYLOAD_BINDING_INVALID`     | The agent's binding signature does not verify                                                     |
| `PAYLOAD_DIGEST_INVALID`      | A digest is not `sha256:` + 64 hex                                                                |
| `PAYLOAD_NOT_CANONICALIZABLE` | The arguments cannot be canonical JSON                                                            |
| `PAYLOAD_DIGEST_MISMATCH`     | The grant's digest is not the one this claim stated (for example an issuer that predates binding) |

`verifyRequest(signed, { payloadDigest, requirePayloadBinding })` is the lower-level form. Needs mcp-guard ≥ 0.11.0. See [Payload binding](https://docs.metamynd.ai/core-concepts/payload-binding).

#### Service identity and trusted counterparties

A claim token proves "I made the claim", not who you are. Give the guard a signing identity and it signs the claim and every settlement call instead (since 0.8.0):

```js
const guard = createMcpGuard({
  serviceDid: 'did:key:z6Mk…',     // or did:hedera:…; the key must be the one the DID commits to
  serviceKey: privateKeyHex,
  issuerApi, policyPublicKey, requireAuthorization: true,
});
```

The issuer records `svc:<did>` as the claimer, only that identity can lower or void the hold, and no claim token is issued. Each signed call covers the action, the authorization id, its own values, a one-time nonce and a timestamp. The issuer verifies that the key controls the DID, not that you are trusted. That is the owner's registry:

| Code                                    | Meaning                                                                               | Fix                                                                                |
| --------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `COUNTERPARTY_NOT_REGISTERED`           | The mandate's owner has a trusted-counterparty registry and this service is not on it | The owner registers your `serviceDid` under **Dashboard → Trusted Counterparties** |
| `COUNTERPARTY_AUTH_REQUIRED`            | The registry is enforced and this claim was anonymous                                 | Configure `serviceDid` + `serviceKey`                                              |
| `COUNTERPARTY_NOT_ALLOWED_FOR_MERCHANT` | Your entry is merchant-scoped and this hold's merchant is outside it                  | The owner widens the scope                                                         |
| `COUNTERPARTY_MISMATCH`                 | A settlement call was signed by someone other than the claimer                        | Settle from the identity that claimed                                              |

The registry is enforced for **every mainnet hold**, and on testnet as soon as the owner registers anyone. Nothing was executed on any of these refusals, and the hold stays claimable by a trusted service. See [Trusted counterparties & payee directory](https://docs.metamynd.ai/core-concepts/trusted-counterparties-and-payee-directory) and [Register trusted counterparties & payee accounts](https://docs.metamynd.ai/guides/register-trusted-counterparties-and-payee-accounts).

{% hint style="info" %}
**Daemon-held service keys (0.13.0).** With `keyProvider: 'daemon'` and an `@metamynd/agentsafe-signer` 0.16.0+ daemon started `--role service`, claims and settlement calls are signed as your `serviceDid` by the daemon, so a daemon-backed service is an authenticated counterparty and can claim mainnet holds. Earlier versions signed only the handshake and claimed anonymously (refused with `COUNTERPARTY_AUTH_REQUIRED` wherever the registry is enforced). If the daemon can't sign — not running, or bound to a different DID — the call is not sent anonymously: the claim returns `claimed: false` and the settlement helpers `ok: false`, both with `reasonCode: 'SERVICE_SIGNING_FAILED'`.
{% endhint %}

#### Signed jurisdiction

Since 0.16.0, `verifyRequest` verifies requests that carry a signed top-level `jurisdiction` (MAGP §8.3.12), from `@metamynd/agentsafe-guard` ≥ 0.16.0 or `metamynd-client` ≥ 0.6.0. An older mcp-guard fails those requests `SIGNATURE_INVALID`, so upgrade services before agents start signing the field.

* The mandate's allowed-jurisdictions term and the `jurisdiction-not-allowed` atom are judged on the **signed** value only. An itinerary `jurisdiction` / `mm:jurisdiction` is dropped. A jurisdiction that **this service** derived (`trustedContext.jurisdiction`) is judged by the rule as `gateway_derived`.
* Refusals (hard blocks, exported as `JURISDICTION_REASON_CODES`): `JURISDICTION_REQUIRED`, `JURISDICTION_NOT_ALLOWED`. The third, `JURISDICTION_MISMATCH` (a registered payee's country differs from the signed one), comes only from the issuer's gate, at authorize or claim, because the guard cannot see the owner's payee registry.

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

#### Risk provenance

A missing or unrecognised `riskLevel` escalates (`CONTEXT_UNVERIFIABLE`) for any rule that uses the risk atom (since 0.10.0). The mandate owner's `riskTier` is a floor under the agent's claim, `trustedContext` is another, and a rule with `requireProvenance: { riskLevel: 'gateway_derived' }` is satisfied only by a trusted source. See [Context provenance & risk floors](https://docs.metamynd.ai/core-concepts/context-provenance-and-risk-floors).

#### Payments (x402)

MAGP authorizes and reserves budget; it never custodies funds. This guard binds each x402 settlement to exactly one authorization:

```js
const requirements = guard.requirePayment({
  authorizationId, agentDid, amount: 150, payTo: SERVICE_ADDR, asset: 'USDC', resource: '/book-flight',
});

const { settled, txHash, reasonCode } = await guard.settle({
  requirements, authorizationId, paidAmountMinor, xPayment,
  settleFn: async ({ xPayment }) => facilitator.settle(xPayment),  // returns { settled, txHash }
});
```

`settle` returns `AMOUNT_MISMATCH` for an overpayment, `SETTLEMENT_REUSED` if the authorization already settled, and `SETTLEMENT_FAILED` if the facilitator can't settle, all fail-closed. By default it tracks settled ids in-process; inject a `settlementStore` (for example one backed by `POST /magp/settlement/{reserve,finalize,release}`) so "one settlement per authorization" holds across instances and restarts. Declare the x402 rail at the claim so the hold is **x402-bound** (0.14.0+): `guardIncomingTool(action, handler, { x402: true })`, `verifyRequest(signed, { x402: true })` or `claimAuthorization({ authorizationId, x402: true })`. An x402-bound hold settled *below* its authorization must then be confirmed by the settlement observer, so after `settle()` capture with `settlementTxHash: txHash` and `payTo: requirements.payTo`. Without the flag the claim request is unchanged and the hold is not observed. See [x402 Payment Binding](https://docs.metamynd.ai/agent-protocol/x402-payment-binding).

#### Commitment-bound capabilities

Inject `verifyCapability(signed)` and a request that carries a signed capability must authorize **this exact transaction**: the host reconstructs the transaction and verifies MetaMynd's signature offline (for example with `checkCapabilityBinding`). Presenting a capability is otherwise the caller's choice; `requireCapability: true` blocks a permit that carries none (`CAPABILITY_REQUIRED`).

#### Version notes

| Version | Change                                                                                                                                                                                                                                                                                        |
| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 0.5.0   | `keyProvider: 'daemon'`; **`handshakeChallenge` became `async`**                                                                                                                                                                                                                              |
| 0.5.3   | Claims refuse revoked (`AUTHORIZATION_VOIDED`) and expired (`AUTHORIZATION_EXPIRED`) holds and a different action (`AUTHORIZATION_ACTION_MISMATCH`)                                                                                                                                           |
| 0.7.0   | Claim token relayed; `captureAuthorization`, `releaseAuthorization`, `markAuthorizationUnknown`; `guardIncomingTool({ settle })`                                                                                                                                                              |
| 0.8.0   | Signed service identity for claims and settlements                                                                                                                                                                                                                                            |
| 0.9.0   | Claim `Idempotency-Key` + one retry; `AUTHORIZATION_ALREADY_CLAIMED`; `lookupOutcome`                                                                                                                                                                                                         |
| 0.10.0  | Risk provenance; `trustedContext`                                                                                                                                                                                                                                                             |
| 0.11.0  | Payload binding (`bindPayload`, `requirePayloadBinding`)                                                                                                                                                                                                                                      |
| 0.12.0  | `POLICY_BUNDLE_UNVERIFIED` for an unpinned guard on plain http; `allowUnverifiedBundle`                                                                                                                                                                                                       |
| 0.12.2  | `captureAuthorization({ payTo })`                                                                                                                                                                                                                                                             |
| 0.16.0  | Signed jurisdiction: v2 message verified; jurisdiction judged on the signed value only; `JURISDICTION_REASON_CODES`                                                                                                                                                                           |
| 0.17.0  | Verifies the agent's `envelopeSignature` (context signature, MAGP §8.3.13) before judging the itinerary: an altered context → `CONTEXT_SIGNATURE_INVALID` (0.16.0 ignored it). `requireContextSignature` (factory, per call, per tool) refuses an unsigned one (`CONTEXT_SIGNATURE_REQUIRED`) |

#### Where this fits

MetaMynd is the control plane: it publishes the DID resolver (`GET /did/:did`) and the signed policy bundle (`GET /policy/bundle/:did`). The agent guard and this service guard are the data plane. A value-bearing action is governed by both: the agent's guard, then this guard's independent re-check and claim. For plain HTTP APIs, [agentsafe-http-gateway](https://docs.metamynd.ai/sdks/agentsafe-http-gateway) wraps this guard as a reverse proxy; for Agent2Agent, see [agentsafe-a2a-guard](https://docs.metamynd.ai/sdks/agentsafe-a2a-guard). Walkthrough: [Integrate an MCP Server](https://docs.metamynd.ai/guides/integrate-an-mcp-server).


---

# 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-mcp-guard-service-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.
