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

# MCP Integration

> This guide explains the user journey from the first request to stable usage within a paid MCP session.

<Badge color="gray">MCP</Badge>
<Badge color="gray">Fortytwo Prime</Badge>
<Badge color="green">Installing to Client</Badge>
<Badge color="blue">JSON-RPC</Badge>
<Badge color="blue">x402Escrow Payments</Badge>

<Note>
  Prerequisites:<br />
  **MCP endpoint:** `POST https://mcp.fortytwo.network/mcp`.<br />
  **Web3 wallet** with at least **2 USDC** on Base or Monad to sign **HTTP 402** payment requests.<br />
  A client that sends **JSON-RPC requests** (`initialize`, `tools/list`, `tools/call`)
</Note>

## User Journey: MCP + x402Escrow Payments

<Card title="Implementation reference on GitHub" icon="github" href="https://github.com/Fortytwo-Network/fortytwo-mcp-skills/blob/main/skills/fortytwo-mcp/scripts/fortytwo_query.py" cta="Explore the MCP skill repository: github.com/Fortytwo-Network/fortytwo-mcp-skills/" vertical>
  <br />
</Card>

### Step 1. Initialize the MCP Connection and Inspect Available Tools

These calls are free and do not require payment.

```bash theme={null}
# Initialize:
curl -i -X POST "https://mcp.fortytwo.network/mcp" \
  -H "content-type: application/json" \
  -d '{
    "jsonrpc":"2.0",
    "id":"init-1",
    "method":"initialize",
    "params":{
      "protocolVersion":"2026-03-03",
      "capabilities":{},
      "clientInfo":{"name":"example-client","version":"1.0.0"}
    }
  }'
```

```bash theme={null}
# List available tools:
curl -i -X POST "https://mcp.fortytwo.network/mcp" \
  -H "content-type: application/json" \
  -d '{
    "jsonrpc":"2.0",
    "id":"tools-1",
    "method":"tools/list"
  }'
```

The tool exposed by the server is `ask_fortytwo_prime`.

<Tip>
  In conversation with an AI agent, phrases like **"Ask Fortytwo"** and **"Ask Fortytwo Prime"** refer to calling this tool.
</Tip>

### Step 2. Send a `tools/call` Request

```bash theme={null}
curl -i -X POST "https://mcp.fortytwo.network/mcp" \
  -H "content-type: application/json" \
  -d '{
    "jsonrpc":"2.0",
    "id":"call-1",
    "method":"tools/call",
    "params":{
      "name":"ask_fortytwo_prime",
      "arguments":{"query":"Explain quantum entanglement in simple words"}
    }
  }'
```

#### Server Response

If no active session exists, the server responds with `HTTP 402` and a `payment-required` header.

<Card title="Payments are Handled with x402Escrow Protocol" icon="money-check-dollar">
  <Columns cols={2}>
    <Card title="What is x402Escrow" icon="arrow-right" href="https://platform.fortytwo.network/x402escrow" vertical>
      <br />
    </Card>

    <Card title="Open-sourced on GitHub" icon="github" href="https://github.com/Fortytwo-Network/fortytwo-x402Escrow" vertical>
      <br />
    </Card>
  </Columns>
</Card>

### Step 3. Build Payment from `payment-required`

The `payment-required` header contains `base64(JSON)` with payment options.

```json JSON theme={null}
// Decoded `payment-required` example:
{
  "x402Version": 2,
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "1000000",
      "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
      "payTo": "0x9562f50f73d8eE22276F13A18D051456d8D137a0",
      "maxTimeoutSeconds": 90
    }
  ]
}
```

Several `accepts[]` options can be listed, each with unique network details (eip155:8453 for Base, eip155:143 for Monad).

Choose one of the `accepts[]` options, sign the payment with your wallet, and construct a `payment-signature` (base64-encoded JSON) containing:

* `network` — Selected network
* `client` — Payee address
* `maxAmount` — Max amount
* `validBefore` — Signature validity window
* Cryptographic signature

```json JSON theme={null}
// Decoded `payment-signature` example:
{
  "x402Version": 2,
  "scheme": "exact",
  "network": "eip155:8453",
  "payload": {
    "client": "0x1111111111111111111111111111111111111111",
    "maxAmount": "1000000",
    "validAfter": "0",
    "validBefore": "1760000000",
    "nonce": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "v": 27,
    "r": "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
    "s": "0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
  }
}
```

### Step 4. Repeat the `tools/call`  and Now Include `payment-signature`

```bash theme={null}
curl -i -X POST "https://mcp.fortytwo.network/mcp" \
  -H "content-type: application/json" \
  -H "payment-signature: <base64_x402_signature_json>" \
  -d '{
    "jsonrpc":"2.0",
    "id":"call-1",
    "method":"tools/call",
    "params":{
      "name":"ask_fortytwo_prime",
      "arguments":{"query":"Explain quantum entanglement in simple words"}
    }
  }'
```

#### Server Response

On success, the server verifies the signature, settles payment on-chain, and opens a billing session.

The response includes:

* `x-session-id` header — save this for subsequent calls
* `payment-response` header — payment confirmation with `txHash`
* JSON-RPC `result` with tool output

### Step 5. Use `x-session-id` for Subsequent Calls

```bash theme={null}
curl -i -X POST "https://mcp.fortytwo.network/mcp" \
  -H "content-type: application/json" \
  -H "x-session-id: <session_uuid>" \
  -H "x-idempotency-key: <uuid>" \
  -d '{
    "jsonrpc":"2.0",
    "id":"call-2",
    "method":"tools/call",
    "params":{
      "name":"ask_fortytwo_prime",
      "arguments":{"query":"Summarize this idea in 5 bullet points"}
    }
  }'
```

| Header              | Purpose                                   |
| ------------------- | ----------------------------------------- |
| `x-session-id`      | Ties calls to one paid session            |
| `x-idempotency-key` | Prevents duplicate payments on retries    |
| `jsonrpc.id`        | Identifies a single request/response pair |

### Step 6. Session Expiry and Re-payment

When session ends, the server responds with:

| Response               | Meaning                                                                                              |
| ---------------------- | ---------------------------------------------------------------------------------------------------- |
| `402 Payment Required` | Submit a new payment signature and open a new session                                                |
| `410 Gone`             | Session expired — start a new payment cycle.<br />Unused credits from previous session get refunded. |

## Integration Checklist

<Steps>
  <Step>
    Treat `HTTP 402 Payment Required` as the first-payment step.
  </Step>

  <Step>
    Save `x-session-id` after successful payment.
  </Step>

  <Step>
    Send `x-idempotency-key` on every `tools/call`.
  </Step>

  <Step>
    On `HTTP 410` or repeated `HTTP 402`, start a new payment cycle.
  </Step>
</Steps>

## How Sessions Work: Lifetime and Closure

After the first successful payment, a billing session is created and identified: `x-session-id`.

Each `tools/call` reserves budget first that gets locked in a [x402Escrow <Icon icon="arrow-up-right" />](https://www.platform.fortytwo.network/x402escrow) contract. With each request, the contract charges the actual cost of inference, and releases unused reserve back to the available session balance.

**Session closure conditions:**

* If there is no activity for **10 minutes**.
* Session hits a **hard cap of 60 minutes** from session opening.
* Session **budget  is exhausted**.
* Connection is dropped mid-response.
* An upstream error occurs on a newly opened session.

If a session is close to expiry, new calls may be rejected to avoid starting operations that cannot be completed.

<Note>
  Automatic closure may occur with a small delay, typically up to tens of seconds.
</Note>

## Fund Release

After session closure, the release process starts automatically:

1. The service finalizes the actual amount spent.
2. A release transaction is sent on-chain.
3. The spent portion goes to the service; unused remainder returns to the client's wallet.

This typically takes a few seconds to a couple of minutes. Network congestion may cause longer delays.

### If Release Does Not Happen

A fallback is available via on-chain refund: `refundAfterTimeout(escrowId)`.<br />
Funds always return to the **original client address** regardless of who calls it.

<Warning>
  This refund is only available after the escrow's `refundAt` deadline (typically \~90 minutes, exact timing depends on on-chain configuration).
</Warning>

**How to get `escrowId`:** from the settle transaction's `Deposited` event, or via [support on <Icon icon="discord" />  Discord](https://discord.com/invite/fortytwo).

## What to Store Client-Side

Minimum data worth storing:

| Data                                                               | Purpose                                                                |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------- |
| `x-session-id`                                                     | Current payment session identifier                                     |
| `payment-response`<br />(especially `transaction` / `txHash`)      | Payment confirmation and settle proof after successful session opening |
| `payment-signature`<br />(at least `network` + `client` + `nonce`) | Required for support and refund flows                                  |

## Supported Payment Networks

USDC payments are currently accepted on two networks:

| Network | Chain ID      |
| ------- | ------------- |
| Base    | `eip155:8453` |
| Monad   | `eip155:143`  |

The `accepts[].network` and `accepts[].asset` fields in the payment response indicate which network and token address to use.

## Token Usage

The actual cost is calculated from **input** and **output tokens**.<br />
`tools/call` responses include usage data:

```json JSON theme={null}
{
  "result": {
    "content": [{"type":"text","text":"..."}],
    "_meta": {
      "usage": {
        "tokens_in": 123,
        "tokens_out": 456
      }
    }
  }
}
```

## Error Reference

| Code          | Meaning                         | Action                                                                                                                                       |
| ------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `402`         | Payment required                | Sign a new payment and repeat the `tools/call` request                                                                                       |
| `410`         | Session expired                 | Open a new session, start a new payment cycle                                                                                                |
| `4xx` (other) | Request or signature issue      | Verify `network`, signature validity window, and JSON-RPC format                                                                             |
| `5xx`         | Temporary server/upstream error | Wait and retry. If persistent, contact [support on <Icon icon="discord" />  Discord](https://discord.com/invite/fortytwo) with your `txHash` |
