gemmozero commited on
Commit
f1e6aff
·
verified ·
1 Parent(s): 3bb0b6e

Dataset #1: signed MCP tool-change events + Agent Tool-Change Benchmark (window 42540-43539, head 43540)

Browse files

Compilation CC BY 4.0; third-party tool text not relicensed. Validation: DATASET_OK (865/865 signatures, 40/40 inclusion proofs, 1522/1522 JCS list hashes).

.gitattributes CHANGED
@@ -58,3 +58,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ data/benchmark/test.jsonl filter=lfs diff=lfs merge=lfs -text
62
+ data/benchmark/train.jsonl filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,83 @@
1
  ---
2
  license: cc-by-4.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: cc-by-4.0
3
+ pretty_name: MCP Tool-Change Events & Agent Tool-Change Benchmark (signed, LEGION)
4
+ language:
5
+ - en
6
+ task_categories:
7
+ - text-classification
8
+ - tabular-classification
9
+ tags:
10
+ - mcp
11
+ - model-context-protocol
12
+ - ai-agents
13
+ - agent-security
14
+ - tool-use
15
+ - function-calling
16
+ - drift-detection
17
+ - benchmark
18
+ - transparency-log
19
+ - merkle-tree
20
+ - ed25519
21
+ - provenance
22
+ size_categories:
23
+ - 10K<n<100K
24
+ configs:
25
+ - config_name: events
26
+ data_files:
27
+ - split: train
28
+ path: data/events/train.parquet
29
+ - split: test
30
+ path: data/events/test.parquet
31
+ - config_name: benchmark
32
+ data_files:
33
+ - split: train
34
+ path: data/benchmark/train.parquet
35
+ - split: test
36
+ path: data/benchmark/test.parquet
37
  ---
38
+
39
+ # MCP Tool-Change Events & Agent Tool-Change Benchmark
40
+
41
+ Real changes to the `tools/list` of public MCP (Model Context Protocol) servers, **observed from the outside, timestamped, and signed** (Ed25519) into a public Merkle transparency log (RFC 6962/9162). Every row can be traced to its signed record and inclusion proof.
42
+
43
+ **Do not trust this card: verify.** `python3 verify.py` re-checks every record signature and a random sample of inclusion proofs against the pinned signed head.
44
+
45
+ ## What is inside (this release)
46
+
47
+ | config | rows | split | one row = |
48
+ |---|---|---|---|
49
+ | `events` | 865 (train 692 / test 173) | temporal: test = most recent 20% (from 2026-10-28T23:09:01Z) | one signed `changed` record: tools added / removed / modified, server, time, full signed record |
50
+ | `benchmark` | 34648 (train 26707 / test 7941) | by server (no server in both splits) | one tool in a signed before/after pair, label `added/removed/modified/unchanged` + `description_changed`, `schema_changed`, params added/removed |
51
+
52
+ Benchmark labels: added 1424, removed 631, modified 3851, unchanged 28742. Labels are **computed** from the archived before/after definitions (no heuristic, no model) and checked against the signed record (0 mismatches).
53
+
54
+ ## Uses
55
+ - Drift / "rug pull" detection: does an agent notice that a tool it already approved has changed?
56
+ - Change localization: did the description change, the input schema, or both? Which parameters appeared/disappeared?
57
+ - Evaluating agent guards that pin tool definitions (re-review on change).
58
+
59
+ ## Provenance (signed)
60
+ - Source: the public API of the LEGION MCP transparency log, read-only: `https://tlog.legion-api.com/tlog/v0` (`/records/{i}`, `/tools/{sha256}`, `/proof/inclusion`, `/head`, `/keyring`).
61
+ - Pinned signed head: tree_size **43540**, 2026-10-29T14:43:39Z, root `14c12688c4766fa721731ea6e8f67b28916b4bba4d1ba12eb4dfb637a6595646`.
62
+ - Window of this release: leaves 42540–43539 (the most recent part of the log at build time); older records are used only as "before" context.
63
+ - Validation at build (`validation.json`): 865/865 event signatures valid, 40/40 sampled inclusion proofs valid, 1522 archived tools lists hash-checked (0 mismatch), head signature valid, secret-like patterns found: 0. Status: **DATASET_OK**.
64
+
65
+ ## Collection method
66
+ LEGION's collector periodically calls `tools/list` on MCP servers listed in the public MCP Registry, hashes the tool definitions (`sha256(JCS(sorted[{name,description,inputSchema}]))`) and appends a signed record when the fingerprint changes. Dates are the collector's clock.
67
+
68
+ ## Limits (read before use)
69
+ - **Annotations are not covered** by the fingerprint: an annotation-only change (e.g. `readOnlyHint`) is invisible here.
70
+ - A change is not an attack; a signature is not a statement about quality. One operator; no independent witness counted.
71
+ - Not exhaustive: unreachable or auth-only servers are observed partially or not at all. This release is a recent **window**, not the full log.
72
+ - 0 changed records lack an archived "before" list and appear only in `events`, not in `benchmark`.
73
+ - Tool names, descriptions and schemas are written by the MCP server authors (third-party text).
74
+ - 6 secret-like strings (token patterns) were masked as `[REDACTED-SECRET-LIKE]` in `benchmark` definitions; masked rows no longer hash to the archived list (labels were computed before masking and are unaffected).
75
+
76
+ ## License
77
+ **CC BY 4.0 applies to the compilation**: the selection and arrangement of records, the signed observations made by LEGION (timestamps, fingerprints, change sets, signatures), the computed labels and the splits.
78
+
79
+ **Third-party content is not relicensed.** Tool names, descriptions and input schemas were written by the authors of the MCP servers. They are factual content, included only so that each row can be verified against the signed log; they remain under whatever terms their authors chose. Do not assume CC BY 4.0 covers them. This note applies to every config of this dataset.
80
+
81
+ ## Related
82
+ - MCP Directory (browse servers and their signed history): https://legion-api.com/mcp-directory/ — machine-readable: https://legion-api.com/mcp-directory/llms.txt
83
+ - Log API: https://tlog.legion-api.com/tlog/v0
SHA256SUMS ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ f8d1557814945fa1f4d0fc5b95aeab1481fb74903eef03ca9543d8df157e5c66 ./README.md
2
+ 0099439c9d4172d410ac98c11557df43d8cae77b17e34db3ce3c089020b1586e ./SHA256SUMS
3
+ e1bbc29fb6d82a017e05832325e4af1b4b043c3722118645650b5abe49077f0b ./build.py
4
+ 2c749b80c00a3ec85b320683f2451980e0b60f25e2558a9b877c347dcf60d8a1 ./build_report.json
5
+ 9d83fe4d62a88c9514e444e3b12ce252a139f7b0d3f771ee003eaa5af4b6ab13 ./collect.py
6
+ a36ededa697de5825db807c35748422b6d69c3f268894dbb82825bfb2ae46b18 ./data/benchmark/test.jsonl
7
+ e860b8f460fa40866035483865bafd22134529df5e38caee56784644e41c25cc ./data/benchmark/test.parquet
8
+ bd812ee7c8800a9efe3dcce95d41af9770232f66b79370786eac5725154e24e7 ./data/benchmark/train.jsonl
9
+ c0dca2c4de508b2a2f9eef799ed17b0c1600a5fbeb370ddd0b6415f1a9249a0c ./data/benchmark/train.parquet
10
+ ecb387d7ee7cbf70f5804572da6edb0862f192fbca0af9130ee1237bab19b40a ./data/events/test.jsonl
11
+ 2d128bc84789f47f546ad5d70d7c4d7b0f0328c09a4daf7145b84e9893488e54 ./data/events/test.parquet
12
+ f077118bf972d25af3bd498097a5cf83659029811b643df5f26a0697295d60ad ./data/events/train.jsonl
13
+ ae84c4292d4665dc3a626604c238b07e5a9265549eecfe675e69d53223777213 ./data/events/train.parquet
14
+ 04bb334392a696c7ef09e02a56efb66f97e26cbff79e9709a1a83190331926a6 ./data/sample/benchmark.jsonl
15
+ 9d7d4bcc93f6d64abfe2a938cb573f18572fec527346caaaf24d388d94f5b771 ./data/sample/events.jsonl
16
+ c3958b11fc6165ba542b7f6c14a231e869b05bd6338454d72b6848a146ed506f ./jcs_min.py
17
+ dbfe52f38dbc9dede60717f19fd248ea0afec86fcec63ae0c613c943735492a4 ./load_example.py
18
+ f913e611d0dfaacfff7fc44e969f54dad7d6825d3c45fa4e7e7d7095fe608993 ./meta/head_43540.json
19
+ 14ca2c75193e79050d1697e04ba765b8158c1fab81cc0b24123df6b4cd584ade ./meta/keyring.bin
20
+ 9e82e6122b51c841d8bc6fd9b17d046a96589cf4c023100e6eec42530fa3210b ./validation.json
21
+ 0026c4698ee12c1b7268ce2c333a474479f7d52202b816bbc4aedfac6b240f9c ./verify.py
build.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Construit le dataset depuis le cache de l'API publique (aucune autre source, aucune donnée inventée).
3
+ Sorties : data/events/{train,test}.jsonl|parquet, data/benchmark/{train,test}.jsonl|parquet, data/sample/*.jsonl, build_report.json
4
+ - events : un record « changed » signé = une ligne (record signé complet inclus pour vérification hors ligne).
5
+ - benchmark : une ligne par outil d'une paire avant/après signée ; étiquettes CALCULÉES (aucune heuristique).
6
+ Splits : events = temporel (20 % les plus récents en test) ; benchmark = par serveur (hash(server_id) % 5 == 0 -> test, pas de fuite).
7
+ Usage : python3 build.py --from-leaf A (pyarrow requis pour le parquet)"""
8
+ import glob, hashlib, json, os, re
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+ C = os.path.join(HERE, "cache")
12
+ OUT = os.path.join(HERE, "data")
13
+ BASE = "https://tlog.legion-api.com/tlog/v0"
14
+ SECRET = re.compile(r"(sk-[A-Za-z0-9]{20,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|hf_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16}|xox[bp]-[A-Za-z0-9-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.)")
15
+
16
+
17
+ import sys as _sys
18
+ _sys.path.insert(0, HERE)
19
+ import jcs_min # noqa: E402
20
+
21
+
22
+ def canon(o):
23
+ """RFC 8785 (JCS) — identique à la canonicalisation du journal (json.dumps trié diffère sur les flottants : 8.0 vs 8)."""
24
+ return jcs_min.dumps(o)
25
+
26
+
27
+ def load(kind, key):
28
+ p = os.path.join(C, kind, key + ".json")
29
+ return json.load(open(p)) if os.path.exists(p) else None
30
+
31
+
32
+ def scrub(s, stats):
33
+ def rep(m):
34
+ stats["secret_like_redacted"] += 1
35
+ return "[REDACTED-SECRET-LIKE]"
36
+ return SECRET.sub(rep, s) if isinstance(s, str) else s
37
+
38
+
39
+ def params(schema):
40
+ return (schema or {}).get("properties") or {}
41
+
42
+
43
+ def main():
44
+ import sys
45
+ lo = int(sys.argv[sys.argv.index("--from-leaf") + 1]) if "--from-leaf" in sys.argv else 0 # fenêtre déclarée (records « prev » plus anciens = contexte seulement)
46
+ head = json.load(open(sorted(glob.glob(os.path.join(C, "meta", "head_*.json")))[-1]))
47
+ th = head["sth"]["tree_head"]
48
+ stats = {"records_cached": 0, "changed_events": 0, "benchmark_rows": 0, "pairs_with_both_lists": 0, "pairs_missing_lists": 0,
49
+ "secret_like_redacted": 0, "kinds": {}}
50
+ events, bench = [], []
51
+ files = sorted(glob.glob(os.path.join(C, "records", "*.json")), key=lambda p: int(os.path.basename(p)[:-5]))
52
+ for p in files:
53
+ r = json.load(open(p))
54
+ stats["records_cached"] += 1
55
+ ch = r.get("change") or {}
56
+ k = ch.get("kind") or r.get("kind") or "unknown"
57
+ stats["kinds"][k] = stats["kinds"].get(k, 0) + 1
58
+ if k != "changed" or r["leaf_index"] < lo:
59
+ continue
60
+ i = r["leaf_index"]
61
+ fp = r.get("tools_fingerprint") or {}
62
+ events.append({"leaf_index": i, "server_id": r["server_id"], "observed_at": r["observed_at"],
63
+ "tools_added": ch.get("added", []), "tools_removed": ch.get("removed", []), "tools_modified": ch.get("modified", []),
64
+ "n_tools_after": len(fp.get("per_tool_sha256") or []), "tools_sha256_after": fp.get("sha256"), "fingerprint_algo": fp.get("algo"),
65
+ "prev_leaf_index": r.get("prev_leaf_index"), "key_id": r["key_id"],
66
+ "signed_record": canon(r), "record_url": "%s/records/%d" % (BASE, i), "diff_url": "%s/diff/%d" % (BASE, i),
67
+ "inclusion_proof_url": "%s/proof/inclusion?leaf_index=%d&tree_size=%d" % (BASE, i, th["tree_size"]),
68
+ "signed_head_tree_size": th["tree_size"]})
69
+ prev = load("records", str(r.get("prev_leaf_index"))) if r.get("prev_leaf_index") is not None else None
70
+ after = load("tools", fp.get("sha256") or "")
71
+ before = load("tools", ((prev or {}).get("tools_fingerprint") or {}).get("sha256") or "") if prev else None
72
+ if not (after and before):
73
+ stats["pairs_missing_lists"] += 1
74
+ continue
75
+ stats["pairs_with_both_lists"] += 1
76
+ A = {t["name"]: t for t in after["tools"]}
77
+ Bf = {t["name"]: t for t in before["tools"]}
78
+ for name in sorted(set(A) | set(Bf)):
79
+ a, b = A.get(name), Bf.get(name)
80
+ if a and not b:
81
+ status = "added"
82
+ elif b and not a:
83
+ status = "removed"
84
+ else:
85
+ status = "modified" if canon({k: a.get(k) for k in ("name", "description", "inputSchema")}) != canon({k: b.get(k) for k in ("name", "description", "inputSchema")}) else "unchanged"
86
+ pa, pb = params((a or {}).get("inputSchema")), params((b or {}).get("inputSchema"))
87
+ row = {"id": "%d:%s" % (i, name), "leaf_index": i, "prev_leaf_index": r.get("prev_leaf_index"), "server_id": r["server_id"],
88
+ "observed_at": r["observed_at"], "tool_name": name, "label": status,
89
+ "description_changed": bool(a and b and a.get("description") != b.get("description")),
90
+ "schema_changed": bool(a and b and canon(a.get("inputSchema")) != canon(b.get("inputSchema"))),
91
+ "params_added": sorted(set(pa) - set(pb)) if a and b else [], "params_removed": sorted(set(pb) - set(pa)) if a and b else [],
92
+ "before_definition": scrub(canon(b), stats) if b else None, "after_definition": scrub(canon(a), stats) if a else None,
93
+ "tools_sha256_before": before["tools_sha256"], "tools_sha256_after": after["tools_sha256"]}
94
+ # cohérence avec le record signé : le label doit correspondre à la liste signée
95
+ signed = "added" if name in ch.get("added", []) else "removed" if name in ch.get("removed", []) else "modified" if name in ch.get("modified", []) else "unchanged"
96
+ row["label_matches_signed_record"] = signed == status
97
+ bench.append(row)
98
+ stats["changed_events"], stats["benchmark_rows"] = len(events), len(bench)
99
+ stats["benchmark_labels"] = {l: sum(1 for x in bench if x["label"] == l) for l in ("added", "removed", "modified", "unchanged")}
100
+ stats["benchmark_label_mismatch_vs_signed"] = sum(1 for x in bench if not x["label_matches_signed_record"])
101
+ events.sort(key=lambda e: (e["observed_at"], e["leaf_index"]))
102
+ cut = int(len(events) * 0.8)
103
+ split_ev = {"train": events[:cut], "test": events[cut:]}
104
+ tst = lambda s: int(hashlib.sha256(s.encode()).hexdigest(), 16) % 5 == 0
105
+ split_bm = {"train": [x for x in bench if not tst(x["server_id"])], "test": [x for x in bench if tst(x["server_id"])]}
106
+ stats["splits"] = {"events": {k: len(v) for k, v in split_ev.items()}, "benchmark": {k: len(v) for k, v in split_bm.items()},
107
+ "events_test_from": split_ev["test"][0]["observed_at"] if split_ev["test"] else None}
108
+ stats["head"] = {"tree_size": th["tree_size"], "timestamp": th["timestamp"], "root_sha256": th["root_sha256"]}
109
+ stats["leaf_window"] = [lo, int(os.path.basename(files[-1])[:-5])] if files else None
110
+ stats["context_records_before_window"] = sum(1 for f in files if int(os.path.basename(f)[:-5]) < lo)
111
+ for cfg, splits in (("events", split_ev), ("benchmark", split_bm)):
112
+ os.makedirs(os.path.join(OUT, cfg), exist_ok=True)
113
+ for sp, rows in splits.items():
114
+ with open(os.path.join(OUT, cfg, sp + ".jsonl"), "w") as f:
115
+ for x in rows:
116
+ f.write(json.dumps(x, ensure_ascii=False, sort_keys=True) + "\n")
117
+ os.makedirs(os.path.join(OUT, "sample"), exist_ok=True)
118
+ for cfg, rows in (("events", events[-20:]), ("benchmark", [x for x in bench if x["label"] != "unchanged"][:20] + [x for x in bench if x["label"] == "unchanged"][:5])):
119
+ with open(os.path.join(OUT, "sample", cfg + ".jsonl"), "w") as f:
120
+ for x in rows:
121
+ f.write(json.dumps(x, ensure_ascii=False, sort_keys=True) + "\n")
122
+ try:
123
+ import pandas as pd
124
+ for cfg in ("events", "benchmark"):
125
+ for sp in ("train", "test"):
126
+ src = os.path.join(OUT, cfg, sp + ".jsonl")
127
+ pd.read_json(src, lines=True, dtype=False).to_parquet(src[:-6] + ".parquet", index=False)
128
+ stats["parquet"] = "ok"
129
+ except Exception as e:
130
+ stats["parquet"] = "NON GÉNÉRÉ: %r" % e
131
+ json.dump(stats, open(os.path.join(HERE, "build_report.json"), "w"), indent=1, ensure_ascii=False)
132
+ print(json.dumps(stats, indent=1, ensure_ascii=False))
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()
build_report.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "records_cached": 1824,
3
+ "changed_events": 865,
4
+ "benchmark_rows": 34648,
5
+ "pairs_with_both_lists": 865,
6
+ "pairs_missing_lists": 0,
7
+ "secret_like_redacted": 6,
8
+ "kinds": {
9
+ "initial": 233,
10
+ "rebaseline": 3,
11
+ "changed": 1588
12
+ },
13
+ "benchmark_labels": {
14
+ "added": 1424,
15
+ "removed": 631,
16
+ "modified": 3851,
17
+ "unchanged": 28742
18
+ },
19
+ "benchmark_label_mismatch_vs_signed": 0,
20
+ "splits": {
21
+ "events": {
22
+ "train": 692,
23
+ "test": 173
24
+ },
25
+ "benchmark": {
26
+ "train": 26707,
27
+ "test": 7941
28
+ },
29
+ "events_test_from": "2026-10-28T23:09:01Z"
30
+ },
31
+ "head": {
32
+ "tree_size": 43540,
33
+ "timestamp": "2026-10-29T14:43:39Z",
34
+ "root_sha256": "14c12688c4766fa721731ea6e8f67b28916b4bba4d1ba12eb4dfb637a6595646"
35
+ },
36
+ "leaf_window": [
37
+ 42540,
38
+ 43539
39
+ ],
40
+ "context_records_before_window": 824,
41
+ "parquet": "ok"
42
+ }
collect.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collecteur LECTURE SEULE de l'API PUBLIQUE du journal MCP LEGION (https://tlog.legion-api.com/tlog/v0).
3
+ Respecte la limite publiée (60 req/min) : plafond 55 req/min. Cache disque + reprise (rien n'est re-téléchargé).
4
+ N'utilise aucun jeton, aucun fichier de production.
5
+
6
+ Usage : collect.py --from-leaf A --to-leaf B [--tools] (B exclu ; --tools : récupère aussi les tools/list archivés avant/après
7
+ de chaque record « changed » de la fenêtre, pour la variante éval)"""
8
+ import argparse, json, os, sys, time, urllib.error, urllib.request
9
+
10
+ BASE = "https://tlog.legion-api.com/tlog/v0"
11
+ HERE = os.path.dirname(os.path.abspath(__file__))
12
+ CACHE = os.path.join(HERE, "cache")
13
+ UA = {"User-Agent": "legion-hf-dataset-builder/0.1 (read-only, <=55 req/min)"}
14
+ MIN_INTERVAL = 60.0 / 55
15
+ _last = [0.0]
16
+
17
+
18
+ def get(path, raw=False):
19
+ for attempt in range(6):
20
+ wait = MIN_INTERVAL - (time.monotonic() - _last[0])
21
+ if wait > 0:
22
+ time.sleep(wait)
23
+ _last[0] = time.monotonic()
24
+ try:
25
+ with urllib.request.urlopen(urllib.request.Request(BASE + path, headers=UA), timeout=60) as r:
26
+ b = r.read()
27
+ return b if raw else json.loads(b)
28
+ except urllib.error.HTTPError as e:
29
+ if e.code in (429, 503):
30
+ time.sleep(int(e.headers.get("Retry-After") or 30))
31
+ continue
32
+ if e.code == 404:
33
+ return None
34
+ raise
35
+ except Exception:
36
+ time.sleep(10 * (attempt + 1))
37
+ raise RuntimeError("échec répété sur " + path)
38
+
39
+
40
+ def cached(kind, key, path, raw=False):
41
+ d = os.path.join(CACHE, kind)
42
+ os.makedirs(d, exist_ok=True)
43
+ p = os.path.join(d, key + (".bin" if raw else ".json"))
44
+ if os.path.exists(p):
45
+ return open(p, "rb").read() if raw else json.load(open(p))
46
+ v = get(path, raw)
47
+ if v is not None:
48
+ tmp = p + ".tmp"
49
+ with open(tmp, "wb" if raw else "w") as f:
50
+ f.write(v) if raw else json.dump(v, f, ensure_ascii=False, sort_keys=True)
51
+ os.replace(tmp, p)
52
+ return v
53
+
54
+
55
+ def main():
56
+ ap = argparse.ArgumentParser()
57
+ ap.add_argument("--from-leaf", type=int, required=True)
58
+ ap.add_argument("--to-leaf", type=int, required=True)
59
+ ap.add_argument("--tools", action="store_true")
60
+ a = ap.parse_args()
61
+ head = get("/head")
62
+ cached("meta", "head_%d" % head["sth"]["tree_head"]["tree_size"], "/head")
63
+ cached("meta", "keyring", "/keyring", raw=True)
64
+ t0, n = time.time(), 0
65
+ for i in range(a.from_leaf, a.to_leaf):
66
+ rec = cached("records", str(i), "/records/%d" % i)
67
+ n += 1
68
+ if a.tools and rec and (rec.get("change") or {}).get("kind") == "changed":
69
+ sha = (rec.get("tools_fingerprint") or {}).get("sha256") or rec.get("tools_sha256")
70
+ if sha:
71
+ cached("tools", sha, "/tools/%s" % sha)
72
+ prev = rec.get("prev_leaf_index")
73
+ if prev is not None:
74
+ pr = cached("records", str(prev), "/records/%d" % prev)
75
+ psha = pr and ((pr.get("tools_fingerprint") or {}).get("sha256") or pr.get("tools_sha256"))
76
+ if psha:
77
+ cached("tools", psha, "/tools/%s" % psha)
78
+ if n % 100 == 0:
79
+ print("%s leaf %d (%d faits, %.0f s)" % (time.strftime("%H:%M:%S"), i, n, time.time() - t0), flush=True)
80
+ print("FIN collecte %d..%d en %.0f s" % (a.from_leaf, a.to_leaf, time.time() - t0), flush=True)
81
+
82
+
83
+ if __name__ == "__main__":
84
+ sys.exit(main())
data/benchmark/test.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a36ededa697de5825db807c35748422b6d69c3f268894dbb82825bfb2ae46b18
3
+ size 31885533
data/benchmark/test.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e860b8f460fa40866035483865bafd22134529df5e38caee56784644e41c25cc
3
+ size 7921682
data/benchmark/train.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd812ee7c8800a9efe3dcce95d41af9770232f66b79370786eac5725154e24e7
3
+ size 114077643
data/benchmark/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0dca2c4de508b2a2f9eef799ed17b0c1600a5fbeb370ddd0b6415f1a9249a0c
3
+ size 29608376
data/events/test.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/events/test.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d128bc84789f47f546ad5d70d7c4d7b0f0328c09a4daf7145b84e9893488e54
3
+ size 655634
data/events/train.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/events/train.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae84c4292d4665dc3a626604c238b07e5a9265549eecfe675e69d53223777213
3
+ size 1333756
data/sample/benchmark.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/sample/events.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
jcs_min.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sérialisation JSON canonique RFC 8785 (JCS), minimale et autonome : nombres au format ECMAScript (8.0 -> 8, 1e21 -> 1e+21),
2
+ clés triées par unités UTF-16, chaînes échappées comme JSON.stringify. Suffisant pour les données de ce dataset."""
3
+ import json, math
4
+
5
+
6
+ def _num(x):
7
+ if isinstance(x, bool):
8
+ return "true" if x else "false"
9
+ if isinstance(x, int):
10
+ return str(x)
11
+ if math.isnan(x) or math.isinf(x):
12
+ raise ValueError("JCS: NaN/Infinity interdits")
13
+ if x == 0:
14
+ return "0"
15
+ if x.is_integer() and abs(x) < 1e21:
16
+ return str(int(x))
17
+ r = repr(x) # plus courte représentation aller-retour (comme ECMAScript)
18
+ if "e" in r:
19
+ m, e = r.split("e")
20
+ e = int(e)
21
+ if -7 < e < 21: # ECMAScript : notation décimale dans cet intervalle
22
+ return format(x, "f").rstrip("0").rstrip(".") if "." in format(x, "f") else format(x, "f")
23
+ return "%se%s%d" % (m, "+" if e > 0 else "-", abs(e))
24
+ return r
25
+
26
+
27
+ def dumps(o):
28
+ if o is None:
29
+ return "null"
30
+ if isinstance(o, (bool, int, float)):
31
+ return _num(o)
32
+ if isinstance(o, str):
33
+ return json.dumps(o, ensure_ascii=False)
34
+ if isinstance(o, list):
35
+ return "[" + ",".join(dumps(v) for v in o) + "]"
36
+ if isinstance(o, dict):
37
+ ks = sorted(o, key=lambda k: k.encode("utf-16-be"))
38
+ return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + dumps(o[k]) for k in ks) + "}"
39
+ raise TypeError(type(o))
load_example.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Exemples de chargement (local ou, après publication, depuis le Hub).
3
+ pip install datasets # optionnel
4
+ """
5
+ import json, sys
6
+
7
+ # 1) Hugging Face `datasets` (après publication ; REPO_ID à confirmer au GO)
8
+ # from datasets import load_dataset
9
+ # ev = load_dataset("gemmozero/mcp-tool-change-events", "events") # splits: train / test (temporel)
10
+ # bm = load_dataset("gemmozero/mcp-tool-change-events", "benchmark") # splits: train / test (par serveur)
11
+
12
+ # 2) Sans dépendance : JSON Lines
13
+ import os
14
+ import pandas as pd
15
+ ev = pd.read_parquet("data/events/train.parquet").to_dict("records")
16
+ bm = pd.read_parquet("data/benchmark/test.parquet").to_dict("records") if os.path.exists("data/benchmark/test.parquet") else []
17
+ print(len(ev), "events (train);", len(bm), "benchmark rows (test)")
18
+ if not bm:
19
+ raise SystemExit(0)
20
+
21
+ # 3) Tâche benchmark minimale : prédire `label` (added/removed/modified/unchanged) à partir de before/after,
22
+ # ou `description_changed` / `schema_changed`. Baseline exacte (diff textuel) pour vérifier le chargement :
23
+ correct = sum(((x["before_definition"] is None and x["label"] == "added") or (x["after_definition"] is None and x["label"] == "removed") or
24
+ (x["before_definition"] is not None and x["after_definition"] is not None and
25
+ (x["label"] == "unchanged") == (json.loads(x["before_definition"]).get("description") == json.loads(x["after_definition"]).get("description") and
26
+ json.dumps(json.loads(x["before_definition"]).get("inputSchema"), sort_keys=True) == json.dumps(json.loads(x["after_definition"]).get("inputSchema"), sort_keys=True))))
27
+ for x in bm)
28
+ print("exact-diff baseline agreement on test:", correct, "/", len(bm))
29
+
30
+ # 4) Vérifier un record hors ligne : python3 verify.py (signatures Ed25519 + preuves d'inclusion Merkle échantillonnées)
meta/head_43540.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"anchors": {"opentimestamps": {"label": "ancrage pending", "ots_url": "/tlog/v0/anchor/43540/ots", "ots_verify": "not_run", "status": "pending"}, "rekor": {"status": "absent"}}, "claim_boundary": "Tête signée par LEGION. Ancrage pending : scellé seulement quand `ots verify` (client OpenTimestamps + nœud Bitcoin) passe.", "claim_state": "signed_observation_not_anchored", "key_id": "cf9d6db5abbcc13e3a2ae2c25cece35b77f3a330aacfa7194bbfa8a03d2935fd", "sth": {"signature_ed25519": "TuzAtq6JagIG20gmT8GqjfK6yLl8OrjDuy0OWnLaA3TILB39cooJ0G8uw+C11OHknQ//+FQ/io3Lva0Ids1PAA==", "tree_head": {"canonicalization": "RFC 8785 (JCS)", "hash": "SHA-256 RFC 6962 (feuille 0x00, noeud 0x01)", "issuer_pin_sha256": "cf9d6db5abbcc13e3a2ae2c25cece35b77f3a330aacfa7194bbfa8a03d2935fd", "root_sha256": "14c12688c4766fa721731ea6e8f67b28916b4bba4d1ba12eb4dfb637a6595646", "schema": "legion-mcp-tlog-sth/0.1", "timestamp": "2026-10-29T14:43:39Z", "tree_size": 43540}}}
meta/keyring.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14ca2c75193e79050d1697e04ba765b8158c1fab81cc0b24123df6b4cd584ade
3
+ size 2782
validation.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checks": {
3
+ "schema_events_uniform": true,
4
+ "schema_benchmark_uniform": true,
5
+ "no_duplicate_events": true,
6
+ "no_duplicate_benchmark_ids": true,
7
+ "no_train_test_server_overlap_benchmark": true,
8
+ "all_event_record_signatures_valid": true,
9
+ "archived_tools_lists_hash_ok": true,
10
+ "pinned_head_signature_valid": true,
11
+ "inclusion_proofs_sample_ok": true,
12
+ "no_secret_like_patterns": true,
13
+ "benchmark_labels_consistent_with_signed_records": true
14
+ },
15
+ "records_signature_checked": 865,
16
+ "records_signature_bad": 0,
17
+ "tools_lists_checked": 1522,
18
+ "tools_lists_hash_mismatch": 0,
19
+ "inclusion_proofs_sampled": 40,
20
+ "inclusion_proofs_ok": 40,
21
+ "secret_like_patterns_found": 0,
22
+ "status": "DATASET_OK"
23
+ }
verify.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validation du dataset construit (aucun statut écrit à la main).
3
+ 1. schéma : toutes les lignes d'une config ont les mêmes clés ; 2. doublons ; 3. signature Ed25519 de CHAQUE record d'événement
4
+ (clé publique du /keyring public, épinglée par key_id = sha256(clé)) ; 4. intégrité des tools/list archivés (sha256(JCS) == haché signé) ;
5
+ 5. preuves d'inclusion Merkle (RFC 9162) pour un échantillon aléatoire d'événements contre la tête signée épinglée + signature de la tête ;
6
+ 6. balayage secrets (motifs de jetons) + aucun champ hors API publique. Écrit validation.json. Statut : DATASET_OK seulement si tout passe.
7
+ Usage : python3 verify.py [--sample 40]"""
8
+ import base64, glob, hashlib, json, os, random, re, sys, urllib.request
9
+
10
+ HERE = os.path.dirname(os.path.abspath(__file__))
11
+ sys.path.insert(0, HERE)
12
+ from build import SECRET, canon, BASE # noqa: E402
13
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey # noqa: E402
14
+
15
+
16
+ def has(cfg):
17
+ return os.path.exists(os.path.join(HERE, "data", cfg, "train.jsonl")) or os.path.exists(os.path.join(HERE, "data", cfg, "train.parquet"))
18
+
19
+
20
+ def _read(path):
21
+ if os.path.exists(path + ".jsonl"):
22
+ return [json.loads(l) for l in open(path + ".jsonl")]
23
+ import pandas as pd # paquet publié : parquet seulement
24
+ return json.loads(pd.read_parquet(path + ".parquet").to_json(orient="records"))
25
+
26
+
27
+ def meta_dir():
28
+ for d in (os.path.join(HERE, "meta"), os.path.join(HERE, "cache", "meta")):
29
+ if os.path.isdir(d):
30
+ return d
31
+ raise SystemExit("meta/ (keyring + tête signée) introuvable")
32
+
33
+
34
+ def rows(cfg):
35
+ out = []
36
+ for sp in ("train", "test"):
37
+ out += _read(os.path.join(HERE, "data", cfg, sp))
38
+ return out
39
+
40
+
41
+ def leaf_hash(b):
42
+ return hashlib.sha256(b"\x00" + b).digest()
43
+
44
+
45
+ def node(l, r):
46
+ return hashlib.sha256(b"\x01" + l + r).digest()
47
+
48
+
49
+ def root_from_path(index, size, leaf, path):
50
+ fn, sn, r = index, size - 1, leaf
51
+ for p in path:
52
+ if sn == 0:
53
+ return None
54
+ if fn & 1 or fn == sn:
55
+ r = node(p, r)
56
+ while not fn & 1 and fn != 0:
57
+ fn >>= 1
58
+ sn >>= 1
59
+ else:
60
+ r = node(r, p)
61
+ fn >>= 1
62
+ sn >>= 1
63
+ return r if sn == 0 else None
64
+
65
+
66
+ def main():
67
+ k = int(sys.argv[sys.argv.index("--sample") + 1]) if "--sample" in sys.argv else 40
68
+ v = {"checks": {}}
69
+ ev, bm = rows("events"), (rows("benchmark") if has("benchmark") else None)
70
+ v["checks"]["schema_events_uniform"] = len({tuple(sorted(x)) for x in ev}) == 1
71
+ if bm is not None:
72
+ v["checks"]["schema_benchmark_uniform"] = len({tuple(sorted(x)) for x in bm}) == 1
73
+ v["checks"]["no_duplicate_events"] = len({x["leaf_index"] for x in ev}) == len(ev)
74
+ if bm is not None:
75
+ v["checks"]["no_duplicate_benchmark_ids"] = len({x["id"] for x in bm}) == len(bm)
76
+ v["checks"]["no_train_test_server_overlap_benchmark"] = not ({x["server_id"] for x in rows_split("benchmark", "train")} & {x["server_id"] for x in rows_split("benchmark", "test")})
77
+ keys = {}
78
+ for l in open(os.path.join(meta_dir(), "keyring.bin"), encoding="utf-8"):
79
+ if l.strip():
80
+ kk = json.loads(l)
81
+ if kk.get("public_key_b64"):
82
+ keys[hashlib.sha256(base64.b64decode(kk["public_key_b64"])).hexdigest()] = kk["public_key_b64"]
83
+ bad = 0
84
+ for x in ev:
85
+ r = json.loads(x["signed_record"])
86
+ sig = r.pop("signature_ed25519")
87
+ try:
88
+ Ed25519PublicKey.from_public_bytes(base64.b64decode(keys[r["key_id"]])).verify(base64.b64decode(sig), canon(r).encode())
89
+ except Exception:
90
+ bad += 1
91
+ v["records_signature_checked"], v["records_signature_bad"] = len(ev), bad
92
+ v["checks"]["all_event_record_signatures_valid"] = bad == 0 and len(ev) > 0
93
+ tbad = tn = 0
94
+ for p in glob.glob(os.path.join(HERE, "cache", "tools", "*.json")): # vide dans le paquet publié -> contrôle N/A
95
+ d = json.load(open(p))
96
+ tn += 1
97
+ tbad += hashlib.sha256(canon(d["tools"]).encode()).hexdigest() != d["tools_sha256"]
98
+ v["tools_lists_checked"], v["tools_lists_hash_mismatch"] = tn, tbad
99
+ if tn:
100
+ v["checks"]["archived_tools_lists_hash_ok"] = tbad == 0
101
+ else:
102
+ v["not_applicable"] = ["archived_tools_lists_hash_ok (no cache/tools in this copy: re-fetch with collect.py --tools to run it)"]
103
+ head = json.load(open(sorted(glob.glob(os.path.join(meta_dir(), "head_*.json")))[-1]))
104
+ th = head["sth"]["tree_head"]
105
+ try:
106
+ Ed25519PublicKey.from_public_bytes(base64.b64decode(keys[th["issuer_pin_sha256"]])).verify(base64.b64decode(head["sth"]["signature_ed25519"]), canon(th).encode())
107
+ v["checks"]["pinned_head_signature_valid"] = True
108
+ except Exception:
109
+ v["checks"]["pinned_head_signature_valid"] = False
110
+ random.seed(20261029)
111
+ smp = random.sample(ev, min(k, len(ev)))
112
+ ok = 0
113
+ for x in smp:
114
+ pr = json.load(urllib.request.urlopen(urllib.request.Request(x["inclusion_proof_url"], headers={"User-Agent": "legion-hf-dataset-verify/0.1"}), timeout=60))
115
+ rt = root_from_path(x["leaf_index"], th["tree_size"], leaf_hash(x["signed_record"].encode()), [bytes.fromhex(h) for h in pr["audit_path"]])
116
+ ok += bool(rt and rt.hex() == th["root_sha256"])
117
+ v["inclusion_proofs_sampled"], v["inclusion_proofs_ok"] = len(smp), ok
118
+ v["checks"]["inclusion_proofs_sample_ok"] = ok == len(smp) and len(smp) > 0
119
+ blob = "\n".join(json.dumps(x, ensure_ascii=False) for x in ev + (bm or []))
120
+ v["secret_like_patterns_found"] = len(SECRET.findall(blob))
121
+ v["checks"]["no_secret_like_patterns"] = v["secret_like_patterns_found"] == 0
122
+ if bm is not None:
123
+ v["checks"]["benchmark_labels_consistent_with_signed_records"] = all(x["label_matches_signed_record"] for x in bm)
124
+ v["status"] = "DATASET_OK" if all(v["checks"].values()) else "REVIEW_REQUIRED"
125
+ out = os.path.join(HERE, "validation.json") if os.path.isdir(os.path.join(HERE, "cache")) else os.path.join(HERE, "validation_local_rerun.json")
126
+ json.dump(v, open(out, "w"), indent=1)
127
+ print(json.dumps(v, indent=1))
128
+
129
+
130
+ def rows_split(cfg, sp):
131
+ return _read(os.path.join(HERE, "data", cfg, sp))
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()