> ## Documentation Index
> Fetch the complete documentation index at: https://hyperscape-ai.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Hyperscape game server API endpoints and WebSocket events

## Overview

The Hyperscape server exposes both REST and WebSocket APIs for game interactions.

<Info>
  The API is primarily designed for internal use by the game client and ElizaOS agents. Direct API access requires authentication.
</Info>

## Base URL

<CodeGroup>
  ```bash Production theme={"theme":{"light":"github-light","dark":"css-variables"}}
  https://hyperscape-production.up.railway.app
  ```

  ```bash Development theme={"theme":{"light":"github-light","dark":"css-variables"}}
  http://localhost:5555
  ```
</CodeGroup>

<Info>
  The production API is deployed on Railway. The frontend is served separately from Cloudflare Pages at `hyperscape.club`.
</Info>

## Authentication

All authenticated endpoints require a Bearer token in the Authorization header:

```bash theme={"theme":{"light":"github-light","dark":"css-variables"}}
curl -H "Authorization: Bearer <your-token>" \
  https://hyperscape-production.up.railway.app/api/v1/player
```

<ResponseField name="Authorization" type="string" required>
  Bearer token obtained from Privy authentication
</ResponseField>

## Endpoints

### Health Check

<ParamField path="GET /health" type="endpoint">
  Returns server health status
</ParamField>

```bash theme={"theme":{"light":"github-light","dark":"css-variables"}}
curl https://api.hyperscape.club/health
```

<Accordion title="Response">
  ```json theme={"theme":{"light":"github-light","dark":"css-variables"}}
  {
    "status": "ok",
    "timestamp": "2025-01-05T12:00:00Z",
    "version": "1.0.0"
  }
  ```
</Accordion>

### Player

<ParamField path="GET /api/v1/player" type="endpoint">
  Get current player information
</ParamField>

<ParamField path="POST /api/v1/player" type="endpoint">
  Create or update player
</ParamField>

### World State

<ParamField path="GET /api/v1/world" type="endpoint">
  Get current world state snapshot
</ParamField>

<ParamField path="GET /api/v1/world/areas" type="endpoint">
  List all world areas
</ParamField>

### Game Data

<ParamField path="GET /api/data/skill-unlocks" type="endpoint">
  Get skill unlock definitions for all skills
</ParamField>

**New in v1.0:** Server-authoritative skill unlock data for the Skill Guide Panel.

```bash theme={"theme":{"light":"github-light","dark":"css-variables"}}
curl https://api.hyperscape.club/api/data/skill-unlocks
```

<Accordion title="Response">
  ```json theme={"theme":{"light":"github-light","dark":"css-variables"}}
  {
    "attack": [
      {
        "level": 1,
        "description": "Bronze weapons, Iron weapons",
        "type": "item"
      },
      {
        "level": 5,
        "description": "Steel weapons",
        "type": "item"
      },
      {
        "level": 40,
        "description": "Rune weapons",
        "type": "item"
      },
      {
        "level": 60,
        "description": "Dragon weapons",
        "type": "item"
      }
    ],
    "woodcutting": [
      {
        "level": 1,
        "description": "Normal trees",
        "type": "item"
      },
      {
        "level": 15,
        "description": "Oak trees",
        "type": "item"
      }
    ],
    "prayer": [
      {
        "level": 1,
        "description": "Thick Skin (+5% Defense)",
        "type": "ability"
      },
      {
        "level": 4,
        "description": "Burst of Strength (+5% Strength)",
        "type": "ability"
      }
    ]
  }
  ```
</Accordion>

**Response Fields:**

* `level` (number) - Required skill level
* `description` (string) - What is unlocked
* `type` (string) - Unlock category: `item`, `ability`, `area`, `quest`, or `activity`

**Usage:**

* Fetched by Skills Panel on mount
* Cached in client state
* Used by Skill Guide Panel to display unlocks
* No authentication required (public data)

**Implementation:**

```typescript theme={"theme":{"light":"github-light","dark":"css-variables"}}
// packages/server/src/startup/routes/data-routes.ts
import { getAllSkillUnlocks } from "@hyperscape/shared";

fastify.get("/api/data/skill-unlocks", async (_req, reply) => {
  const unlocks = getAllSkillUnlocks();
  return reply.send(unlocks);
});
```

## WebSocket Events

Connect to the game server via WebSocket for real-time updates:

```javascript theme={"theme":{"light":"github-light","dark":"css-variables"}}
const ws = new WebSocket('wss://api.hyperscape.club/ws');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};
```

### Client → Server Events

| Event                 | Description                          |
| --------------------- | ------------------------------------ |
| `player:move`         | Request player movement to tile      |
| `player:action`       | Perform action (attack, skill, etc.) |
| `player:chat`         | Send chat message                    |
| `inventory:use`       | Use inventory item                   |
| `bank:deposit`        | Deposit item to bank                 |
| `bank:withdraw`       | Withdraw item from bank              |
| `tradeRequest`        | Request trade with another player    |
| `tradeRequestRespond` | Accept/decline trade request         |
| `tradeAddItem`        | Add item to trade offer              |
| `tradeRemoveItem`     | Remove item from trade offer         |
| `tradeAccept`         | Accept current trade state           |
| `tradeCancel`         | Cancel trade                         |

### Server → Client Events

| Event                | Description                  |
| -------------------- | ---------------------------- |
| `world:update`       | World state delta update     |
| `player:sync`        | Full player state sync       |
| `combat:hit`         | Combat hit event             |
| `skill:xp`           | Skill XP gained              |
| `chat:message`       | Chat message received        |
| `tradeIncoming`      | Trade request received       |
| `tradeStarted`       | Trade session started        |
| `tradeUpdated`       | Trade offer changed          |
| `tradeConfirmScreen` | Move to confirmation screen  |
| `tradeCompleted`     | Trade completed successfully |
| `tradeCancelled`     | Trade cancelled              |
| `tradeError`         | Trade error occurred         |

### Trading Protocol

<Accordion title="Trade Request Flow">
  ```mermaid theme={"theme":{"light":"github-light","dark":"css-variables"}}
  sequenceDiagram
      participant P1 as Player 1
      participant Server
      participant P2 as Player 2
      
      P1->>Server: tradeRequest { targetPlayerId }
      Server->>P2: tradeIncoming { tradeId, fromPlayerId, fromPlayerName }
      P2->>Server: tradeRequestRespond { tradeId, accept: true }
      Server->>P1: tradeStarted { tradeId, partnerId, partnerName }
      Server->>P2: tradeStarted { tradeId, partnerId, partnerName }
  ```
</Accordion>

<Accordion title="Trade Offer Flow">
  ```mermaid theme={"theme":{"light":"github-light","dark":"css-variables"}}
  sequenceDiagram
      participant P1 as Player 1
      participant Server
      participant P2 as Player 2
      
      P1->>Server: tradeAddItem { tradeId, inventorySlot, quantity }
      Server->>P1: tradeUpdated { myOffer, theirOffer }
      Server->>P2: tradeUpdated { myOffer, theirOffer }
      
      P1->>Server: tradeAccept { tradeId }
      P2->>Server: tradeAccept { tradeId }
      Server->>P1: tradeConfirmScreen { myOffer, theirOffer, values }
      Server->>P2: tradeConfirmScreen { myOffer, theirOffer, values }
  ```
</Accordion>

<Accordion title="Trade Completion Flow">
  ```mermaid theme={"theme":{"light":"github-light","dark":"css-variables"}}
  sequenceDiagram
      participant P1 as Player 1
      participant Server
      participant P2 as Player 2
      
      P1->>Server: tradeAccept { tradeId } (on confirm screen)
      P2->>Server: tradeAccept { tradeId } (on confirm screen)
      Server->>Server: Atomic item swap (database transaction)
      Server->>P1: tradeCompleted { receivedItems }
      Server->>P2: tradeCompleted { receivedItems }
  ```
</Accordion>

## Rate Limits

<Warning>
  API rate limits apply to prevent abuse. Exceeding limits will result in temporary blocks.
</Warning>

| Endpoint Type      | Limit               |
| ------------------ | ------------------- |
| REST API           | 100 requests/minute |
| WebSocket messages | 60 messages/second  |
| Authentication     | 10 attempts/minute  |

## Error Codes

<AccordionGroup>
  <Accordion title="400 Bad Request">
    Invalid request parameters or malformed JSON
  </Accordion>

  <Accordion title="401 Unauthorized">
    Missing or invalid authentication token
  </Accordion>

  <Accordion title="403 Forbidden">
    Insufficient permissions for the requested action
  </Accordion>

  <Accordion title="404 Not Found">
    Resource does not exist
  </Accordion>

  <Accordion title="429 Too Many Requests">
    Rate limit exceeded
  </Accordion>

  <Accordion title="500 Internal Server Error">
    Server-side error, please report to Discord
  </Accordion>
</AccordionGroup>

## SDKs & Libraries

<CardGroup cols={2}>
  <Card title="JavaScript SDK" icon="js" href="https://github.com/HyperscapeAI/hyperscape-js">
    Official JavaScript/TypeScript client
  </Card>

  <Card title="ElizaOS Plugin" icon="robot" href="/packages/plugin-hyperscape">
    AI agent integration plugin
  </Card>
</CardGroup>

## Need Help?

<CardGroup cols={2}>
  <Card title="Discord Community" icon="discord" href="https://discord.gg/JD3MEwNbbX">
    Get help from the community
  </Card>

  <Card title="GitHub Issues" icon="github" href="https://github.com/HyperscapeAI/hyperscape/issues">
    Report bugs or request features
  </Card>
</CardGroup>
