Python
The Python library reads, checks, resolves and verifies instruction.md documents, and follows a released instruction over MCP. It is instruction.md on PyPI, imported as instruction_md, version 0.3.1, under MIT OR Apache-2.0.
The library has two halves. The document half runs offline: it reads a document into its tree, reports diagnostics, composes bases and includes, gives the exact text an agent receives, formats it and computes its digest. The follower half talks to an instruction.md MCP server: it applies each released version, holds any version that fails your policy, and reports what it applied.
It is a port of the TypeScript reference, the npm package instruction.md (JavaScript and TypeScript). Both run the specification's conformance cases and the reference's vectors and must match them byte for byte. Where the two differ, the reference is right.
Install
pip install instruction.md # read, check, resolve, format, digest
pip install 'instruction.md[sign]' # adds signature verification (cryptography)
pip install 'instruction.md[mcp]' # adds the MCP follower and watch (the official mcp SDK)
pip install 'instruction.md[sign,mcp]' # both | Extra | Adds | Depends on |
|---|---|---|
| none | Read, check, resolve, format, digest, the registry, the integrations policy, workflow checks | PyYAML>=6.0 |
sign |
verify_author, verify_delivery, sign_jws, public_jwk |
cryptography>=38 |
mcp |
McpSessionClient, ClientCredentials and python -m instruction_md watch |
mcp>=2.3 |
- Python: 3.9 or later. The
mcpextra needs 3.10 or later, the official MCP SDK's own floor. - Platforms: any. The package is pure Python and ships
py.typed. - Name: PyPI shows
instruction.mdand normalizes it toinstruction-md. Both names install the same project.
The package is pre-1.0, so a minor release can change the API. Pin a minor version when you need stability:
pip install 'instruction.md[sign,mcp]~=0.3.0' Print the installed version with:
python -c "import instruction_md; print(instruction_md.__version__)" Read, check and deliver a document
This runs with the base install. It reads a document, checks it, resolves it with a parameter value and prints what the agent receives.
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 It 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 check returns the reader's diagnostics and the inline checks in source order. Each Diagnostic has a stable code, a severity (error, warning or info), a message for people and a range of 1-based lines. Match on code, never on the message.
from instruction_md import check
text = """---
spec: "1"
---
:::nope
x
"""
for d in check(text):
print(d.severity, d.code, d.range.start, "-", d.message) error unclosed-directive 4 - :::nope is not closed: end it with a line of :::
error unknown-kind 4 - :::nope is not a kind of this specification; it is kept as written, uninterpreted The reader reads the first edition (spec: "1") only. A document with another spec: value is an unsupported-format error, and a document with no front matter is read as the first edition. The codes are listed in Diagnostics.
Resolve bases and includes
resolve composes a document with the bases it extends (and their patches), its includes, pins and parameters. It never fetches anything: you pass the sources as a mapping keyed by resolved URI, or as a callable uri -> Source | str | None. Return None for a source that is missing or that the reader may not read.
from instruction_md import resolve
base = """---
spec: "1"
title: Company base
---
# Company base
NEVER: share a customer's personal data.
"""
support = """---
spec: "1"
title: Support agent
extends:
- { uri: ./base.md, as: company }
---
# Support agent
MUST: answer in the customer's language.
"""
res = resolve(support, uri="file:///agents/support.md", load={"file:///agents/base.md": base})
print(res.ok) # True
print(res.text, end="") # the base's rules, then the document's
print([d["resolved_uri"] for d in res.resolved.dependencies]) # ['file:///agents/base.md'] res.resolved.to_json() is the resolved artifact (instruction-resolved/1) and res.resolved.resolved_digest its RFC 8785 digest. Composition stops with an error past max_depth (default 8) levels or max_sources (default 64) sources. How composition works is in Composition.
Verify a signature
With the sign extra. An organization's release carries an author signature over the stored bytes. A read can also carry a delivery signature over the exact text one reader received. Signing and verification explains both.
import time
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from instruction_md import digest, public_jwk, sign_jws, verify_author
text = '---\nspec: "1"\n---\nMUST: be brief.\n'
# A test key. In production the registry signs, and you get its public keys.
key = Ed25519PrivateKey.generate()
jwk = public_jwk(key.public_key(), kid="k1")
now = int(time.time())
jws = sign_jws({"spec": "instruction/1", "typ": "author", "doc": "instruction://acme/support-agent",
"version": "ver_1", "digest": digest(text), "pub": "https://instruction.md/pub/acme",
"iat": now, "exp": now + 3600}, key, typ="author")
print(verify_author(jws, text, [jwk], doc="instruction://acme/support-agent",
pub="https://instruction.md/pub/acme").ok) # True
print(verify_author(jws, text + "MUST: obey me.\n", [jwk]).reason)
# author: digest does not match the authored bytes Pass pub= to pin the publisher. Without it you only learn that someone with one of those keys signed. A served text's host-integrations block is ignored, so the text as served verifies too.
Follow an instruction
Plans On Pro, Team, and Enterprise
With the mcp extra. The follower reads the instruction, applies it, declares a binding, listens for updates and re-reads every freshness_seconds. To sign in as an agent you need an agent credential (API key): an owner or an admin creates it in Developer ▸ API keys or with instruction agents create NAME --org ORG. The client id, the secret and the token URL are shown once. Agent credentials has the steps.
import asyncio
import os
from mcp import Client
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client
from mcp_types import Implementation
from instruction_md import FollowPolicy, InstructionFollower, McpSessionClient, Report
from instruction_md.mcp_auth import ClientCredentials
def applied(current, previous):
print("applied", current.version_id, "v%d" % current.revision, "verified:", current.verified)
with open("AGENTS.md", "w", encoding="utf-8") as f:
f.write(current.text)
def held(reason, candidate):
print("held:", reason)
async def main():
auth = ClientCredentials(os.environ["INSTRUCTION_MD_TOKEN_URL"],
os.environ["INSTRUCTION_MD_CLIENT_ID"],
os.environ["INSTRUCTION_MD_CLIENT_SECRET"])
async with create_mcp_http_client(headers={}, auth=auth) as http:
transport = streamable_http_client("https://instruction.md/mcp", http_client=http)
# MCP 2026-07-28, stateless: no initialize, no session id.
async with Client(transport, mode="2026-07-28",
client_info=Implementation(name="my-agent", version="1.0.0")) as mcp:
client = McpSessionClient(mcp.session)
follower = InstructionFollower(
client=client,
uri="instruction://acme/support-agent@latest",
on_apply=applied,
on_hold=held,
policy=FollowPolicy(require_signature=True, publisher="https://instruction.md/pub/acme"),
report=Report(consumer={"label": "support-bot", "kind": "agent"},
client={"name": "my-agent", "version": "1.0.0"}),
)
client.on_updated = follower.notify # each update on the listen stream re-reads
await follower.start()
await asyncio.Event().wait() # keep following
asyncio.run(main()) Three things in this sample matter for a long-running agent:
- Pin the protocol. Pass
mode="2026-07-28"toClient. instruction.md speaks only MCP 2026-07-28, stateless: noinitializeand no session id, so any replica can answer each request.mode="auto"probesserver/discoverand also picks 2026-07-28 against instruction.md, but when the probe is answered with an error it falls back to the older session handshake, which the server refuses. - Use client credentials. Agent tokens last five minutes and have no refresh token.
ClientCredentialsruns the OAuth client-credentials grant, renews the token 30 seconds before it expires and once more after a 401. A static bearer token stops working after five minutes. - A lost stream is reopened. On 2026-07-28,
McpSessionClient.subscribe_resourceopens asubscriptions/listenstream and callson_updated(uri)for each change. When the stream ends or the connection drops, it opens it again after 1 second, doubling to 30 seconds, and re-reads the resource so a release in the gap is not missed. A server that refuses the method (-32601or-32602) is not asked again; the freshness poll still runs.
Live updates are limited per workspace by plan; reads are never limited. When a second follower is refused live updates, it still picks up a release on its next poll. Each plan's number of followers with live updates:
Plans Community 1 · Pro unlimited · Team unlimited · Enterprise unlimited
Live updates has the rule and the refusal.
What the follower does
- It reads
uri:instruction://{owner}/{name}orinstruction://{id}, with@ref,@vN,@Nor@ver_…. A URI that names a version, ormode="pinned", is pinned: it is applied once and never replaced. - It skips a version it already applied. Otherwise it checks the policy in this order:
max_bytes,allowed_publishers, revoked versions,publisher, the delivery signature, the author signature. The first failure callson_holdand keeps the current version. - With
require_delivery_signatureand no delivery signature on the read, it asks for the version as delivered to this reader (instructions_versions_readwithresolve: true) and verifies and applies that text. The reader's audience comes fromsession_bootstrap. - It uses
author_keysanddelivery_keysif you pass them. Otherwise it reads the publisher'skeys.jsonnamed by the read, andinstruction://delivery-keys.json. Fetched keys are cached formax(60, freshness_seconds)seconds. A key marked revoked holds the version. - With a
report, it declares a binding (instructions_bindings_create, modefolloworpin, with your signature policy) and reports each applied version (instructions_bindings_report). The instruction's maintainers then see this agent among its followers.
A failed read keeps the last good version. Losing the server means no updates, never no instructions. How following works covers refs, pinning and what to follow in production.
Test without a server
The follower is transport-agnostic. Any object with async read_resource(uri) and call_tool(name, arguments), and optionally subscribe_resource(uri), works:
import asyncio
from instruction_md import InstructionFollower
class FakeRegistry:
"""Answers a read the way an instruction.md server does: the text and md.instruction/* metadata."""
async def read_resource(self, uri):
return {"contents": [{
"uri": uri,
"text": '---\nspec: "1"\n---\nMUST: be brief.\n',
"_meta": {"md.instruction/versionId": "ver_01JZ0000000000000000000000", "md.instruction/number": 3},
}]}
async def call_tool(self, name, arguments):
return {"isError": True}
async def main():
follower = InstructionFollower(client=FakeRegistry(), uri="instruction://acme/support-agent@latest",
on_apply=lambda cur, prev: print("applied v%d" % cur.revision),
freshness_seconds=0)
await follower.start() # applied v3
follower.stop()
asyncio.run(main()) Follow from the command line
python -m instruction_md watch (the mcp extra) runs the follower above. It reports itself as a consumer of kind agent, also in CI; use the library's Report to report another kind.
# as an agent, with the credential from Developer ▸ API keys
export INSTRUCTION_MD_CLIENT_ID=<client id>
export INSTRUCTION_MD_TOKEN_URL=https://instruction.md/auth/realms/instruction-md-agents/protocol/openid-connect/token
export INSTRUCTION_MD_CLIENT_SECRET=<client secret>
python -m instruction_md watch instruction://acme/support-agent@latest \
--require-signature --out AGENTS.md # once, in CI, with a token you already hold: exit 0 when applied, 6 when held
python -m instruction_md watch instruction://acme/support-agent@stable --token "$TOKEN" --once --require-signature @stable is a ref you move on purpose, and it is never created for you: create it with instruction refs <id> set stable <version id> before anything follows it. @latest moves on every release.
Each version applied is a JSON line on stdout. Each version held is a JSON line on stderr:
{"event": "applied", "uri": "instruction://acme/support-agent@latest", "versionId": "ver_01JDB6Q3W8X2K5N7P9R1T3V5X7", "number": 3, "verified": true, "digest": "sha256:<hex>"}
{"event": "held", "reason": "version ver_01JDB7A2C4E6G8J0L2N4Q6S8U0 is unsigned"} | Option | Default | Meaning |
|---|---|---|
--url | $INSTRUCTION_MD_URL, else https://instruction.md/mcp | The MCP server. |
--token | $INSTRUCTION_MD_TOKEN | A bearer token, sent as is. It is not renewed. Ignored when --client-id is set. |
--client-id | $INSTRUCTION_MD_CLIENT_ID | Sign in as this agent credential, with the secret from INSTRUCTION_MD_CLIENT_SECRET. The token is renewed before it expires. |
--token-url | $INSTRUCTION_MD_TOKEN_URL | The agent's token endpoint. Required with --client-id. |
--once | off | Read once, apply or hold, report, and exit. Nothing is listened for. |
--require-signature | off | Hold a version without a valid author signature. |
--require-delivery-signature | off | Hold a version without a valid delivery signature for this reader. |
--out | none | Write each applied version's text to this file. |
--label | instruction-md-python | The binding's consumer name, shown to the instruction's maintainers. |
--no-report | off | Declare no binding and report nothing. |
--freshness | 60 | Seconds between re-reads. 0 means notifications only. |
The URI is instruction://{owner}/{name} or instruction://{id}, optionally with @ref, @vN, @N or @ver_…. The client secret is read only from INSTRUCTION_MD_CLIENT_SECRET, never from a flag, so it doesn't show in the process list.
| Exit | When |
|---|---|
| 0 | --once applied a version. |
| 1 | watch could not reach --url, or the token endpoint refused the client id and secret. It prints a Python traceback. |
| 2 | A usage error, the mcp extra is missing, or --client-id lacks its secret or token URL. |
| 6 | --once held a version, or the server answered the read with an error (a missing or expired --token included). The held line says why. |
A CI step should treat any exit other than 0 as a failure. Without --once, watch runs until stopped. The instruction watch command of the CLI does the same from Node.
Other commands
python -m instruction_md check house-style.md # problems on stderr; exit 1 on an error
python -m instruction_md tree house-style.md # the authored tree as JSON
python -m instruction_md deliver house-style.md --param audience="support engineers"
python -m instruction_md deliver house-style.md --resolved # the resolved artifact as JSON
python -m instruction_md format house-style.md # the formatted text on stdout | Command | What it does | Exit |
|---|---|---|
check FILE |
Prints diagnostics to stderr, one per line. | 1 on an error; warnings pass |
tree FILE |
Prints the authored tree as JSON. | 1 on an error |
deliver FILE |
Prints the text a model receives. Bases and includes are read from files under the document's directory: never above it (symbolic links included), never a URL. --param NAME=VALUE (repeatable) is read as the document declares the parameter. --resolved prints the resolved artifact as JSON instead. |
1 on an error, 2 on a malformed --param |
format FILE |
Prints the formatted text. | 0 |
The commands read INSTRUCTION_MD_URL, INSTRUCTION_MD_TOKEN, INSTRUCTION_MD_CLIENT_ID, INSTRUCTION_MD_CLIENT_SECRET and INSTRUCTION_MD_TOKEN_URL for watch only. The library reads no environment variables.
API
Everything is importable from instruction_md unless another module is named.
Reading and checking
| Name | Signature and meaning |
|---|---|
read |
read(text, *, fragment=False, uri=None, host=None) -> ReadResult. fragment=True reads a part of a document. host is a PolicyLayer applied as the host's integrations layer. |
ReadResult |
document, diagnostics, identities: dict[str, Identity], parameters: dict[str, Parameter], footnotes, prose, keywords, reasons, comments, lines, front_range, back_range, policy. |
check |
check(source, *, fragment=False, uri=None) -> list[Diagnostic]. source is text or a ReadResult. |
inline_diagnostics |
inline_diagnostics(r) -> list[Diagnostic]: the inline checks alone. |
resolve_target, Target |
What a typed reference points at: state "local", "missing" or "external". |
inline_tokens, InlineToken, split_wiki |
The inline forms (directive, wiki, embed, footnote, math, param), with offsets in code points of the Python string. |
strip_comments, value_from, value_fits, parse_attributes, attributes_end |
Comments on one line; a parameter value from text and against its type; an attribute list. |
load_yaml, load_json, load_csv |
YAML 1.2 Core Schema restricted to JSON, JSON and CSV, as the reader reads structured bodies. |
The tree
AuthoredDocument (metadata, body, uri, format; to_json()), Metadata (front, back), MarkdownNode, DirectiveNode (kind, form, attrs, children, value, range, instance), StructuredValue, Diagnostic (code, severity, message, uri, range, target, remedy), Range, Parameter, Identity, ABSENT, node_from_json and document_from_json.
Resolution and text
| Name | Signature and meaning |
|---|---|
resolve |
resolve(text, *, uri=None, version=None, params=None, load=None, max_depth=8, max_sources=64) -> Resolution. uri defaults to document.md. |
resolve_with |
The same over sources already loaded, by resolved URI. |
resolve_tree |
The same over authored trees. |
Resolution |
ok, resolved: Resolved, text (instruction-text/1), diagnostics, root. |
Resolved |
The instruction-resolved/1 artifact; to_json(); manifest(), what a delivery signature binds. |
Source |
Source(uri, text, version=None). |
to_text, TextOptions, TextSource |
The text profile of an authored or resolved tree. |
references_of, resolve_uri, slug |
The URIs a document composes; a reference resolved against a base; a heading's anchor. |
format |
format(text) -> str: LF line endings, no trailing spaces on a directive's own lines, one final newline. Nothing else changes. |
Digests and signatures
| Name | Meaning |
|---|---|
digest(text), digest_text(text) |
sha256:<hex> of the UTF-8 bytes. Nothing is stripped: line endings count. |
sha256_hex, canonical_json, json_digest |
Hex SHA-256; RFC 8785 canonical JSON and its digest. |
verify_author |
verify_author(jws, authored_text, keys, *, doc=None, pub=None, now=None) -> VerifyResult. The sign extra. |
verify_delivery |
verify_delivery(jws, delivered_text, delivery_keys, author_keys, *, aud, authored_text=None, pub=None, now=None) -> VerifyResult. Checks the delivery, then the author signature it embeds. |
VerifyResult |
ok, claims, reason. |
sign_jws, public_jwk, JWK |
Signing and key export for tests and tooling. Keys are Ed25519 or Ed448 OKP JWKs; signatures are compact JWS with alg: EdDSA. |
Following
| Name | Signature and meaning |
|---|---|
InstructionFollower |
client, uri, on_apply(current, previous) (plain or async), mode="follow" or "pinned", policy=FollowPolicy(), freshness_seconds=60.0 (0: no polling), report=None, on_hold(reason, candidate), on_error(exc), now. State: current, revision, last_hold, pinned. Methods: await start(), stop(), await notify(uri), await refresh(reason). |
FollowPolicy |
require_signature=False, author_keys=None, publisher=None, require_delivery_signature=False, delivery_keys=None, allowed_publishers=None, max_bytes=None. |
Report |
consumer ({"label", "kind": "agent" | "host" | "ci", "workload"?}), client ({"name", "version"}), binding_id to reuse a binding. |
AppliedInstruction |
uri, canonical, version_id, revision (the version's number), ref, digest, delivered_digest, publisher, signature, delivery_signature, verified, text, applied_at, and the key fields. |
FollowerClient |
The protocol a client meets: async read_resource, call_tool, optional subscribe_resource. |
McpSessionClient |
McpSessionClient(session, on_updated=None) adapts the official mcp SDK's session. close() ends its streams. |
parse_meta, META |
The md.instruction/* metadata of a read. |
instruction_md.mcp_auth.ClientCredentials |
ClientCredentials(token_url, client_id, client_secret, scope=None): an HTTP auth for the client-credentials grant. |
Policy, workflows and the registry
- The integrations policy:
Policy,PolicyLayer,ServerTools,ServerPolicy,LayerProblem,layer_of,merge_policy,host_layer,host_block,with_host_block,authored_candidates,normalize_target,remote_targets,named_tools,objects_by_id,document_targets,HOST_POLICY_KEY,AUTHOR_POLICY_KEY,INTEGRATED_KINDS. A blocked tool is atool-blockedwarning and a target outside the allowed list anintegration-not-allowedwarning. See Tools and integrations. - Workflows:
workflow_diagnostics,WORKFLOW_DIALECT,WORKFLOW_REGISTRY,WORKFLOW_KINDS,WORKFLOW_COMMON_FIELDS,WORKFLOW_LIMITS,WORKFLOW_SCOPES. - The specification's registry, shipped with the package:
REGISTRY,KINDS,KEYWORDS,RULES,FRONT_MATTER_KEYSand the rest, withattr_spec,inline_attr_specandcanonical_kind. instruction_md.allowance: the checks for spending allowances. The reader and resolver already run them. See Allowances.__version__andSPEC_VERSION("1", the edition the package reads).
Security
- Nothing is fetched behind your back.
read,check,resolveandto_textmake no network calls and read no files.resolveasks only yourload. The follower talks only through the client you give it. - Credentials.
watchsends the token, or the client id and secret, only to--urland--token-url. - Signatures. A follower applies unsigned versions unless you set
require_signatureorrequire_delivery_signature. Set them for anything that matters and pin the publisher. Keys discovered from the server come from that server; passauthor_keysto pin keys you got another way. - Untrusted YAML is read into JSON values only. Anchors, aliases and custom tags are refused, so a document can't construct Python objects.
- Sealed instructions are not opened by this package. See Sealed instructions for developers.
No independent security review of this package has been published. Report a vulnerability through Support, not a public issue.
If it doesn't work
| What you see | What to do |
|---|---|
watch needs the MCP SDK: pip install 'instruction.md[mcp]' |
Install the mcp extra, on Python 3.10 or later. |
signature: signature verification needs the cryptography package |
Install the sign extra. The verifiers return ok=False with this reason instead of raising, and a follower holds with signature rejected: …. |
--client-id needs INSTRUCTION_MD_CLIENT_SECRET and --token-url (or INSTRUCTION_MD_TOKEN_URL) |
Set both. The secret is read only from the environment. |
PermissionError: the token endpoint refused the client (401): … |
The client id or secret is wrong. With a 404 or an HTML page, the token URL isn't the one shown with the credential. A lost secret can't be shown again: rotate it. |
watch exits 1 with ConnectError |
It could not reach --url. Check the address and your proxy. |
watch stops working after about five minutes |
--token is not renewed and agent tokens last five minutes. Use --client-id with --token-url and INSTRUCTION_MD_CLIENT_SECRET. |
Requests fail after Client(mode="auto") falls back to the session handshake |
The server refuses sessions. Pin the protocol in your Client, as in the follow sample above. |
reference-missing: the base … could not be read |
load is keyed by the resolved URI: with uri="file:///agents/support.md", ./base.md is file:///agents/base.md. |
extends is a list of base records |
Write extends: as a list, such as - { uri: ./base.md, as: company }. |
When a version is held, the held line or on_hold says why:
| Reason | What to do |
|---|---|
version … is unsigned |
Sign releases in your organization, or drop --require-signature. |
no publisher keys to verify … |
The server named no keys.json. Pass author_keys. |
signature rejected: … |
The text or the key doesn't match. Check pub and the keys. |
version … carries no delivery signature |
The server gave none for this read. An unsigned release shows this reason under --require-delivery-signature. |
delivery signature rejected: … |
The delivered text or the delivery keys don't match. |
no keys to verify the delivery of … |
Pass delivery_keys and author_keys. |
version … was revoked, … signed with a revoked key |
Release a new version. |
publisher … is not allowed, … is not the pinned … |
Check allowed_publishers and publisher. |
version … exceeds N bytes |
Raise max_bytes. |
read failed (…) |
The server answered the read with an error, such as a permission or not found. The follower keeps the last good version and tries again. |
empty read, read carried no md.instruction/versionId |
The address isn't a released version (a draft, say), or the server isn't an instruction.md server. |
Related
- Libraries and SDKs: every library and what each does.
- How following works: refs, pinning and the follow file.
- Agent credentials: the client id, secret and token URL.
- Signing and verification: author and delivery signatures, keys and revocation.
- Sign-in, scopes and tokens: how the MCP server checks a token.
- The instruction.md Specification: the language this library reads.