JavaScript and TypeScript
This page is for developers who read, check or follow instructions from JavaScript or TypeScript. It covers the two npm packages, everything they export, and how to give an agent the instruction it follows, with each new version as it is released.
instruction.md(0.11.2) is the reference library of the specification and theinstructioncommand. Use it to read, check and resolve documents, to follow instructions over MCP, and to draw them on a page.@instruction.md/agents(0.4.3) runs coding agents. Itsfollow()gives an agent you run with the Claude Agent SDK, the Codex SDK or your own loop its instruction.
Both are MIT, ES modules with type declarations. Other languages are on Libraries and SDKs.
Install
npm install instruction.md # or: pnpm add instruction.md, yarn add instruction.md
npm pkg set type=module # the examples use import and top-level await npm install @instruction.md/agents instruction.mdneeds Node.js 20.19 or later for the command, the stdio MCP server andinstruction.md/cli. The reader, the resolver and the text profile use no Node.js API, and the client needs onlyfetch, so they also run in browsers and workers.@instruction.md/agentsneeds Node.js 20.19 or later.- The examples use
importand top-levelawait, so run them as ES modules ("type": "module", or.mjsand.mtsfiles). In a CommonJS project, tsx and tsc refuse top-levelawait(ERR_REQUIRE_ASYNC_MODULE, TS1309).
What you can import
Import the subpath you need. The renderer's dependency (Lit) loads only from instruction.md/render and its subpaths. This table is read from both packages' manifests.
| Import | What it is |
|---|---|
instruction.md | The reader and its checks, the resolver and the text profile, the formatter, quick fixes, 1.1 upgrade, digests, signature verification, the language's data. |
instruction.md/schema | The specification's JSON Schema of the authored tree (import it with with { type: "json" }). |
instruction.md/registry.json | The specification's registry of kinds, keywords and attributes. |
instruction.md/extension | Experimental: the client side of the MCP Instructions extension (below). |
instruction.md/consumer | InstructionFollower: one agent follows one instruction. |
instruction.md/follow | followInstructions: an agent platform follows every instruction it was granted. |
instruction.md/follow-kit | MockPlatform and checkReleaseReachesPlatform: test that a release reaches your platform. |
instruction.md/connect | The MCP hosts' connection snippets and coding agents' hook settings, as instruction connect prints them. |
instruction.md/service | The spec_* tools, their definitions and handlers. |
instruction.md/client | An MCP client for the 2026-07-28 stateless protocol, and asSdkClient for code written for the MCP SDK's client. |
instruction.md/render | The <instruction-md> element, render() and the renderer's helpers. |
instruction.md/render/project | The renderer's parts, for a host that draws its own. |
instruction.md/render/icons | The renderer's parts, for a host that draws its own. |
instruction.md/render/html | The renderer's parts, for a host that draws its own. |
instruction.md/render/outline | The renderer's parts, for a host that draws its own. |
instruction.md/render/figures | The renderer's parts, for a host that draws its own. |
instruction.md/render/diagrams | The renderer's parts, for a host that draws its own. |
instruction.md/render/styles | The renderer's parts, for a host that draws its own. |
instruction.md/render/ssr | renderToString and renderToPage: server-side rendering, declarative shadow DOM. |
instruction.md/render/themes/* | The themes as CSS files: default, paper, terminal, github-like. |
instruction.md/render/releases.json | The renderer's CDN releases with their integrity hashes. |
instruction.md/render/client | The renderer's registry client (what ref= reads with). |
instruction.md/render/markdown-it | A markdown-it plugin: each instruction code fence becomes an element. |
instruction.md/render/enhance | enhance and watch: turn fences on a page into elements. |
instruction.md/render/tokens | The element's attributes and CSS parameters. |
instruction.md/render/i18n | The renderer's translations. |
instruction.md/render/languages | The renderer's languages and text direction. |
instruction.md/package.json | The manifest. |
instruction.md/cli | What @instruction.md/agents builds on. No stability promise of its own. |
instruction.md/cli/registry | What @instruction.md/agents builds on. No stability promise of its own. |
@instruction.md/agents/agent | follow(): an instruction as the instructions of an agent you run with an SDK. |
@instruction.md/agents/pi | The pi extension (piExtension, piSection, PI_SECTION). |
@instruction.md/agents/package.json | The manifest. |
Read, check and resolve
import { check, read, resolve } from "instruction.md";
const text = `---
spec: "1"
title: Support agent
---
# Support agent
MUST[verify-identity]: verify the customer's identity before discussing an account.
BECAUSE: an account holds another person's data.
`;
const { document: tree, diagnostics } = read(text); // the authored tree (instruction/1)
console.log(tree.metadata.front.title, diagnostics.length, check(text).length);
const { ok, text: delivered } = await resolve(text, { uri: "file:///agents/support-agent.md" });
console.log(ok);
console.log(delivered); // the bytes a model receives (instruction-text/1) It prints:
read(text, options?)returns the authored tree (document) with itsdiagnostics,identities,parameters,footnotes,keywords,reasons,linesand the front matter's and backmatter's ranges.check(text)returns the diagnostics a release refuses on (severityerror) or warns about. Each has a stablecode; every code is on Diagnostics and fixes.resolve(text, { uri?, version?, params?, load?, limits? })is async and returns{ ok, resolved, text, diagnostics, root }.textis what a model receives (instruction-text/1);resolvedis the resolved artifact (instruction-resolved/1).uriis the document's own address, which relative references resolve against (defaultdocument.md). Giveparamsfor parameter values, andload(uri)to supply the bases and includes the document composes (Includes, inheritance and extensions).limitscaps the composition depth (default 8) and the sources read (default 64); past either,resolvereports an error instead of a shorter text.- Also in
instruction.md:format(text)(the conservative formatter),fixesForandapplyEdits(quick fixes as edits),upgrade(text)(Specification 1.1 lines converted),digestanddigestText(sha256:…),verifyAuthorandverifyDelivery(Signing and trust),agentManifestandmachineryOf(the servers, skills and agents a document declares), and the language's data (KINDS,KEYWORDS,FRONT_MATTER_KEYSand the rest).
Follow one instruction
InstructionFollower (instruction.md/consumer) keeps one agent on one instruction. It reads the version a ref names, hands it to onApply, and reads again when the server says the ref moved, or every freshnessMs. A version its policy refuses goes to onHold, and the last good one stays.
import { resolve } from "instruction.md";
import { asSdkClient, createClient } from "instruction.md/client";
import { InstructionFollower } from "instruction.md/consumer";
const client = asSdkClient(createClient({
url: "https://instruction.md/mcp",
token: () => process.env.INSTRUCTION_MD_TOKEN, // asked before every request
}));
const follower = new InstructionFollower({
client,
uri: "instruction://acme/support-agent@stable",
policy: { requireSignature: true, publisher: "https://instruction.md/pub/acme" },
report: { consumer: { label: "support-bot", kind: "agent" } },
onApply: async (applied) => { // the first version, then each release
const { text } = await resolve(applied.text, { uri: applied.canonical }); // authored text -> what a model receives
setSystemPrompt(text); // your code
},
onHold: (reason) => console.warn("held:", reason), // refused by the policy: the last good one stays
});
await follower.start();
// when your agent shuts down
follower.stop();
await client.close(); // stop() leaves the client's update stream open The client is the library's own (instruction.md/client). It speaks MCP 2026-07-28 statelessly, with no initialize and no session, which is the only protocol instruction.md's server speaks; asSdkClient gives it the MCP SDK client's call shape. Its update stream reopens after a drop, with a pause that grows from 1 to 30 seconds.
applied.text is the version's authored text, as the resource read returns it, so the sample resolves it before it reaches the model. With policy.requireDeliverySignature, it is the delivered text the signature covers. A document that extends or includes another instruction needs a load that reads it, or its delivered text is partial.
| Option | Default | Effect |
|---|---|---|
client |
required | Anything with readResource and callTool; with subscribeResource and setNotificationHandler, it gets live updates |
uri |
required | instruction://{id}, instruction://{id}@ref, @ver_… (pinned), or an owner/name alias |
mode |
"follow" |
"pinned" never changes after the first apply. A URI naming a version is pinned too |
policy |
{} |
requireSignature, authorKeys (else the publisher's keys, revoked ones excluded), publisher (the expected https://instruction.md/pub/<owner>), requireDeliverySignature, deliveryKeys, allowedPublishers, maxBytes |
freshnessMs |
60000 |
How often to read again; 0 turns it off |
report |
none | { consumer: { label, kind, workload? }, client?: { name, version }, bindingId? }: declare a binding (label is its name, kind is agent, host or ci, workload where it runs) and report each version applied, so maintainers see it. bindingId reuses a binding you already have |
onApply(applied, previous) |
required | Called with each new version |
onHold(reason, candidate) |
none | A version the policy refused |
onError(error) |
none | A read failed |
Its methods are start(), refresh(reason) and stop(), and current is the last good version (null before the first). stop() doesn't close the client you passed: call client.close(), or the process doesn't exit. How a follower behaves offline and on a hold is on How following works.
The live updates a follower subscribes to are limited per plan, counted as the agents and apps that hold them at the same time. Reads are never limited (Live updates).
Plans Community 1 · Pro unlimited · Team unlimited · Enterprise unlimited
A token for your agent
Plans On Pro, Team, and Enterprise
The server answers only a caller with a token, even for a public instruction. Without one, the follower holds with read failed (start): authentication required. For an agent, an organization admin creates an agent account once with instruction agents create <name>, which prints its client_id, its client_secret (shown once) and its token_url. Mint its tokens with the client-credentials grant. A token lasts about five minutes, so pass a function that mints a new one as it runs out:
// INSTRUCTION_MD_TOKEN_URL, _CLIENT_ID and _CLIENT_SECRET: what `instruction agents create` printed
let minted = { token: "", until: 0 };
export async function token() {
if (Date.now() < minted.until) return minted.token;
const r = await fetch(process.env.INSTRUCTION_MD_TOKEN_URL!, {
method: "POST",
body: new URLSearchParams({
grant_type: "client_credentials",
client_id: process.env.INSTRUCTION_MD_CLIENT_ID!,
client_secret: process.env.INSTRUCTION_MD_CLIENT_SECRET!,
}),
}).then((res) => res.json() as Promise<{ access_token: string; expires_in: number }>);
minted = { token: r.access_token, until: Date.now() + (r.expires_in - 30) * 1000 };
return minted.token;
} {tokenConnect} prints the same code with your agent's values. See Agent credentials and CI tokens.
Follow every instruction a platform is granted
An agent platform that runs agents from every instruction people grant it uses followInstructions (instruction.md/follow). Each release is read and verified first, with the agents its text declares; one that can't be verified goes to onHold and is never handed over.
import { asSdkClient, createClient } from "instruction.md/client";
import { followInstructions } from "instruction.md/follow";
import { token } from "./token";
const client = asSdkClient(createClient({ url: "https://instruction.md/mcp", token }));
const f = await followInstructions({
client,
policy: { requireSignature: true },
onRelease: (r) => startAgent(r.instructionId, r.text, r.manifest), // your code: a verified version and its agents
onRemoved: (r) => stopAgent(r.instructionId), // your code: no longer granted
onHold: (reason, item) => console.warn("held", item.instructionId, reason),
});
// keep f.cursor() to go on from there next time; f.stop() to end | Option | Default | Effect |
|---|---|---|
client |
required | As for InstructionFollower |
onRelease(release) |
required | instructionId, owner, name, title, versionId, number, uri (the pinned address it was read at), text (the authored text), manifest (the agents it declares), verified, signed |
onRemoved(removal) |
none | instructionId, reason, versionId |
onHold(reason, item), onError(error) |
none | A refused release; a failed read |
policy |
{} |
requireSignature, authorKeys (else the publisher's keys), publisher |
pollMs |
30000 |
How often to ask; 0: only when you call sync() |
cursor |
none | Where an earlier run stopped (its cursor()): only what happened since, no snapshot |
limit |
100 |
Items per call |
It returns { stop(), cursor(), sync() }. instruction.md/follow-kit tests the whole path: MockPlatform runs nothing and remembers every release and removal, and checkReleaseReachesPlatform({ client, publish, platform?, policy? }) follows, publishes, follows again and answers { ok, checks, platform }.
Follow with an agent SDK
follow() (@instruction.md/agents/agent) is for an agent you run with an SDK. It reads the version now, gives you its delivered text, and between turns says whether a new version was released and what to tell the model. It holds no live connection: each refresh is one read, so it never takes a Community workspace's live-update place. Neither SDK is a dependency; you hand the text to the SDK yourself. The token is the function above.
The Claude Agent SDK
The whole version goes in the system prompt as a context block, and a new version reaches the model at the next prompt through the UserPromptSubmit hook:
import { query } from "@anthropic-ai/claude-agent-sdk";
import { follow } from "@instruction.md/agents/agent";
import { token } from "./token";
const ins = await follow("instruction://acme/support-agent@stable", { token, requireSignature: true });
for await (const message of query({
prompt: "Answer the oldest open ticket.",
options: {
systemPrompt: { type: "preset", preset: "claude_code", append: ins.contextBlock() },
hooks: {
UserPromptSubmit: [{
hooks: [async () => (await ins.changedSinceLastTurn())
? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: ins.updateBlock() } }
: {}],
}],
},
},
})) console.log(message);
await ins.close(); contextBlock() gives the version in hand, with what it is and that it is to be followed:
After changedSinceLastTurn() answered true, updateBlock() gives the new version, which replaces the earlier one in full:
The digest and version numbers here are made up for a sample; ins.digest is the sha256: of the delivered text.
The Codex SDK
The text becomes a thread's developer instructions. A thread keeps the instructions it started with, so a new version starts a new thread:
import { Codex } from "@openai/codex-sdk";
import { follow } from "@instruction.md/agents/agent";
import { token } from "./token";
const ins = await follow("instruction://acme/support-agent@stable", { token, requireSignature: true });
let codex = new Codex({ config: { developer_instructions: ins.text } });
let thread = codex.startThread();
await thread.run("Answer the oldest open ticket.");
// between tasks: a new version starts a new thread with the new text
if (await ins.changedSinceLastTurn()) {
codex = new Codex({ config: { developer_instructions: ins.text } });
thread = codex.startThread();
}
await ins.close(); follow() options and members
| Option | Default | Effect |
|---|---|---|
url |
INSTRUCTION_MD_URL, else https://instruction.md/mcp |
The MCP server |
token |
INSTRUCTION_MD_TOKEN |
A bearer token, or a function asked before each read. Required, even for a public instruction, unless you pass client. The sign-in stored by instruction login is not used |
client |
none | Your own client with readResource and callTool; url and token are then not used |
requireSignature |
false |
Only versions whose author signature verifies |
keys |
the publisher's keys | The author keys accepted |
refreshSeconds |
60 |
How long a version is used before the next read |
deadlineMs |
5000 |
How long a read may take before the version in hand is kept |
| Member | What it is |
|---|---|
text, version, versionId, digest, verified |
The version in hand: its delivered text, number, id, sha256: digest, and whether its signature was checked and holds |
uri, label, current |
The address followed, owner/name, and the whole version in hand |
refresh() |
Read now: true when a new version came. A failed read keeps the version in hand and answers false |
changedSinceLastTurn() |
Read again once refreshSeconds passed: true once per new version |
updateBlock(), contextBlock() |
The blocks above |
close() |
Closes the client it made, never one you passed |
follow() throws when there is no version to hand over: not found, not allowed, or held for its signature. Without a token the read fails with read failed (hook): authentication required (the word "hook" is a wrong label for follow()'s own read).
The language service in code
instruction.md/service exports the spec_* tools every instruction.md MCP server answers alike, the same handlers the server and instruction mcp run. SPEC_TOOL_DEFS holds their names, titles, descriptions and input schemas, and SPEC_TOOLS their handlers. They are pure: nothing is stored or sent.
import { readFileSync } from "node:fs";
import { SPEC_TOOLS, SPEC_TOOL_DEFS } from "instruction.md/service";
const text = readFileSync("support-agent.md", "utf8");
// the same tools a server lists, for your own MCP server or agent loop
const tools = SPEC_TOOL_DEFS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
// and their handlers: plain data in, plain data out, nothing stored or sent
const answer = SPEC_TOOLS.spec_validate({ content: text }) as { ok: boolean; diagnostics: { code: string; line?: number; message: string }[] };
console.log(answer.ok, answer.diagnostics); | Tool | Title | What it does |
|---|---|---|
spec_validate | Check a text | Use to check any instruction text: its diagnostics (code, severity, line, message: an error is what a release refuses), the capability families it needs, and its spec version. Changes nothing; a stored draft is instructions_validate's, by its id. |
spec_format | Format a text | Use to format an instruction text the conservative way the studio does. Returns the formatted text; changes nothing. |
spec_outline | Outline a text | Use to see a text's sections, rules and blocks with their lines, and its word and rule counts. Changes nothing. |
spec_fixes | Get fixes for a problem | Use to get the quick fixes for a diagnostic, as replace ops ready for instructions_draft_edit; a text still in Specification 1.1 gets its conversion. Changes nothing. |
spec_deliver | Show what a model receives | Use to see what a model would receive from a text for given parameters: its agent text (instruction-text/1), whether it resolved completely, and its diagnostics. Changes nothing. |
spec_convert | Convert a prompt | Use to turn a system prompt into an instruction: its rules become MUST, SHOULD and NEVER lines. Returns the text to create; changes nothing. |
spec_explain | Explain the language | Use to explain a kind, a keyword or a diagnostic code, with a link into spec://. Changes nothing. |
Their arguments and answers are on Tool reference. The functions behind them are exported too (check, outline, fixes, deliver, convert, explain), with CODES (every diagnostic code with its meaning) and SPEC_RESOURCES.
The editor completions, the lists the web editor's source view and the VS Code extension offer, come from a separate library that is not published on npm. Both apps bundle it.
Experimental: the MCP Instructions extension
It exports EXTENSION_KEY, EXTENSION_VERSION, clientCapabilities(settings?), extensionActive(settings, serverCapabilities), validateDescriptor, the InstructionsHydrator class (negotiate, read the index, check digests, approve, order, budget, subscribe and reconcile), and its pure steps (orderItems, applyBudget, envelope, composeManagedContext, planReconcile, sha256Digest, DEFAULT_CLIENT_SETTINGS). The hydrator takes the MCP SDK's Client, which opens a session that instruction.md's server refuses.
If it doesn't work
| What you see | Why | What to do |
|---|---|---|
read failed (start): authentication required |
The follower has no token | Pass token, or set INSTRUCTION_MD_TOKEN (A token for your agent) |
McpError: authentication failed: invalid or expired credential (status 401) |
The token was refused, often because it lapsed (about five minutes) | Pass a function that mints a new one, not a fixed string |
held: … from onHold |
The policy refused the version: no valid signature, another publisher, too large, or sealed with no key here | The last good version stays. Check policy; Signing and trust |
| The process never exits | follower.stop() stops the follower, not the client |
await client.close() after stop() |
ERR_REQUIRE_ASYNC_MODULE, or TS1309 |
Top-level await in a CommonJS project |
npm pkg set type=module, or use .mjs and .mts files |
| Still stuck | Support, with the package versions and the smallest script that shows it |
Questions
Can I use the official MCP SDK's client instead?
Not against instruction.md's server: the SDK's Client opens a session, and the server speaks the stateless 2026-07-28 protocol only. Use asSdkClient(createClient(…)), which has the same call shape. A server of your own that speaks sessions works with either.
Which follower should I use?
follow() for an agent you run turn by turn with an SDK; InstructionFollower for a long-running process that should switch the moment a version is released; followInstructions for a platform that runs agents from many instructions. All three check signatures the same way.
Does reading a document need the network?
No. read, check, resolve, format and the spec_* handlers work offline with no account. Only the client and the followers talk to a server.
How do I release an instruction from code?
The libraries don't release. Use instruction push and instruction publish (The instruction CLI), or call the server's tools over MCP with the client.