MDK Logo
GuidesApps

Build a third-party app

Ship an MDK app from your own repository: scaffold it, declare its Kernel access, write its routes and UI, then publish and list it

TL;DR

An app package is:

  • mdk-app.yaml at the package root
  • A route table, plugin/mdk-plugin.json, and the controller file each route's handler names
  • A UI module that mdk create app scaffolds in ui-src/ and builds into ui/index.js, which a routes-only app deletes

The listing gate is the exit code of mdk validate app --path . --smoke --strict, which you run when you test the app.

Overview

Want a quick tutorial first? Build your first app with a UI takes a clean machine to a running app in about 15 minutes.

This guide is for partners who want to ship an app: a set of HTTP routes over Worker data with a page in the MDK dashboard. The app lives in their own public or private repository.

It walks through creating one app from an empty repository to a listing request: scaffolding the package, declaring its Kernel access, writing routes and controllers, shaping the starter UI, unit-testing the controllers, publishing to npm or GitHub, and requesting a listing. Testing the finished package, from the listing gate to an operator-style install, is its own guide, and the listing itself is a separate PR to the supported apps reference.

What you get

mdk-app-fleet/
├── package.json           # npm identity; `files` decides what ships
├── mdk-app.yaml           # manifest: id, version, displayName, permissions, config
├── README.md              # what operators read before installing
├── smoke.config.js        # you add this: sample requests and a mock fleet for the gate
├── plugin/
│   ├── mdk-plugin.json    # route table
│   ├── types.d.ts         # response types, shared by the controllers and the UI
│   ├── lib/client.js      # the app's Kernel client
│   └── controllers/       # one module per route
├── test/                  # controller unit tests, run by `npm test`
├── ui-src/                # UI source and its build tooling, not published
└── ui/                    # the built UI module, committed and published

mdk create app --flat scaffolds everything except smoke.config.js from the app template. The scaffold's files list ships mdk-app.yaml, plugin/, ui/ and README.md, so tests, ui-src/ and smoke.config.js stay in your repository.

Prerequisites

  • Node.js >=24
  • npm 11 (< 12)
  • The mdk CLI >=0.14
  • A basic understanding of what an app is and how MDK works. An app serves HTTP routes upward to people and agents and reads and commands devices through the Kernel; a Worker speaks a device protocol downward to hardware
  • A Git repository for the app, and an npm account with publish rights to your scope if you publish to npm
  • Comfort with plain async JS for the controllers, and React with TypeScript if the app has pages

Scaffold the package

1.1 Create the repository

Scaffold at the repository root. --flat writes the package into the current directory, the layout that mdk add app github:<owner>/<repo> installs and mdk validate app --path . checks, and it touches no MDK project:

mkdir ~/mdk-app-fleet && cd ~/mdk-app-fleet
git init
mdk create app fleet --flat --org your-org --id io.your-org.fleet

--org scopes the npm package name to @your-org/fleet, and --id writes your reverse-DNS app id into mdk-app.yaml and the UI source. The command installs dependencies and builds the starter UI, so it needs network access. It refuses a directory that holds an mdk.yaml or any file the scaffold writes unless you pass --force.

Expected output includes:

✔ Scaffolded app fleet → /home/you/mdk-app-fleet
  package @your-org/fleet
  ✔ Built the starter UI → ui/index.js (source in ui-src/)

1.2 Make the package publishable

The scaffold writes "private": true, and npm publish refuses a private package with EPRIVATE. Delete that line, then set the fields npm and your consumers read in package.json:

{
  "name": "@your-org/mdk-app-fleet",
  "description": "Fleet overview and power control for MDK sites",
  "repository": { "type": "git", "url": "git+https://github.com/your-org/mdk-app-fleet.git" },
  "publishConfig": { "access": "public" }
}

Do not add preinstall, install or postinstall scripts. mdk add app installs with --ignore-scripts, so they never run, and --strict fails on them.

The mdk-app- prefix is the naming convention. mdk add app @your-org/mdk-app-fleet installs the app under the name fleet, because the CLI drops the prefix. That instance name is the third of three names an app carries:

NameWhere it livesRulesWho sets it
App idid in mdk-app.yaml and in ui-src/index.tsxLowercase reverse-DNS such as io.your-org.fleet, treated as permanentYou
Package namename in package.jsonAn npm name, @your-org/mdk-app-<name>You
Instance namespec.apps[].name in an operator's mdk.yaml^[a-z][a-z0-9-]*$ and unique in the stack. Defaults to the package name without mdk-app-. It also sets the route prefix /apps/<name> and the service account app:<name>.The operator

Declare the Kernel access

2.0 Declare the Kernel access

The Kernel checks every call a controller makes against the app's own service account, app:<name>, and a call made through req.mdk is checked against the signed-in user too. permissions in mdk-app.yaml is the access you request from the operator's spec.rbac. mdk add app writes it as the role app-<name>, which the operator may narrow, and the key is required even when the app makes no Kernel call ([]).

The fleet app's summary route lists Workers and its power-mode route commands a device, so replace the scaffold's permissions line in mdk-app.yaml with:

permissions:
  - resources: [workers]
    verbs: [list]
  - resources: [devices]
    verbs: [write]

A rule names a Kernel resource and the verbs that resource takes. Only these resources are valid, and the RBAC library defines the rule shape:

ResourceVerbsresourceNames scope
devicesread, writefamily/brand/worker/device, such as miner/antminer/antminer-a/AM-001
workerslist, read, deletefamily/brand/worker
commandsreadNone
actionsread, write, vote, delegateNone
policyread, writeNone
identitiesread, writeNone

Each client call needs one permission:

Client callNeeds
listWorkers()workers: list
pullTelemetry(), pullState(), getCapabilities(), getCommandStatus()devices: read
sendCommand(), sendCommandBatch()devices: write

Request the least access the routes use. Add resourceNames when the app targets one family, for example ["miner/*"] for every miner or ["powermeter/*"] for every power meter. A rule without resourceNames covers every device.

When a release changes permissions, mdk add app shows the old and new rules and refuses until the operator passes --accept-permissions or --keep-permissions. Widen access only when a route needs it, and say so in your release notes.

Write the routes and controllers

3.1 Declare the routes

plugin/mdk-plugin.json lists one entry per route. The scaffold's fleet.summary route is a read. This fleet.set-power-mode route is a write, modeled on the Starter site's site.miner-command. Add it to the routes array:

{
  "id": "fleet.set-power-mode",
  "description": "Sets the power mode of one device, as the signed-in user.",
  "handler": "./controllers/set-power-mode.js",
  "safety": "write",
  "errors": ["ERR_INVALID_POWER_MODE", "ERR_DEVICE_NOT_FOUND"],
  "http": {
    "method": "POST",
    "path": "/api/fleet/devices/{deviceId}/power-mode",
    "parameters": [
      { "in": "path", "name": "deviceId", "required": true, "schema": { "type": "string" } }
    ],
    "requestBody": {
      "required": true,
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "required": ["mode"],
            "properties": { "mode": { "type": "string", "enum": ["eco", "normal", "high"] } }
          }
        }
      }
    }
  }
}

A few fields are more than documentation:

  • safety is read-only or write. mdk run mcp turns routes into agent tools and withholds every write route unless it starts with --allow-write.
  • description is what operators and agents read, so put the constraint in it and not only a label
  • parameters and requestBody are enforced by the Gateway before your controller runs, and a violation answers 400
  • path is declared without the /apps/<name> prefix, which the Gateway adds, and path parameters use {param}

Do not put permissions on a route. spec.rbac decides who may call a route, so the field gates nothing, and the gate warns about it. Declare a nullable number, string, boolean or array as a type list such as "type": ["number", "null"]. An anyOf that pairs a null branch with a scalar one lets the Gateway's type coercion turn a JSON null into 0, "", false or an array, and the gate warns about that too.

The route table also takes a flat method/path form and #namedExport handlers, and the real manifests to start from are on the Gateway apps page.

3.2 Write the controllers

Every controller exports async function (req) and returns plain data, which goes out as a 200 JSON body. The scaffolded plugin/controllers/summary.js is the read pattern: it calls the Kernel through the app's client and, when the Kernel is unreachable, answers with a degraded result instead of failing, so the route stays callable during boot. Check for the error's code:

try {
  const { workers } = await mdkClient.listWorkers()
  // ...
} catch (err) {
  if (err && err.code === 'ERR_MDK_CLIENT_UNAVAILABLE') return { ok: true, kernelConnected: false }
  throw err
}

plugin/controllers/set-power-mode.js is the write pattern:

'use strict'

const POWER_MODES = ['eco', 'normal', 'high']

module.exports = async function setPowerMode (req) {
  const { deviceId } = req.params
  const mode = req.body && req.body.mode
  if (!POWER_MODES.includes(mode)) throw new Error('ERR_INVALID_POWER_MODE')

  // Sent as the signed-in user: the Kernel checks their rules as well as the app's.
  const result = await req.mdk.sendCommand(deviceId, 'setPowerMode', { mode })

  // A command the Kernel will not queue (unknown device, undeclared command, bad params) comes back as
  // status REJECTED. An access refusal throws ERR_KERNEL_ACTION_FORBIDDEN before this line.
  if (result.status === 'REJECTED') {
    const code = String(result.error || 'ERR_COMMAND_REJECTED')
    throw Object.assign(new Error(code), { statusCode: code.startsWith('ERR_DEVICE_NOT_FOUND') ? 404 : 422 })
  }

  return { deviceId, mode, commandId: result.commandId, status: result.status }
}

Two clients are in play, and which one a controller uses decides whose access the Kernel checks:

ClientActs asUse it for
req.mdkThe signed-in user, and the appWork done for a request, so the Kernel checks both and the write-command log records the user
The client in plugin/lib/client.js, from the app's contextThe app alone, as app:<name>Work no request owns, such as the setup in main. The Kernel does not re-check the signed-in user.

A thrown Error('ERR_...') answers 400, an integer statusCode on the error sets the status, and a Kernel refusal answers 403: how a failure reaches the caller has the full mapping and the body shape.

sendCommand returns the Kernel's acceptance, not the command's outcome. A command the Kernel will not queue, such as one for an unknown device, a command the device does not declare, or params that break the contract, comes back as status: 'REJECTED' rather than a thrown error, so a controller that does not raise it answers 200 for a command that never ran. An access refusal is different: sendCommand throws ERR_KERNEL_ACTION_FORBIDDEN, which the Gateway answers as 403. Read the outcome with getCommandStatus when the caller needs it.

Caching, stream routes, and the per-route verb and resourceName fields that let an operator scope who may call a route make up the rest of the route surface.

Shape the starter UI

4.0 Shape the starter UI

mdk create app scaffolds the UI with the app, so no separate command adds one. ui-src/ holds one page and one Home panel that render the summary route, split across the MDK UI layers: the request in data/summary.ts, a hook in hooks/use-summary.ts, the components in pages/ and components/, and index.tsx, which default-exports defineMdkApp({ id, displayName, routes, panels }) from @tetherto/mdk-react-adapter. The scaffold builds it into ui/index.js and ui/style.css. With --no-install, ui/index.js stays a placeholder that exports no pages, which the gate flags.

Rebuild after every edit, or rebuild on each save:

npm run build:ui
npm run dev:ui

Four rules keep the module loadable, and the gate checks the first three:

  • The module id equals id in mdk-app.yaml, because the dashboard refuses a package that loads under another app's identity
  • The module imports only the packages the dashboard lends it: react, react/jsx-runtime, react-dom, react-router, @tanstack/react-query, @tetherto/mdk-ui-foundation, @tetherto/mdk-react-adapter and @tetherto/mdk-react-devkit
  • The module bundles no copy of React, and the scaffold's Vite config marks those packages external
  • Pages reach the app's routes with useMdkApp().apiUrl('/api/fleet/...') and never a hardcoded /apps/fleet/... URL, because the operator chooses the installed name

Commit ui/ after every rebuild. mdk add app github:... runs no build, so an unbuilt ui/ reaches the consumer as a missing module. plugin/types.d.ts types each route's response once for both halves, as the UI module contract describes.

To add pages and panels with a coding agent, mdk skill add installs the MDK Developer Skill suite for Cursor or Claude. Its mdk-ui-component skill covers the module contract, the build, and the data, hook, and component layers.

A routes-only app deletes ui/ and ui-src/. The gate checks the UI only when ui/ exists, and the dashboard lists an app that ships no UI without loading anything for it.

ui-src/ also owns the installs behind the scaffold's lint and typecheck:plugin scripts. If you drop the UI, replace those two scripts, change typecheck to run only typecheck:plugin, and remove build:ui, dev:ui, and typecheck:ui along with ui-src/.

Unit-test the controllers

5.1 Write the write-controller test

The scaffold ships test/summary.test.js. It stubs plugin/lib/client.js through require.cache, because the app runtime provides that client. req.mdk is part of the request itself, so a write controller needs only the client you pass in. test/set-power-mode.test.js:

'use strict'

const { test } = require('node:test')
const assert = require('node:assert')

const setPowerMode = require('../plugin/controllers/set-power-mode')

// `req.mdk` is the request's Kernel client, so the test passes its own.
const request = (body, sendCommand) => ({ params: { deviceId: 'rig-0' }, query: {}, headers: {}, body, mdk: { sendCommand } })

test('sends the mode to the device and returns the queued command', async () => {
  let sent
  const sendCommand = async (...args) => { sent = args; return { commandId: 'c1', status: 'QUEUED' } }
  const result = await setPowerMode(request({ mode: 'eco' }, sendCommand))
  assert.deepStrictEqual(sent, ['rig-0', 'setPowerMode', { mode: 'eco' }])
  assert.deepStrictEqual(result, { deviceId: 'rig-0', mode: 'eco', commandId: 'c1', status: 'QUEUED' })
})

test('refuses a mode outside the list before calling the Kernel', async () => {
  const sendCommand = async () => assert.fail('the Kernel must not be called')
  await assert.rejects(setPowerMode(request({ mode: 'turbo' }, sendCommand)), /ERR_INVALID_POWER_MODE/)
})

test('raises a rejected command with the status the caller should see', async () => {
  const sendCommand = async () => ({ status: 'REJECTED', error: 'ERR_DEVICE_NOT_FOUND' })
  await assert.rejects(
    setPowerMode(request({ mode: 'eco' }, sendCommand)),
    (err) => err.message === 'ERR_DEVICE_NOT_FOUND' && err.statusCode === 404
  )
})

Cover at minimum a read that answers while the Kernel is down, a write that reaches the client with the right arguments, input validation before any Kernel call, and a REJECTED command raised with the status the caller should see.

5.2 Run the checks

The scaffold's scripts run the tests, the linter, and the type check:

npm test               # node --test
npm run lint           # oxlint over plugin/, test/ and ui-src/
npm run typecheck      # the controllers (JSDoc under // @ts-check) and the UI against plugin/types.d.ts

Write a README

6.0 Write a README

The scaffold's README.md ships in the tarball and is the page an operator reads before installing, so replace it. State the app's setup requirements, supported capabilities, configuration, permissions, and release information, which the contribution guide asks of every released package.

Publish the package

Pass the listing gate before you publish.

7.1 Check what ships

mdk validate checks the directory, not the tarball. List what npm would publish:

npm pack --dry-run

Expected output lists these files, each with its size:

README.md
mdk-app.yaml
package.json
plugin/controllers/set-power-mode.js
plugin/controllers/summary.js
plugin/lib/client.js
plugin/mdk-plugin.json
plugin/types.d.ts
ui/index.js
ui/style.css

The list holds package.json, the manifest, plugin/, ui/ and the README, and nothing else. Tests, ui-src/, smoke.config.js, keys and .env files do not belong in it.

7.2 Version the release

Set the same version in package.json and mdk-app.yaml, because the gate fails when they differ. A release that changes permissions also needs a release note, because mdk add app stops for the operator on changed permissions.

7.3 Publish it

Either source works, and an app does not have to reach npm at all. The apps MDK ships install from GitHub.

A. Push a tag to GitHub

git push origin main
git tag v0.1.0 && git push --tags

mdk add app needs only the tag. Create a GitHub Release on it for the release notes, which is where an operator stopped by changed permissions looks for them.

B. Publish the package to npm

npm publish

publishConfig.access makes the scoped package public, and without it you pass --access public. Install the release from a clean project to see it the way an operator does.

Get listed

8.0 Get listed

Publishing makes the app installable, and a listing is a request that maintainers review. Before you ask:

  1. Run the listing gate on the commit you tag, and keep it in CI. Its exit code is the gate a package is listed at, and passing it does not guarantee a listing.

  2. Check that the README covers setup requirements, supported capabilities, configuration, permissions, and release information.

  3. Propose an entry in the supported apps reference with your own PR. Include the app's package or repository, purpose, installation instructions, and requested permissions.

    Alternatively, open an issue requesting inclusion.

Maintainers review the proposed addition. The contribution guide defines the process.

Conformance checklist

Before calling your app done, confirm what the listing gate checks:

  • mdk validate app --path . --smoke --strict exits 0 on the commit you tag
  • id is your own reverse-DNS id and equals the UI module's id
  • version is the same in package.json and mdk-app.yaml
  • permissions names Kernel resources with verbs they take, and every route stays within it
  • Every route answers JSON or an ERR_* code, including while the Kernel is down
  • No route marked read-only or served as get or list writes to the Kernel
  • Every route that takes input has a sample in smoke.config.js
  • ui/ parses, bundles no React, and imports only the modules the dashboard lends it
  • package.json has no install scripts, and mdk-app.yaml has no unknown keys

Then confirm what the gate does not check:

  • package.json has no private field, and npm pack --dry-run lists only the manifest, plugin/, ui/ and the README
  • dependencies come from the registry, with no file:, workspace: or git sources and no * or latest ranges
  • ui/ is rebuilt from ui-src/ and committed, and CI fails on a stale build
  • Every route declares safety and a description that states its constraint
  • A write route sends commands through req.mdk, raises a REJECTED result, and validates its input
  • permissions is the least access the routes use, scoped with resourceNames where the app targets one device family
  • A stack run answers both routes after signing in, and a clean project can install your release
  • The README states setup requirements, supported capabilities, configuration, permissions, and release information

Troubleshooting

Problems the gate, a live stack or an install reports have their own troubleshooting. Publishing has one of its own:

MessageFires whenFix
npm error code EPRIVATEnpm publish found "private": true in package.jsonDelete the field

Next steps

On this page