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

# Integrate an MCP Server

{% embed url="<https://youtu.be/XZ3CgvoUsec>" %}

If you're building the *service* side — an MCP server that should only execute a tool call when it's actually authorised, and shouldn't have to trust the caller's word for it — this is your guide. Library reference: [agentsafe-mcp-guard](https://docs.metamynd.ai/sdks/agentsafe-mcp-guard-service-side) (`@metamynd/agentsafe-mcp-guard`, Node ≥ 18, zero external dependencies).

Governing a plain HTTP API or an Agent2Agent skill instead? The same model applies through [agentsafe-http-gateway](https://docs.metamynd.ai/sdks/agentsafe-http-gateway) and [agentsafe-a2a-guard](https://docs.metamynd.ai/sdks/agentsafe-a2a-guard).

By the end you will have a flight-booking tool server that runs a booking once per authorization, refuses a replay and a changed payload, and settles every hold it claims. Every snippet below is the code of a working run, written for mcp-guard 0.35.

#### The shape of the integration <a href="#user-content-the-shape-of-the-integration" id="user-content-the-shape-of-the-integration"></a>

1. Give the service its own identity, pin MetaMynd's policy key, and name the agents it serves.
2. Implement the handshake so agents can mutually authenticate with your service.
3. Wrap every governed tool with `guardIncomingTool`. Never call the real implementation from an unwrapped route.
4. Turn on `requireAuthorization` and payload binding.
5. Have the mandate's owner register your service as a trusted counterparty. Your service signs its consent.
6. Settle every hold you claim.
7. Call the service from the agent, and check the refusals.

#### What you need <a href="#user-content-what-you-need" id="user-content-what-you-need"></a>

* Node 18 or later.
* An agent with a mandate for the action your tool performs (`flight-purchase` here). [Onboard Your First Agent](https://docs.metamynd.ai/guides/onboard-your-first-agent) creates one, and writes the agent's `agent.metamynd.json`.
* Access to the dashboard of that agent's owner, for step 5.

```
npm install @metamynd/agentsafe-mcp-guard express
```

`express` is only the web framework these examples use; the guard itself has no dependencies.

#### Step 1 — Identity, the policy key and the agents you serve <a href="#user-content-step-1--identity-the-policy-key-and-the-agents-you-serve" id="user-content-step-1--identity-the-policy-key-and-the-agents-you-serve"></a>

**Make the service's identity.** Your service needs its own DID and the Ed25519 key behind it. The `service-id` command of the MetaMynd gateway package makes both, a `did:key` and its key, and writes them to a file readable only by you:

```
npx -y -p @metamynd/agentsafe-http-gateway agentsafe-gateway service-id --out service-identity.json
```

It prints `Service DID: did:key:z6Mk…`. Keep that DID; the owner needs it in step 5. The file holds the service's signing key: keep it out of version control. It refuses to overwrite an existing file unless you pass `--force`, because a replaced key is a new service that has to be registered again.

**Fetch MetaMynd's policy-signing key** once, out of band, and pin it:

```
curl https://metamynd.ai/api/v1/magp/policy/pubkey
```

The key is the hex string in `data.publicKey`.

**Find the agents you serve and their owner.** Since mcp-guard 0.22.0 the guard won't start until it names the agents it acts for and their owner. You need two values:

* `allowedAgents`: the agent DIDs this service acts for. `agentDid` in the agent's `agent.metamynd.json`.
* `gatewayOwnerPrincipal`: the principal DID of the owner those agents belong to. `ownerPrincipal` in the same file, or `principal.dids` in the agent's public manifest (`GET https://metamynd.ai/api/v1/magp/manifest/{agentDid}`).

Then create the guard (`guard.mjs`):

```
import { readFileSync } from 'node:fs';import { createMcpGuard } from '@metamynd/agentsafe-mcp-guard';
const id = JSON.parse(readFileSync('./service-identity.json', 'utf8'));
export const guard = createMcpGuard({  serviceDid: id.serviceDid,                  // this service's own did:key  serviceKey: id.serviceKey,                  // its Ed25519 key, held only by this service  issuerApi: 'https://metamynd.ai/api/v1',  policyPublicKey: process.env.MAGP_POLICY_PUBLIC_KEY, // data.publicKey from GET /magp/policy/pubkey  requireAuthorization: true,  allowedAgents: ['did:key:z6Mk…your-agent'],  // the agents this service acts for  gatewayOwnerPrincipal: 'did:hedera:testnet:z…the-owner', // the principal those agents belong to});
```

* **Your own DID and key.** With `serviceDid` plus a key, the guard signs the handshake and every claim and settlement call as your service. The issuer records your DID as the claimer, and no bearer claim token is issued that could leak. (The key can instead live in the local [agentsafe-signer](https://docs.metamynd.ai/sdks/agentsafe-signer) daemon via `keyProvider: 'daemon'`, so it never enters your service's process. With mcp-guard 0.13.0 and signer 0.16.0 or later the daemon signs the handshake **and** every claim and settlement call. It can't yet sign the registration consent in step 5, so do that step with the key file.) The `serviceDid` must be a `did:key` or `did:hedera`, because the key must be inside the identifier.
* **`policyPublicKey`.** The guard re-evaluates every request against the agent's signed policy bundle. Pinning MetaMynd's policy-signing key means a bundle that was tampered with, unsigned or stale is refused. Without a pinned key, a guard that fetches its bundle over plain `http://` refuses every call (`POLICY_BUNDLE_UNVERIFIED`); over `https://` it warns and relies on TLS. Walkthrough: [Pin the Policy Key](https://docs.metamynd.ai/guides/pin-the-policy-key).
* **`allowedAgents` and `gatewayOwnerPrincipal`.** The guard judges each caller against the caller's own policy. Without a list of agents, a service that holds one owner's credentials would run them for any agent on the platform whose owner granted it an action of the same name. A request signed by an agent not on the list is refused `AGENT_NOT_ADMITTED` before anything is claimed. Leaving `allowedAgents` out is a startup error; a list without `gatewayOwnerPrincipal` is a startup error too (`GATEWAY_OWNER_UNBOUND`). A public tool server that holds no one owner's credentials can set `allowedAgents: 'any'` instead, and then takes no owner; the guard warns at startup that it serves every governed agent.

#### Step 2 — The handshake <a href="#user-content-step-2--the-handshake" id="user-content-step-2--the-handshake"></a>

`handshakeChallenge` is **async** (since mcp-guard 0.5.0): `await` it, or you'll send back a serialised Promise.

```
import express from 'express';import { guard } from './guard.mjs';
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)); // HELLO → CHALLENGE    if (req.body.type === 'PROVE') return res.json(guard.handshakeVerify(req.body));          // PROVE → READY (throws if invalid)    return res.status(400).json({ error: 'unknown handshake message' });  } catch {    return res.status(401).json({ error: 'handshake failed' });  }});
```

Each side proves control of its own DID; neither calls the issuer, because the verification keys are embedded in the DIDs. The agent drives the initiator side with `handshake()` from `agentsafe-guard` (step 7).

#### Step 3 — Wrap every governed tool <a href="#user-content-step-3--wrap-every-governed-tool" id="user-content-step-3--wrap-every-governed-tool"></a>

The rest of `server.mjs`: the real tool, wrapped, and its route.

```
async function rawBookFlight(signed, args) {   // the real tool: runs only on a permit  // call your booking API here  return { booked: true, pnr: 'PNR-' + signed.authorizationId.slice(0, 6).toUpperCase(), ...args };}
const bookFlight = guard.guardIncomingTool('flight-purchase', rawBookFlight, {  bindPayload: true,            // digest the tool's arguments and hold the agent to them  requirePayloadBinding: true,  // refuse an authorization the agent did not bind  settle: true,                 // capture the hold when the tool returns (step 6)});
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;  }});
app.listen(4610, () => console.log('flight tool server on :4610, governed by agentsafe-mcp-guard'));
```

```
MAGP_POLICY_PUBLIC_KEY=<data.publicKey> node server.mjs
```

The wrapped tool's own action (`'flight-purchase'`) is authoritative: a signature valid for some other action can't unlock this tool. For each call the guard:

1. verifies the agent's signature against the key inside its DID, and the request's freshness;
2. checks the agent is one of your `allowedAgents`;
3. fetches the agent's signed policy bundle and verifies it against your pinned key;
4. re-evaluates Standards → SOPs → mandate with the same deterministic evaluator the gate runs;
5. with `bindPayload`, compares the digest of the arguments it is about to execute with the digest the agent signed (`PAYLOAD_NOT_BOUND` on a difference);
6. with `requireAuthorization`, **claims** the hold at the issuer, atomically and single-use, before your handler runs.

A request for an action the calling agent's mandate never granted is refused outright (`NO_PERMISSION_FOR_ACTION` / `NO_MANDATE`), before any Standard or SOP is evaluated. A caller can't get an ungranted action through by relying on your service to fall through to a general policy check.

**Risk.** A missing or unrecognised `riskLevel` escalates (`CONTEXT_UNVERIFIABLE`) for any rule that judges risk. If your service knows the risk of a tool better than the agent does — wiring money versus reading a report — pass `trustedContext: { riskLevel: 'high' }` (or a function of the call). It is applied as `gateway_derived` context: the agent can raise the risk above it, never lower it. See [Context Provenance & Risk Floors](https://docs.metamynd.ai/core-concepts/context-provenance-and-risk-floors).

#### Step 4 — Why `requireAuthorization` and payload binding are not optional in production <a href="#user-content-step-4--why-requireauthorization-and-payload-binding-are-not-optional-in-production" id="user-content-step-4--why-requireauthorization-and-payload-binding-are-not-optional-in-production"></a>

**`requireAuthorization`.** Re-evaluating policy per request proves a request is well-formed and in-policy. It can't stop a captured, still-fresh request being replayed, and it can't enforce the mandate's total budget, rate limits, circuit breakers or spend-anomaly checks, all of which depend on the agent's history at the issuer. `requireAuthorization: true` makes your service claim the authorization's single-use transition itself, so the exact request goes back through the stateful gate before anything executes. A second claim of the same authorization, a replay or a race, is refused with `AUTHORIZATION_ALREADY_CLAIMED`. The claimed hold's agent, action, amount, currency and merchant are also checked against what you are executing (`AUTHORIZATION_*_MISMATCH`), and a voided or expired hold can't be claimed (`AUTHORIZATION_VOIDED`, `AUTHORIZATION_EXPIRED`). It is off by default because it costs a round trip per value-bearing call; with it off, the guard logs a warning on every value-bearing call it permits.

**Payload binding.** The agent's signature covers eight fields — agent, action, amount, currency, merchant, resource, nonce, time — not the payee, account number or booking details your tool actually acts on. With payload binding the agent also signs a digest of the complete payload, and the issuer refuses a claim whose digest differs from the one it stored (`PAYLOAD_DIGEST_MISMATCH`), leaving the hold claimable by an honest executor. Details: [Require Payload Binding](https://docs.metamynd.ai/guides/require-payload-binding).

The reference demo's "rogue" scenario shows what this closes: an agent that tries to act despite its own local guard refusing is still blocked, because your service never trusted the agent's side of the conversation.

#### Step 5 — Get registered as a trusted counterparty <a href="#user-content-step-5--get-registered-as-a-trusted-counterparty" id="user-content-step-5--get-registered-as-a-trusted-counterparty"></a>

Authenticating your service proves it controls a key; it doesn't say the agent's owner trusts it. Each owner keeps a registry of the services allowed to claim their holds. It is **always enforced for mainnet agents**, and for testnet agents once the owner has registered any service.

A claim from a service that isn't registered is refused and nothing executes:

| Code                                    | Meaning                                                                              |
| --------------------------------------- | ------------------------------------------------------------------------------------ |
| `COUNTERPARTY_NOT_REGISTERED`           | Your service's DID is not an active entry in the owner's registry                    |
| `COUNTERPARTY_AUTH_REQUIRED`            | The claim didn't identify itself (no `serviceDid` + key)                             |
| `COUNTERPARTY_NOT_ALLOWED_FOR_MERCHANT` | Your entry is scoped to merchants, and this hold's merchant isn't one of them        |
| `COUNTERPARTY_MISMATCH`                 | A settlement call was signed by someone other than the service that claimed the hold |

The fix is on the owner's side, not in your code, but a service is registered only with its own signed consent, so nobody can name someone else's service as theirs. Registration takes the owner and the service's operator together:

1. **Owner:** in the dashboard, open **Authority & Controls → Trusted Counterparties**. Under **Register a service**, paste the service's DID into **Service DID**, add a **Label**, and optionally limit it to some merchants.
2. **Owner:** press **Get acceptance challenge** and copy the challenge it shows. It is valid for 10 minutes.
3. **Operator:** sign the challenge with the service's key, using the same identity file:

   ```
   npx -y -p @metamynd/agentsafe-http-gateway agentsafe-gateway accept-challenge --identity service-identity.json "<challenge>"
   ```

   Or, from your service's code: `console.log(await guard.acceptCounterpartyChallenge(challenge))`. Either way the output is a 128-character hex signature. The service signs only a `MAGP-COUNTERPARTY-ACCEPT-v1` challenge that names its own DID and hasn't expired, never arbitrary text.
4. **Owner:** paste the signature into **Signature from the service (hex)** and press **Register**. If it is the owner's first registered service, the dashboard asks to confirm with **Register and restrict**: from then on only registered services can claim that owner's holds, including any other gateway or tool server they run.

The service appears under **Registered services**, and its claims on that owner's holds now succeed. Walkthrough, including merchant scoping and the payee directory: [Register Trusted Counterparties & Payee Accounts](https://docs.metamynd.ai/guides/register-trusted-counterparties-and-payee-accounts).

#### Step 6 — Settle what you claimed <a href="#user-content-step-6--settle-what-you-claimed" id="user-content-step-6--settle-what-you-claimed"></a>

Once your service has claimed a hold, it's a commitment: it stays against the mandate's cap until settled (it does not lapse with the 15-minute hold window), and only your service can settle it below its amount or release it. Settle every claim:

* **Simplest:** `guardIncomingTool(action, handler, { settle: true, … })`, as in step 3, captures at the authorized amount when the handler returns, and marks the effect **unknown** when it throws. It never releases the hold, because a throw doesn't prove nothing happened.
* **Charged less, the upstream refused, or the outcome is ambiguous:** call `captureAuthorization` (with `payTo` when you settle lower), `releaseAuthorization` (only when the upstream provably did not execute) or `markAuthorizationUnknown` yourself.
* **Before any retry:** `lookupOutcome({ authorizationId })` tells you whether a retry is safe.

The claim and the capture both appear in the owner's **Activity Log**. Full walkthrough, including every `settlementEvidence` value and the refund route: [Settle a Claimed Hold](https://docs.metamynd.ai/guides/settle-a-claimed-hold).

#### Step 7 — Call it from the agent, and check the refusals <a href="#user-content-step-7--call-it-from-the-agent-and-check-the-refusals" id="user-content-step-7--call-it-from-the-agent-and-check-the-refusals"></a>

On the agent side, with [agentsafe-guard](https://docs.metamynd.ai/sdks/agentsafe-guard-agent-side) (`npm install @metamynd/agentsafe-guard`) and the agent's `agent.metamynd.json`: run the handshake, authorize at the gate with the complete payload bound, then hand the service the signed request together with the `authorizationId` it claims.

```
import { createGuardFromConfig } from '@metamynd/agentsafe-guard';
const guard = await createGuardFromConfig('./agent.metamynd.json');const SERVICE = 'http://localhost:4610';const post = (path, body) =>  fetch(SERVICE + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })    .then(async (r) => [r.status, await r.json()]);
// Mutual handshake: each side proves it controls its own DIDconst hs = guard.handshake();const { nonceA, message } = hs.hello();const [, challenge] = await post('/magp/handshake', { type: 'HELLO', ...message });const { sigA, handshakeId } = await hs.prove({ nonceA, challenge }); // verifies the serviceawait post('/magp/handshake', { type: 'PROVE', handshakeId, sigA });
// Authorize with the complete payload bound, then send the signed requestconst args = { amount: 180, currency: 'USD', merchant: 'skyward-air', flight: 'SQ-321', passenger: 'A. Lee' };const { amount, currency, merchant } = args;const req = { action: 'flight-purchase', amount, currency, merchant, context: { riskLevel: 'low' }, payload: args };const permit = await guard.authorize(req);if (permit.decision !== 'allow') throw new Error(`gate said ${permit.decision}: ${permit.reasonCode}`);
const signed = { ...(await guard.buildSignedRequest(req)), authorizationId: permit.authorizationId };const [status, body] = await post('/tools/book-flight', { signed, args });if (status !== 200) await guard.void(permit.authorizationId, 'the service refused it: nothing ran');console.log(status, body);
```

If the service refuses, nothing ran, so the agent voids its hold rather than leave it counting against the mandate until it expires.

What you should see:

| Case                                                                    | Result                                                                                                                                 |
| ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Before step 5 (owner has registered other services, or a mainnet agent) | The gate allows, the service's claim is refused: `403`, `COUNTERPARTY_NOT_REGISTERED`. The tool doesn't run.                           |
| After step 5                                                            | `200` with the booking. The hold is claimed, the tool runs once, and `settle: true` captures it.                                       |
| The same `signed` request sent again                                    | `403`, `AUTHORIZATION_ALREADY_CLAIMED`.                                                                                                |
| `args` changed after signing (say, a different `passenger`)             | `403`, `PAYLOAD_NOT_BOUND`, before anything is claimed.                                                                                |
| An agent not in `allowedAgents`                                         | Refused `AGENT_NOT_ADMITTED`: its handshake fails (`401` from the route above), and a tool call is refused before anything is claimed. |

#### If you're accepting payment <a href="#user-content-if-youre-accepting-payment" id="user-content-if-youre-accepting-payment"></a>

Add [x402 Payment Binding](https://docs.metamynd.ai/agent-protocol/x402-payment-binding): `requirePayment()` builds a payment challenge bound to the specific authorization, and `settle()` verifies the amount actually paid matches what was authorized before you consider the payment final. `settle` refuses an overpayment (`AMOUNT_MISMATCH`) and a second settlement of the same authorization (`SETTLEMENT_REUSED`); for more than one instance, inject a durable `settlementStore`. MAGP never custodies funds — your facilitator moves the money.

#### Testing your integration <a href="#user-content-testing-your-integration" id="user-content-testing-your-integration"></a>

Beyond the cases in step 7, construct these against your own service. Every one must be refused by your service, independently of what the caller's own guard decided:

* a signed request your guard would reject locally, sent anyway;
* the same authorization presented twice (replay);
* a request signed by a different agent, or for a different action, than the authorization was issued for;
* a request from an agent you don't serve;
* a request under an expired or revoked mandate;
* a payload that differs from the one the agent signed;
* a settlement amount that doesn't match the authorization.

<br>


---

# 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/get-started/integrate-an-mcp-server.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.
