#!/usr/bin/env -S uv run # /// script # requires-python = ">=3.11" # dependencies = [ # "huggingface_hub>=1.24.0", # ] # /// """Create the immutable legacy initialize-traffic dashboard backfill once.""" from __future__ import annotations import argparse import json import sys import tempfile from collections import defaultdict from datetime import date, timedelta from pathlib import Path from typing import Any from huggingface_hub import CommitOperationAdd, HfApi, HfFileSystem, hf_hub_download try: import pipeline except ModuleNotFoundError: helper = hf_hub_download("evalstate/mcp-clients", "pipeline.py", repo_type="dataset") sys.path.insert(0, str(Path(helper).parent)) import pipeline def session_paths(fs: HfFileSystem, repo: str, revision: str, start: date, through: date) -> list[str]: paths = [] for day in pipeline.daterange(start - timedelta(days=1), through + timedelta(days=1)): paths.extend(sorted(fs.glob(f"datasets/{repo}@{revision}/sessions/{day}/*.jsonl"))) return paths def protocol_version(row: dict[str, Any]) -> str | None: if row.get("methodName") != "initialize" or not isinstance(row.get("requestJson"), str): return None try: request = json.loads(row["requestJson"]) except json.JSONDecodeError: return None value = request.get("protocolVersion") if isinstance(request, dict) else None return value if value in pipeline.VALID_PROTOCOLS else None def historical_other_names( fs: HfFileSystem, repo: str, revision: str, start: date, through: date, ) -> set[str]: totals: dict[str, int] = defaultdict(int) for path in pipeline.report_paths(fs, repo, revision, start, through): with fs.open(path, "rt") as stream: for line in stream: try: row = json.loads(line) seen = pipeline.parse_time(row["time"]) except (json.JSONDecodeError, KeyError, TypeError, ValueError): continue name = row.get("name") if ( not start <= seen.date() <= through or row.get("methodName") in {"initialize", "session_delete"} or not isinstance(name, str) or not name or "mcp-remote" in name.casefold() or pipeline.client_group(name) ): continue totals[name] += 1 return {name for name, calls in totals.items() if calls >= pipeline.OTHER_MINIMUM_TOOL_CALLS} def backfill_report(fs: HfFileSystem, repo: str, revision: str, start: date, through: date) -> dict[str, Any]: named_daily: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) other_daily: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) group_names: dict[str, set[str]] = defaultdict(set) capability_counts: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) included_other = historical_other_names(fs, repo, revision, start, through) observed_other: set[str] = set() for path in session_paths(fs, repo, revision, start, through): with fs.open(path, "rt") as stream: for line in stream: try: row = json.loads(line) seen = pipeline.parse_time(row["time"]) except (json.JSONDecodeError, KeyError, TypeError, ValueError): continue if not start <= seen.date() <= through: continue name = row.get("name") protocol = protocol_version(row) if not isinstance(name, str) or not name or "mcp-remote" in name.casefold() or not protocol: continue stamp = seen.date().isoformat() group = pipeline.client_group(name) if group: named_daily[group][stamp][protocol] += 1 group_names[group].add(name) capability_counts[group]["observations"] += 1 flags, valid = pipeline.feature_flags(row.get("capabilities")) if valid and flags: for feature in pipeline.HISTORICAL_CAPABILITY_FEATURES: capability_counts[group][feature] += flags[feature] elif name in included_other: other_daily[stamp][protocol] += 1 observed_other.add(name) dates = [day.isoformat() for day in pipeline.daterange(start, through)] return { "schema_version": 2, "kind": "legacy_initialize_protocol_backfill", "window": {"start": start.isoformat(), "end": through.isoformat()}, "cutover": {"first_request_date": pipeline.QUERY_CUTOVER.isoformat()}, "clients": [ { "id": group, "source_names": sorted(group_names[group]), "capability_support": { feature: bool( capability_counts[group]["observations"] and capability_counts[group][feature] / capability_counts[group]["observations"] > pipeline.CAPABILITY_PROPORTION_THRESHOLD ) for feature in pipeline.HISTORICAL_CAPABILITY_FEATURES }, "traffic": pipeline.protocol_series(named_daily[group], dates, "initialize"), } for group, _ in pipeline.CLIENT_GROUPS ], "everything_else": { "source_names": sorted(observed_other), "traffic": pipeline.protocol_series(other_daily, dates, "initialize"), }, } def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--source-repo", default=pipeline.SOURCE_REPO) parser.add_argument("--target-repo", default=pipeline.TARGET_REPO) parser.add_argument("--since", default="2026-06-07") parser.add_argument("--through", default=(pipeline.QUERY_CUTOVER - timedelta(days=1)).isoformat()) args = parser.parse_args() start, through = date.fromisoformat(args.since), date.fromisoformat(args.through) if through >= pipeline.QUERY_CUTOVER: parser.error("--through must precede the query cutover") api, fs = HfApi(), HfFileSystem() source = api.repo_info(args.source_repo, repo_type="dataset") target = api.repo_info(args.target_repo, repo_type="dataset") report = backfill_report(fs, args.source_repo, source.sha, start, through) with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "dashboard-session-backfill-v1.json" path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") commit = api.create_commit( repo_id=args.target_repo, repo_type="dataset", parent_commit=target.sha, commit_message=f"Backfill dashboard protocol traffic through {through}", commit_description=( "One-time legacy initialize-traffic backfill. " f"Source: {args.source_repo}@{source.sha}; dates: {start} through {through}." ), operations=[CommitOperationAdd(path_in_repo=pipeline.BACKFILL_PATH, path_or_fileobj=path)], ) print(f"published https://huggingface.co/datasets/{args.target_repo}/commit/{commit.oid}") return 0 if __name__ == "__main__": raise SystemExit(main())