MDK Logo
GuidesApps

Test an app with MDK

Check a third-party app package with the listing gate, run it in a live stack, and install a release

This guide is for partners who have built an app package in their own repository, and for operators who want to test one before adding it to a site.

Overview

An app's package is the contract between its routes and the stacks that install it, so test it before you publish or list it. This page tests at three levels, each closer to an operator's site:

  • The listing gate checks the package with a mock Kernel and no stack
  • A scratch project runs it beside a mock Worker behind a real Gateway
  • A clean project installs a published release the way mdk add app does for an operator.

The controllers' own unit tests live with the package.

Prerequisites

  • Node.js >=24
  • npm 11 (< 12)
  • The mdk CLI, installed from npm
  • A completed app package at the root of its repository, as mdk create app --flat scaffolds it
  • curl and jq for the calls to a running stack, and ports 3847 (Gateway) and 3848 (Kernel) free

Check the package

1.1 Add a smoke sample

The gate calls every route, and skips one with a path parameter or required input unless smoke.config.js supplies a sample. Under --strict, a skipped route fails the gate. Add smoke.config.js at the repository root. For the fleet app:

'use strict'

module.exports = {
  setup: async () => ({
    requests: {
      'fleet.set-power-mode': { params: { deviceId: 'smoke-0' }, body: { mode: 'eco' } }
    }
  })
}
Other fields setup() can return

setup() may return these fields, and --smoke-config takes the same object as inline JSON or a .json file:

FieldDefaultDescription
workersOne worker smoke with one device smoke-0The mock fleet: [{ workerId, family?, brand?, devices: [{ id, telemetry?, state?, capabilities? }] }]
requestsNoneA sample { params, query, body, headers } per route id
configNoneOperator config laid over the config defaults in mdk-app.yaml
teardownNoneStops whatever setup() started

1.2 Run the gate

Run the listing gate from the app's repository root. It exits 1 on any problem, so the same command works as a CI gate:

mdk validate app --path . --smoke --strict

Expected output for the fleet app from the build guide:

✔ fleet (io.your-org.fleet 0.1.0) is a valid app: 2 routes, 2 permission rules, UI; 8 smoke checks passed
Read the verdict as JSON in CI

--json prints the same verdict as one JSON object, for a CI step to parse:

mdk validate app --path . --smoke --strict --json

Expected output, with your own name and path:

{"ok":true,"kind":"app","name":"io.your-org.fleet","path":"/home/you/fleet","errors":[],"warnings":[]}
What the gate checks, and why a check fails

The bare command, mdk validate app --path ., checks three parts of the package and runs no controller:

  • The manifest: mdk-app.yaml has the required keys, a reverse-DNS id, a semver version equal to the one in package.json, and permissions rules that name Kernel resources with verbs they take
  • The route table — follows the Gateway's own loader rules, and every handler resolves inside plugin/ and compiles
  • The built UI, when ui/ exists: it parses, bundles no React, imports only the modules the dashboard lends it, and exports a contract whose id matches the manifest

--smoke adds a run of the routes. It loads them and main through the app runtime's own loader, then calls every route against an in-memory Kernel that serves a mock fleet and grants the app exactly its declared permissions. No Kernel, Gateway, or DHT runs. --strict turns every warning into an error, so a package passes the gate only when it has none. The CLI reference documents every flag.

Smoke checkFails whenFix
Routes load and every handler exports a functionA handler or a module it requires throws, or does not export a functionRun the controller in a unit test and fix the throw
main runs to completionmain rejects, throws or does not settle within --timeoutMake main finish, and move long work out of it
Each route answers with JSON or an ERR_*The route throws a non-ERR_* error, returns a value JSON cannot encode, or hangsThrow Error('ERR_...') and return plain data
Each route stays within the permissions in mdk-app.yamlThe route makes a Kernel call the declared rules do not grantAdd the access the message names, such as devices:write
A read-only route makes no Kernel writeA get or list route, or one marked safety: read-only, sends a commandStop it writing, or use a write HTTP method and verb with safety: write
Each route answers with JSON or an ERR_* while the Kernel is downThe route hangs or crashes once every Kernel call fails with ERR_MDK_CLIENT_UNAVAILABLECatch the error by its code, as summary.js does

A stream route cannot pass --strict today, because the smoke pass reports streaming routes are not tested yet as a skipped route. An app that streams installs and runs normally. Say so in your listing request, because the gate cannot clear it.

The gate calls controllers in isolation and trusts the sample you give it. It does not prove that a Worker exists to answer, which a live stack does.

Run the app in a stack

2.1 Start a scratch project

A scratch project hosts your app beside a scaffolded Worker. The app stays in its own repository, and the project's mdk.yaml points at it by path. spec.network.dht starts a private HyperDHT bootstrap on this machine, so the stack needs no traffic to the public network:

mkdir ~/fleet-dev && cd ~/fleet-dev
cat > mdk.yaml <<'YAML'
apiVersion: mdk.tether.io/v1
kind: Stack
metadata:
  name: fleet-dev
spec:
  kernel: { port: 3848 }
  gateway: { port: 3847 }
  network:
    dht: { host: 127.0.0.1 }
  workers: []
  apps:
    - name: fleet
      package: ../mdk-app-fleet
      config: {}
YAML
mdk create worker rig
mdk rbac init
mdk run

mdk create worker scaffolds a Worker with one mock device, rig-0. mdk rbac init writes the access policy under spec.rbac, including the role app-fleet from your manifest. Expected output ends with:

✔ app fleet ready
Starting gateway → :3847
Creating fallback logger
✔ gateway listening on http://localhost:3847

Stack running. Press Ctrl+C to stop.

2.2 Create a user

Leave the stack running. In a second terminal, create a user:

cd ~/fleet-dev
mdk user add admin --admin

The command prompts for a password twice. Expected output starts with:

✔ Created user admin
  mdk.yaml bound admin to admin

2.3 Sign in

No route is open, so a call without a token gets 401:

curl -s http://localhost:3847/apps/fleet/api/fleet/summary | jq .

Expected output:

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "ERR_AUTH_UNAUTHORIZED"
}

Sign in for an access token:

TOKEN=$(curl -s -X POST http://localhost:3847/auth/login \
  -H 'content-type: application/json' \
  -d '{"username":"admin","password":"<password>"}' | jq -er .accessToken)

2.4 Call the summary route

Send the token as a bearer token:

curl -s -H "Authorization: Bearer $TOKEN" http://localhost:3847/apps/fleet/api/fleet/summary | jq .

Expected output:

{
  "ok": true,
  "kernelConnected": true,
  "workerCount": 1,
  "deviceCount": 1,
  "workers": [
    {
      "workerId": "rig",
      "devices": 1
    }
  ]
}

2.5 Call the write route

The write route reaches the Worker through the Kernel as the signed-in user:

curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"mode":"eco"}' http://localhost:3847/apps/fleet/api/fleet/devices/rig-0/power-mode | jq .

Expected output, with your own commandId:

{
  "deviceId": "rig-0",
  "mode": "eco",
  "commandId": "38f4ce92-5a97-4738-b187-c5a5d04982ed",
  "status": "QUEUED"
}

2.6 (Optional) Open the dashboard

To see the UI, run mdk create dashboard and mdk run dashboard in ~/fleet-dev, as the first app tutorial does, then open the dashboard and sign in. The dashboard loads each app's built ui/ from the directory its spec.apps entry resolves to, and a path such as ../mdk-app-fleet resolves like a package name.

2.7 Stop the stack

Press Ctrl+C in each terminal. Delete ~/fleet-dev to remove the stack's state, users included.

Run the checks in CI

3.0 Run the checks in CI

The listing gate belongs in your own CI, next to the unit tests. This GitHub Actions workflow runs the sequence a fresh clone needs. Each Action is pinned to the commit behind a release tag:

name: app
on: [push, pull_request]
permissions:
  contents: read
jobs:
  gate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # pins v7.0.1
      - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # pins v7.0.0
        with:
          node-version: 24
      - run: npm ci
      - run: npm --prefix ui-src ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm test
      - run: npm run build:ui && git diff --exit-code ui/
      - run: npm install --global @tetherto/mdk-cli
      - run: mdk validate app --path . --smoke --strict

The gate's stale-UI check compares file modification times, so it catches a ui/ older than ui-src/ on your machine and does not in a fresh clone. The build:ui and git diff --exit-code ui/ step is what fails CI when you commit a source change without rebuilding. Rebuild before you commit.

Install a release from a clean project

After you publish a release, install it the way an operator does.

4.1 Create a clean project

mkdir ~/fleet-clean && cd ~/fleet-clean
mdk onboard

mdk onboard is a wizard: it asks the setup questions and writes mdk.yaml.

Install the release from the source you published to.

A. Install from GitHub

mdk add app github:your-org/mdk-app-fleet#v0.1.0

Expected output includes:

✔ Added app fleet → @your-org/mdk-app-fleet
  package.json dependency @your-org/mdk-app-fleet pinned to commit <sha>
  mdk.yaml added under spec.apps
  mdk.yaml spec.rbac role app-fleet grants app:fleet the Kernel access it requests

B. Install from npm

mdk add app @your-org/mdk-app-fleet@^0.1.0

Either way, mdk add app installs with npm install --ignore-scripts --save-exact, so no install script of your package runs and the exact version is recorded. A GitHub source is pinned to the commit the lockfile resolved. It then checks the package with the rules of mdk validate app, except that it never runs the app's own code, so there is no smoke pass and no UI contract load, and it writes the spec.apps entry only if the package passes. The gate is stricter than an install, which is why you run it yourself. A refused package leaves mdk.yaml, package.json and the lockfile as they were.

4.2 Grant and run

mdk rbac init
mdk run

mdk add app writes the app's role under spec.rbac and nothing else, so mdk rbac init binds the CLI to admin before mdk run, which refuses a policy that lets nobody administer the Kernel.

Troubleshooting

Package checks

mdk validate app --path . reports these. A warning does not fail a plain run, and --strict turns it into an error:

MessageLevelFires whenFix
"version" <a> does not match package.json version <b>ErrorThe two versions differSet the same version in both files
"permissions" is requiredErrormdk-app.yaml has no permissions keyAdd the rules the app needs, or [] for none
unknown key "<key>" (allowed: ...)Errormdk-app.yaml holds a key outside id, version, displayName, description, permissions, config and mainRemove the key
"id" must be reverse-DNSErrorid is not lowercase reverse-DNSUse a form such as io.your-org.fleet
"id" com.example.<name> is the scaffold placeholderWarningThe id is still the scaffold's defaultSet your own id in mdk-app.yaml and ui-src/index.tsx, then rebuild
route "<id>" handler "<path>" not foundErrorA handler file is missingFix the path, which is relative to plugin/mdk-plugin.json
route "<id>" sets permissions, which spec.rbac ignoresWarningA route carries a permissions fieldDelete the field and request access in mdk-app.yaml
pairs a null branch with a number, integer, string, boolean or array oneWarningA body schema uses anyOf or oneOf with null beside a scalarWrite "type": ["<type>", "null"] instead
ui/index.js declares id "<a>", but mdk-app.yaml says "<b>"ErrorThe UI module and the manifest disagreeSet one id in both, then run npm run build:ui
ui/index.js imports "<module>", which the dashboard does not provideErrorThe built UI imports a package outside the shared listBundle that package into the UI build, or drop it
ui/index.js bundles its own copy of ReactErrorThe UI build did not leave React externalKeep the shared packages in rollupOptions.external
ui/index.js exports no pages and no panelsWarningThe starter placeholder is still in ui/Run npm run build:ui
<file> changed after ui/ was builtWarningA file in ui-src/ is newer than the buildRun npm run build:ui, then commit ui/
scripts.postinstall does not run when the app is installedWarningpackage.json has preinstall, install or postinstallRemove the script and move its work into the build
route '<id>' skipped: it needs inputWarningA route has a path parameter or required input and no sampleAdd requests['<id>'] to smoke.config.js
route '<id>' skipped: streaming routes are not tested yetWarningThe app has a stream: true routeNone today, because a stream route cannot pass --strict

Running in a stack

ResponseFires whenFix
401 ERR_AUTH_UNAUTHORIZEDThe request has no valid bearer tokenSign in at POST /auth/login and send the access token
403 ERR_AUTH_FORBIDDENThe signed-in user's roles hold no rule for the route's resource and verbBind a role that grants it to the user in spec.rbac
403 ERR_KERNEL_ACTION_FORBIDDEN: app:<name> may not ...The app's role lacks a permission, or the operator narrowed itRequest the access in permissions, then widen the role app-<name> in spec.rbac and run mdk rbac apply
400 body/<field> must be ...The request fails the route's parameters or requestBody schemaFix the request, or the schema
404 on /apps/<name>/...The stack does not declare the app, or the path is wrongAdd the app under spec.apps, and call the path without a doubled prefix
503 ERR_APP_RUNTIME_UNAVAILABLE: <name>The app's runtime has not published its key yet, or has stoppedWait for ✔ app <name> ready, or restart the app
ERR_MDK_CLIENT_UNAVAILABLE from a controllerThe Kernel is unreachable and the controller does not catch the errorCatch it by err.code and return a degraded result

Installing

MessageFires whenFix
<ref> is not a valid app; mdk.yaml was not changedmdk add app found package errors, which it listsRun the gate on that release and fix what it reports
A refusal that shows two rule setsA new release requests different Kernel accessPass --accept-permissions or --keep-permissions
spec.rbac binds no user, and lets nobody write the policy, so the Kernel would boot with nobody able to administer it from mdk runmdk add app wrote the app's role and binding, and nothing binds an administratorRun mdk rbac init, then mdk run

Next steps

On this page