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

# MCP Server

> 23 MCP tools (15 read + 8 write) for querying Nile Markets protocol state, positions, oracle prices, and generating unsigned transaction calldata via Streamable HTTP at mcp.nilemarkets.com/api/mcp — no auth required.

<Warning>
  **Sepolia Testnet Only** — All data is from Ethereum Sepolia. Token balances and positions have no real-world value.
</Warning>

## Quick Connect

MCP endpoint: `https://mcp.nilemarkets.com/api/mcp`

* **Transport**: Streamable HTTP (MCP spec 2025-03-26)
* **Auth**: None (open access during M2 testnet)
* **Session**: Stateless — no `initialize` handshake required

<Tabs>
  <Tab title="Claude Code">
    ```bash theme={null}
    claude mcp add nile-markets --transport http https://mcp.nilemarkets.com/api/mcp
    ```
  </Tab>

  <Tab title="Claude Desktop">
    Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

    ```json theme={null}
    {
      "mcpServers": {
        "nile-markets": {
          "url": "https://mcp.nilemarkets.com/api/mcp"
        }
      }
    }
    ```
  </Tab>

  <Tab title="Claude.ai">
    Settings → Connectors → Add Custom Connector → paste:

    ```text theme={null}
    https://mcp.nilemarkets.com/api/mcp
    ```
  </Tab>

  <Tab title="ChatGPT">
    Settings → MCP → Add Server → paste:

    ```text theme={null}
    https://mcp.nilemarkets.com/api/mcp
    ```
  </Tab>

  <Tab title="Cursor">
    Add to `.cursor/mcp.json` in your project root:

    ```json theme={null}
    {
      "mcpServers": {
        "nile-markets": {
          "url": "https://mcp.nilemarkets.com/api/mcp"
        }
      }
    }
    ```
  </Tab>

  <Tab title="VS Code">
    Add to `.vscode/mcp.json` in your project root:

    ```json theme={null}
    {
      "servers": {
        "nile-markets": {
          "type": "http",
          "url": "https://mcp.nilemarkets.com/api/mcp"
        }
      }
    }
    ```
  </Tab>
</Tabs>

For additional platforms (Windsurf, JetBrains, Cline, Zed, Warp, and more), see the full connection guide at [mcp.nilemarkets.com/skill.md](https://mcp.nilemarkets.com/skill.md#quick-connect).

## Read Tools (14)

### Pool and Protocol

| Tool                    | Description                                                                            | Input                        |
| ----------------------- | -------------------------------------------------------------------------------------- | ---------------------------- |
| `get_pool_state`        | Liquidity pool metrics: total assets, shares, share price, exposure, utilization, fees | None                         |
| `get_protocol_mode`     | Operating mode: NORMAL, DEGRADED, REDUCE\_ONLY, or PAUSED                              | None                         |
| `get_pool_transactions` | Historical vault deposits and withdrawals                                              | `first?`, `skip?`            |
| `get_daily_stats`       | Daily volume, fees, position opens/closes, pool PnL                                    | `days?` (default 7, max 365) |

### Positions

| Tool               | Description                                | Input                                                                                                |
| ------------------ | ------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
| `get_positions`    | Positions for a specific account           | `account` (required), `status?` (OPEN/CLOSED), `first?`, `skip?`                                     |
| `get_position`     | Single position with real-time PnL via RPC | `positionId` (required)                                                                              |
| `search_positions` | Search all positions with filters          | `side?` (0=LONG, 1=SHORT), `tenor?` (0=1D, 1=1W, 2=1M), `status?`, `minNotional?`, `first?`, `skip?` |

### Oracle and Pricing

| Tool                | Description                                           | Input                              |
| ------------------- | ----------------------------------------------------- | ---------------------------------- |
| `get_forward_price` | Forward price for a specific tenor                    | `tenor` (1D, 1W, or 1M), `pairId?` |
| `get_oracle_state`  | Full oracle state: spot, all forward prices, validity | `pairId?`                          |

### Accounts and Fees

| Tool             | Description                                                     | Input                |
| ---------------- | --------------------------------------------------------------- | -------------------- |
| `get_account`    | Account margin: collateral, locked, available, position count   | `address` (required) |
| `get_fee_events` | Fee event breakdown (trading, liquidation, termination, oracle) | `first?`, `skip?`    |

### Token

| Tool                | Description                                            | Input                                                              |
| ------------------- | ------------------------------------------------------ | ------------------------------------------------------------------ |
| `get_token_balance` | ERC-20 token balance for an address (defaults to USDC) | `address` (required), `token?`                                     |
| `check_allowance`   | ERC-20 allowance for an owner/spender pair             | `owner` (required), `spender` (contract name or address), `token?` |

### Simulation

| Tool                     | Description                                              | Input                                                                                 |
| ------------------------ | -------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `simulate_open_position` | Preview margin, fee, and entry strike for a new position | `side` (LONG/SHORT), `tenor` (1D/1W/1M), `notional` (USDC string), `margin?`, `from?` |

## Write Tools (8)

Write tools return **unsigned transaction calldata** — they do not execute transactions. Your agent or wallet signs and broadcasts the returned calldata externally.

### Trading

| Tool             | Description                                        | Input                                                     |
| ---------------- | -------------------------------------------------- | --------------------------------------------------------- |
| `open_position`  | Calldata to open a new FX forward position         | `side`, `tenor`, `notional`, `margin`, `pairId?`, `from?` |
| `close_position` | Calldata to close a position via early termination | `positionId`, `from?`                                     |

### Margin

| Tool              | Description                                                             | Input             |
| ----------------- | ----------------------------------------------------------------------- | ----------------- |
| `deposit_margin`  | Calldata to deposit USDC as margin collateral (requires prior approval) | `amount`, `from?` |
| `withdraw_margin` | Calldata to withdraw available USDC margin                              | `amount`, `from?` |

### Vault (Liquidity Providers)

| Tool             | Description                                                            | Input                                  |
| ---------------- | ---------------------------------------------------------------------- | -------------------------------------- |
| `vault_deposit`  | Calldata to deposit USDC into the pool vault (requires prior approval) | `amount`, `receiver`, `from?`          |
| `vault_withdraw` | Calldata to withdraw USDC from the pool vault                          | `amount`, `receiver`, `owner`, `from?` |

### Token Approval and Testnet

| Tool              | Description                                         | Input                                                             |
| ----------------- | --------------------------------------------------- | ----------------------------------------------------------------- |
| `approve_token`   | Calldata to approve a Nile contract to spend tokens | `spender` (contract name or address), `amount`, `token?`, `from?` |
| `mint_test_token` | Calldata to mint test tokens (testnet only)         | `to`, `amount`, `from?`                                           |

All amounts are strings in USDC smallest unit (6 decimals). `"1000000000"` = 1,000 USDC.

## Response Format

Every tool response includes protocol metadata:

```json theme={null}
{
  "protocol": { "name": "Nile Markets", "version": "0.3.2" },
  "network": "sepolia",
  "source": "rpc",
  "blockNumber": "12345678",
  "data": { }
}
```

| Field         | Type                | Description                                             |
| ------------- | ------------------- | ------------------------------------------------------- |
| `protocol`    | `{ name, version }` | Protocol identity and API version                       |
| `network`     | `string`            | Target network (`"sepolia"`)                            |
| `source`      | `string`            | Data source: `"rpc"`, `"subgraph"`, or `"rpc+subgraph"` |
| `blockNumber` | `string?`           | Last indexed block (subgraph-sourced responses only)    |
| `data`        | `object`            | Tool-specific response payload                          |

Write tools return `TransactionCalldata` in the `data` field:

```json theme={null}
{
  "to": "0x8d81E9f1D0F0d1BdAAc0a91AFc2976522429A0cd",
  "data": "0x...",
  "value": "0",
  "estimatedGas": "150000",
  "chainId": 11155111,
  "description": "Open LONG 1M position with 10000000000 notional"
}
```

The `to` address is always pre-filled with the correct contract. You do not need to look up contract addresses when using write tools.

## Write Tool Flow

Write tools produce calldata, not transactions. The signing and broadcasting step happens outside the MCP server.

<Steps>
  <Step title="Pre-flight">
    Call `get_protocol_mode` to verify the protocol is in NORMAL mode. Call `get_token_balance` to confirm the wallet has sufficient USDC.
  </Step>

  <Step title="Simulate">
    For position opens, call `simulate_open_position` to preview the required margin, trading fee, and entry strike before committing.
  </Step>

  <Step title="Approve if needed">
    Call `check_allowance` for the target contract. If the allowance is insufficient, call `approve_token` to generate approval calldata, then sign and broadcast it.
  </Step>

  <Step title="Generate calldata">
    Call the write tool (`open_position`, `deposit_margin`, etc.). The response includes `to`, `data`, `value`, and `chainId`.
  </Step>

  <Step title="Sign and broadcast">
    Sign the transaction with any EVM wallet — Foundry `cast`, viem, ethers.js, MetaMask, OWS, or any signing MCP server. Broadcast to Sepolia.
  </Step>
</Steps>

For complete step-by-step workflows for every write operation, see [mcp.nilemarkets.com/workflow.md](https://mcp.nilemarkets.com/workflow.md).

## Rate Limits

* **Limit**: 100 requests/minute per IP
* **Exceeded**: HTTP 429 with `Retry-After` header
* **No auth tokens**: Rate limiting is IP-based during M2 testnet

## Example Tool Calls

**Check protocol status:**

```text theme={null}
get_protocol_mode → { mode: "NORMAL", allowedOperations: [...] }
```

**Query pool state:**

```text theme={null}
get_pool_state → { totalAssets, totalShares, sharePrice, utilization, ... }
```

**Get EUR/USD 1-month forward price:**

```text theme={null}
get_forward_price { tenor: "1M" } → { strike, forwardPoints, annualizedBasis, ... }
```

**Simulate opening a position:**

```text theme={null}
simulate_open_position {
  side: "LONG",
  tenor: "1W",
  notional: "5000000000"
} → { requiredMargin, tradingFee, entryStrike, success: true }
```

**Search for open short positions above 5,000 USDC notional:**

```text theme={null}
search_positions {
  side: 1,
  status: "OPEN",
  minNotional: "5000000000"
} → { positions: [...], total: 3 }
```

**Check USDC allowance before depositing margin:**

```text theme={null}
check_allowance {
  owner: "0xYourAddress",
  spender: "marginAccounts"
} → { allowance: "0", sufficient: false }
```

**Generate approval calldata:**

```text theme={null}
approve_token {
  spender: "marginAccounts",
  amount: "50000000"
} → { to: "0x319...", data: "0x095ea7b3...", chainId: 11155111 }
```

## Numeric Conventions

| Type                | Decimals     | Example                            |
| ------------------- | ------------ | ---------------------------------- |
| USDC amounts        | 6            | `"1234567890"` = 1,234.567890 USDC |
| Forward/spot prices | 18           | `"1085000000000000000"` = 1.085000 |
| Utilization, fees   | Basis points | `"4500"` = 45%                     |

## Pagination

Tools that return lists support two parameters:

| Parameter | Default | Max  | Description       |
| --------- | ------- | ---- | ----------------- |
| `first`   | 25      | 1000 | Page size         |
| `skip`    | 0       | —    | Offset from start |

## Debugging

Test the server directly with the MCP Inspector:

```bash theme={null}
npx @modelcontextprotocol/inspector --transport http --server-url https://mcp.nilemarkets.com/api/mcp
```

This opens a web UI where you can browse available tools, call them interactively, and inspect raw responses.
