# instruction-md
Read, check, resolve and verify [instruction.md](https://instruction.md) documents in Rust: the reader for the
specification's first edition (`instruction/1`), the exact text an agent receives, composition, and signature
verification.
[crates.io](https://crates.io/crates/instruction-md) ·
[docs.rs](https://docs.rs/instruction-md) ·
[Specification](https://instruction.md/specification/) ·
[Documentation](https://instruction.md/docs/) ·
License: MIT OR Apache-2.0
## At a glance
**What it is.** An instruction is a Markdown document that tells an AI agent what to do, with binding rules
(`MUST:`, `SHOULD:`, `NEVER:`), parameters, and the MCP servers, skills and agents it may use. People write and
release instructions on instruction.md; agents read them over MCP. This crate is the Rust implementation of the
open [instruction.md specification](https://instruction.md/specification/), first edition.
**What it does.**
- Reads a document into its tree, with diagnostics that have stable codes.
- Checks it: the reader's checks, the inline checks, native workflows, and the integrations policy.
- Gives the agent text (`instruction-text/1`): what an agent actually receives, parameters filled in.
- Resolves a document with its bases and includes into the resolved artifact (`instruction-resolved/1`).
- Verifies author and delivery signatures (JWS, Ed25519), so a runtime knows who published what it follows.
- Lists the connected objects (MCP servers, tools, skills, agents, services) and configuration blocks, for a host
that wires them up.
**Who it is for.** Teams building agent runtimes, hosts, gateways, editors or CI checks in Rust that need to read
instruction files the same way instruction.md does.
**What it does not do.** It does no I/O. It does not talk to a registry, follow an instruction over MCP, or report
what was applied. Your code fetches the text (from a file, the registry, an editor) and hands it to the crate. To
follow an instruction from a registry today, use the npm package [`instruction.md`](https://www.npmjs.com/package/instruction.md)
or the Python package [`instruction.md`](https://pypi.org/project/instruction.md/), or connect your agent to
`https://instruction.md/mcp` ([Connect an agent](https://instruction.md/docs/connect/)).
**How it is held to the reference.** It is a port of the Go SDK, itself a port of the TypeScript reference
implementation. Its test suite runs the specification's conformance cases and the reference's implementation
vectors (specification commit `4bb0328`, exposed as `SPEC_COMMIT`) and must agree with them byte for byte.
**Status.** Pre-1.0 (current version 0.6.1), published on crates.io. The reader and the
agent text are complete for the first edition and conformance-tested. Minor versions may still break the API; each
break is marked in the [changelog](https://docs.rs/crate/instruction-md/latest/source/CHANGELOG.md). The signature verification follows the specification and is
tested against the reference, but it has not had an independent security review.
**License.** MIT OR Apache-2.0, at your option: you may use, change and ship it in open or closed software. The
embedded registries are the specification's, under CC BY 4.0 (see [`NOTICE`](https://docs.rs/crate/instruction-md/latest/source/NOTICE)); they travel with the crate
and need no action from you beyond keeping the notice.
**Quality guarantees.**
- No `unsafe` (`#![forbid(unsafe_code)]`).
- Every entry point takes untrusted text and never panics. A problem is a `Diagnostic` with a stable code. A
randomized test feeds every vector and sample, whole, truncated and mutated, to the entry points.
- Linear-time pattern matching, and depth limits for hostile input (see [Limits](#limits)).
- Dependencies: `serde`, `serde_json`, and `ring` for signatures only.
**Support.** Questions and bugs: [GitHub issues on the specification's repository](https://github.com/instruction-md/specification/issues);
start the title with "Rust SDK". Security problems and anything else: [Contact us](https://instruction.md/contacts/).
**Source.** The crate's full source ships in the crates.io package; browse it on
[docs.rs](https://docs.rs/crate/instruction-md/latest/source/). Its own repository is not public yet, so the
"Repository" link on crates.io does not open for now.
## Install
```sh
cargo add instruction-md
```
or in `Cargo.toml`:
```toml
[dependencies]
instruction-md = "0.6"
```
Without signature verification (no `ring`; the crate then depends on `serde` and `serde_json` only):
```toml
[dependencies]
instruction-md = { version = "0.6", default-features = false }
```
The library is imported as `instruction_md`.
### Requirements
- Rust 1.96 or later (edition 2024).
- Any platform Rust supports. With the default `verify` feature, any platform `ring` 0.17 builds on.
- No runtime, no async. Every function is synchronous, and nothing touches files, the network or environment
variables. Two exceptions, both in the `verify` feature: verification reads the system clock unless you pass
`now`, and `SigningKey::generate()` uses the operating system's random number generator.
### Cargo features
| `verify` | yes | The `verify` module: `verify_author`, `verify_delivery`, `VerifyResult`, `VERIFY_CODES`, `Jwk`, `public_jwk`, and signing for tests and tooling (`SigningKey`, `sign_jws`). The only use of `ring`. |
Without `verify` the crate still reads, checks, resolves and computes digests. Its SHA-256 is its own.
## Quickstart
Create a project and add the crate:
```sh
cargo new hello-instruction && cd hello-instruction
cargo add instruction-md
```
Put this in `src/main.rs`:
```rust,no_run
use instruction_md::{check_reading, read, ReadOptions};
fn main() {
let doc = "---\nspec: \"1\"\nparameters:\n tz: { type: string, default: UTC }\n---\n\
# Morning brief\n\n\
MUST: plan the day in ${tz}.\n\
BECAUSE: the owner reads the brief at 7.\n\
NEVER: book a meeting before 9.\n";
let reading = read(doc, &ReadOptions::default());
for d in check_reading(&reading) {
eprintln!("{d}"); // e.g. "4: error unclosed-directive: ..."
}
print!("{}", reading.text(None));
}
```
Run it:
```sh
cargo run
```
It prints the agent text, with the default for `tz` filled in and the front matter gone:
```text
# Morning brief
MUST: plan the day in UTC.
BECAUSE: the owner reads the brief at 7.
NEVER: book a meeting before 9.
```
The `BECAUSE:` line stays with the rule it explains, and the next rule starts a new paragraph.
To check a file instead, read it with `std::fs::read_to_string` and pass the text to `read`.
## Usage
### Read, check, and give the agent its text
```rust
use instruction_md::{check_reading, read, ReadOptions, Severity};
let doc = "---\nspec: \"1\"\nparameters:\n tz: { type: string, default: UTC }\n---\n\
::person{id=owner title=\"Alex\"}\n\n\
MUST (if a meeting moves): tell :person[Alex]{ref=#owner} in ${tz}.\n\
BECAUSE: the owner plans the day around it.\n";
let reading = read(doc, &ReadOptions::default());
let diagnostics = check_reading(&reading); // the reader's and the inline checks', in source order
for d in &diagnostics {
// d.code is stable ("unclosed-directive", …); d.line() is where; d.message is for a person
eprintln!("{d}");
}
let text = reading.text(None); // instruction-text/1, declared defaults substituted
assert!(text.contains("MUST (if a meeting moves): tell Alex (person; #owner) in UTC."));
```
`read` returns a `Reading`: the tree (`reading.document`), the reader's own diagnostics (`reading.diagnostics`),
the identities, the declared parameters, and the effective integrations policy. `check_reading` adds the inline
checks and the workflow checks. An error among the diagnostics means the document should not be delivered.
`reading.changes_text()` says whether the agent text differs from the source at all. Plain prose and rules already
in canonical form (`MUST: …`) are handed on as written, so a host may pass the source on unchanged.
### One call for a runtime: `deliver`
```rust
let (text, diagnostics) = instruction_md::deliver("MUST: be brief.\n", None);
assert_eq!(text, "MUST: be brief.\n");
assert!(diagnostics.is_empty());
```
`deliver(text, params)` reads, checks and gives the agent text in one call. Its diagnostics also include lines
written in the older Specification 1.1 syntax (`legacy_diagnostics`, code `instruction.md/legacy-syntax`, an
error: a `:::!kind` block reads as prose here), ordered as the TypeScript CLI reports them.
### Supply parameter values
```rust
use instruction_md::{read, Object, ReadOptions};
let doc = "---\nparameters:\n tz: { type: string, default: UTC }\n---\nMUST: plan the day in ${tz}.\n";
let reading = read(doc, &ReadOptions::default());
let mut params = Object::new();
params.insert("tz".into(), "Europe/Kyiv".into());
assert_eq!(reading.text(Some(¶ms)), "MUST: plan the day in Europe/Kyiv.\n");
// A value typed on a command line, read as the parameter's declared type:
let tz = reading.parameter("tz").unwrap();
let value = instruction_md::value_from(tz, "Europe/Lisbon");
assert!(instruction_md::value_fits(tz, &value));
```
A supplied value replaces the declared default. `Object` is `serde_json::Map<String, serde_json::Value>`.
### Diagnostics as JSON
Every diagnostic has a stable `code`, a `severity` (`Error`, `Warning`, `Info`), a `message` for a person, and
optionally a `range` (1-based lines), `uri`, `target` and `remedy`. `to_json()` gives the specification's shape,
for CI output or an editor:
```rust
use instruction_md::{check, ReadOptions};
let diagnostics = check(":::note\nAn unclosed note.\n", &ReadOptions::default());
let json: Vec<_> = diagnostics.iter().map(|d| d.to_json()).collect();
assert_eq!(json[0]["code"], "unclosed-directive");
assert_eq!(json[0]["severity"], "error");
```
The codes are the ones the Go and TypeScript readers emit (`unclosed-directive`, `invalid-attributes`,
`reference-optional`, `invalid-workflow`, `tool-blocked`, …).
### Connected objects, configuration and workflows
```rust
use instruction_md::{configuration_blocks, connected_objects, read, ReadOptions};
let r = read(":::mcp{id=cal src=\"https://example.org/mcp\" tools=\"events.list\"}\nRead appointments.\n:::\n",
&ReadOptions::default());
for o in connected_objects(&r.document.body) {
// kind, id, title, src, endpoint, attrs (list("tools")…), body (its source as written), location
assert_eq!((o.kind, o.id, o.body), ("mcp", Some("cal"), Some("Read appointments.\n")));
assert_eq!(o.list("tools"), ["events.list"]);
assert!(o.location.in_layout()); // at the top level or inside layout containers only
}
assert!(configuration_blocks(&r.document.body).is_empty()); // config, workflow, schedule, sandbox, test, eval, data, properties
```
Connected objects are the kinds a typed reference names (the registry's `connected` family, and `resource`): a
person, role, skill, MCP server, tool, agent, service, source or resource. Configuration blocks are the `technical`
family's structured bodies. `walk(body, visitor)` visits every directive with the directives that hold it;
`Node::body_source()` is a container's body exactly as written; `split_backmatter(text)` cuts a document at its
backmatter's `---` separator, where `Reading::back_range` starts.
`check_reading` holds every `:::workflow{dialect="instruction/workflow"}` body to the specification's workflow
registry and graph rules, as the TypeScript and Go readers do:
- `invalid-workflow`: an unknown kind or field, a missing required field, a step that depends on nothing but is not
a trigger, a missing dependency or route, a cycle, no trigger or finish, an unreachable step.
- `limit-exceeded`: more than 512 steps in a scope, bodies nested deeper than 4, `retry.max` over 20.
- `extension-unavailable`: an `alias:node` kind whose alias isn't declared.
Each is an error on the line of the key it is about. The specification lists no host events, so an `event`
trigger's `on` is the host's to check. Only the scoping kinds' `body` or `branches` hold nested steps
(`WORKFLOW_SCOPES`, `workflow_scope`: `foreach`, `batch`, `iterate`, `subgraph`; `parallel`, `race`). Another
kind's field of that name, such as an `http` request's `body`, is data. `workflow_diagnostics(definition,
extensions)` checks a definition on its own.
### The integrations policy
A workspace's integrations policy travels in the front matter: `host-integrations`, which only the host that serves
the document writes (outside the author-signed bytes), and `integrations`, the author's, which can only narrow it.
The reader merges them into `Reading::policy`: a target is allowed only where every layer that lists targets lists
it, and a tool is blocked where any layer blocks it. The reader warns, never refuses: `tool-blocked` (a tool that an
`mcp`'s `tools` or `allow`, or a `tool` on its server, names) and `integration-not-allowed` (an `mcp`, `skill`,
`agent` or `service` outside the allowed targets). A layer of the wrong shape is `invalid-metadata`.
```rust
use instruction_md::{check_reading, read, ReadOptions};
let served = "---\nhost-integrations:\n allowed: [\"https://cal.example.org/mcp\"]\n servers:\n \
\"https://cal.example.org/mcp\": {\"blocked\": [\"events.delete\"]}\n---\n\n\
::mcp{id=cal src=\"https://cal.example.org/mcp\" tools=\"events.list,events.delete\"}\n";
let r = read(served, &ReadOptions::default());
let policy = r.policy.as_ref().unwrap(); // None when the document has neither key
assert!(policy.targets_allowed(&["https://Cal.Example.org/mcp/"])); // targets compared normalized
assert!(policy.tool_blocked(&["https://cal.example.org/mcp"], "events.delete"));
let d = &check_reading(&r)[0];
assert_eq!((d.code, d.target.as_str()), ("tool-blocked", "events.delete"));
```
`ReadOptions::host` reads a document as if it were served with a host's layer (an editor before serving).
`remote_targets(kind, attrs)`, `named_tools(node, body)` and `normalize_target` are what the checks compare.
`layer_of`, `merge_policy`, `host_block` and `with_host_block` build the layers and the host's block.
`authored_candidates` takes the block out of a served text again (`verify_author` does).
### Resolve bases, includes and parameters
A document can extend others (`extends:` in the front matter) and include parts of them. The resolver fetches
nothing itself: you hand it a loader, or the sources already loaded.
```rust,no_run
use instruction_md::{resolve, ResolveOptions, Source};
std::fs::read_to_string(uri).ok().map(|text| Source { uri: uri.to_string(), text, version: String::new() })
};
let r = resolve("---\nextends:\n - { uri: base.md, as: base }\n---\nMUST: be brief.\n",
&ResolveOptions { uri: "instruction.md".into(), load: Some(&load), ..ResolveOptions::default() });
// r.ok: no error; r.text: the agent text; r.resolved: the instruction-resolved/1 artifact (to_json(), resolved_digest)
```
The same with the sources in memory, which runs as written:
```rust
use std::collections::HashMap;
use instruction_md::{resolve_with, ResolveOptions, Source};
let base = Source { uri: "base.md".into(), text: ":::instruction{id=tone}\nBe kind.\n:::\n".into(), version: String::new() };
let sources = HashMap::from([("base.md".to_string(), base)]);
let r = resolve_with("---\nextends:\n - { uri: base.md, as: base }\n---\nMUST: be brief.\n", &sources,
&ResolveOptions { uri: "instruction.md".into(), ..ResolveOptions::default() });
assert!(r.ok, "{:?}", r.diagnostics);
assert_eq!(r.text, "### Instruction: tone\n\nBe kind.\n\nMUST: be brief.\n");
assert!(r.resolved.resolved_digest.starts_with("sha256:"));
```
`resolve_tree` resolves JSON trees (the specification's resolution cases are trees). Composition is bounded: by
default 8 levels deep and 64 sources (`max_depth`, `max_sources`). Past either is an error, never a silently
truncated result.
### Verify a signed read
instruction.md signs every release. An **author attestation** signs the authored bytes. A **delivery attestation**
signs the text one reader received and the resolution's manifest, and embeds the author signature. See
[Signing and trust](https://instruction.md/docs/signing/).
```rust
use instruction_md::{verify_delivery, DeliveryVerifyOptions, Jwk};
fn admit(delivery_jws: &str, delivered_text: &str, delivery_keys: &[Jwk], publisher_keys: &[Jwk]) -> bool {
let r = verify_delivery(
delivery_jws,
delivered_text.as_bytes(),
delivery_keys,
publisher_keys,
&DeliveryVerifyOptions { aud: "principal://usr_1".into(), ..DeliveryVerifyOptions::default() },
);
if !r.ok {
// r.code is stable ("digest-mismatch", "expired", "bad-signature"… VERIFY_CODES); r.reason is for a person
eprintln!("refused ({}): {}", r.code, r.reason);
}
// when ok: r.claims are the delivery's, r.author the embedded author attestation's, both verified
r.ok
}
fn main() {
assert!(!admit("x.y.z", "text", &[], &[])); // garbage is refused
}
```
The delivery signature binds the delivered text's digest, the audience, the resolution manifest and the embedded
author signature, whose digest must be the resolved document's. The delivered capabilities may not exceed the
author's. `Resolved::manifest()` is what a delivery signs of its resolution (`Manifest::to_json()` is the
`manifest` claim).
An author signature on its own, signed and verified end to end. This example builds the claims with `serde_json`,
so add it to your project first (`cargo add serde_json`):
```rust
use instruction_md::{digest, sign_jws, verify_author, Object, SigningKey, VerifyOptions};
use serde_json::json;
let doc = "---\nspec: \"1\"\n---\nMUST: be brief.\n";
let key = SigningKey::generate().unwrap(); // a registry signs with its own keys; this is for tests
let jwk = key.public_jwk("k1");
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
let claims: Object = json!({
"spec": "instruction/1", "typ": "author", "doc": "instruction://ins_1", "version": "ver_1",
"digest": digest(doc.as_bytes()), "capabilities": ["default"],
"pub": "https://instruction.md/pub/acme", "iat": now, "exp": now + 3600,
}).as_object().unwrap().clone();
let jws = sign_jws(&claims, &key, "author");
let opts = VerifyOptions {
doc: "instruction://ins_1".into(),
publisher: "https://instruction.md/pub/acme".into(), // pin the publisher you trust
now: None,
};
let r = verify_author(&jws, doc.as_bytes(), &[jwk.clone()], &opts);
assert!(r.ok, "{r:?}");
let tampered = verify_author(&jws, b"MUST: be long.\n", &[jwk], &opts);
assert_eq!(tampered.code, "digest-mismatch");
```
Pin the publisher. Without `publisher` you learn that *somebody* signed the document; with it, that the publisher
you expected did. An organization's public keys are published at `instruction://pub/<owner>/keys.json`. Which keys
to trust (active, retired, revoked) is your decision: the crate verifies against the key set you pass.
### Digests, formatting and older syntax
```rust
use instruction_md::{author_digest, digest, format, front_matter_id, legacy_diagnostics};
let doc = "---\nid: acme/brief\n---\nMUST: be brief. \r\n";
assert!(digest(doc.as_bytes()).starts_with("sha256:")); // sha256:<64 lower hex>
assert_eq!(author_digest(doc.as_bytes()), digest(doc.as_bytes())); // the stored bytes, as they are
assert_eq!(front_matter_id(doc.as_bytes()).as_deref(), Some("acme/brief"));
// The conservative formatter: LF endings, one final newline; never what an agent receives
assert_eq!(format("MUST: be brief.\r\n\r\n"), "MUST: be brief.\n");
// Lines written in Specification 1.1, each an error with what it needs
let legacy = legacy_diagnostics(":::!policy\nBe kind.\n:::\n");
assert_eq!(legacy[0].code, "instruction.md/legacy-syntax");
```
This crate reports 1.1 lines; converting them is done by `upgrade()` in the npm package
[`instruction.md`](https://www.npmjs.com/package/instruction.md).
## Reference
Everything below is exported from the crate root unless a module path is given. Full signatures and field docs are
on [docs.rs](https://docs.rs/instruction-md).
### Constants
| `SPEC_COMMIT` | `"4bb0328"` | The specification commit the embedded registries and conformance data are from. |
| `TREE_FORMAT` | `"instruction/1"` | The authored tree's format. |
| `RESOLVED_FORMAT` | `"instruction-resolved/1"` | The resolved artifact's format. |
| `LEGACY_SYNTAX` | `"instruction.md/legacy-syntax"` | The diagnostic code of a line in Specification 1.1 syntax. |
| `WORKFLOW_DIALECT` | `"instruction/workflow"` | The workflow dialect `check_reading` checks. |
| `WORKFLOW_SCOPES` | `&[(&str, &str)]` | Scoping workflow kinds and the field holding their nested steps. |
| `HOST_POLICY_KEY` | `"host-integrations"` | The front matter key only the serving host writes. |
| `AUTHOR_POLICY_KEY` | `"integrations"` | The front matter key an author writes to narrow the host's policy. |
| `INTEGRATED_KINDS` | `["mcp", "skill", "agent", "service"]` | The kinds the integrations policy applies to. |
| `VERIFY_CODES` | 15 codes | Every `VerifyResult::code` (feature `verify`, see below). |
### Reading and checking
| `read` | `fn(&str, &ReadOptions) -> Reading` | Reads a document into its tree, with the reader's diagnostics in source order. |
| `check` | `fn(&str, &ReadOptions) -> Vec<Diagnostic>` | Reads and checks: the reader's, the inline and the workflow diagnostics. |
| `check_reading` | `fn(&Reading) -> Vec<Diagnostic>` | `check` for a document already read. |
| `inline_diagnostics` | `fn(&Reading) -> Vec<Diagnostic>` | The inline checks only, prose node by prose node. |
| `workflows_diagnostics` | `fn(&Reading) -> Vec<Diagnostic>` | Each `instruction/workflow` body's diagnostics, on the body's lines. |
| `deliver` | `fn(&str, Option<&Object>) -> (String, Vec<Diagnostic>)` | Agent text with declared defaults, plus every diagnostic including 1.1 lines. |
| `legacy_diagnostics` | `fn(&str) -> Vec<Diagnostic>` | The lines written in Specification 1.1 syntax, each an error. |
| `resolve_target` | `fn(&Reading, kind: &str, reference: &str) -> Target` | Where a typed reference points: `Target::Local { id, kind, matches }`, `Missing { id }` or `External { uri }`. |
| `split_backmatter` | `fn(&str) -> SplitBackmatter` | Cuts a document at its backmatter: `before`, `backmatter`, `range`, `data`, `diagnostics`. |
| `strip_comments` | `fn(line: &str, open: bool) -> Stripped` | Removes comment bytes from one line: `text`, `still_open`, `opened`, `only`. |
| `value_from` | `fn(&Parameter, &str) -> Value` | A value written as text, read as the parameter's declared type. |
| `value_fits` | `fn(&Parameter, &Value) -> bool` | Whether a value satisfies a parameter's declared type. |
| `read::requires_of` | `fn(&Reading) -> Vec<String>` | The capabilities an author attestation names: the families used, plus `agents` and `spending` grants. |
| `classify_lines` | `fn(&Reading) -> Vec<LineInfo>` | One class per line (`front-matter`, `code`, `heading`, `directive`, `keyword`, `prose`, …) for an editor. |
| `format` | `fn(&str) -> String` | The conservative formatter: LF endings, one final newline, no trailing whitespace on directive lines. |
| `inline_tokens` | `fn(&str) -> Vec<InlineToken>` | The inline forms in Markdown (directive, wiki, embed, footnote, math, param), byte offsets. |
| `split_wiki` | `fn(&str) -> (String, String, bool)` | Splits a wiki link's text into target, label, and whether it was piped. |
| `parse_attributes` | `fn(&str, spec_of, strict: bool) -> (Attrs, Vec<String>)` | Parses an attribute list's text into attributes and problems. |
| `parse_yaml` | `fn(&str) -> Result<Value, String>` | YAML 1.2 Core Schema, JSON-compatible values only, as metadata is read. |
`ReadOptions` (all `Default`):
| `fragment` | `bool` | `false` | Read a part of a document, with no metadata regions. |
| `uri` | `String` | `""` | The document's URI, which the tree carries. |
| `host` | `Option<PolicyLayer>` | `None` | Read as if served with this `host-integrations` layer. One in the front matter wins. |
`Reading` fields: `document: Document`, `diagnostics: Vec<Diagnostic>`, `identities: Vec<Identity>`,
`parameters: Vec<Parameter>`, `footnotes: BTreeMap<String, u32>`, `comments: BTreeSet<u32>` (comment-only lines),
`lines: Vec<String>`, `front_range: Option<Range>`, `back_range: Option<Range>`, `policy: Option<Policy>`.
Methods: `text(Option<&Object>) -> String`, `changes_text()`, `has_errors()`, `identity(id)`, `parameter(name)`,
`source()`, `line_offset(line)`.
### Agent text
| `Reading::text` | `fn(&self, Option<&Object>) -> String` | The agent text (`instruction-text/1`) with supplied parameter values. |
| `to_text` | `fn(&Document, &TextOptions) -> String` | The text profile of any tree, for example a resolved body. |
| `value_text` | `fn(&Value) -> Option<String>` | How a parameter value reads in text; `None` for null. |
`TextOptions` (all `Default`): `params: Option<Object>`, `parameters: Vec<Parameter>`, `use_prose: bool`,
`identities: Option<Vec<Identity>>` (`None`: no `#id` is checked), `known: Option<Known>` (for a resolved body:
does an instance have an id). A reference to a missing id reads `[unresolved]`.
### Tree types
| `Document` | `format`, `uri`, `metadata: Metadata { front, back }`, `body: Vec<Node>`. `new(body)`, `to_json()`, `from_json(&Value)`. |
| `Node` | `node_type: NodeType` (`Markdown`, `Directive`), `kind`, `form: Option<Form>`, `attrs`, `children`, `value: Option<StructuredValue>`, `source`, `range`, `instance`. Methods: `markdown(..)`, `directive(..)`, `is_markdown`, `is_directive`, `keyword`, `reason_range`, `is_prose`, `body_source`, `children()`, `attr_str`, `to_json`, `from_json`. |
| `Form` | `Container` (`:::kind … :::`), `Leaf` (`::kind{…}`), `Keyword` (`MUST: …`), `Alert` (`> [!TIP]`). `as_str`, `parse`. |
| `StructuredValue` | A structured body: `format` (`yaml`, `json`, `csv`, `text`, `html`, `code`), `source`, `data: Option<Value>`. |
| `Range` | 1-based inclusive lines: `start`, `end`. `new`, `line`, `to_json`. |
| `Diagnostic` | `code: &'static str`, `severity: Severity`, `message`, `uri`, `range`, `target`, `remedy`. `line()`, `is_error()`, `to_json()`, `Display`. |
| `Severity` | `Error`, `Warning`, `Info`. |
| `Identity` | An explicit id: `id`, `kind`, `line`. |
| `Parameter` | `name`, `param_type`, `required`, `values`, `default`, `example`, `description`, `source`, `line` (0: front matter). |
| `Object`, `Attrs` | `serde_json::Map<String, Value>`. |
| `LineInfo` | `class`, `label_end`, `keyword`, `kind`. |
| `InlineToken`, `TokenType` | An inline form: `token_type`, `start`, `end` (byte offsets), `kind`, `label`, `attributes`, `target`, `piped`, `formula`, `name`. |
### Connected objects and configuration
| `connected_objects` | `fn(&[Node]) -> Vec<ConnectedObject>` | Every connected object in document order, wherever it stands. |
| `configuration_blocks` | `fn(&[Node]) -> Vec<ConfigurationBlock>` | Every configuration block in document order. |
| `walk` | `fn(&[Node], &mut dyn FnMut(&Node, &[&Node]) -> bool)` | Visits every directive with its ancestors; return `false` to skip its children. |
| `is_connected`, `carries_configuration`, `is_layout` | `fn(kind: &str) -> bool` | A kind's role, by the registry's families. |
`ConnectedObject`: `node`, `kind`, `form`, `id`, `title`, `description`, `src`, `endpoint`, `attrs`, `body`,
`location`; `attr(key)`, `list(key)` (`tools`, `allow`, `deny`, `skills`). `ConfigurationBlock`: `node`, `kind`,
`id`, `title`, `dialect`, `adapter`, `target`, `schema`, `schema_sha256`, `format`, `data`, `body`, `attrs`,
`location`; `attr(key)`. `Location`: `range`, `parents` (kinds, outermost first), `instance`; `in_layout()`,
`line()`.
### Integrations policy
| `Policy` | The effective policy: `allowed: Option<Vec<String>>`, `servers: BTreeMap<String, ServerPolicy>`, `from: PolicyFrom { host, author }`. `tool_blocked(targets, tool)`, `targets_allowed(targets)`, `to_json()`. |
| `PolicyLayer` | One layer as written: `allowed`, `servers: Option<BTreeMap<String, ServerTools>>`. |
| `ServerTools` | `allowed`, `blocked`, `default: Option<ToolDefault>`. |
| `ServerPolicy` | `blocked`, `default: ToolDefault`, `allowed`. |
| `ToolDefault` | `Allowed` (the default) or `Blocked` (new tools blocked until reviewed). |
| `LayerProblem` | `key`, `message`: an `invalid-metadata` error. |
| `NamedTools` | `targets`, `tools`. |
| `layer_of(&Value, key)` | A layer from its front matter value, with its problems. |
| `merge_policy(host, author)` | The layers merged; `None` when neither is given. |
| `normalize_target(&str)` | A target as compared: an http(s) URL as the WHATWG parser serializes it, without default port, credentials, fragment or trailing slash; anything else trimmed and lower-cased. |
| `remote_targets(kind, &Attrs)` | The targets by which an object reaches outside its document. |
| `named_tools(&Node, body)` | The tools an object names, and its server's targets. |
| `host_block(layer)`, `with_host_block(text, block)` | The host's `host-integrations` lines, and the text as served with them. |
| `authored_candidates(&[u8])` | What an author may have signed, given a served text. |
### Resolution
| `resolve` | `fn(&str, &ResolveOptions) -> Resolution` | Reads, loads what the document composes through `opts.load` (each source once), composes. |
| `resolve_with` | `fn(&str, &HashMap<String, Source>, &ResolveOptions) -> Resolution` | The same over sources already loaded, by resolved URI. |
| `resolve_tree` | `fn(&Document, &HashMap<String, Document>, &ResolveOptions) -> Resolution` | Resolves JSON trees; a tree's digest is its canonical JSON's. |
| `references_of` | `fn(&Reading, base: &str) -> Vec<String>` | The sources a document composes (its bases and includes), as resolved URIs. |
| `resolve_uri` | `fn(reference: &str, base: &str) -> String` | RFC 3986 reference resolution. |
| `slug` | `fn(&str) -> String` | A heading's generated anchor. |
| `resolve::allowance_of` | `fn(text, id, &sources, &ResolveOptions) -> Option<(Object, Vec<Diagnostic>)>` | One allowance as a host applies it, parameters filled in. |
`ResolveOptions` (all `Default`):
| `uri` | `String` | `"document.md"` when empty | The document's URI; relative references resolve against it. |
| `version` | `String` | `""` | The document's version, recorded in the artifact. |
| `params` | `Object` | empty | Parameter values. A base gets its record's `with`. |
| `load` | `Option<Loader>` | `None` | `&dyn Fn(&str) -> Option<Source>`; `resolve` only. `None` from it: absent or not readable. |
| `max_depth` | `usize` | 8 when 0 | Deepest composition. |
| `max_sources` | `usize` | 64 when 0 | Most sources. |
`Source { uri, text, version }`. `Resolution { ok, resolved: Resolved, text, diagnostics, root: Reading }`.
`Resolved { format, status ("complete" or "partial"), document: ResolvedDocument { uri, sha256, version }, body,
extensions, objects, resources, dependencies, provenance, diagnostics, resolved_digest }`, with `manifest()` and
`to_json()`. `Manifest { format, status, document, dependencies, resolved_digest }`. `Dependency`, `Provenance`,
`ExtensionBinding`, `Selector` (`Id`, `Heading`, `Lines`), `ReferenceRecord`: each with `to_json()`.
### Signatures (feature `verify`)
| `verify_author` | `fn(jws, authored: &[u8], keys: &[Jwk], &VerifyOptions) -> VerifyResult` | Verifies an author signature over the authored bytes. A served text's `host-integrations` block is outside them. |
| `verify_delivery` | `fn(jws, delivered: &[u8], delivery_keys, author_keys, &DeliveryVerifyOptions) -> VerifyResult` | Verifies a delivery signature, then the embedded author signature. |
| `public_jwk` | `fn(public_key: &[u8], kid: &str) -> Jwk` | The JWK (OKP, Ed25519) of a raw 32-byte public key. |
| `SigningKey` | `from_seed(&[u8])`, `generate()`, `public_key()`, `public_jwk(kid)` | An Ed25519 key, for tests and tooling. |
| `sign_jws` | `fn(&Object, &SigningKey, typ: &str) -> String` | Signs claims as a compact EdDSA JWS. |
| `verify::b64url_encode`, `verify::b64url_decode` | | Base64url without padding. |
`Jwk` is `Object`. `VerifyOptions`: `doc` (the expected `doc` claim; empty: any), `publisher` (the pinned `pub`;
empty: any), `now: Option<i64>` (Unix seconds; `None`: now). `DeliveryVerifyOptions`: `aud` (required: this
reader's audience), `authored: Option<Vec<u8>>` (when known, the author digest must be theirs), `publisher`, `now`.
`VerifyResult { ok, code, claims, author, reason }`.
| `ok` | Verified. |
| `malformed` | Not a compact JWS, or a part that is not base64url JSON. |
| `unknown-key` | No key in the set is an Ed25519 JWK to try. |
| `bad-algorithm` | The header's `alg` is not `EdDSA`. |
| `bad-signature` | No key in the set verifies the signature. |
| `unknown-format` | The `spec` claim is not `instruction/1`. |
| `typ-mismatch` | The `typ` claim (or header) is not the attestation expected. |
| `expired` | The `exp` claim is past. |
| `digest-mismatch` | A digest is not the bytes': authored, delivered, or the resolved document's. |
| `doc-mismatch` | The author's `doc` is not the expected one, or not the delivery's. |
| `unpinned-publisher` | The `pub` claim is not the pinned publisher. |
| `audience-mismatch` | The delivery's `aud` is not this reader. |
| `manifest-invalid` | The delivery does not name its resolution. |
| `author-missing` | The delivery embeds no author signature. |
| `capabilities-exceeded` | The delivery's capabilities exceed the author attestation's. |
A delivery whose embedded author signature fails has that signature's code.
### Digests and canonical JSON
| `digest(&[u8])` | `sha256:<hex>` of bytes. |
| `digest_text(&str)` | The digest of a text's UTF-8 bytes. |
| `author_digest(&[u8])` | The digest an author signature binds: the stored bytes as they are. Same as `digest`. |
| `front_matter_id(&[u8])` | The front matter's `id`, the value an attestation's `doc` claim names. |
| `sha256_hex(&[u8])`, `digest::sha256(&[u8])` | Lower-hex and raw SHA-256 (the crate's own, no `ring`). |
| `canonical_json(&Value)`, `json_digest(&Value)` | RFC 8785 canonical JSON, and its digest. |
| `js_number(f64)` | How ECMAScript writes a number. |
### Registry
| `registry()` | The embedded specification registry, typed (`Registry`: `format`, `spec`, `common_attributes`, `kinds`, `inline`, `keywords`, `keyword_flags`; `kind(name)` and the grammar's patterns). |
| `registry::kind(name)` | A block kind's `KindSpec`: `body`, `forms`, `attributes`, `required`, `family`, `alias`, `flags`, `parent`, `opaque`, `formats`. |
| `attr_spec(kind, key)`, `inline_attr_spec(kind, key)` | An attribute's `AttrSpec` (`attr_type`, `enum_values`, `pattern`, `minimum`, `maximum`, `items`). |
| `canonical_kind(kind)`, `is_rule(kind)`, `all_families()` | A kind's normalized meaning (`always` → `must`), whether it is a rule, every family. |
| `registry::{RULES, TYPED_REFERENCES, FRONT_MATTER_KEYS, BACKMATTER_KEYS, PRESENTATION_ATTRS, REGISTRY_JSON, inline_required}` | The registry's lists, and the raw JSON. |
| `Pattern` | The crate's linear-time regular expressions: `new`, `is_match`, `find`, `find_str`, `captures`, `find_iter`, `captures_iter`, `replace_all`, `captures_at`. |
### Workflows
| `workflow_diagnostics(&Value, extensions: Option<&Object>)` | A workflow definition's diagnostics, without lines. |
| `workflow_registry()` | The embedded workflow registry (`WorkflowRegistry`: `format`, `dialect`, `revision`, `kinds: WorkflowKind`, `common_fields`, `limits: WorkflowLimits { steps, body_depth, retry_max }`). |
| `workflow_scope(kind)` | The field that holds a scoping kind's nested steps. |
### Modules for hosts
These are public modules, used by path:
- `allowance`: spending allowances, the first edition's `allowance` blocks (§10.1). `typed(&Map) -> Allowance` (`id`, `title`, `wallets`,
`currency`, `max`, `budget`, `per`, `times`, `payees`, `categories`, `from`, `until`, `approve_above`,
`approver`; amounts are decimal strings, never floats), `problems`, `unresolved`, `widenings(before, after)`,
`sentence`, `instant`, `list`, `protocol_ok`, `PERIODS`, `PARAMETER_KEYS`, `Problem { code, message }`.
- `protocol`: protocol values such as `a2a` or `x402/1,2`, and the versions two sides share (what a host needs to
decide `protocol-unsupported`). `parse(&str) -> Option<Protocol { name, versions }>`,
`Compat` (`Exact`, `SemverMinor`, `Date`), `compatible(compat, want, have)`, `shared_versions`.
- `bindings`: protocol bindings. `known(name)`, `x402()`, `openapi()`, `binding_from(&Value)`,
`Binding { id, version, name, versions, compat, kinds, meaning }` with `stable()`, `Maturity` (`Draft`, `Stable`,
`Deprecated`).
- `jcs`, `digest`, `inline`, `lines`, `objects`, `policy`, `read`, `registry`, `resolve`, `text`, `types`, `verify`,
`workflow`, `yaml`, `check`, `attributes`, `legacy`: the modules behind the root re-exports.
The crate reads no environment variables and no configuration files.
## Limits
Guards for hostile input:
- Directives nest at most 128 deep. A deeper opener stays prose, with an `invalid-nesting` diagnostic.
- YAML nests at most 256 deep.
- Directive labels are scanned for nested forms 32 deep.
- Patterns run on a Pike VM, linear in their input.
- Composition stops at 8 levels and 64 sources by default, with an error.
Offsets (`InlineToken::start`, …) are byte offsets into the source.
## Security
- **No I/O.** The crate opens no files and no connections and reads no environment variables. What it reads is
what you pass. With the `verify` feature it reads the system clock (unless you pass `now`) and, in
`SigningKey::generate()`, the operating system's random number generator.
- **Untrusted input.** Every entry point is meant for untrusted text: no panics, no `unsafe`, bounded nesting.
- **Signatures.** Ed25519 over compact JWS (`alg: EdDSA`), through `ring`. Other algorithms are refused
(`bad-algorithm`). Pin the publisher and the document (`VerifyOptions::publisher`, `doc`) or you only learn that
someone signed. Key state (active, retired, revoked) is yours to apply before you pass the key set.
- **Not reviewed.** The verification has not had an independent security review yet.
- **What a signature means.** It proves who published the bytes, not that following them is safe. See
[Signing and trust](https://instruction.md/docs/signing/).
Report a vulnerability privately, not in a public issue: write to us through
[Contact us](https://instruction.md/contacts/) and say it is a security report. Include what you found, how to
reproduce it (a document or code that shows it) and the crate version. Fixes go into the latest release.
## Compatibility and versioning
- The crate follows [semantic versioning](https://semver.org/). While it is 0.x, a minor version (0.5 → 0.6) may
break the API, and a patch version does not. The [changelog](https://docs.rs/crate/instruction-md/latest/source/CHANGELOG.md) marks every break as **Breaking**.
- Build option structs with `..Default::default()` (`ReadOptions`, `ResolveOptions`, `VerifyOptions`,
`DeliveryVerifyOptions`, `TextOptions`): new fields have been added in minor versions.
- It reads the specification's first edition, `instruction/1` (`spec: "1"`). Documents in the older 1.1 syntax are
reported (`instruction.md/legacy-syntax`), not converted.
- Each release names the specification commit it implements (`SPEC_COMMIT`).
- The minimum Rust version is 1.96. Raising it is a minor-version change.
### How it differs from the Go SDK
- The YAML reader is this crate's own (Go wraps `gopkg.in/yaml.v3`). The values and every refusal the
specification names (repeated keys, anchors and aliases, tags, non-string keys, non-finite numbers, a second
document) are the reference's, with its messages; a syntax error's wording is this reader's. Where yaml.v3 (a
YAML 1.1 reader) and the reference's YAML 1.2 reader disagree, this crate reads as the reference does: `?` inside
a plain scalar in a flow collection (`{ uri: https://example.org/?q }`) and `key:[…]` in a flow mapping are
values, and a flow collection's or quoted scalar's continuation lines must be indented past their block
collection.
- The inline tokenizer is a hand-written scanner with micromark's precedence (Go ports micromark itself): code
spans, escapes, autolinks, raw HTML, link destinations and titles, definitions, tables and GFM autolink literals
hide the forms, as there. It passes every inline vector and the read vectors.
- Patterns use this crate's small regular-expression engine.
- Policy targets: a host with non-ASCII characters is lower-cased, not converted to its IDNA (punycode) form.
### Coming from `agentd-instruction`
`agentd-instruction` reads the 1.1 syntax; this crate reads `instruction/1`. Where a concept carried over:
| `parse(text) -> Result<Document, Vec<Refusal>>` | `read(text, &ReadOptions) -> Reading` | `reading.document` is the tree; `reading.diagnostics` (plus `check_reading` for the inline checks) replace the `Err`; `reading.has_errors()` |
| `Refusal { line, code, message }` | `Diagnostic { code, severity, message, range, uri, … }` | same stable codes as the Go/TS readers; `d.line()` is `range.start`; warnings too, not only refusals |
| `deliver(&doc, &ctx) -> Delivery { text, manifest }` | `reading.text(params)`, or `resolve(...) -> Resolution { text, resolved, ok, diagnostics }` | `deliver(text, params)` is the one-call shortcut |
| `Context { params, resolve_include, .. }` | `ResolveOptions { params, load, uri, .. }`, `TextOptions { params, .. }` | instruction/1 has no grants, facts or variants |
| `Manifest` (§7.4) | `Resolved::manifest() -> Manifest` | format, status, document (the authored digest and version), dependencies (the includes and bases), resolved_digest; no facts or variants in instruction/1 |
| `digest(&[u8])` | `digest(&[u8])` | `sha256:<hex>` |
| `author_digest(&[u8])` | `author_digest(&[u8])` | the stored bytes as they are: in instruction/1 no `signature:` line is left out |
| `front_matter_id(&[u8])` | `front_matter_id(&[u8])` | read from the front matter by the YAML reader |
| `doc::Node`, `doc::Block` | `Node` (`node_type`: `Markdown` or `Directive`) | a block is a directive node: `kind`, `form`, `attrs`, `children`, `value`, `range` |
| `doc::Form` | `Form` (`Container`, `Leaf`, `Keyword`, `Alert`) | no sets or sections in instruction/1 |
| `doc::BodyKind` | `KindSpec::body` (`markdown`, `yaml`, `none`) and `StructuredValue::format` (`yaml`, `json`, `csv`, `text`, `html`, `code`) | from `registry().kind(name)` |
| `doc::Disposition` | `is_connected`, `carries_configuration`, `is_layout` | by the registry's families: `connected_objects`, `configuration_blocks`, `walk` |
| `doc::all_families()` | `all_families()` | the registry's families |
| `doc::lookup(kind)`, `registry()` | `registry::kind(kind)`, `registry()` | the embedded `registry.json`, typed |
| `tree_json(&doc)` | `Document::to_json()` | the tree `instruction.schema.json` validates |
| `validate(&doc, &ctx)` | `check_reading(&reading)` | |
| `yaml::parse(src) -> Result<Value, YamlError>` | `parse_yaml(src) -> Result<Value, String>` | YAML 1.2 Core Schema, JSON-compatible values only |
| `sign::verify_author`, `sign::verify_delivery`, `sign::verify_document` | `verify_author`, `verify_delivery` | keys as JWKs (`public_jwk(raw, kid)`); results are `VerifyResult { ok, code, claims, author, reason }` |
| `sign::Claims` | `VerifyResult::claims` (a JSON object) | |
## Troubleshooting and FAQ
**`cargo` says the crate needs a newer Rust.** It needs Rust 1.96 or later. Run `rustup update stable`.
**`ring` fails to build on my target.** Turn the `verify` feature off (`default-features = false`). Reading,
checking, resolving and digests still work.
**`verify_author` and friends are not found.** They need the `verify` feature, which is on by default. Check that
you did not set `default-features = false`.
**My struct literal for `ReadOptions` stopped compiling after an upgrade.** A field was added. Write
`ReadOptions { uri: "…".into(), ..ReadOptions::default() }`.
**A `:::!policy` block reads as plain text.** That is the 1.1 syntax. `deliver` and `legacy_diagnostics` report
each such line as `instruction.md/legacy-syntax`. Convert the file with `upgrade()` from the npm package
[`instruction.md`](https://www.npmjs.com/package/instruction.md).
**`resolve` reports a base or include as missing.** The resolver fetches nothing. Your loader got the resolved URI
(relative to `ResolveOptions::uri`, without a fragment) and returned `None`. Log the URIs it is asked for, or use
`references_of` to list them first.
**`verify_delivery` says `audience-mismatch`.** `DeliveryVerifyOptions::aud` must be exactly the audience the
delivery was signed for (the reader's principal).
**Can this crate follow an instruction over MCP?** No, it does no I/O. Use the npm or Python package, or connect
your agent to `https://instruction.md/mcp`. See [Connect an agent](https://instruction.md/docs/connect/).
## Contributing
Bug reports and fixes are welcome. Open an [issue](https://github.com/instruction-md/specification/issues) (start
the title with "Rust SDK") with the document or code you ran, what came out, what you expected, and the crate
version; a failing test is best. For a new API, open an issue first so we can agree on its shape.
The crate is held to the TypeScript reference and the Go SDK byte for byte, so a fix that makes it disagree with
them needs the same fix there. It keeps three rules: no `unsafe` and no panic on any input, no I/O, and no new
dependencies without discussion. The tests read the conformance data in the crate's source repository (it is left
out of the crates.io package):
```sh
cargo test # the conformance cases and vectors, the reader, resolution, signatures, no-panic
cargo test -- --nocapture # with each conformance suite's count
NO_PANIC_ROUNDS=2000 cargo test --release --test no_panic # a longer randomized search
cargo test --no-default-features # without signature verification (and ring)
```
A change to what the language means belongs in the
[specification](https://github.com/instruction-md/specification), not here.
## Changelog
See [CHANGELOG.md](https://docs.rs/crate/instruction-md/latest/source/CHANGELOG.md). Releases are tagged `rust-sdk-v<version>` and published to
[crates.io](https://crates.io/crates/instruction-md/versions).
## License
Licensed under either of the [MIT license](https://docs.rs/crate/instruction-md/latest/source/LICENSE-MIT) or the [Apache License, Version 2.0](https://docs.rs/crate/instruction-md/latest/source/LICENSE-APACHE), at
your option. Unless you say otherwise, a contribution you submit for inclusion in this crate is licensed as above,
without other terms.
The embedded registries (`src/registry.json`, `src/workflow-registry.json`) are the instruction.md specification's,
redistributed verbatim under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). See [`NOTICE`](https://docs.rs/crate/instruction-md/latest/source/NOTICE).
Copyright (c) 2026 TSOK Inc.