# How to embed the StackQL MCP server in a Kotlin or JVM application

> Embed the StackQL MCP server in a Kotlin/JVM app as a library or Gradle plugin, so a JVM service or CI/CD pipeline can run cloud queries and cost gates over SQL with no runtime dependency.

Source: https://stackql.io/ai/how-tos/embed-stackql-mcp-server-in-kotlin

StackQL's MCP server can run inside a Kotlin or JVM application with no `npx`, no separate install, and no runtime dependency. The `io.stackql:stackql-mcp` library spawns the signed StackQL binary over stdio behind the official Kotlin MCP SDK client, and a companion Gradle plugin wires the same launch into a build. This is the pattern behind **costgate**, a cost gate for CI/CD shipped as a CLI and a Gradle plugin.

## Steps

1. **Add the library** to your Gradle dependencies:

```kotlin
dependencies {
    implementation("io.stackql:stackql-mcp:0.1.0")
}
```

Requires JDK 17 and Kotlin 2.x. The client comes from the official Kotlin MCP SDK.

2. **Start the server and list tools.** The builder defaults to `Mode.ReadOnly`:

```kotlin
import io.stackql.mcp.LaunchArgs
import io.stackql.mcp.Mode
import io.stackql.mcp.StackqlMcp

suspend fun main() {
    val server = StackqlMcp.builder()
        .mode(Mode.ReadOnly)
        .auth(LaunchArgs.authFor("github", "null_auth"))
        .start()

    server.use {
        val tools = server.client.listTools().tools
        println("${tools.size} tools available")
    }
}
```

3. **Choose a mode.** `.mode()` defaults to `Mode.ReadOnly`. Set `Mode.Safe`, `Mode.DeleteSafe`, or `Mode.FullAccess` only when the app needs to provision. Escalation is explicit.

## Run StackQL queries from a Gradle build

The Gradle plugin wires the embedded server into your build so CI tasks run StackQL queries without a separate install step. The **costgate** demo gates infrastructure deploys on cost budgets, as a CLI:

```bash
costgate check --intent examples/costgate.yaml --explain
```

and as a Gradle plugin:

```kotlin
plugins {
    id("io.stackql.costgate") version "0.1.0"
}

costgate {
    intent.set(layout.projectDirectory.file("costgate.yaml"))
    explain.set(true)
}
```

## Related concepts

- [Embedded MCP: Kotlin / JVM reference](/mcp/embedded/kotlin) - install, API, and the Gradle plugin
- [How to use StackQL with AI agents](/ai/how-tos/use-stackql-with-ai-agents) - the MCP model and safety modes
- [StackQL MCP Architecture](/ai/architecture/stackql-mcp-architecture) - transports, modes, and audit internals
- [What is Agentic Infrastructure?](/ai/canonical-definitions/what-is-agentic-infrastructure) - the pattern this enables
