Цю сторінку ще не перекладено.

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 the instruction command. 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. Its follow() 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

Shell
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
Shell
npm install @instruction.md/agents
  • instruction.md needs Node.js 20.19 or later for the command, the stdio MCP server and instruction.md/cli. The reader, the resolver and the text profile use no Node.js API, and the client needs only fetch, so they also run in browsers and workers.
  • @instruction.md/agents needs Node.js 20.19 or later.
  • The examples use import and top-level await, so run them as ES modules ("type": "module", or .mjs and .mts files). In a CommonJS project, tsx and tsc refuse top-level await (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.

ImportWhat it is
instruction.mdThe 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/schemaThe specification's JSON Schema of the authored tree (import it with with { type: "json" }).
instruction.md/registry.jsonThe specification's registry of kinds, keywords and attributes.
instruction.md/extensionExperimental: the client side of the MCP Instructions extension (below).
instruction.md/consumerInstructionFollower: one agent follows one instruction.
instruction.md/followfollowInstructions: an agent platform follows every instruction it was granted.
instruction.md/follow-kitMockPlatform and checkReleaseReachesPlatform: test that a release reaches your platform.
instruction.md/connectThe MCP hosts' connection snippets and coding agents' hook settings, as instruction connect prints them.
instruction.md/serviceThe spec_* tools, their definitions and handlers.
instruction.md/clientAn MCP client for the 2026-07-28 stateless protocol, and asSdkClient for code written for the MCP SDK's client.
instruction.md/renderThe <instruction-md> element, render() and the renderer's helpers.
instruction.md/render/projectThe renderer's parts, for a host that draws its own.
instruction.md/render/iconsThe renderer's parts, for a host that draws its own.
instruction.md/render/htmlThe renderer's parts, for a host that draws its own.
instruction.md/render/outlineThe renderer's parts, for a host that draws its own.
instruction.md/render/figuresThe renderer's parts, for a host that draws its own.
instruction.md/render/diagramsThe renderer's parts, for a host that draws its own.
instruction.md/render/stylesThe renderer's parts, for a host that draws its own.
instruction.md/render/ssrrenderToString 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.jsonThe renderer's CDN releases with their integrity hashes.
instruction.md/render/clientThe renderer's registry client (what ref= reads with).
instruction.md/render/markdown-itA markdown-it plugin: each instruction code fence becomes an element.
instruction.md/render/enhanceenhance and watch: turn fences on a page into elements.
instruction.md/render/tokensThe element's attributes and CSS parameters.
instruction.md/render/i18nThe renderer's translations.
instruction.md/render/languagesThe renderer's languages and text direction.
instruction.md/package.jsonThe manifest.
instruction.md/cliWhat @instruction.md/agents builds on. No stability promise of its own.
instruction.md/cli/registryWhat @instruction.md/agents builds on. No stability promise of its own.
@instruction.md/agents/agentfollow(): an instruction as the instructions of an agent you run with an SDK.
@instruction.md/agents/piThe pi extension (piExtension, piSection, PI_SECTION).
@instruction.md/agents/package.jsonThe manifest.

Read, check and resolve

read.ts
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:

Support agent 0 0
true
# Support agent

MUST: verify the customer's identity before discussing an account.
BECAUSE: an account holds another person's data.
  • read(text, options?) returns the authored tree (document) with its diagnostics, identities, parameters, footnotes, keywords, reasons, lines and the front matter's and backmatter's ranges.
  • check(text) returns the diagnostics a release refuses on (severity error) or warns about. Each has a stable code; every code is on Diagnostics and fixes.
  • resolve(text, { uri?, version?, params?, load?, limits? }) is async and returns { ok, resolved, text, diagnostics, root }. text is what a model receives (instruction-text/1); resolved is the resolved artifact (instruction-resolved/1). uri is the document's own address, which relative references resolve against (default document.md). Give params for parameter values, and load(uri) to supply the bases and includes the document composes (Includes, inheritance and extensions). limits caps the composition depth (default 8) and the sources read (default 64); past either, resolve reports an error instead of a shorter text.
  • Also in instruction.md: format(text) (the conservative formatter), fixesFor and applyEdits (quick fixes as edits), upgrade(text) (Specification 1.1 lines converted), digest and digestText (sha256:…), verifyAuthor and verifyDelivery (Signing and trust), agentManifest and machineryOf (the servers, skills and agents a document declares), and the language's data (KINDS, KEYWORDS, FRONT_MATTER_KEYS and 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.

follow.ts
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:

token.ts
// 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.

platform.ts
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:

agent.ts
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:

These are this project's instructions from instruction.md (acme/support-agent v5). Follow them.
<instruction uri="instruction://acme/support-agent@stable" version="v5" digest="sha256:f609a2740a77495aaad19521e20da627c163e895ea5918f53036a4ec1db26b06">
# Support agent

MUST: verify the customer's identity before discussing an account.
BECAUSE: an account holds another person's data.
</instruction>

After changedSinceLastTurn() answered true, updateBlock() gives the new version, which replaces the earlier one in full:

<instruction-update uri="instruction://acme/support-agent@stable" from="v5" to="v6" digest="sha256:f609a2740a77495aaad19521e20da627c163e895ea5918f53036a4ec1db26b06">
These instructions replace the earlier version of acme/support-agent in full.
# Support agent

MUST: verify the customer's identity before discussing an account.
BECAUSE: an account holds another person's data.
</instruction-update>

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:

agent.ts
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.

tools.ts
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);
ToolTitleWhat it does
spec_validateCheck a textUse 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_formatFormat a textUse to format an instruction text the conservative way the studio does. Returns the formatted text; changes nothing.
spec_outlineOutline a textUse to see a text's sections, rules and blocks with their lines, and its word and rule counts. Changes nothing.
spec_fixesGet fixes for a problemUse 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_deliverShow what a model receivesUse 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_convertConvert a promptUse to turn a system prompt into an instruction: its rules become MUST, SHOULD and NEVER lines. Returns the text to create; changes nothing.
spec_explainExplain the languageUse 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.

Last checked against the product:

Was this page helpful? Report a problem