Metadata-Version: 2.4
Name: instruction.md
Version: 0.3.0
Summary: Read, check, resolve and verify instruction.md files (the specification's first edition, instruction/1), and follow them from a registry
Author: TSOK Inc.
License-Expression: MIT OR Apache-2.0
Project-URL: Homepage, https://instruction.md
Project-URL: Documentation, https://instruction.md/docs/
Project-URL: Specification, https://instruction.md/specification/
Project-URL: Issues, https://github.com/instruction-md/specification/issues
Keywords: instruction.md,agents,mcp,markdown
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup :: Markdown
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE-MIT
License-File: LICENSE-APACHE
License-File: NOTICE
Requires-Dist: PyYAML>=6.0
Provides-Extra: sign
Requires-Dist: cryptography>=38; extra == "sign"
Provides-Extra: mcp
Requires-Dist: mcp>=2.3; extra == "mcp"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: cryptography>=38; extra == "dev"
Requires-Dist: jsonschema>=4.20; extra == "dev"
Dynamic: license-file

# instruction.md (Python)

The [instruction.md](https://instruction.md) specification's [first edition](https://instruction.md/specification/)
(`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.

```sh
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)
```

```python
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

```text
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

```sh
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.

```sh
# 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:

```sh
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](https://github.com/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.
