# Server quickstart

> Canonical URL: https://docs.mountaya.com/en/sdks/kotlin/quickstart-server/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Mint a session token with your secret key on the JVM, call the Data API with it, and serve tokens to your app.

A Kotlin program on the JVM that mints a session token, calls the Data API with it, and hands tokens to your app.

## Before you start

You need JDK 17 or newer and Gradle. You also need two keys from **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys): a secret key, and a publishable key with the `publishing` and `data` scopes. Export both:

```bash
export MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key
export MOUNTAYA_SECRET_KEY=sk_your_secret_key
```

## Install

Create a Kotlin JVM application and add the admin package, which brings the client with it:

```kotlin
plugins {
    kotlin("jvm") version "2.4.21"
    application
}

dependencies {
    implementation("com.mountaya:mountaya-admin:0.1.0")
}

application { mainClass.set("MainKt") }
```

Each program below is a whole `src/main/kotlin/Main.kt`. Run it with `./gradlew run`.

## Mint a session token

A client built over the secret key mints the token through the admin package:

```kotlin
import com.mountaya.admin.admin
import com.mountaya.admin.generated.AdminSchema
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya
import com.mountaya.client.invoke

suspend fun main() {
    val server = Mountaya(Credential.Secret(System.getenv("MOUNTAYA_SECRET_KEY").orEmpty()))
    val publishableKey = System.getenv("MOUNTAYA_PUBLISHABLE_KEY").orEmpty()
    val session = server.admin.sessions.postSession(AdminSchema.SessionCreateParams(publishable_key = publishableKey)).data
    // Never print the token itself.
    println("Minted a session token that expires at ${session.expires_at}")
    server.close()
}
```

## Call the Data API

Every other call sends the publishable key with the minted token:

```kotlin
import com.mountaya.admin.admin
import com.mountaya.admin.generated.AdminSchema
import com.mountaya.client.Credential
import com.mountaya.client.FieldSelection
import com.mountaya.client.Mountaya
import com.mountaya.client.SessionToken
import com.mountaya.client.generated.DataSchema
import com.mountaya.client.generated.RestSchema
import com.mountaya.client.invoke

suspend fun main() {
    val publishableKey = System.getenv("MOUNTAYA_PUBLISHABLE_KEY").orEmpty()
    val server = Mountaya(Credential.Secret(System.getenv("MOUNTAYA_SECRET_KEY").orEmpty()))
    val session = server.admin.sessions.postSession(AdminSchema.SessionCreateParams(publishable_key = publishableKey)).data
    val mountaya = Mountaya(Credential.Publishable(publishableKey, SessionToken.Minted(session)))

    // Map Studio API: your five most recently updated itineraries.
    val itineraries =
        mountaya.studio.itineraries.getItineraries {
            sort = RestSchema.GetItinerariesSort.UpdatedAtDescending
            limit = 5
        }
    for (itinerary in itineraries.data) println("${itinerary.name}, updated ${itinerary.updated_at}")

    // Data API: a hike from Chamonix to Argentière.
    val found =
        mountaya.data.directions(
            DataSchema.DirectionsInput(
                activity = DataSchema.ActivitySlug.HikingAndTrail,
                waypoints = listOf(listOf(6.8712, 45.9231), listOf(6.9271, 45.9822)),
            ),
            select =
                FieldSelection {
                    field("routes") {
                        field("distance")
                        field("duration")
                        field("summary")
                    }
                },
        )
    println(found.routes?.firstOrNull()?.summary)

    mountaya.close()
    server.close()
}
```

```text
Docs Tour du Mont-Blanc, updated 2026-11-09T10:53:23.814Z
9.0 km, ~2h40m, +277m / -56m elevation, 67% path, 12% track, 8% road.
```

## Hand tokens to your app

An app never holds the secret key. Your server answers `POST /session` with a token minted for the member your own sign-in vouches for:

```kotlin
import com.mountaya.admin.admin
import com.mountaya.admin.generated.AdminSchema
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.RestSchema
import com.mountaya.client.invoke
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import java.net.InetSocketAddress
import java.util.concurrent.ConcurrentHashMap

// Your own sign-in fills this: each of its session cookies, to the member it vouches for.
private val signedIn = ConcurrentHashMap<String, String>()

fun main() {
    val publishableKey = System.getenv("MOUNTAYA_PUBLISHABLE_KEY").orEmpty()
    val server = Mountaya(Credential.Secret(System.getenv("MOUNTAYA_SECRET_KEY").orEmpty()))
    val http = HttpServer.create(InetSocketAddress("127.0.0.1", 8787), 0)
    http.createContext("/") { exchange ->
        when {
            exchange.requestURI.path != "/session" -> answer(exchange, 404, "")
            exchange.requestMethod != "POST" -> answer(exchange, 405, "")
            else -> {
                val member = signedIn[exchange.requestHeaders.getFirst("Cookie").orEmpty()]
                val params = AdminSchema.SessionCreateParams(publishable_key = publishableKey) { member?.let { user_id = it } }
                val session = runBlocking { server.admin.sessions.postSession(params).data }
                answer(exchange, 200, Json.encodeToString(RestSchema.Session.serializer(), session))
            }
        }
    }
    http.start()
    println("POST http://127.0.0.1:8787/session")
}

private fun answer(exchange: HttpExchange, status: Int, body: String) {
    val bytes = body.encodeToByteArray()
    exchange.responseHeaders.add("Content-Type", "application/json")
    exchange.responseHeaders.add("Cache-Control", "no-store")
    if (status == 405) exchange.responseHeaders.add("Allow", "POST")
    exchange.sendResponseHeaders(status, if (bytes.isEmpty()) -1 else bytes.size.toLong())
    exchange.responseBody.use { it.write(bytes) }
}
```

The app's `SessionTokenEngine` posts to that address and reads the `Session` it answers. [Authentication in the SDK](https://docs.mountaya.com/en/sdks/kotlin/authentication.md#rotate) wires it.

- `Credential.Secret(key)` reads as a constructor once `com.mountaya.client.invoke` is imported; `Credential(secretKey = ...)` builds the same credential from parts. Both are declared on the jvm alone. The secret key authenticates `postSession` alone: the client refuses it for every other operation with a `ConfigurationException` before any request.
- `postSession` answers the core's `RestSchema.Session`: `token`, `expires_at` (a `kotlin.time.Instant`), `user_id`. `SessionToken.Minted(session)` takes it as it is and tells the client which user the token names.
- `AdminSchema.SessionCreateParams(publishable_key) { user_id = …; surface = … }`: `user_id` is the member the token acts as, read from your server's own session, never from the request. Left out, the token is minted without `user_id`: it reads published content and writes nothing. A token that writes is minted with `surface = RestSchema.SessionSurface.StudioEmbedded` and `user_id` set, under a publishable key carrying `studio-embedded`.
- The mint is refused with `BillingException` (`402`) where the organization lacks the product the surface needs, and `ForbiddenException` (`403`) for a key without the scope.
- A Data API call needs a session token beside the publishable key: without one, the client refuses it with `ConfigurationException` before sending. Every field of a Data API result is nullable.
- Trail's session server (`examples/trail/session`, `mise run trail:session` in the SDK repository) is this route with its refusals (`502` where a mint fails, naming no key or token): it listens on `127.0.0.1:8787` alone, and the Android emulator reaches it at `http://10.0.2.2:8787/session`.
- `getItineraries { sort = RestSchema.GetItinerariesSort.UpdatedAtDescending; limit = 5 }`: `limit` is 1 to 100, 50 by default; the rows are `response.data`, a `List<RestSchema.Itinerary>`. A token minted without `user_id` lists only what the organization published; mint for a member to list drafts. Read every page with `walkGetItineraries` ([pagination](https://docs.mountaya.com/en/sdks/kotlin/pagination.md)).
- `SessionToken.Minted(session)` holds one minted session and is not refreshed: a long-running program hands the client a `SessionTokenEngine` instead.
- `mountaya.data.directions` answers the operation's own result (`DataSchema.DirectionsResult`), not a `Response`. `select` narrows the GraphQL document; the result type comes back whole, every field nullable, a field not selected `null`.
- The route answers the `RestSchema.Session` JSON at the top level (`token`, `expires_at`, `user_id`), which an app decodes with `RestSchema.Session.serializer()`, under `Cache-Control: no-store`: `404` on another path, `405` (with `Allow: POST`) on another method. The JDK's `com.sun.net.httpserver` keeps the program running after `main` returns.
- Never print a session token: a printed `RestSchema.Session` writes its token as `<redacted>`; print `expires_at`.

## Next steps

- [Authentication in the SDK](https://docs.mountaya.com/en/sdks/kotlin/authentication.md): Keep the app's token fresh with `SessionTokenEngine`.
- [Client basics](https://docs.mountaya.com/en/sdks/kotlin/client.md): The three APIs, writes, streams and answers.
