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

# Getting Started with the SDK

> Everything you need to know to build apps with the MentraOS SDK

## Installation

Install the MentraOS SDK using Bun:

```bash theme={null}
bun add @mentraos/sdk
```

## Basic Concepts

The MentraOS SDK provides two main classes:

<CardGroup cols={2}>
  <Card title="AppServer" icon="server">
    Base class you extend to create your app server. Handles webhook registration and session lifecycle.
  </Card>

  <Card title="AppSession" icon="plug">
    Manages the connection to a specific user session. Created automatically when users start your app.
  </Card>
</CardGroup>

<Note>
  **Important**: Apps should extend `AppServer` and override the `onSession` method. The sessionId parameter follows the format `"userId-packageName"` (e.g., `"user@example.com-com.example.app"`).
</Note>

## Creating an App Server

```typescript theme={null}
import { AppServer, AppSession } from '@mentraos/sdk';

// Extend AppServer to create your app
class MyAppServer extends AppServer {
  // Override onSession to handle new user sessions
  protected async onSession(
    session: AppSession,
    sessionId: string,  // Format: "userId-packageName" 
    userId: string      // User's email address
  ): Promise<void> {
    // Your app logic goes here
    console.log(`New session ${sessionId} for user ${userId}`);
  }
}

// Create instance with configuration
const server = new MyAppServer({
  packageName: 'com.yourcompany.yourapp',  // Your app's unique identifier
  apiKey: process.env.MENTRAOS_API_KEY!,    // Your API key from dev portal
  port: 3000,                               // Port to listen on (default: 7010)
  publicDir: './public'                     // Optional: static files directory
});
```

## Handling Sessions

When a user starts your app, your `onSession` method is called:

```typescript theme={null}
protected async onSession(
  session: AppSession,    // Session instance for this user
  sessionId: string,      // Session ID (format: "userId-packageName")
  userId: string          // User's email address
): Promise<void> {
  console.log(`New session ${sessionId} for user ${userId}`);
  
  // Set up event handlers
  session.events.onTranscription((data) => {
    // Handle speech-to-text
  });
  
  session.events.onButtonPress((data) => {
    // Handle button presses
  });
  
  // Show initial UI
  await session.layouts.showTextWall('Welcome!');
}
```

## Session Lifecycle

<Steps>
  <Step title="User starts app">
    User says "Start \[app name]" or taps in the mobile app
  </Step>

  <Step title="Cloud sends webhook">
    MentraOS Cloud sends a webhook to your server
  </Step>

  <Step title="Session created">
    Your `onSession` handler is called with an AppSession
  </Step>

  <Step title="Real-time connection">
    AppSession connects via WebSocket for real-time data
  </Step>

  <Step title="Session ends">
    User stops app or connection is lost
  </Step>
</Steps>

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

```typescript theme={null}
import { 
  AppServer,
  AppSession,
  TranscriptionData,
  ButtonPress,
  PhotoData,
  LocationUpdate
} from '@mentraos/sdk';

// All types are available for your use
```

## Environment Variables

Recommended environment variables:

```bash theme={null}
# Required
MENTRAOS_API_KEY=your_api_key_here

# Optional
PORT=3000
LOG_LEVEL=info
```

## Project Structure

A typical MentraOS app project:

```
my-mentraos-app/
├── src/
│   ├── index.ts        # Main server file
│   ├── server.ts       # Your AppServer class
│   ├── handlers/       # Event handlers
│   └── utils/          # Helper functions
├── public/             # Static assets
├── .env                # Environment variables
├── package.json
├── tsconfig.json       # TypeScript config
└── bun.lockb           # Bun lock file
```

### TypeScript Configuration

Use strict TypeScript for better type safety:

```json theme={null}
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "lib": ["ES2022"],
    "moduleResolution": "bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "allowJs": false,
    "types": ["bun-types"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="AppSession Reference" icon="plug" href="/sdk/app-session">
    Learn about the AppSession class and its methods
  </Card>

  <Card title="Event Handlers" icon="bolt" href="/sdk/event-handlers">
    Handle transcriptions, button presses, and more
  </Card>

  <Card title="Display Layouts" icon="tv" href="/sdk/display-layouts">
    Show content on the glasses display
  </Card>

  <Card title="Hardware Modules" icon="microchip" href="/sdk/hardware-modules">
    Access camera, audio, location, and sensors
  </Card>
</CardGroup>
