A device module is an npm package that countinghouse loads and exposes as one
or more MCP tools. This document is the full reference; README.md
has the short version.
my-module/
├── package.json # name and version
├── api.json # device/service/action metadata -- the single declaration
├── schema.json # JSON Schema 2020-12 input/output/fault per action
└── handlers/
└── <serviceShortName>/
└── <actionName>.js # one handler per action
That is the whole module, and the only format: the framework assembles the
device from api.json, reads schema.json itself, and matches handlers by
name. A module has no main entry. One with a main entry (package.json
"main", or an index.js) and no handlers/ directory is refused before any
of its code runs, with MODULE_LAYOUT_UNSUPPORTED; one that has both loads
from handlers/, and its main entry is never run. See
design-decisions.md
for why the old boilerplate went away.
A handler is a function of (input, ctx):
// handlers/greetService/hello.js
module.exports = async (input, ctx) => ({
output: {text: `hello ${input.name}`}
});
input is the validated input object. ctx carries the caller, this device’s
identity, and the helpers a handler needs — see ctx below.
Code that several handlers share goes in an ordinary file of the module that
the handlers require (require('../../lib/shared.js')); it runs when a handler
file is first required, never as a main entry.
The directories under handlers/ are service short names — the part after
:serviceID: in the URN. api.json remains the only place the full URN
appears.
Mismatches are startup errors, not silent omissions. An action declared in
api.json with no handler, a handler api.json does not declare, a service
short name that does not resolve, or one that two URNs both claim: each fails
the module at load with a message naming the module, the stage, the offending
name and the fix. A module never half-loads.
ctx| field | what it is |
|---|---|
ctx.caller |
{id, isAdmin} — the caller: id is an opaque id (u_ and 22 characters), the same for that user everywhere on this server, never a key or a user name. For a hop’s callee, the identity the hop authorized as (the calling module’s binding) |
ctx.device |
{deviceID, friendlyName} — this device |
ctx.serviceID, ctx.actionName |
the action being served |
ctx.log(entry) |
device log, already bound to this device |
ctx.serviceClient(opts, cb) |
call another module by deviceID, as ctx.call authorizes (no as) — see below |
ctx.call(address, input, opts) |
call another module by name — see below |
ctx.job |
{id, progress(n), info(cb)}. Inside a task: the job’s id; progress(n) (0–100) updates the job; info reads it. Outside a task: id is null; progress(n) (0–100) is the call’s own progress, sent to a client that asked for it (at most one every 250 ms, the latest winning, none after the answer; a composite’s parts’ reports are dropped); info calls back with an error. Ask ctx.job.id == null, not ctx.job == null, to tell a call that is not a task |
ctx.redis |
your module’s own key-value space, in node_redis v3’s callback style: Redis db 5 under --store redis, a local store with the same commands and answers under --store local. Every key you name is your module’s alone: the runtime stores it as m:<module name, URI-encoded>:<key>, by the name it loaded your module under, so another module’s get('x') never sees your x, and you never see the runtime’s own keys. You write and read the key as you named it. The commands are del, get, hdel, hget, hgetall, hmget, hmset (fields as pairs or one {field: value} object), hset, llen, lpush, lrange, ltrim, mget, pexpire, rpush, set, zadd, zrange and zrem; there is no multi/exec |
ctx.recordUsage(tool, cost, cb) |
app-layer bookkeeping; never touches balance; answers {id, tool, cost, ts} |
ctx.usage() |
a promise of the current tools/call’s counts so far, read-only: {calls, linesIn, bytesIn, tokensInEst, servers: {name: calls}, sentence}, plus standIn: [names] when an acceptance stand-in answered (--remoteOriginMap). They are the call’s remote server calls, its parts’ included, and the lines and bytes of text those calls returned; tokensInEst is bytes/4, an estimate; sentence is the first half of the runtime’s receipt sentence, word for word (read 48,210 lines (3.1 MB) in 14 calls to github, or no server was called). The call’s own output is measured when it returns, so it is not counted here. null when the call is not a counted one (not a tools/call, or one that has already answered). In a worker the query carries the call’s token and is refused CALL_TOKEN_INVALID without it (a direct peer channel’s call has none, and a call’s token ends when it answers). Never a key, an id or a caller. A scenario writes its receipt sentence from it |
ctx.ask(name, values) |
a promise of the user’s answer to one of this action’s declared questions: the form’s content, or null when the user declined — see Asking the user |
ctx.httpHeaders |
request headers, when the call arrived over HTTP, minus X-CH-Key, X-App-Key and Authorization |
A module is never handed an API key or a user name (R2-1): not in ctx,
not in its hops, its job info or its environment. Its hops are authorized as
the identity the operator binds to it (runsModules) and billed to the
caller, by a per-call token the runtime keeps out of the module’s reach. The
global CHUtil a module sees has no dm or ci; CHUtil.createServiceClient
takes no appKey in a worker.
ctx replaces the device instance that used to be bound as this. That is a
narrowing on purpose: handlers used to be able to reach setAction,
deviceControl and the rest of the framework’s own surface. They no longer
can.
ctx.askA handler may ask its user one of the questions its action declares:
module.exports = async (input, ctx) => {
const answer = await ctx.ask('overwrite', {id: input.id});
if (answer == null || answer.replace !== true) return {output: {saved: false}};
// ... save it
};
The question is declared in api.json, never written by the handler:
"questions": {"overwrite": {"message": "Replace the saved note {id}?", "schema": "/notesService/saveNote/questions/overwrite"}}
values fills the message’s {name} placeholders with strings (cut to 200
characters), numbers and booleans. The user reads
<module name>: <the message>, and answers a form made from the
schema (see api.json for what a form may hold). The name is
the module whose tool the user called: your own, or, when your action is a
part reached through a scenario’s ctx.call, the scenario’s. A part is
never named to the client; the runtime’s log and usage record name it.
The handler runs again. MCP is stateless here, so the first time
ctx.ask has no answer it rejects with ASK_PENDING, which ends your
handler; the client shows the form, and when the user answers the call is
made again and your handler runs from the top, where ctx.ask returns
the answer at once. So:
countinghouse-validate cannot see either: whether a handler acts
before it asks is in its code. The usage record of a pass that asked
shows its round, so an operator can see a module that asks late.ASK_PENDING pass. Do not catch it. If you do and return a
result, that result is the call’s answer and the question is dropped.
This holds through composition too: a part’s question rejects the
calling handler’s ctx.call with ASK_PENDING, and the caller should
let it pass; on the retry both run again and the part’s ctx.ask gets
its answer.ctx.ask('overwrite', {id: 'a'})
and ctx.ask('overwrite', {id: 'b'}) are two questions, and each needs
its own answer.ASK_UNAVAILABLE means there is no one to ask, and you may catch it
to fall back: the client offered no form, the call came by HTTP
invoke-action or as a task, the operator turned questions off
(--moduleQuestions off), the outer call (when your action is a part)
has no one to ask for any of these reasons, three rounds brought no valid
answer, or the call has had eight rounds in all already (every
question’s together). A part reached in single-thread mode
(--no-workerThread) has no one to ask either.values makes a new question each time, and the answer the user gave
is for the old one.ASK_NOT_DECLARED is your own mistake: no such question on this
action, or a value that is missing or is not a string, a number or a
boolean.The answer is the form’s content and nothing else: no client name, no session, no user.
Return ctx.error(code, message?, details?):
module.exports = async (input, ctx) => {
if (typeof input.text !== 'string') return ctx.error('INPUT_REJECTED', 'text must be a string');
return {output: {text: input.text.toUpperCase()}};
};
The code is your module’s own: an UPPER_SNAKE_CASE name for what went
wrong (INPUT_REJECTED for input your schema can’t rule out,
REPO_TOO_LARGE, …). The runtime’s codes (its error catalogue) are the
runtime’s, and a module never raises them. The caller gets your code and
the message CODE: message, in worker and single-thread mode alike. So
does a module that calls yours with ctx.call: it gets your error whole
(code, message and details, as a copy: never your cause or your object),
in either mode.
When you call another module, its rejection’s origin says whose error it
is: 'runtime' for the runtime’s (MODULE_RELOADING, PEER_GONE, a
CTX_CALL_… refusal), 'module' for the callee’s own. A callee is free to
name its code anything, a catalogue name included, so check
err.origin === 'runtime' before acting on a runtime code (retrying on
MODULE_RELOADING, say), not the code alone.
Under --moduleSandbox enforce, origin can be trusted: only an error
the runtime itself issued is 'runtime'. However a
module builds its error (setting origin on it, or constructing one
through its constructor), it answers as the module’s own,
origin: 'module', with no runtime meaning for a code that spells a
catalogue name. A runtime error you were given (a callee’s
MODULE_RELOADING, a CTX_CALL_… refusal, a ctx.serviceClient
refusal) and pass on stays the runtime’s, with the code it was issued
with and the message it reached you with (in worker mode a runtime
error’s message is the catalogue’s text, without the detail single-thread
mode keeps): changing them on it changes nothing, so to answer with your
own code, return ctx.error(...) (with the runtime’s error as its
cause if you want to keep it). Any sandbox mode freezes the error class
in the module’s worker and keeps the runtime’s way of issuing errors out
of the module’s reach; only enforce also blocks a module from requiring
countinghouse’s own files. audit, the worker default, records such a
require but allows it, and single-thread mode and --moduleSandbox off
have no sandbox (security model): there a module can
forge this as it can do anything else.
Returning the error is the preferred form. Throwing it
(throw ctx.error(…)), from an async function or a plain one, or passing it
to a callback gives the same answer. A helper that has no ctx can throw a
plain Error that carries your code instead:
Object.assign(new Error('path must be a string'), {code: 'INPUT_REJECTED'}).
Its code counts as yours when it looks like one (/^[A-Z][A-Z0-9_]{2,}$/)
and is not a system error’s (one with errno or syscall, such as
ENOENT) or someone else’s: Node’s own (ERR_…, MODULE_NOT_FOUND,
ABORT_ERR, and the HTTP parser’s HPE_…), any errno name even without
errno (ECONNRESET, ETIMEDOUT, …, as a network failure carries),
undici’s (UND_ERR_…, from fetch), and the certificate-verification codes
Node gives a TLS error (CERT_HAS_EXPIRED, INVALID_CA,
UNABLE_TO_VERIFY_LEAF_SIGNATURE, …: an exact list of 28, in
lib/countinghouse-error.js, so your own UNABLE_TO_PARSE is still yours).
Those are crashes,
answered as DEVICE_INVOKE_EXCEPTION with the original in the fault, so an
operator can tell a failure you didn’t handle from one you meant. To raise
such a code on purpose, use ctx.error. Only an Error counts: a thrown
plain object (even one with a code), null, or a rejection with nothing
is a crash too, and a callback handler’s callback({code: …}) is an
untyped failure (DEVICE_INVOKE_FAIL).
Catch your dependencies’ errors and wrap them with ctx.error. A
dependency’s own coded Error that you let escape (SQLITE_BUSY,
ER_DUP_ENTRY) looks like a module code, so it is answered as yours, with
its code; countinghouse-validate can’t warn about it, since it sees your
source, not the codes your dependencies throw.
To wrap an underlying error, pass it as details.cause:
ctx.error('INNER_CALL_FAILED', ${label}: ${e.message}, {cause: e}). The
cause stays on the error and is never sent to the caller. A runtime error you
rethrow unchanged (from ctx.call, say) keeps its own code.
Anything else you throw becomes DEVICE_INVOKE_EXCEPTION (the runtime reads a
bare throw as “this handler crashed”), and an untyped callback(err)
becomes DEVICE_INVOKE_FAIL. See
design-decisions.md.
The pre-8.0 error globals are gone
(upgrading-to-8.md).
Before 8.0, a module could also be a main entry: a device.js exporting a
handler map, or an index.js exporting a class or EventEmitter that decided
at runtime how many devices to expose (discover, deviceonline,
deviceoffline). Both are retired. Such a module is refused at load, by
countinghouse-validate (stage layout) and by the runtime, with
MODULE_LAYOUT_UNSUPPORTED, which names the file that made it a main entry.
For a device.js handler map, move each entry into its own
handlers/<service>/<action>.js (module.exports = <the entry's function>);
for a 5.x module (a CHDevice with setAction),
npx countinghouse-migrate-module ./my-module converts it to handlers/. A module is one device, described by its api.json; a module
that needs several devices is several modules.
api.jsonDeclares one friendlyName and one or more services (each keyed by a
urn:...:serviceID:...). Each service has an actionList array, and each
action carries its own name, a human-readable description (required;
it is what an LLM sees as the MCP tool’s description, and an action without
one is skipped), and up to three schema pointers into schema.json:
"serviceList": {
"urn:example-com:serviceID:echoService": {
"actionList": [
{
"name": "echo",
"description": "Echoes the input object back, unmodified.",
"input": {"schema": "/echoService/echo/input"},
"output": {"schema": "/echoService/echo/output"},
"fault": {"schema": "/fault/echoService/echo/fault"}
}
]
}
}
input, output and fault are each optional; an action that declares no
input takes none, and one that declares no output is not validated on the
way back. Action names must be unique within a service.
The spec is validated against the framework’s own JSON Schema 2020-12
meta-schema at load time. Required fields it is easy to forget:
device.modelDescription, and each action’s name. Anything the meta-schema
does not know at the top level, in serviceList or in an action is
rejected, not ignored — so a stale field left over from an older format
shows up as a load error rather than silently doing nothing. Directly under
device, unknown fields are accepted; the retired CDIF-era rateLimit and
price are among them, and countinghouse-validate warns about each.
An action may also carry title, annotations, icons, longRunning,
questions and resource, and the device a promptList: what the MCP
layer serves to a client beyond a tool’s name, description and schemas. Each
is served as its part of that layer is released, and one that is not served
yet changes nothing a client sees. All of them are checked already, by the
meta-schema and at load (stage declarations), so a module written against
them is right when they are served:
resource’s uriTemplate is a relative path of literals and {name}
variables, at most 8 and at most one to a segment (notes/{id},
files/{name}.json); each variable is a string property of the action’s
input, and every required input is a variable. No two resources of a
module may match the same URI: notes/{id} and notes/all do;countinghouse-validate;$ref (a variable’s property, a
prompt’s argument); a question’s form may not, it is flat;title,
description, default; a string’s minLength, maxLength and
format; a number’s minimum and maximum; an enum’s enum and
enumNames), within bounds (a title of 128 characters, a description of
500, 64 enum values of 256), and no text in it, the question’s message
included, carries a control or bidi character. A form never asks for a
password, a token, a key or a card number (countinghouse-validate warns
about a property that reads like one);completion takes {argument, value, context} and
gives {values: string[]};A tool’s title, annotations and icons are served on tools/list
(each only when the action declares it). The hints in annotations
(readOnlyHint, destructiveHint, idempotentHint, openWorldHint) are
your claims: the runtime enforces none of them, and a client or an install
review may show them. Icons are read and checked when the module loads: a
missing, oversized or SVG icon refuses the load (stage icons), and a reload
to such a version leaves the loaded one serving. Each is sent inline as a
data: URI from what the load read; nothing is read at list time.
An action that declares a resource is served on resources/list (a
uriTemplate with no variable) or resources/templates/list (one with
variables), as countinghouse://m/<module>/<path>, where <module> is your
module’s name as tool names spell it. It is not also a tool: declare a
second action over the same function if you want both. resources/read
runs your action exactly as a tools/call does, with the URI’s variables as
its input (validated against your input schema, rate limited, billed as
that action): a string output is the resource’s text (your output schema’s
contentMediaType, else the declared mimeType, else text/plain), a
binary string output its blob, anything else its JSON. A variable is
percent-decoded as UTF-8; a value with a control character, a / or a
\, or that is exactly . or .., never reaches you, but anything else
is yours to guard, as any input is. Two things to keep it that way:
%252E%252E arrives as %2E%2E, and a second decode makes it ....., two U+FF0E fullwidth full stops, is not ..), and NFKC turns
them back into .. and /.If two of the modules a runtime lists have names that spell the same
<module> (twin-a and twin_a), neither one’s resources are served, and
the operator is warned; rename one.
An action that declares longRunning: true runs as a task for a 2026-07-28
client that declares the io.modelcontextprotocol/tasks extension (with
--workerThread): the call is answered at once with a taskId, and the
client polls tasks/get for the result your action returns. Anyone else’s
call to it runs inline, as any action’s does. Your handler is the same
either way.
A device’s promptList is served on prompts/list and prompts/get: each
prompt is listed as <module>_<name> (a scenario’s under its bare name), to
the keys that may reach the module, with its title, description and
icons and the arguments its schema declares (name, description, whether
required). prompts/get runs none of your code: it checks the arguments
against that schema, replaces each `` once with the argument’s value
(an absent optional one is the empty string; substituted text is never
scanned again) and returns your messages, at most 64 KiB in all.
Specs written for 4.x (argumentList + serviceStateTable) do not load. The
error says so and names the converter:
npx countinghouse-migrate-spec ./my-module. See
MIGRATION.md.
schema.jsonSupplies the JSON Schema 2020-12 documents the action’s input/output/fault
pointers resolve to. This is what becomes each MCP tool’s
inputSchema/outputSchema.
Every call’s input and output is validated in one of the server’s validator workers, which all modules share:
--validationCompileMs (10 s by default), or the load is refused
(MODULE_ASSEMBLY_FAIL, stage schemaCompile);--validationTimeoutMs, 1000 ms by default),
past which the call is refused VALIDATION_TIMEOUT;VALIDATION_QUARANTINED, until it is loaded again;--maxOutputBytes (16 MiB by default) is refused
OUTPUT_TOO_LARGE, and so is a ctx.call input over it, INPUT_TOO_LARGE,
on the main-thread-routed path. A hop’s input is sent as bytes: a value
structured clone cannot carry, or a SharedArrayBuffer, fails the
ctx.call in your own worker.
Any other message your worker sends the runtime (a log line, a
ctx.redis command) over the output cap plus 64 KiB is refused
MESSAGE_TOO_LARGE before it leaves the worker. A file write is split
for you, so it has no such limit.OUTPUT_NOT_JSON in your worker, naming the field (a bare
ArrayBuffer is only caught by a typed field’s check, and is sent as {}
otherwise). Binary data goes in a field declared
{"type": "string", "contentEncoding": "base64", "contentMediaType": "image/png"}
(your type in place of image/png), as buf.toString('base64'). Such a
field is checked for canonical base64 (the standard alphabet, padded, no
whitespace), in an input as in an output. Declare an output’s binary
field inline, under properties or an array’s items, at most 8 levels
down and 16 to an action, with a media type of the form type/subtype.
One anywhere else (under oneOf or the like) is refused at load, at stage
declarations (below), and so is a $ref under an output that leads to
one, also to one declared inline elsewhere: schema.json is dereferenced
before the fields are mapped, so the $ref would be a second field. An MCP client gets an
image/* or audio/* value as a block of its own
({type: "image" | "audio", data, mimeType}), after the text block, in
schema order; in structuredContent and the text the value is a
reference, {mimeType, bytes, block} (bytes its decoded size, block
its index in content), and tools/list advertises that shape for the
field. A result can carry at most 16 such values (an array counts each
item), else TOO_MANY_BINARY_VALUES. Another media type is still sent as
its base64 string for now. ctx.call and HTTP invoke-action always get
the base64 string itself.console) reaches the
operator’s log line by line, prefixed with your module’s name: each line
cut at 8 KiB, control characters other than tab removed (and the line
separators and bidi controls), and under audit and enforce at most
256 KiB a minute per stream of what is written, each line counted with
its prefix and newline; past that it is dropped and counted. The streams
are the runtime’s: assigning process.stdout throws (TypeError) in
strict mode. Use the log for diagnostics, not for data.Keep patterns simple, schemas small, and outputs modest: return a reference
(a path in your data namespace) to anything large. A schema.json that is plainly unsafe is refused at load
(MODULE_ASSEMBLY_FAIL, stage schemaSafety, naming the schema path):
schema.json larger than 1 MB (checked before it is parsed);pattern, a patternProperties key, a
propertyNames pattern) longer than 1000 characters, or one that can
backtrack catastrophically: a repetition inside a repeated group, such as
^(a+)+$ or (\d+)*, or a repeated group whose alternatives start alike,
such as ^(ab|ac)+$. Write ^a+$, ^\d+(?:,\d+)?$ with a bounded group,
or ^(a[bc])+$, instead;$refs are
expanded, or actions whose schemas come to that many together;$ref that refers to itself, or one that names no place in
schema.json (only #/... JSON pointers are followed);countinghouse-validate runs this same check, in the load’s own order and
words (stage schemaSafety, code MODULE_ASSEMBLY_FAIL), so you meet it
before an operator’s load does. Its problems at the stages declarations
and readRootSchema carry that code too: each is one the load refuses the
module for.
What your module declares is checked at load as well, where the meta-schema
cannot say it (MODULE_ASSEMBLY_FAIL, stage declarations, naming the
action):
properties or items (above);x-mcp-header anywhere in an input schema. MCP 2026-07-28 lets a property
mirror itself into an HTTP header; this runtime does not serve that yet, so
a schema may not carry the keyword;api.json takes for MCP clients.The load stops at the first such problem. countinghouse-validate prints
them all.
At startup:
node ./framework.js --workerThread --loadModule ./path/to/my-module
Into a running server (requires an admin apiKey — see
authentication.md):
curl -X POST http://127.0.0.1:9527/load-module \
-H 'Content-Type: application/json' -H 'X-CH-Key: <your-admin-key>' \
-d '{"path":"./path/to/my-module","name":"my-module","version":"1.0.0"}'
You do not need --debug for either. --debug disables authentication
for the whole server; it is not how you get access to an endpoint.
Under --workerThread your module runs in a worker of its own
(lib/lean-worker.js). The main thread reads your api.json and
schema.json itself, before the worker starts; the worker only requires
your handler files, each once, and answers the calls the main thread sends
it. Your device is what the main thread read from api.json. Nothing your
code does in the worker can change it, add a device or rename one.
The worker loads as little of the runtime as it can. CHUtil is a facade:
each helper (CHUtil.request, createServiceClient, deviceLog, and the
rest) loads its implementation the first time it is called, so a module
that uses none never pays for them. ctx works the same way: ctx.call,
ctx.log and ctx.redis load what they need on first use. CHUtil has no
dm or ci. Those were the runtime’s own objects, never part of the
module API.
Since 8.0.0 a module in worker mode (the default) sees its own file
namespace, the same in every --moduleSandbox mode:
| Path your code uses | What it is | Access |
|---|---|---|
/app |
your module’s install directory | read-only under enforce; writes are logged under audit |
/data |
your module’s private data directory | read-write, counted against your disk limits, kept across restarts |
/tmp |
your module’s private temp directory | read-write, counted against your disk limits, emptied every time your worker starts |
each path you declared in fs |
the same path on the host | r or rw, as the operator approved |
__dirname and __filename are under /app (/app/handlers/...),
process.cwd() is /app, and os.tmpdir() is /tmp. Paths in results and
errors are virtual too. Use require and relative paths as usual; build file
paths from __dirname (or import.meta.dirname) rather than from a host path
you know. Paths inside a module use / on every OS. On Linux and macOS a \
is part of a file name; on Windows it is a separator, the same as /.
Write under /data or /tmp. Writing next to your code under /app is
refused under enforce (EROFS). /data is for what must survive a
restart; /tmp starts empty each time. On the host they are
<moduleDataPath>/<your package name>/data and .../tmp; the operator sets
--moduleDataPath (default $HOME/.countinghouse/module_data). Unloading,
restarting and reloading never delete them; an operator’s
POST /uninstall-module does, unless told to keep them.
Anything else, declare. A path outside your namespace is answered
ENOENT under enforce (and logged on the host); under audit and off it
reaches the host and is logged. Declare each outside path in fs (see
Declaring permissions) and the operator approves
it.
Disk limits. /data and /tmp together count against diskMb (default
ceiling 1024) and diskEntries (files and directories, default ceiling
100 000). Over either, a write fails with ENOSPC under enforce; under
audit crossing a threshold is logged. Declared paths are not counted.
Start-up time grows with the number of entries in /data and /tmp: your
worker’s start walks them, about 70-145 µs per entry on the maintainer’s VM
(715 ms for 10 000 entries at dab69d0, 1.1-1.5 s at cd411ee on a slower
disk; so 7-15 s near the 100 000 default). The walk is asynchronous and does
not block the server.
Links. In every mode a hard link works only within one writable root, and
a symbolic link only with a relative target that stays inside its root
(absolute targets are EPERM). chmod drops setuid, setgid and sticky bits.
A rename across roots (/tmp to /data, say) answers EXDEV, so copy
fallbacks such as fs-extra’s move work.
What works differently.
fs call is a message to the main thread, synchronous calls
included. Fewer, larger operations cost less: readFile, writeFile and
appendFile are one call each. On a 2-CPU machine, 250 rounds of a 4 KB
write, read, stat and unlink took about 1.2 s under off and 1.9 s under
enforce, against about 30 ms with no broker (measured at 9246db1; see
the benchmarks).fs.open are numbers from 0x10000000
up, not small integers. fs.writeSync(1, ...) and fs.writeSync(2, ...)
still go to your module’s console (pino and sonic-boom work).fs.watch, fs.watchFile and fs.promises.watch are not available
(ERR_FEATURE_UNAVAILABLE_ON_PLATFORM).respondWithFile is not available: read the file with fs and
stream it.process.env holds only the variables you declared (see
below), so code that read undeclared variables sees them missing.Single-thread mode (--no-workerThread) is for debugging modules and
has no sandbox. Modules still see /app, /data and /tmp through fs,
fs/promises, os and CHUtil.loadFile, but only as a translation, with no
checks, quota or link rules. The differences from worker mode:
process.cwd() is the server’s real working directory.module.filename, require.cache keys and require.resolve
results are host paths, and so is import.meta.dirname in ES modules.fs, fs/promises, os and
CHUtil.loadFile are not translated.createRequire with a virtual (/app) path fails with MODULE_NOT_FOUND;
use require, or createRequire(import.meta.url) in ES modules.NODE_PATH.Upgrading a module or a deployment from 7.x: see
upgrading-to-8.md.
Under --workerThread, each module runs inside the module sandbox
(security-model.md says what that does and does not
guarantee). A module that stays inside its own directory needs to declare
nothing. One that needs more declares it in package.json, beside
countinghouse.calls:
"countinghouse": {
"calls": ["…"],
"permissions": {
"fs": [ { "path": "/var/log/app", "access": "r" } ],
"net": [ { "host": "api.example.com", "ports": [443] } ],
"env": [ "WEATHER_API_KEY" ],
"limits": { "heapMb": 128, "externalMb": 128, "maxBlockMs": 5000, "diskMb": 200 }
}
}
| Field | Rules |
|---|---|
fs |
Paths outside the module only. Absolute, normalized, no ... access is r or rw. /, /app, /data, /tmp and anything under them are reserved and cannot be declared. |
net |
host is a hostname or a *.-prefixed wildcard (one leading label only); ports is optional, integers 1-65535. |
env |
Environment variable names ([A-Z_][A-Z0-9_]*). |
limits |
What the module asks for; all optional: heapMb (JS heap), externalMb (Buffers and typed arrays), maxBlockMs (how long the event loop may be blocked), diskMb and diskEntries (/data and /tmp together). The operator’s ceiling applies; the default ceilings are 256, 256, 10000, 1024 and 100000. |
A declaration is a request. The operator’s --modulePolicy file can grant it
as declared or narrow it, never widen it. Under --moduleSandbox enforce a
module that declares fs, net or env gets none of them until the
operator adds an entry for it: no access outside its own directory, and no
environment variables at all. Under audit the declaration is granted.
fs, env and limits take effect now. net is validated and logged, and
takes effect when the network brokers ship, so declare it now and expect to
need it. Targets of CHUtil.request are already checked
against the effective net entries: under audit a disallowed target is
logged and the request still goes ahead; only enforce refuses it. Under
enforce, CHUtil.request also accepts only the ordinary request options (method,
headers, body, json, qs, timeout, … but not baseUrl, proxy,
agent, har and similar) and checks every redirect.
Self-contained. Every dependency of your module, followed through the
whole tree, must be installed inside the module’s own directory. Install
with npm install --prefix <module> (or run npm install inside it), and
ship that node_modules. A dependency that resolves outside the module is
a problem countinghouse-validate reports and enforce refuses to load.
Under enforce the module’s worker can require built-ins and files under
its own directory, nothing else (not countinghouse’s lib/, not global
folders, not other modules); under audit such a require works and is
logged.
No native addons. A .node file, a binding.gyp, or "gypfile": true
anywhere in the tree is refused under enforce, and loading native code at
run time throws under enforce (under audit it works and is logged). Use a pure-JavaScript replacement: bcryptjs is the usual
one for bcrypt. Dependencies with preinstall, install or postinstall
scripts are reported as warnings by countinghouse-validate.
Environment variables. The worker’s process.env holds only the names
you declared in env and the operator approved. The value comes from the
operator’s policy entry if it sets one, otherwise from the server’s own
environment; a name with neither is absent. Read them with
process.env.NAME as usual.
Blocked built-ins. child_process, cluster, worker_threads,
inspector (and inspector/promises), wasi, v8, repl,
trace_events, node:sqlite, node:test and node:sea, and any built-in newer than Node 24.21 (Node 26’s node:ffi among them), are
unavailable:
require of them fails with MODULE_NOT_FOUND under enforce (under
audit it works and is logged). module is reduced to builtinModules,
isBuiltin and a createRequire limited to your directory.
OpenSSL engines (crypto.setEngine, privateKeyEngine, clientCertEngine)
count as native code. process.dlopen, process.binding, process.kill, process.abort,
process.chdir and the process.set*id family throw under enforce; under
audit they work and are logged, so process.kill can still signal the
server. process.exit works in both and ends only your module. net,
http and similar still work in this release, and the first use of each is
logged; fs goes through the file broker (Files and paths).
Limits, restart and suspend. A module that exceeds its heap limit, its
external memory limit, or blocks its event loop longer than maxBlockMs is
terminated, as is one whose worker exits or errors (an uncaught exception
is caught and logged, and does not end the worker). Then:
MODULE_RESTARTING and the reason.MODULE_RESTARTING with the time of the next attempt. Your
tools stay in tools/list; callers should retry after the time given.POST /reload-module, POST /restart-module), calls in flight fail at
once with MODULE_RELOADING, and calls that arrive before its devices
are back get it too; a queued or scheduled job waits for the new worker
(up to 30 s) and runs on it. When it is unloaded, or its new code fails to
load, calls in flight and after get MODULE_UNLOADED, and jobs for it
fail without retrying. Operator actions on your module take effect in
order, the latest winning: a reload superseded by a later load, reload
or unload before its worker is up ends that worker, and the operator who
asked for it gets MODULE_LOAD_SUPERSEDED; an unload arriving then
leaves the module unloaded, and the jobs waiting for it fail
MODULE_UNLOADED at once.MODULE_SUSPENDED with the last reason, until an operator runs
POST /restart-module. A restart that the sandbox refuses (because the
module’s package.json or the policy changed, under enforce) suspends
it at once.Your module also sends at most --moduleMessageRate messages per second
(default 2000) to the main thread, and Redis commands count; beyond that
calls fail with RATE_LIMITED. Cache what you can.
Check a module with countinghouse-validate before loading it: it reports
permission syntax, dependencies outside the module, native code and install
scripts.
ctx.call — by name (the default)const data = await ctx.call('repo-scan/scanService.scan', input);
const {data, platformMetering} = await ctx.call('repo-scan/scanService.scan', input, {detail: true});
The address form is <module>/<service>.<action>:
<module> — the target’s friendlyName (its api.json’s
device.friendlyName), not package.json’s name.<service> — the service label: the raw last segment of the service’s
URN (urn:...:serviceID:scanService → scanService), not a made-up short
name.<action> — the action’s name, exactly as declared in api.json.Exactly one / and one . are allowed, and none of the three parts may
themselves contain either character — repo-scan/scanService.scan is valid,
repo.scan/scanService.scan is not. This is deliberately not the MCP tool
name (repo_scan_scanservice_scan): tool names are deduped with a _2 suffix
on collision, in an order that depends on module load order, so a hardcoded
tool name cannot survive another module being loaded first.
Declare what you call, in your own package.json — not api.json, whose
format did not change:
{
"countinghouse": {
"calls": [
"repo-scan/scanService.scan",
"secret-detect/detectService.detect"
]
}
}
Bind the identity your hops run as, in the auth config — not in the module. Your module’s inner calls are made with an internal key that the operator sets up. Each entry in the auth config is one key: the entry’s name is the key itself.
A complete config for the repo-review composite (examples/repo-review) has
two entries, one for the person calling and one for the module’s inner calls:
{
"<the caller's key>": {
"userName": "demo",
"devices": ["<deviceID of repo-review>"]
},
"<an internal key that is not its user name>": {
"userName": "repo-review-internal",
"devices": ["<deviceID of repo-scan>", "<deviceID of secret-detect>"],
"runsModules": ["repo-review"]
}
}
The key idea: the internal entry’s two fields answer two different questions.
devices is what the key may call. It lists the tools this key is
allowed to reach: here, repo-scan and secret-detect.runsModules is who uses the key. It lists the modules whose inner
calls are made with this key: here, repo-review. This is the only link
from a module to its key; without it, ctx.call refuses with
CTX_CALL_UNBOUND.Read it as: demo may call repo-review; repo-review makes its inner calls
with the internal key; that key may call repo-scan and secret-detect. When
demo calls repo-review:
demo’s devices. demo
needs no access to repo-scan or secret-detect.ctx.call('repo-scan/scanService.scan', …).
The runtime finds the entry whose runsModules lists repo-review and
checks the call against that entry’s devices. It passes.demo, not to the internal key (see below).Each inner call needs both halves: the address in your package.json’s
countinghouse.calls (the author’s declaration) and the target in the bound
key’s devices (the operator’s grant). Either one missing fails the module
when it loads, with a message naming the address and the file to fix.
When the modules you call make calls of their own, each of them gets its
own internal entry the same way, with its own runsModules and only the
devices it calls. A module that calls nothing needs no entry. One entry may
list several modules in runsModules, but a module may be listed by only one
entry (a second claim is refused as a conflict). Separate entries keep each
module limited to the calls the operator granted it, so a module update that
declares a new call gets nothing until the operator grants it. Don’t grant a
set of modules that lets them call each other in a loop: no hop-depth limit
ends one, only the call timeouts.
Give an internal key a value that differs from its userName: user names are
shown to callers (a composite’s bill, check_balance), so a key that doubles
as one is handed to every caller. The file provider warns at startup when it
sees one.
That split is deliberate: which identity a module runs as is the operator’s
decision, not the author’s, so the same module can be deployed twice under
two different identities with two different grants. A handler never names
its own identity — it just calls ctx.call.
As with ctx.serviceClient, authorization and billing are two different
identities: the hop is authorized as the bound identity above, but billed
to ctx.caller — the real outer caller — so per-hop cost lands on whoever
actually called your tool, not on the module.
Only the key the call came in with is billed. That is the key the client authenticated with, over any route (an HTTP request, an MCP client, or a job, whose run is billed to the key that added it). It pays for the call itself and for every inner hop the call causes, however deep the chain. No other key is charged: an internal key only authorizes, so it needs no balance. The auth config has no billing field; who pays is a fixed rule of the runtime, not something an entry can change or redirect.
Everything is verified at load time, not at first call. For modules
present at startup, every address in countinghouse.calls is resolved
against the target’s real spec, the identity is bound via runsModules, a
duplicate binding is refused, and the bound identity’s grant to each target
is checked. A typo, a missing binding, or a missing grant fails the module
at startup with a message naming the module, the address, and the file to
fix — it does not wait until the first call to surface.
Load time is still where you want to find a broken chain, because only the
load-time error can name the module, the address and the file to fix. But a
runtime refusal is no longer anonymous: each ctx.call guard rejects with
a typed code that reaches an MCP client intact. A failed tools/call
comes back isError: true with _meta["countinghouse/code"] set to one of
(before 8.0.0 it was structuredContent.code; an error result now carries no
structuredContent, because MCP clients validate it against the tool’s output
schema even on errors):
code |
what it means |
|---|---|
CTX_CALL_NOT_READY |
composition verification has not finished for this module yet — retry; this does not mean the config is wrong |
CTX_CALL_UNBOUND |
verification finished and bound nothing: the address is missing from countinghouse.calls, or no identity’s runsModules lists this module (both are required) |
CTX_CALL_UNDECLARED |
an identity is bound, but this address is not in countinghouse.calls |
CTX_CALL_BAD_ADDRESS |
the address is not of the form <module>/<service>.<action> |
CTX_CALL_UNRESOLVED |
the address does not resolve against the target module’s spec |
A callee that genuinely threw still reports DEVICE_INVOKE_EXCEPTION —
telling a misconfigured chain apart from a failing one is the whole point of
the codes. Because they come from the error catalogue (lib/error-catalogue.js), each code’s
message text is actionable on its own.
What still does not cross the MCP boundary is a runtime error’s per-call
detail. Under --workerThread, the main thread rebuilds a runtime error
from a worker’s reply by its code alone
(CountinghouseError.fromReply), so a client sees the code’s generic
message, not “… for address x/y.z”. The full text survives in
single-thread mode and over REST /devices/:id/invoke-action. A module’s own
error (ctx.error) is different: every reply between threads carries it
whole, so its code and message reach the client in either mode, and a
composing module’s ctx.call gets its details too. The callee’s structured .fault
reaches neither.
A short startup window remains, but it now says so. A device appears in
tools/list and can serve its own actions before composition verification
has finished — that verification is asynchronous and runs after all modules
are discovered. A call landing in that window is refused with
CTX_CALL_NOT_READY, whose message says to retry, rather than being blamed
on an auth config that is in fact correct. Treat that code as retryable and
every other CTX_CALL_* code as a configuration bug.
examples/repo-review/token-comparison.js waits for the server’s “all
module discovered” log line plus a settle buffer to stay out of the window
entirely — see its comment on waitForAllModulesDiscovered for the full
timeline.
Composition verification also runs for modules loaded at runtime, including
into an instance started with no --loadModule flags at all — the
--authoringTools setup recommended above. A bare instance completes
discovery vacuously at startup, and each later countinghouse_load_module
re-runs verification for what was just loaded, so a module authored and
loaded entirely at runtime can ctx.call normally.
This was not always true: allmodulediscovered used to be gated on a
startup module count that a bare instance never reached, so verification
never ran there and every ctx.call was refused against a perfectly correct
auth config. test/composition/08-bare-server-discovery.js guards both
halves — that a bare instance reaches discovery completion, and that a
composing module loaded into one at runtime can actually call through.
ctx.serviceClient — addressing a device by IDctx.call resolves a declared address by name. ctx.serviceClient reaches a
target by deviceID (computed offline or looked up yourself, with no name
resolution), for the same declared targets:
ctx.serviceClient({deviceID, serviceID}, (err, client) => {
client.invoke({actionName: 'echo', input: {...}}, (err, data, platformMetering) => { ... });
});
It authorizes exactly as ctx.call does: as the one identity the operator
bound to your module (runsModules, by its package.json name), which must be
granted the target device, and only to targets your module declared in
countinghouse.calls. The hop is billed to ctx.caller, so per-hop cost
lands on whoever called your tool rather than on your module. A module never
names the identity: as is refused since R2-1 with “identities come from the
operator’s runsModules binding; remove as”, and a module with no binding
gets CTX_CALL_UNBOUND. A module that needs two identities is two modules.
pre-installed-packages/composite-demo stays on ctx.serviceClient
deliberately, so both paths keep a live example and test coverage; see
composite-tools.md.
A module can call one remote MCP server, the user’s own GitHub for example, without ever holding the user’s credential. The runtime’s main thread connects to the server, adds the credential the operator allowed, and hands the module the server’s answer.
Declare it in package.json:
"countinghouse": {
"remotes": [
{
"name": "github",
"transport": "streamable-http",
"url": "https://api.githubcopilot.com/mcp/",
"headers": {"X-MCP-Toolsets": "actions,repos"},
"credential": {"env": "COUNTINGHOUSE_GITHUB_TOKEN", "fallbackEnv": "GITHUB_TOKEN",
"header": "Authorization", "scheme": "Bearer"}
}
]
}
name: lower-case letters, digits and -, starting with a letter. It
is the name in the address below.transport: "streamable-http", the only one.url: https:, with no user info and no fragment. http: is accepted
only for a loopback host under --debug, for local testing. A loopback
or private address, or the Redis endpoint, is refused.headers (optional): static, non-secret headers, sent as written on
every request. A secret goes only through credential. The
credential’s header, hop-by-hop headers and the headers the transport
sets itself (Host, Content-Type, Accept, Mcp-Session-Id and the
like) are refused.credential (optional): the environment variable to read (env, then
fallbackEnv when env is empty), the header (default
Authorization) and the scheme (default Bearer; "" sends the bare
value). It is a request, not a grant: the operator’s
--remoteCredentials file decides which variables may go to which
origin.One remote per module in this version. countinghouse-validate reports a
declaration problem by position and field, and the load refuses the
module with REMOTE_DECLARATION_INVALID.
Call it from a handler:
const result = await ctx.call('remote:github/actions_list', {method: 'list_workflow_runs', owner, repo});
// result: {content: [{type: 'text', text}], isError?, structuredContent?}
The result is the MCP CallToolResult as the server sent it, with nothing
parsed and nothing stripped. A tool’s own error (isError: true) is a
result, so the module can read its text. Only a failure to get an answer
rejects, with a code:
| Code | When | Retryable |
|---|---|---|
REMOTE_UNREACHABLE |
DNS, connection or TLS failure, a redirect (refused, never followed), a 502 or 503, or the module was reloaded during the call | yes |
REMOTE_TIMEOUT |
no answer within --remoteTimeout, or a 504 |
yes |
REMOTE_AUTH_FAILED |
the server answered 401 or 403; the message names the variable, never its value | no |
REMOTE_PROTOCOL |
an answer that is not valid MCP | no |
REMOTE_RESULT_TOO_LARGE |
an answer over --remoteMaxBytes |
no |
REMOTE_ADDRESS_REFUSED |
the host resolves to a loopback, private or Redis-endpoint address | no |
REMOTE_UNDECLARED |
the module declares no remote by that name | no |
REMOTE_ARGS_INVALID |
not an address remote:<name>/<tool>, or the arguments are not a plain JSON object |
no |
REMOTE_CREDENTIAL_NOT_ALLOWED |
the operator’s file does not allow the variable for this origin; the remote is disabled | no |
REMOTE_CREDENTIAL_MISSING |
the variable is allowed but was not set when the module loaded | no |
A remote needs no net permission: the connection is the main thread’s,
and the module never sees the credential, the socket or any header. Each
call is metered to the outer caller as an inner hop, and counted in the
usage records and the receipt under the outer tools/call
(module-authoring.md).
Make it before your handler answers: once a part has answered, the call is
no longer its own, and a remote call made then is refused
USAGE_CALL_FOREIGN. The server’s tools/list is taken at load and recorded with a hash in the log. It
refuses nothing in this version: a tool missing from it is called all the
same.
tools/listWork down this list in order. Every case below now logs an explicit error — check the server log first, it very likely already names the cause.
MODULE_LAYOUT_UNSUPPORTEDmy-module: a module is api.json, schema.json and handlers/<service>/<action>.js; this one has package.json "main": "device.js" and no handlers/ directory. See docs/module-development.md.
The module has a main entry (package.json "main", or an index.js) and no
handlers/ directory: the retired format (see
Retired: main entries and dynamic discovery).
None of its code was run. Move each action into
handlers/<service>/<action>.js and remove the main entry (for a 5.x
module, npx countinghouse-migrate-module ./my-module does it).
DEVICE_SPEC_VALIDATION_FAILDevice spec validation failed: my-module stage=validateDeviceSpec -- 2 schema error(s):
/device must have required property 'modelDescription' | /device/serviceList/urn:.../actionList/0 must have required property 'name'
Your api.json doesn’t satisfy the meta-schema. Each error gives the JSON
pointer (instancePath) into your spec and what is wrong there, and all
errors are reported, so you can fix the spec in one pass. Common causes:
missing device.modelDescription, an action without a name, an
actionList that is still an object rather than an array.
MODULE_NO_DEVICE_ONLINEThe device assembled from your api.json failed its interface check: an
earlier error on the device was recorded, and the message quotes it.
MODULE_ASSEMBLY_FAIL with stage=schemaSafetyYour schema.json is one the validators will not compile: too large, a
pattern that can backtrack catastrophically, or $refs that expand too far,
refer to themselves or name no place in the file. The message names the
schema path; see schema.json for the limits. A call refused
VALIDATION_TIMEOUT or VALIDATION_QUARANTINED means a schema that passed
these checks still takes too long to compile or to validate a value.
MODULE_ASSEMBLY_FAIL with stage=declarationsSomething your module declares breaks a rule a schema cannot express: a
binary output field under oneOf or behind a $ref, x-mcp-header in an
input schema, a resource whose variable is no input property, a prompt whose
`` is no argument. The message names the action (or the prompt) and
says what to change. The load stops at the first one; run
npx countinghouse-validate ./my-module to see every one, with the warnings.
LOAD_MODULE_FAILA handler file threw while being required — a syntax error, a missing
require, a bad path in CHUtil.loadFile. The message names the handler
file (handlers/<service>/<action>.js) and its error; the worker is ended
and the module is not loaded.
MODULE_LOAD_TIMEOUTYour module did not finish loading within the operator’s
--moduleLoadTimeout (120 s by default), and its worker was ended. Something
your module runs while it is required never returns: a busy loop, an
Atomics.wait, a synchronous read that never ends. Do that work in an action,
or start it asynchronously after load.
Then the device did come online, and the problem is downstream:
tools/list while others from the same module
appear → that action has no description in api.json. Actions without
one are skipped deliberately (description is what an LLM reads), and this
is logged at info level: action ... has no description, skipping.tools/list is filtered per apiKey. That key isn’t granted the
device. See authentication.md.{"type":"object",
"properties":{}}) → the schema fetch failed and fell back to a permissive
default. Server-side validation still enforces the real schema, so calls
with wrong arguments are still rejected; but the LLM is flying blind. Check
that schema.json resolves and each action’s input/output/fault
pointers are right.npx countinghouse-validate ./my-module
Checks api.json, schema.json and the handler map against each other, what
the module declares for MCP clients (stage declarations) and its icon
files, and prints every problem it finds, each naming the stage and the way
out. Exit
codes: 0 clean, 1 problems found, 2 the path could not be read. No
Redis and no server required.
--verifyModule remains available for checking a module in the context of a
running framework: it makes the framework continue past validation failures
and report everything it finds, rather than stopping at the first one.
node ./framework.js --verifyModule --loadModule ./path/to/my-module
Full reference for the authoring toolchain — the four tools, the loop, the
security boundary and its known limits — is in
module-authoring.md.
Start the runtime with --authoringTools and an admin key, and a coding
agent can validate a design, write the module, validate it, load it and call
it without a human editing JSON. The four tools are
countinghouse_validate_plan, countinghouse_validate_module,
countinghouse_load_module and countinghouse_call_tool; they are admin-only
and absent from tools/list unless the flag is set. Keep the default worker
mode: countinghouse_load_module runs a module’s main entry in the runtime,
and worker mode is what turns a crash or process.exit() there into a
reported failure. Under --no-workerThread the same crash takes the whole
server down.
The repo ships the skill that drives them at
.claude/skills/countinghouse-module/SKILL.md.
Before 6.0.0 a handler took a Node-style callback. That form still works, and every 5.x handler keeps running unchanged:
module.exports = (input, ctx, callback) => callback(null, {output: {...}});
It is deprecated and will be removed in 7.0.0. Write new handlers as
async (input, ctx); the migrator converts old ones for you
(npx countinghouse-migrate-module ./my-module).
Which form you are using is decided by what the handler returns — a thenable is awaited, anything else waits for the callback — so both can coexist in one module while you migrate.
One difference worth knowing while both forms are in play: an untyped error
resolves differently by route. callback(new Error('boom')) becomes
DEVICE_INVOKE_FAIL (“I am reporting a failure”), while throw new
Error('boom') becomes DEVICE_INVOKE_EXCEPTION (“I crashed”). A module’s
own error (ctx.error) keeps its code either way, which is the reason to use
one.