Skip to main content

instruction.md (Python)

The instruction.md specification's first edition (instruction/1) in Python: the reader and its checks, the inline syntax, resolution and the agent's text profile, the registry, the formatter, digests and signature verification — and a follower for instructions served over MCP. It is a port of the TypeScript reference, instruction.md on npm, byte-exact with its vectors and with the specification's conformance data.

pip install instruction.md               # Python 3.9 or later; PyYAML is its one dependency
pip install 'instruction.md[sign]'       # signature verification (cryptography)
pip install 'instruction.md[mcp]'        # following over MCP (the official mcp SDK 2.3 or later, Python 3.10 or later)
from instruction_md import check, digest, read, resolve

text = """---
spec: "1"
title: House style
parameters:
  audience: { type: string, default: developers }
---

# House style

You write for ${audience}.

MUST: write in the second person.
BECAUSE: the reader is the one acting.

NEVER: promise a date you cannot keep.
"""

r = read(text)
print(r.document.to_json()["format"])  # instruction/1: the authored tree, as the schema has it
print(check(r))                         # []: no diagnostics
res = resolve(text, uri="house-style.md", params={"audience": "support engineers"})
print(res.ok)                           # True
print(res.text, end="")                 # what the agent receives (instruction-text/1)
print(digest(text))                     # sha256:… of the stored bytes

prints

instruction/1
[]
True
# House style

You write for support engineers.

MUST: write in the second person.
BECAUSE: the reader is the one acting.

NEVER: promise a date you cannot keep.
sha256:20f4f08abec3d38ca9b2324884e1063fd1b0eb1751da2a5c08b29945b775ae84
  • read(text, fragment=False, uri=None, host=None) → ReadResult: document, diagnostics, identities, parameters, footnotes, and which Markdown nodes are prose, which keyword a rule was written with, where its reason was. Nodes are MarkdownNode and DirectiveNode (to_json() gives the reference's JSON: {format: "instruction/1", metadata: {front, back}, body: [...]}); a structured body is a StructuredValue with its source and, parsed, its data. Metadata and structured bodies are YAML 1.2's Core Schema restricted to JSON: no anchors, aliases, custom tags, non-string keys, non-finite numbers or second document, duplicate keys refused.
  • check(text | ReadResult) → list[Diagnostic], the reader's diagnostics (§18) with the inline checks, in source order: code, severity, message, range (and uri for another source's).
  • A tool's server=#id names the document's mcp or service (§10, S32): another kind is a reference-kind error, an id the document doesn't have a reference-optional warning (none when it extends others: a base may hold it).
  • The integrations policy (S34): ReadResult.policy is the front matter's host-integrations (the host's, put in at serve time; or read(text, host=layer)) and integrations (the author's, which only narrows) merged, a Policy (tool_blocked, targets_allowed, to_json()); a blocked tool is a tool-blocked warning, a target outside the allowed an integration-not-allowed one, a layer of the wrong shape invalid-metadata, all worded as the reference's. host_block / with_host_block put a host's layer into a served text, authored_candidates takes it out again for a signature check; normalize_target compares targets as the WHATWG URL parser serializes them (a non-ASCII host is lower-cased, not converted to punycode).
  • inline_tokens(source) → the inline forms — :kind[label]{attrs}, [[target|label]], ![[…]], [^note], $math$, ${parameter} — read where CommonMark reads text: never in code, raw HTML, an autolink, a link destination or title, or a definition (the tokenizer is a port of micromark's, with GFM's tables, task list items and autolink literals).
  • resolve(text, uri=, version=, params=, load=) composes bases (extends) with their patches, includes as separate instances, pins and parameters; load is a callable (uri → Source | str | None) or a mapping of resolved URIs to sources, and nothing is ever fetched. res.text is the agent text, res.resolved.to_json() the resolved artifact (instruction-resolved/1, its resolved_digest in RFC 8785 form). resolve_with(text, sources) takes the sources already loaded, resolve_tree(tree, trees) authored trees (as AuthoredDocument or JSON).
  • to_text(tree, params=, parameters=, prose=, identities=, known=) → the text profile of any tree, authored or resolved; canonical_json / json_digest → RFC 8785; format(text) → the conservative formatter; digest(text) → sha256: of the stored bytes, nothing stripped; the registry → KINDS, INLINE, KEYWORDS, PATTERNS, … (the specification's registry.json, shipped with the package).
  • The workflow registry (workflow-registry.json, shipped with the package): WORKFLOW_KINDS, WORKFLOW_COMMON_FIELDS, WORKFLOW_LIMITS; WORKFLOW_SCOPES, the kinds whose body or branches hold nested steps (foreach, batch, iterate, subgraph; parallel, race), from reference/workflows.md, since the registry doesn't say: another kind's field of that name (an http request's body) is data. The reader checks each :::workflow{dialect="instruction/workflow"} body against it (unknown kinds and fields, required fields, triggers, dependencies, routes, cycles, scopes and limits: invalid-workflow, limit-exceeded, extension-unavailable); workflow_diagnostics(definition) checks a definition on its own.

Offsets (an inline token's, a range's lines) index the Python string, by code point.

Signatures

With the sign extra, verify_author(jws, text, keys, doc=, pub=) checks an author signature over the stored bytes; verify_delivery(jws, delivered, delivery_keys, author_keys, aud=, authored_text=, pub=) a delivery signature over what one reader received, with the author signature it embeds. A delivery binds its resolution: its manifest is {format: "instruction-resolved/1", status, document: {uri, sha256, version?}, dependencies, resolved_digest} (Resolved.manifest()), and the author's digest must be its document's sha256. sign_jws and public_jwk are for tests and tooling.

Following

Following (asyncio, any MCP client with read_resource / call_tool / subscribe_resource): InstructionFollower; McpSessionClient adapts the official mcp SDK's session (the mcp extra). On the 2026-07-28 wire its subscription is a subscriptions/listen stream that calls follower.notify, and reopens after a drop; mcp_auth.ClientCredentials signs an agent in (the client-credentials grant, renewed before its five minutes are up).

watch speaks MCP 2026-07-28, statelessly: Client(transport, mode="2026-07-28"). There is no initialize and no session id, so any replica of the server answers each request. It is the only protocol instruction.md supports, so pin it in your own code too: mode="auto" falls back to the older session handshake when its server/discover probe is answered with an error.

Command line

python -m instruction_md check FILE        # diagnostics on stderr; exit 1 on an error (warnings pass)
python -m instruction_md tree FILE         # the authored tree as JSON
python -m instruction_md deliver FILE [--param NAME=VALUE ...] [--resolved]
                                           # the text a model receives; its bases and includes are read from the files
                                           # beside it, under its directory (never above it, never a URL)
python -m instruction_md format FILE       # the formatted text

and watch (the mcp extra) to follow an instruction on an instruction.md server. Each version applied is a JSON line on stdout, and each one held is a JSON line on stderr. The follower declares a binding and reports what it applied, so the instruction's maintainers see it among its consumers.

# as an agent: the studio's Settings ▸ Security makes the credential, and shows its id, secret and token URL once
export INSTRUCTION_MD_CLIENT_ID=… INSTRUCTION_MD_TOKEN_URL=… INSTRUCTION_MD_CLIENT_SECRET=…
python -m instruction_md watch instruction://acme/support-agent@latest \
  --require-signature --require-delivery-signature --out AGENTS.md
# once, in CI, with a token you already hold: exit 0 applied, 6 held
python -m instruction_md watch instruction://ins_…@stable --token "$TOKEN" --once --require-signature

Conformance

The tests run the vendored data (conformance/, listed in its README): the specification's source, model (with jsonschema installed), resolution and text cases and its samples, and the reference's vectors — every read case's tree, diagnostics, identities, parameters and text, every resolution's artifact and text, the inline tokens — compared exactly. The source distribution carries both, so an unpacked sdist runs them:

python3 -m venv .venv && .venv/bin/pip install '.[dev]'
.venv/bin/pytest

In the repository the package is built from, scripts/sync-fixtures.sh [--check] keeps those copies, the package's registry.json and workflow-registry.json in step with their sources. Malformed YAML is reported under the same code and line as the reference does, its message PyYAML's.

Licence

Licensed under either of the MIT licence (LICENSE-MIT) or the Apache License, Version 2.0 (LICENSE-APACHE), at your option; the repository it is built from keeps its own licence, which does not apply to this package. It redistributes the specification's registries (instruction_md/registry.json, instruction_md/workflow-registry.json), unchanged, from instruction-md/specification by instruction.md (TSOK Inc.), under the Creative Commons Attribution 4.0 International licence (https://creativecommons.org/licenses/by/4.0/); NOTICE says so, and lists the licences of the conformance data the source distribution carries.

Metadata

Release files for instruction.md 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for instruction.md 0.3.0
File Size Uploaded Provenance Actions
instruction_md-0.3.0.tar.gz 228.6 kB Without provenance Details for instruction_md-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for instruction.md 0.3.0
File Interpreter ABI Platform Actions
instruction_md-0.3.0-py3-none-any.whl Python 3 none any Details for instruction_md-0.3.0-py3-none-any.whl

Total release size: 362.0 kB

Release files / instruction_md-0.3.0.tar.gz

Download URL instruction_md-0.3.0.tar.gz
Size 228.6 kB
Tags Source
SHA-256 checksum
How to use checksums
1bd8072f62afa5760bb2cabeffe189ed5d68e838e9129048d3dca103b8f740ec
BLAKE2b-256 checksum
How to use checksums
38a0a6622a456dbab0cfcc02ee775377d18881681f7ab1f2866456a4128b2b7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Release files / instruction_md-0.3.0-py3-none-any.whl

Download URL instruction_md-0.3.0-py3-none-any.whl
Size 133.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e582e92635324eb0388768da392e324d72a80906e9ea40155b917abcc8bdb0c8
BLAKE2b-256 checksum
How to use checksums
d3f5b946980924772a0faed7f61f4b6d51bb1a24d9e8e48532f8905790638065
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Security for instruction.md 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page