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.yamlat the package root- A route table in
plugin/mdk-plugin.json, and the controller file each route'shandlernames - A UI module that
mdk create appscaffolds inui-src/and builds intoui/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 10 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 final app lives in your own public or private repository.
Use this guide to walk through creating your 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 publishedmdk 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
-
npm 11 (< 12)
-
The
mdkCLI>=0.15 -
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 (optionally) an npm account with publish rights to your scope
-
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, and one that holds a file the scaffold writes unless you pass --force.
Run every later command from
~/mdk-app-fleet, your app's repository root, not an MDK project.
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 Name the package
Give the package the mdk-app- prefix, the naming convention, in package.json:
{
"name": "@your-org/mdk-app-fleet"
}Set name in plugin/mdk-plugin.json to the same package name, because the scaffold copied the old one there.
mdk add app installs the app under the name fleet, from GitHub or npm alike, because the CLI drops the npm scope and the
mdk-app- prefix. An app carries these names:
| Name | Where it lives | Rules | Who sets it |
|---|---|---|---|
| App id | id in mdk-app.yaml and in ui-src/index.tsx | Lowercase reverse-DNS such as io.your-org.fleet, treated as permanent | You |
| Package name | name in package.json | An npm name, @your-org/mdk-app-<name> | You |
| Instance name | spec.apps[].name in an operator's mdk.yaml | ^[a-z][a-z0-9-]*$ and unique in the stack. Defaults to the package name without its scope and mdk-app-. It also sets the route prefix /apps/<name> and the service account app:<name>. | The operator |
Do not add preinstall, install, or postinstall scripts. mdk add app installs with --ignore-scripts, so they never run, and --strict fails
on them.
Declare the Kernel access
2.0 Request permissions in mdk-app.yaml
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:
| Resource | Verbs | resourceNames scope |
|---|---|---|
devices | read, write | family/brand/worker/device, such as miner/antminer/antminer-a/AM-001 |
workers | list, read, delete | family/brand/worker |
commands | read | None |
actions | read, write, vote, delegate | None |
policy | read, write | None |
identities | read, write | None |
Each client call needs one permission:
| Client call | Needs |
|---|---|
listWorkers() | workers: list |
pullTelemetry(), pullState(), getCapabilities(), queryDevices(), pullSnapshot(), pullAggregate(), pullWorkerQuery(), getCommandStatus(), getCommandStatusBatch() | devices: read |
sendCommand(), sendCommandBatch() | devices: write |
To find devices by the labels their Workers declare, such as a container or rack, use queryDevices().
Request the least access the routes use. Add resourceNames when the app targets one family, for example ["miner/*"] for every miner or
["power-meter/*"] 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"] } }
}
}
}
}
}
}The following fields decide what the Gateway enforces and what operators and agents see:
safetyisread-onlyorwrite.mdk run mcpturns routes into agent tools and withholds every write route unless it starts with--allow-write.descriptionis what operators and agents read, so put the constraint in it and not only a labelparametersandrequestBodyare enforced by the Gateway before your controller runs, and a violation answers400pathis 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"]. In a request body, 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:
const mdkClient = require('../lib/client')
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 }
}A controller can reach the Kernel through either of these clients, and which one it uses decides whose access the Kernel checks:
| Client | Acts as | Use it for |
|---|---|---|
req.mdk | The signed-in user, and the app | Work 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 context | The 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 Edit and rebuild ui-src/
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:
npm run build:uiOr rebuild on each save. The watcher runs until you stop it with Ctrl+C:
npm run dev:uiThese rules keep the module loadable, and the gate checks all but the last:
- The module
idequalsidinmdk-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.js. It stubs plugin/lib/client.js through require.cache, because the app runtime provides that client.
The name has no .test part on purpose: the app's npm test runs node --test, which runs every file under test/, and
the name keeps a Vitest run from the MDK repository root from collecting the template's copy. Tests you add can use
.test.js.
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.tsThe type check covers only controllers that start with // @ts-check, as the scaffold's summary.js does. The
set-power-mode.js above has no such line, so it is skipped. To check it, add the line, import the type as summary.js
does with /** @typedef {import('../types').AppRequest} AppRequest */, and type req with a JSDoc @param {AppRequest} req;
req.body is then unknown, so read mode through a type guard.
Write a README
6.0 Replace the scaffold's 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
Add a smoke sample and 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-runExpected 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.cssThe 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
Commit the release, push it to the app's GitHub repository, and push a v0.1.0 tag on that commit.
Show me
git add -A && git commit -m "Release v0.1.0"
git remote add origin git@github.com:your-org/mdk-app-fleet.git
git push -u origin HEAD
git tag v0.1.0 && git push origin v0.1.0mdk 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
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:
{
"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" }
}npm publishpublishConfig.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 Ask for a listing
Publishing makes the app installable, and a listing is a request that maintainers review. Before you ask:
- 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.
- Check that the README covers setup requirements, supported capabilities, configuration, permissions, and release information.
- 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 --strictexits0on the commit you tag -
idis your own reverse-DNS id and equals the UI module'sid -
versionis the same inpackage.jsonandmdk-app.yaml -
permissionsnames 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
getorlistwrites 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.jsonhas no install scripts, andmdk-app.yamlhas no unknown keys
Then confirm what the gate does not check:
-
npm pack --dry-runlists onlypackage.json, the manifest,plugin/,ui/, and the README - Published to npm:
package.jsonhas noprivatefield -
dependenciescome from the registry, with nofile:,workspace:, or git sources, and no*orlatestranges -
ui/is rebuilt fromui-src/and committed, and CI fails on a stale build - Every route declares
safetyand adescriptionthat states its constraint - A write route sends commands through
req.mdk, raises aREJECTEDresult, and validates its input -
permissionsis the least access the routes use, scoped withresourceNameswhere 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:
| Message | Fires when | Fix |
|---|---|---|
npm error code EPRIVATE | npm publish found "private": true in package.json | Delete the field |
Next steps
- Test your app with MDK: run the listing gate, a live stack, and an install from a clean project
- Add more to your routes: caching, stream routes, per-route access, and the rest of the Gateway apps guide
- Expose your routes to the operator agent: turn routes into MCP tools with no separate manifest
- Build the Worker your app reads: connect your own hardware so the app has real devices
- Understand the security boundaries: who may call what, and why the Kernel checks the app and the user