لم تُترجم هذه الصفحة بعد.

Rust

The Rust crate instruction-md reads, checks and resolves instruction.md documents, gives the exact text an agent receives, and verifies author and delivery signatures. It is published on crates.io, imported as instruction_md, under MIT OR Apache-2.0. This page describes version 0.6.1.

The crate does no I/O. It doesn't talk to a registry, follow an instruction over MCP, or report what was applied. Your code fetches the text, from a file, the registry or an editor, and hands it to the crate. To follow an instruction from Rust today, connect your agent to the MCP server (Connect an MCP client) and pass what it reads to the crate, or use the Python, Go or JavaScript follower.

Status

Version 0.6.1, pre-1.0. A minor version may still break the API; the crate's changelog marks each break as Breaking.
Specification First edition, instruction/1 (spec: "1"). The embedded registries are from specification commit 4bb0328, exposed as SPEC_COMMIT.
Conformance The test suite runs the specification's conformance cases and the reference's vectors, and agrees with them byte for byte.
Rust 1.96 or later, edition 2024. Raising the minimum is a minor-version change.
Dependencies serde, serde_json, and ring for signatures only.
Safety No unsafe (#![forbid(unsafe_code)]). Every entry point takes untrusted text and never panics.
Review The signature verification follows the specification and is tested against the reference. It has not had an independent security review.
Source The full source ships in the crates.io package; browse it on docs.rs. The crate's own repository isn't public yet, so its Repository link on crates.io doesn't open.

Install

Shell
cargo add instruction-md

or in Cargo.toml:

Cargo.toml
[dependencies]
instruction-md = "0.6"
Feature Default Adds
verify yes 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, with its own SHA-256. Turn it off when ring doesn't build on your target:

Cargo.toml
[dependencies]
instruction-md = { version = "0.6", default-features = false }

Every function is synchronous, with no runtime. Nothing touches files, the network or environment variables. With verify, verification reads the system clock unless you pass now, and SigningKey::generate() uses the operating system's random number generator.

Read, check and give the agent its text

Put this in src/main.rs and run cargo run:

src/main.rs
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));
}

It prints the agent text, with the default for tz filled in and the front matter gone:

Output
# Morning brief

MUST: plan the day in UTC.
BECAUSE: the owner reads the brief at 7.

NEVER: book a meeting before 9.

read returns a Reading: the tree (reading.document), the reader's diagnostics, the identities, the declared parameters and the effective integrations policy. check_reading adds the inline and 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, so a host may pass an unchanged source on as it is.

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 (instruction.md/legacy-syntax, an error):

Rust
let (text, diagnostics) = instruction_md::deliver("MUST: be brief.\n", None);
assert_eq!(text, "MUST: be brief.\n");
assert!(diagnostics.is_empty());

Parameter values

A supplied value replaces the declared default. Object is serde_json::Map<String, serde_json::Value>.

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(&params)), "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));

Diagnostics as JSON

Every diagnostic has a stable code, a severity (Error, Warning, Info), a message, and optionally a range (1-based lines), uri, target and remedy. to_json() gives the specification's shape, for CI output or an editor. The codes are the ones the Go and TypeScript readers emit; Diagnostics lists them.

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");

Connected objects, configuration and workflows

connected_objects lists the kinds a typed reference names: a person, role, skill, MCP server, tool, agent, service, source or resource. configuration_blocks lists the structured bodies of the technical family. A host uses both to wire an instruction up.

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

walk(body, visitor) visits every directive with the directives that hold it. check_reading holds every :::workflow{dialect="instruction/workflow"} body to the specification's workflow registry and graph rules: invalid-workflow, limit-exceeded and extension-unavailable, each an error on the line of its key. See Workflow node reference.

The integrations policy

A workspace's policy travels in the front matter: host-integrations, which only the serving host writes, and integrations, the author's, which can only narrow it. The reader merges them into Reading::policy and warns, never refuses: tool-blocked and integration-not-allowed. A layer of the wrong shape is invalid-metadata. See Tools and integrations.

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. authored_candidates takes the host's block out of a served text again, as verify_author does.

Resolve bases, includes and parameters

The resolver fetches nothing. You hand it a loader, or the sources already loaded:

With a loader
use instruction_md::{resolve, ResolveOptions, Source};

let load = |uri: &str| -> Option<Source> {
    // the host loads sources (a file, a registry, an editor's workspace); the resolver fetches nothing itself
    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)
With sources in memory
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. Composition stops at 8 levels and 64 sources by default (max_depth, max_sources); past either is an error, never a truncated result. See Composition.

Verify a signed read

An organization's release on instruction.md carries an author attestation, which signs the authored bytes. A delivery attestation signs the text one reader received and the resolution's manifest, and embeds the author signature. Signing and verification explains both.

Verify a delivery
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.

An author signature on its own, signed and verified end to end. It builds the claims with serde_json, so cargo add serde_json first:

Verify an author signature
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; with it, that the publisher you expected did. An organization's public keys are 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.

VerifyResult { ok, code, claims, author, reason }. Match on code; reason is for a person.

codeWhen
okVerified.
malformedNot a compact JWS, or a part that is not base64url JSON.
unknown-keyNo key in the set is an Ed25519 JWK to try (an empty set, or none usable).
bad-algorithmThe header's alg is not EdDSA.
bad-signatureNo key in the set verifies the signature.
unknown-formatThe spec claim is not instruction/1.
typ-mismatchThe typ claim (or the header's) is not the attestation expected (author, delivery).
expiredThe exp claim is past.
digest-mismatchA digest is not the bytes': the authored bytes' (author), the delivered bytes' (delivery), or the resolved document's (the embedded author's).
doc-mismatchThe author's doc is not the one expected, or the embedded author's doc or version is not the delivery's.
unpinned-publisherThe publisher (pub) is not the pinned one.
audience-mismatchThe delivery's aud is not this reader.
manifest-invalidThe delivery does not name its resolution (format instruction-resolved/1, document, dependencies, resolved_digest).
author-missingThe delivery embeds no author signature.
capabilities-exceededThe delivery's capabilities exceed the author attestation's.

A delivery whose embedded author signature fails has that signature's code.

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");

The crate reports lines in the 1.1 syntax but doesn't convert them. upgrade() in the npm package instruction.md converts them; see Upgrade from 1.1.

API

Everything is exported from the crate root unless a module path is given. Full signatures are on docs.rs.

Reading and checking

Item Signature What it does
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, workflows_diagnostics fn(&Reading) -> Vec<Diagnostic> The inline checks only; each workflow body's diagnostics.
deliver fn(&str, Option<&Object>) -> (String, Vec<Diagnostic>) The agent text with declared defaults, and every diagnostic including 1.1 lines.
legacy_diagnostics fn(&str) -> Vec<Diagnostic> Each line in Specification 1.1 syntax, as an error.
resolve_target fn(&Reading, kind, reference) -> Target Where a typed reference points: Local, Missing or External.
split_backmatter, strip_comments A document cut at its backmatter; comments removed from one line.
value_from, value_fits A parameter value from text, and checked against its type.
classify_lines fn(&Reading) -> Vec<LineInfo> One class per line, for an editor.
format fn(&str) -> String LF endings, one final newline, no trailing whitespace on directive lines.
inline_tokens, split_wiki, parse_attributes, parse_yaml The inline forms with byte offsets; wiki links; attribute lists; YAML 1.2 Core Schema as metadata is read.

ReadOptions (all Default): fragment: bool, uri: String, host: Option<PolicyLayer>. Reading fields: document, diagnostics, identities, parameters, footnotes, comments, lines, front_range, back_range, policy. Methods: text(params), changes_text(), has_errors(), identity(id), parameter(name), source(), line_offset(line).

Tree and text

Document (format, uri, metadata, body; to_json, from_json), Node, Form (Container, Leaf, Keyword, Alert), StructuredValue, Range, Diagnostic, Severity, Identity, Parameter, Object, Attrs, LineInfo, InlineToken. to_text(&Document, &TextOptions) gives the text profile of any tree; value_text how a parameter value reads in text.

Connected objects and configuration

connected_objects, configuration_blocks, walk, and is_connected, carries_configuration, is_layout (a kind's role by the registry's families). ConnectedObject has kind, id, title, src, endpoint, attrs, body, location, with attr(key) and list(key).

Integrations policy

Policy (tool_blocked, targets_allowed, to_json), PolicyLayer, ServerTools, ServerPolicy, ToolDefault, LayerProblem, NamedTools, layer_of, merge_policy, normalize_target, remote_targets, named_tools, host_block, with_host_block, authored_candidates, HOST_POLICY_KEY, AUTHOR_POLICY_KEY, INTEGRATED_KINDS.

Resolution

Item Signature What it does
resolve fn(&str, &ResolveOptions) -> Resolution Reads, loads what the document composes through opts.load, each source once, and 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.
references_of, resolve_uri, slug The sources a document composes; RFC 3986 resolution; a heading's anchor.
resolve::allowance_of One allowance as a host applies it, parameters filled in.

ResolveOptions (all Default): uri ("document.md" when empty), version, params, load (resolve only), max_depth (8 when 0), max_sources (64 when 0). Resolution { ok, resolved, text, diagnostics, root }. Resolved::manifest() is what a delivery signs of its resolution.

Signatures (feature verify)

verify_author(jws, authored, keys, &VerifyOptions), verify_delivery(jws, delivered, delivery_keys, author_keys, &DeliveryVerifyOptions), public_jwk(raw, kid), SigningKey (from_seed, generate, public_key, public_jwk), sign_jws, verify::b64url_encode and b64url_decode. VerifyOptions: doc, publisher, now. DeliveryVerifyOptions: aud (required), authored, publisher, now. Jwk is Object.

Digests, registry and modules

  • Digests: digest, digest_text, author_digest, front_matter_id, sha256_hex, digest::sha256, canonical_json, json_digest, js_number.
  • The embedded registry: registry(), registry::kind(name), attr_spec, inline_attr_spec, canonical_kind, is_rule, all_families(), and Pattern, the crate's linear-time regular expressions.
  • Workflows: workflow_diagnostics, workflow_registry(), workflow_scope, WORKFLOW_DIALECT, WORKFLOW_SCOPES.
  • Constants: SPEC_COMMIT, TREE_FORMAT, RESOLVED_FORMAT, LEGACY_SYNTAX, VERIFY_CODES.
  • Modules for hosts: allowance (spending allowances; see Allowances), protocol (protocol values and the versions two sides share), bindings (protocol bindings such as x402 and openapi).

The crate reads no environment variables and no configuration files.

Limits

  • 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 and the rest) are byte offsets into the source.

Versioning

  • The crate follows semantic versioning. While it is 0.x, a minor version may break the API and a patch version doesn't.
  • Build option structs with ..Default::default() (ReadOptions, ResolveOptions, VerifyOptions, DeliveryVerifyOptions, TextOptions): new fields have been added in minor versions.
  • Depend on a minor line, such as instruction-md = "0.6", and read the changelog before you move to the next.

If it doesn't work

What you see What to do
cargo says the crate needs a newer Rust It needs Rust 1.96 or later. Run rustup update stable.
ring fails to build on your target Turn verify off (default-features = false). Reading, checking, resolving and digests still work.
verify_author is not found It needs the verify feature, which is on by default. Check you didn't set default-features = false.
A 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. Convert the file with upgrade(); see Upgrade from 1.1.
resolve reports a base or include as missing Your loader got the resolved URI (relative to ResolveOptions::uri, without a fragment) and returned None. List the URIs first with references_of.
verify_delivery says audience-mismatch DeliveryVerifyOptions::aud must be exactly the audience the delivery was signed for.

Report a vulnerability through Support, not a public issue.

Last checked against the product:

Was this page helpful? Report a problem