Skip to content

Kotlin plugin services ​

A plugin service does not have to be written in TypeScript. When a project needs functions that wrap a JVM library, a solver, or state that has to live outside the platform, it can ship them as a Kotlin plugin service: its own process, registered like any other plugin, that contributes functions to the script language and answers calls to them.

The platform provides two modules for this, the Kotlin counterpart of @mdeo/service-common:

ModuleWhat it gives you
plugin-serviceThe manifest at GET /, the session endpoint with token verification, version negotiation and keepalives, and configuration from the environment
script-plugin-servicescriptContribution, which declares script functions and implements them in one place, and the service that answers the script-functions protocol

Contributions only

A Kotlin plugin service provides contribution plugins. A language needs a Langium frontend, which only exists in TypeScript, so a plugin that adds a language is written with @mdeo/service-common.

For the same reason the module serves no /data or /:languageId/executions endpoints. It does serve /request for its contributions, see One-shot requests; a request addressed at a contribution carries no contribution payloads or hashes, and the module does not read the caller's deadline header.

Depending on the modules ​

The modules live in the platform Gradle build and are not published to a repository. Include that build in yours, and Gradle substitutes the dependency with the module built from source:

kotlin
// settings.gradle.kts
includeBuild("../mdeo-cloud/platform")
kotlin
// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.10"
    application
}

dependencies {
    implementation("com.mdeo:script-plugin-service:1.0.0-SNAPSHOT")
}

kotlin { jvmToolchain(21) }

application { mainClass.set("com.example.routing.MainKt") }

script-plugin-service brings plugin-service, the protocol, and the type references of com.mdeo.expression.ast.types with it.

A complete service ​

kotlin
package com.example.routing

import com.mdeo.expression.ast.types.BuiltinTypes
import com.mdeo.expression.ast.types.genericClassType
import com.mdeo.pluginservice.PluginDefinition
import com.mdeo.pluginservice.icon
import com.mdeo.pluginservice.runPluginService
import com.mdeo.scriptfunctions.service.scriptContribution

fun main() {
    val stopsIn = genericClassType("builtin", "ReadonlyList", typeArgs = mapOf("T" to BuiltinTypes.STRING))
    val stopsOut = genericClassType("builtin", "List", typeArgs = mapOf("T" to BuiltinTypes.STRING))

    val routing = scriptContribution("routing") {
        description = "Route planning"

        function("shortestTour") {
            parameter("stops", stopsIn)
            returns(stopsOut)
            implementation { call -> solve(call.argument<List<String>>(0)) }
        }

        function("tourLength") {
            parameter("stops", stopsIn)
            returns(BuiltinTypes.DOUBLE)
            implementation { call -> length(call.argument<List<String>>(0)) }
        }
    }

    runPluginService(
        PluginDefinition(
            id = "routing-service",
            name = "Routing",
            description = "Route planning functions for scripts",
            icon = icon("path" to mapOf("d" to "M3 12h18")),
            contributions = listOf(routing)
        )
    )
}

A script in a project that has the plugin enabled now calls stops = shortestTour(stops) like any other function. runPluginService blocks until the process is stopped.

Declaring functions ​

scriptContribution(id) { … } declares a contribution to the script language. Its id is what calls address, as contrib:<id>, and must be unique within a project.

In scriptContributionMeaning
descriptionShown in the plugin details view
sessionNameThe name of the script-functions session, functions by default
function(name, overload = "") { … }One signature of one function. Declare the same name again with another overload key to add an overload
In functionMeaning
parameter(name, type)The next parameter
returns(type)The return type; void unless declared
generics("T", …)Generic type parameters, referenced with GenericTypeRef("T")
parameter(name, type, default)The next parameter, which a call may leave out. default is an Int, Long, Float, Double, Boolean or String matching type, or null for a nullable type. The script evaluates it, so the operation always gets every argument
readsModelWhether calls are sent the model the script runs on, as call.model
operationThe operation name on the wire; the function name, or name/overload for a named overload
implementation { call -> … }What answers a call

Types are the references from com.mdeo.expression.ast.types: BuiltinTypes for scalars, genericClassType("builtin", "List", typeArgs = …) for collections, and classType("class<metamodel path>", "House") for a class of a metamodel — for a metamodel at /houses.mm, the package is class/houses.mm.

From that one declaration the service builds both halves: the external implementations in the contribution payload, and the operation table of the session answering them. A declared function cannot lack an operation, and an operation cannot answer a function nobody declared.

Mistakes surface when the service starts, not when a project loads the plugin: a function without an implementation, a signature declared twice, and a type the protocol cannot carry are all rejected by scriptContribution. Parameters, results and record fields follow the same rule, which the script language applies again when it loads the contribution: scalars, strings, Any, model instances, enum values, the contribution's own records and opaque classes, declared generics, and collections of those. A lambda is code inside the execution and cannot be sent, and parameters take the read-only collection types, because an operation cannot change its arguments.

Writing an operation ​

An operation receives the call and returns the result:

kotlin
implementation { call ->
    val values = call.argument<List<Double>>(0)
    val total = values.sum()
    values.map { it / total }
}

Arguments arrive as plain Kotlin values:

Script typeKotlin value
int, long, float, doubleInt, Long, Float, Double
boolean, stringBoolean, String
nullnull
List, Bag and their readonly typesList, readonly
Set, OrderedSet and their readonly typesSet, readonly, iterating in insertion order
Map, ReadonlyMapMap, readonly, iterating in insertion order
A metamodel classScriptModelInstance, readonly
A metamodel enumScriptEnumValue(enumName, entry); return one to return an enum value
A record of the contributionRecordValue
An opaque class of the contributionThe state behind the handle

Return any of these, or null for a void function. A returned collection can be a new one or one of the arguments — returning an argument returns that very collection to the script — and it becomes the collection type the signature declares.

The rules of a call:

  • Arguments are in. Whatever their declared type, the operation gets readonly views of collections and copies of records, and trying to change a collection fails the call. What the operation computes reaches the script through its return value only.
  • An operation that throws fails the call, and the script sees the exception's message.
  • Identity is kept. The same collection passed twice is the same object twice, and a collection that contains itself does so here as well.

Calls on one session are answered one at a time, in the order they arrive, and operations run on Dispatchers.Default. Wrap blocking I/O in withContext(Dispatchers.IO). call.session says which project and execution the call belongs to.

Each connection starts with nothing: collections are never shared between two executions.

Records and opaque classes ​

A contribution can define its own classes for its functions to exchange with scripts:

kotlin
val geo = scriptContribution("geo") {
    val point = record("Point") {
        field("x", BuiltinTypes.DOUBLE)
        field("label", BuiltinTypes.STRING)
    }
    val index = opaque("Index")

    function("buildIndex") {
        returns(index.type)
        implementation { index.wrap(SpatialIndex(loadPoints())) }
    }
    function("nearest") {
        parameter("index", index.type)
        returns(point.type)
        implementation { call ->
            val found = call.argument<SpatialIndex>(0).nearest()
            point.of("x" to found.x, "label" to found.name)
        }
    }
}

A record is a value with named fields. Scripts use it like a record they declare themselves: they create one with Point(2.5, label = "home"), read and assign its fields, copy it with with, compare records by content, and pass them to the contribution's functions. A field follows the same type rule as a signature (see above), may name a record declared after it, and no field may be named with. field(name, type, default) gives a field a constant default, which the constructor may leave out. Operations receive and return records as RecordValue, a copy of the script's record; create one with point.of(…), which checks that every field is given.

An opaque class is a handle to state that stays on the service, like an index that is expensive to build. Return index.wrap(state); when a script passes the handle back, the operation receives state itself, and returning the same state again gives the script the same handle. The service drops the state once the script no longer holds the handle, and also when the script moves on to a different model: a handle never outlives the model it was created on.

Use point.type and index.type in signatures. Referring to a class the contribution does not define is rejected when the contribution is declared.

Reading the model ​

A function that sets readsModel, or is passed model instances, gets the model the script runs on as call.model, readonly:

kotlin
function("totalRooms") {
    readsModel = true
    returns(BuiltinTypes.INT)
    implementation { call ->
        val model = call.model!!
        model.instancesOf("Building").sumOf { it.attribute("rooms") as Int }
    }
}
On ScriptModelMeaning
instancesEvery instance, by name
instancesOf(className)The instances of a class, including its subclasses
linksEvery link, each once: association, source and target instance
metamodelThe metamodel the model is an instance of
cacheScratch space for what you derive from this model
On ScriptModelInstanceMeaning
name, classNameIdentify the instance
attribute(name), attributes(name)A single-valued attribute, or all values of a multi-valued one. Enum values are ScriptEnumValues, as in arguments
reference(name), references(name)The instances an association end refers to

An instance passed as an argument is the same object as the one in call.model.instances, and an operation can return an instance of the call's model to the script.

The metamodel describes what the model's instances can hold, so a service can work on models of any metamodel without knowing it in advance:

On ScriptMetamodelMeaning
pathWhere the metamodel lives in the project
classesEvery class by name, with isAbstract, extends and its own attributes (name, type, isEnum, multiplicity)
enumsThe entries of every enum, by name
associationsEvery association: its source and target end (className, name, multiplicity) and its operator
subtypesOf(className)A class and every class inheriting from it
cacheScratch space for what you derive from this metamodel

An association end's name is the property its class refers to the other end through, so instance.references(end.name) walks it. links does that for every association, and lists a link whose association has a property on both ends once rather than from each side.

A model lives exactly as long as the script works on it. The model is uploaded once and reused for every call on the same model: an optimizer evaluating several guidance functions on one solution sends that solution's model once. When the script moves on to another model, the service drops the previous one together with its cache and every collection it held. Use cache for anything worth computing once per model, like an index or a distance matrix; nothing in it is ever seen while working on a different model.

A metamodel lives as long as the session. It is sent once, before the first model of it, and every later model of the same metamodel shares the same ScriptMetamodel object and its cache. Derive what depends only on the metamodel — which associations to follow, which attributes are numeric — there, once.

Configuration ​

runPluginService reads the same environment variables as the TypeScript services:

VariableDefaultMeaning
PORT3000Port to listen on
HOST0.0.0.0Host to bind to
BACKEND_API_URLhttp://localhost:8080/apiThe backend API. Session tokens are verified against the keys it publishes at /.well-known/jwks.json
JWT_ISSUERmdeo-platformThe issuer every accepted token must name
MAX_SESSIONS64How many sessions may be open at once; another is refused with 4503

A numeric variable set to something that is not a whole number in its range stops the service at startup. Pass a PluginServiceConfig instead to set them in code.

One-shot requests ​

A contribution can also answer the platform's plain request/response channel, the same one a language plugin serves at POST /request/lang/<id>/<key>. Declare a handler per request key and it is reached at contrib:<id>/<key>:

kotlin
val stats = scriptContribution("model-stats") {
    description = "Statistics over the model"

    request("version") { JsonPrimitive(BuildInfo.VERSION) }

    request("describe") { context ->
        buildJsonObject {
            put("project", context.projectId)
            put("operations", operationCount)
        }
    }
}

The handler is given a RequestContext: the projectId the caller speaks for, the addressed target, the key, the body the caller sent as a JsonElement, and the token the request arrived with, to pass on to the backend. What travels in body and what comes back is between the two sides; the platform only carries it.

A request is authorized on its own — the token must carry plugin:request:send and name the project in the body — and nothing is kept once it is answered. Reach for it when there is no state to remember between calls, and for a session when there is: a session stays open, negotiates a protocol version, and can hold a heap, a model or open handles across messages.

An exception thrown by a handler is logged and answered with a generic 500, so nothing internal reaches the caller; report an expected failure yourself by returning it in the answer.

Adding routes of your own ​

runPluginService starts a server that serves nothing but the plugin. To add routes, health checks or other Ktor plugins, install the plugin service into an application you configure yourself:

kotlin
embeddedServer(Netty, port = config.port, host = config.host) {
    pluginService(definition, JwksPluginTokenVerifier(config.backendApiUrl, config.jwtIssuer), config.maxSessions)
    routing {
        get("/health") { call.respondText("ok") }
    }
}.start(wait = true)

A route that throws is answered with 500 in the platform's error shape, with a generic message; the exception itself only goes to the log. An unknown route answers 404 and an unreadable body 400, in the same shape. Report an expected failure yourself with call.respondError(HttpStatusCode.NotFound, "No such thing").

Deployment ​

A Kotlin plugin service is deployed like any other plugin: run it where the backend and the execution services can reach it, then register its URL as a plugin. The backend reads the manifest from GET /, and executions dial its sessions directly, so the execution services must be able to reach the same URL. A session is a WebSocket upgrade on the service's own port; see Sessions — Deployment for what a proxy in front of it needs.

Testing ​

ScriptFunctionsServiceSession answers protocol messages without any connection, which is the quickest way to test operations:

kotlin
val service = ScriptFunctionsServiceSession(routing.operations)
val answer = runBlocking {
    service.handle(ClientMessage.Call(1, "tourLength", objects, args))
}

To test the whole service, pluginService runs inside Ktor's testApplication. Pass a PluginTokenVerifier that accepts a fixed token instead of verifying against a backend.

See also ​

Released under the terms of the repository licence.