MDK Logo

Gateway plugins

Use the default Gateway plugins, mount third-party plugins, and build your own using the mdk-plugin.json format

Overview

The Gateway exposes HTTP routes through a declarative plugin system. Each plugin is a directory containing an mdk-plugin.json manifest and one or more controller files. MDK ships a set of default plugins that load automatically; you can mount additional plugins for your own site logic.

Plugins call into the Kernel through services.mdkClient, an instance of @tetherto/mdk-client. No knowledge of the MDK Protocol envelope or internal message shapes is required.

Default plugins

MDK ships plugins that load automatically on Gateway startup:

  • The telemetry plugin serves site metrics (hashrate, consumption, efficiency, temperature, and more)
  • The site-hashrate plugin serves aggregated site hashrate history
  • The site-monitor plugin serves site configuration, feature flags, and live per-device hashrate

The auth plugin (@tetherto/mdk-plugin-auth) ships in the same package but is not among them, and mounting it via extraPluginDirs does not give you working identity endpoints: its controllers depend on a services.authLib and a populated req._info that the Gateway does not provide. Supply your own identity layer.

The plugin reference lists every route each of these plugins serves, with its method, generated from the plugin's mdk-plugin.json. Plugins you mount yourself are documented by their own manifests.

Mount a plugin

Pass an extraPluginDirs array to startGateway() to load additional plugins at boot alongside the default plugins:

const { startGateway } = require('@tetherto/mdk')

await startGateway({
  kernel,
  port: 3000,
  extraPluginDirs: [
    path.join(__dirname, 'plugins/custom-metrics'),
    path.join(__dirname, 'plugins/alerts')
  ]
})

Each entry must be an absolute path to a directory containing an mdk-plugin.json. The plugin loader validates the manifest and all handler files at startup — missing files or invalid manifests throw immediately before the server comes up.

Build a plugin

A plugin is a directory with two things: a manifest and controllers.

1.1 Create the manifest

mdk-plugin.json declares the plugin identity (name, version) and a routes array. Each route needs an id, a handler path, and an http block with a method and path. Rather than copy a synthetic example, start from a real manifest and trim it:

Path parameters use {param} syntax — the loader normalises them to Fastify's :param format. For named exports use "handler": "./controllers/foo.js#namedExport". The plugin reference explains what each field means and what the loader requires.

1.2 Write a controller

Every controller exports an async function (req, services):

// controllers/live.js — read live telemetry
module.exports = async function live (req, services) {
  const deviceId = req.query.deviceId
  const telemetry = await services.mdkClient.pullTelemetry(deviceId, 'metrics')
  return { deviceId, ...telemetry }
}
// controllers/command.js — dispatch a command
module.exports = async function command (req, services) {
  const deviceId = req.params.deviceId
  const { mode } = req.body

  const result = await services.mdkClient.sendCommand(deviceId, 'setPowerMode', { mode })

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

The req object

FieldTypeContains
req.paramsobjectPath parameters (e.g. { deviceId: 'wm-001' })
req.queryobjectQuery string parameters
req.bodyobjectParsed JSON request body
req.headersobjectHTTP headers
req._infoobjectInternal request metadata (rarely needed)

The services object

FieldTypeUse for
services.mdkClientMdkClientLive reads and command dispatch — sendCommand, pullTelemetry, getCapabilities, listWorkers
services.dataProxyDataProxyHistorical and aggregated data from Worker tail-logs — requestData, requestDataMap
services.confobjectGateway runtime config

Always guard services.mdkClient — it is null when the Gateway starts without a live Kernel connection:

if (!services.mdkClient) throw new Error('ERR_MDK_CLIENT_UNAVAILABLE')

Read hardware data

For live device data use mdkClient:

// Pull a live metrics snapshot
const tel = await services.mdkClient.pullTelemetry(deviceId, 'metrics')

// Pull the declared capabilities (from the Worker's mdk-contract.json)
const { capabilities } = await services.mdkClient.getCapabilities(deviceId)

// List all registered Workers
const { workers } = await services.mdkClient.listWorkers()

For historical or aggregated series from a Worker's persisted tail-log use dataProxy:

const results = await services.dataProxy.requestData('tailLogRangeAggr', {
  type: 'miner',
  startDate: start,
  endDate: end,
  fields: { hashrate_sum: 1 }
})

The default telemetry controllers show worked examples of both patterns.

Send a command

sendCommand dispatches via the Kernel to the Worker that owns the device. The command must be declared in the Worker's mdk-contract.json. It returns:

FieldTypeDescription
commandIdstringCorrelation ID generated by Kernel. Echo this to the HTTP caller so they can track the operation.
statusstring'SUCCESS' or 'FAILED'
resultobjectCommand-specific response payload (present when status is 'SUCCESS')
errorstringError message (present when status is 'FAILED')
const result = await services.mdkClient.sendCommand(deviceId, 'reboot', {})
if (result.status === 'FAILED') throw new Error(result.error)
return { commandId: result.commandId, status: result.status }

Caching

Add a "cache" array of dot-path strings to a route to enable request-level caching. The cache key is composed from the route ID and the resolved values of each path:

{
  "id": "telemetry.hashrate",
  "cache": ["query.start", "query.end", "query.groupBy"],
  ...
}

Pass ?overwriteCache=true to bypass and refresh.

Auth and permissions

The Gateway applies no authentication of its own. Every route a plugin declares is served to any caller, so a route that needs protecting carries that logic in its own controller. Identity is yours to supply: the manifest "auth" and "permissions" fields have no reader and change nothing.

Validate the token with your own identity layer and check it in the handler:

const { validateToken } = require('../lib/my-identity-layer')

module.exports = async function protectedRoute (req, services) {
  const token = req.headers.authorization?.replace('Bearer ', '')
  if (!token) throw new Error('ERR_UNAUTHORIZED')

  const { permissions } = validateToken(token)
  if (!permissions.includes('miner:w')) throw new Error('ERR_FORBIDDEN')

  // Your route logic
}

A controller cannot choose its status code. It receives (req, services) and never the Fastify reply, so a returned value goes out as 200 and a thrown ERR_-prefixed error becomes 400 Bad Request carrying that message. ERR_UNAUTHORIZED reaches the client as 400, not 401. A route that needs true status control belongs in raw Fastify routes instead.

Manifest validation errors

The plugin loader validates every manifest and handler at startup and throws if anything is wrong:

ErrorCause
ERR_PLUGIN_MANIFEST_MISSINGNo mdk-plugin.json found in the plugin directory
ERR_PLUGIN_MANIFEST_INVALIDJSON parse error, or missing required field (name, version, or routes)
ERR_PLUGIN_ROUTE_DUPLICATE_IDTwo routes in the same manifest share the same id
ERR_PLUGIN_HANDLER_NOT_FOUNDThe handler file path does not exist or failed to load
ERR_PLUGIN_HANDLER_NOT_FUNCTIONThe handler file exports something other than a function

Next steps

On this page