#!/usr/bin/env -S uv run # /// script # requires-python = ">=3.11" # dependencies = [ # "huggingface_hub>=1.24.0", # "pyarrow>=18.0.0", # ] # /// """Incrementally publish MCP client observations.""" from __future__ import annotations import argparse import json import re import sys import tempfile from collections import defaultdict, deque from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import Any, Iterable from huggingface_hub import CommitOperationAdd, HfApi, HfFileSystem, hf_hub_download from huggingface_hub.errors import EntryNotFoundError SOURCE_REPO = "evalstate/hf-mcp-logs" TARGET_REPO = "evalstate/mcp-clients" RAW_PATH = "raw/raw-00000-of-00001.parquet" DEDUP_PATH = "deduplicated/deduplicated-00000-of-00001.parquet" STATE_PATH = "state/mcp-clients-v1.json" REPORT_PATH = "reports/dashboard-v1.json" BACKFILL_PATH = "reports/dashboard-session-backfill-v1.json" CAPABILITY_BACKFILL_PATH = "reports/dashboard-capability-backfill-v1.json" QUERY_CUTOVER = date(2026, 7, 27) MCP_REMOTE = re.compile(r"\s*\(via mcp-remote [\d.]+\)") VALID_PROTOCOLS = ("2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25", "2026-07-28") MODERN_PROTOCOL = "2026-07-28" CAPABILITY_PROPORTION_THRESHOLD = 0.5 OTHER_MINIMUM_TOOL_CALLS = 1000 CAPABILITY_FEATURES = ("elicitation", "elicitation_url", "mcp_apps", "skills", "tasks") HISTORICAL_CAPABILITY_FEATURES = ("elicitation", "elicitation_url", "mcp_apps") CLIENT_GROUPS = ( ("claude-code", "Claude Code"), ("claude-ai", "Claude.ai"), ("codex-cli", "Codex CLI"), ("codex-web", "Codex Desktop"), ("openai", "OpenAI ChatGPT"), ("huggingface-chatui", "Hugging Face ChatUI"), ("opencode", "OpenCode"), ("cursor", "Cursor"), ("visual-studio-code", "Visual Studio Code"), ("llama-ui", "Llama UI"), ("fast-agent", "fast-agent"), ("antigravity", "Antigravity"), ) README = """--- configs: - config_name: raw data_files: - split: raw path: raw/raw-* - config_name: deduplicated data_files: - split: deduplicated path: deduplicated/deduplicated-* license: mit tags: - code - agent --- # MCP Clients Dataset MCP client identity and capability observations from `huggingface.co/mcp`. The pipeline incrementally processes completed daily source partitions. Each release records its source revision and watermark in `state/mcp-clients-v1.json` and a sanitized 60-day dashboard snapshot in `reports/dashboard-v1.json`. Its `window` is the requested UTC date range. Omitted client traffic dates are unavailable data, not zero traffic. Protocol traffic before 2026-07-27 is a one-time, immutable backfill from legacy `initialize` records; newer traffic is derived from requests. Each traffic point identifies its source. Historical capability evidence is limited to elicitation, URL elicitation, and MCP Apps; Skills and Tasks are request-only. Historical “All other clients” traffic is a best-effort initialization-based aggregate of unclassified names with at least 1,000 legacy tool calls. Current “All other clients” traffic remains request-based and requires at least 1,000 valid-protocol tool calls in the report window. Successful extension-method observations that were available only in cumulative transport metrics are published as a sanitized, restart-aware capability backfill. Evidence applies only while its observation date overlaps the rolling dashboard window and does not contribute to protocol traffic volume. ## Configurations ### `raw` One row per distinct `(name, version, capabilities)` with its latest observed `last_seen` time. | Column | Description | |---|---| | `name` | Client-provided client name | | `version` | Client-provided version | | `capabilities` | Canonicalized capabilities JSON or original string | | `last_seen` | Latest observed RFC 3339 timestamp | ### `deduplicated` One row per normalized `(name, capabilities)`. `mcp-remote` suffixes are removed from names; observed versions are stored as a comma-separated string. | Column | Description | |---|---| | `name` | Normalized client name | | `versions` | Lexically sorted distinct versions | | `capabilities` | Canonicalized capabilities JSON or original string | | `last_seen` | Latest observed RFC 3339 timestamp | Client-provided fields are untrusted telemetry. Consumers should not treat names, versions, or capability values as verified claims. ## Reproducibility Every successful release atomically publishes both configurations, `state/mcp-clients-v1.json`, and `reports/dashboard-v1.json`. The state file identifies the immutable source revision and completed source-date watermark used for that release. """ def parse_time(value: str) -> datetime: parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) if parsed.tzinfo is None: raise ValueError("timestamp must include a timezone") return parsed.astimezone(timezone.utc) def capabilities(value: Any) -> str: if value is None: return "" if isinstance(value, str): try: value = json.loads(value) except json.JSONDecodeError: return value if isinstance(value, dict): return json.dumps(value, sort_keys=True) return str(value) def raw_key(row: dict[str, str]) -> tuple[str, str, str]: return row["name"], row["version"], row["capabilities"] def event_to_raw(event: dict[str, Any]) -> dict[str, str] | None: if event.get("methodName") != "initialize": return None name, version, seen = event.get("name"), event.get("version"), event.get("time") if not all(isinstance(value, str) and value for value in (name, version, seen)): return None parse_time(seen) return { "name": name, "version": version, "capabilities": capabilities(event.get("capabilities")), "last_seen": seen, } def merge(rows: Iterable[dict[str, str]], events: Iterable[dict[str, Any]]) -> tuple[dict[tuple[str, str, str], dict[str, str]], int]: state: dict[tuple[str, str, str], dict[str, str]] = {} for row in rows: normalized = { "name": row["name"], "version": row["version"], "capabilities": capabilities(row.get("capabilities")), "last_seen": row["last_seen"], } parse_time(normalized["last_seen"]) state[raw_key(normalized)] = normalized updates = 0 for event in events: row = event_to_raw(event) if row is None: continue key = raw_key(row) if key not in state or parse_time(row["last_seen"]) > parse_time(state[key]["last_seen"]): state[key] = row updates += 1 return state, updates def deduplicate(rows: Iterable[dict[str, str]]) -> list[dict[str, str]]: groups: dict[tuple[str, str], dict[str, Any]] = {} for row in rows: name = MCP_REMOTE.sub("", row["name"]).strip() key = name, row["capabilities"] group = groups.setdefault(key, {"versions": set(), "latest": row}) group["versions"].add(row["version"]) if parse_time(row["last_seen"]) > parse_time(group["latest"]["last_seen"]): group["latest"] = row return sorted( ( { "name": name, "versions": ",".join(sorted(group["versions"])), "capabilities": group["latest"]["capabilities"], "last_seen": group["latest"]["last_seen"], } for (name, _), group in groups.items() ), key=lambda row: (-parse_time(row["last_seen"]).timestamp(), row["name"], row["capabilities"]), ) def sorted_raw(state: dict[tuple[str, str, str], dict[str, str]]) -> list[dict[str, str]]: return sorted(state.values(), key=lambda row: (-parse_time(row["last_seen"]).timestamp(), *raw_key(row))) def daterange(start: date, through: date) -> Iterable[date]: while start <= through: yield start start += timedelta(days=1) def load_raw(repo: str, revision: str) -> list[dict[str, str]]: import pyarrow.parquet as pq path = hf_hub_download(repo, RAW_PATH, repo_type="dataset", revision=revision) return pq.read_table(path).to_pylist() def load_state(repo: str, revision: str) -> dict[str, Any] | None: try: path = hf_hub_download(repo, STATE_PATH, repo_type="dataset", revision=revision) except EntryNotFoundError: return None return json.loads(Path(path).read_text()) def load_backfill(repo: str, revision: str) -> dict[str, Any] | None: try: path = hf_hub_download(repo, BACKFILL_PATH, repo_type="dataset", revision=revision) except EntryNotFoundError: return None return json.loads(Path(path).read_text()) def load_capability_backfill(repo: str, revision: str) -> dict[str, Any] | None: try: path = hf_hub_download(repo, CAPABILITY_BACKFILL_PATH, repo_type="dataset", revision=revision) except EntryNotFoundError: return None return json.loads(Path(path).read_text()) def capability_backfill_support( backfill: dict[str, Any] | None, client_id: str, start: date, through: date, ) -> set[str]: supported = set() for evidence in backfill.get("evidence", []) if backfill else []: if evidence.get("client_id") != client_id or evidence.get("feature") not in CAPABILITY_FEATURES: continue for point in evidence.get("daily", []): try: observed = date.fromisoformat(point["date"]) calls = int(point["observed_successful_calls"]) except (KeyError, TypeError, ValueError): continue if start <= observed <= through and calls > 0: supported.add(evidence["feature"]) break return supported def write_parquet(path: Path, rows: list[dict[str, str]], columns: list[str]) -> None: import pyarrow as pa import pyarrow.parquet as pq table = pa.Table.from_pylist(rows, schema=pa.schema([(column, pa.string()) for column in columns])) pq.write_table(table, path, compression="zstd") def source_paths(fs: HfFileSystem, repo: str, revision: str, days: Iterable[date]) -> dict[str, list[str]]: found = {} for day in days: stamp = day.isoformat() paths = sorted(fs.glob(f"datasets/{repo}@{revision}/sessions/{stamp}/*.jsonl")) if not paths: raise RuntimeError(f"no source session files for {stamp}; refusing to advance watermark") found[stamp] = paths return found def source_lines( fs: HfFileSystem, path: str, repo: str, revision: str, download=hf_hub_download, ) -> list[str]: try: with fs.open(path, "rt") as stream: text = stream.read() except Exception as error: if "timed out" not in str(error).casefold(): raise prefix = f"datasets/{repo}@{revision}/" if not path.startswith(prefix): raise RuntimeError(f"cannot resolve timed-out source path: {path}") from error filename = path.removeprefix(prefix) print(f"stream timed out; downloading complete source shard: {filename}", file=sys.stderr) cached = download(repo_id=repo, filename=filename, repo_type="dataset", revision=revision) text = Path(cached).read_text() return text.splitlines() def read_events( fs: HfFileSystem, paths: Iterable[str], counters: dict[str, int], repo: str, revision: str, ) -> Iterable[dict[str, Any]]: for path in paths: for line in source_lines(fs, path, repo, revision): counters["source_rows"] += 1 try: event = json.loads(line) except json.JSONDecodeError: counters["invalid_json"] += 1 continue if event.get("methodName") == "initialize": counters["initialize_rows"] += 1 yield event def client_group(name: str) -> str | None: value = name.casefold() if "mcp-remote" in value: return None if value == "claude-code": return "claude-code" if value == "anthropic/claudeai": return "claude-ai" if value == "codex-mcp-client": return "codex-cli" if value == "openai-mcp (codex)": return "codex-web" if value == "openai-mcp": return "openai" if value == "chat-ui-mcp": return "huggingface-chatui" if value == "opencode": return "opencode" if "cursor" in value: return "cursor" if value in {"visual studio code", "visual studio code - insiders"}: return "visual-studio-code" if value == "llama-ui-mcp": return "llama-ui" if value == "fast-agent-mcp": return "fast-agent" if value in {"antigravity", "antigravity-client"}: return "antigravity" return None def feature_flags(capabilities_value: str | None) -> tuple[dict[str, bool] | None, bool]: if not isinstance(capabilities_value, str) or not capabilities_value: return None, False try: capabilities_object = json.loads(capabilities_value) except json.JSONDecodeError: return None, False if not isinstance(capabilities_object, dict): return None, False extensions = capabilities_object.get("extensions") extensions = extensions if isinstance(extensions, dict) else {} elicitation = capabilities_object.get("elicitation") return { "elicitation": "elicitation" in capabilities_object, "elicitation_url": isinstance(elicitation, dict) and "url" in elicitation, "mcp_apps": "io.modelcontextprotocol/ui" in extensions, "tasks": "io.modelcontextprotocol/tasks" in extensions, }, True def report_paths(fs: HfFileSystem, repo: str, revision: str, start: date, through: date) -> list[str]: paths = [] for day in daterange(start - timedelta(days=1), through + timedelta(days=1)): paths.extend(sorted(fs.glob(f"datasets/{repo}@{revision}/queries/{day}/*.jsonl"))) return paths def proportions(versions: dict[str, int]) -> dict[str, float]: total = sum(versions.values()) return {version: round(calls / total, 6) for version, calls in versions.items() if calls} if total else {} def protocol_series( daily: dict[str, dict[str, int]], dates: list[str], source: str, days: int = 30 ) -> list[dict[str, Any]]: window: deque[dict[str, int]] = deque() rolling: dict[str, int] = defaultdict(int) result = [] for stamp in dates: versions = daily[stamp] window.append(versions) for version, calls in versions.items(): rolling[version] += calls if len(window) > days: expired = window.popleft() for version, calls in expired.items(): rolling[version] -= calls daily_proportions = proportions(versions) if daily_proportions: result.append( { "date": stamp, "source": source, "daily_protocol_proportions": daily_proportions, "rolling_30d_protocol_proportions": proportions(rolling), } ) return result def report_rows(rows: list[dict[str, Any]], start: date, through: date) -> list[dict[str, Any]]: return [row for row in rows if start.isoformat() <= row["date"] <= through.isoformat()] def merge_traffic(historical: list[dict[str, Any]], current: list[dict[str, Any]]) -> list[dict[str, Any]]: merged = {row["date"]: row for row in historical} if set(merged) & {row["date"] for row in current}: raise ValueError("historical and request traffic overlap") merged.update({row["date"]: row for row in current}) return [merged[stamp] for stamp in sorted(merged)] def dashboard_report( fs: HfFileSystem, repo: str, revision: str, through: date, report_days: int, backfill: dict[str, Any] | None = None, capability_backfill: dict[str, Any] | None = None, ) -> dict[str, Any]: start = through - timedelta(days=report_days - 1) named_daily: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) other_daily: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) group_names: dict[str, set[str]] = defaultdict(set) other_totals: dict[str, int] = defaultdict(int) capability_counts: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) health: dict[str, int] = defaultdict(int) paths = report_paths(fs, repo, revision, start, through) for path in paths: for line in source_lines(fs, path, repo, revision): try: row = json.loads(line) seen = parse_time(row["time"]) except (json.JSONDecodeError, KeyError, TypeError, ValueError): health["invalid_query_rows"] += 1 continue if not start <= seen.date() <= through or row.get("methodName") in {"initialize", "session_delete"}: continue name = row.get("name") if not isinstance(name, str) or not name: health["missing_client_name_tool_calls"] += 1 continue if "mcp-remote" in name.casefold(): health["excluded_mcp_remote_tool_calls"] += 1 continue protocol = row.get("protocolVersion") if not isinstance(protocol, str) or not protocol: health["missing_protocol_version_tool_calls"] += 1 continue if protocol not in VALID_PROTOCOLS: health["invalid_protocol_version_tool_calls"] += 1 continue stamp = seen.date().isoformat() health["valid_tool_calls"] += 1 group = client_group(name) if group: named_daily[group][stamp][protocol] += 1 group_names[group].add(name) if protocol == MODERN_PROTOCOL: capability_counts[group]["observations"] += 1 flags, valid = feature_flags(row.get("clientCapabilities")) health["modern_tool_calls_with_valid_capabilities" if valid else "modern_tool_calls_without_valid_capabilities"] += 1 if valid and flags: for feature, present in flags.items(): capability_counts[group][feature] += present else: other_daily[name][stamp][protocol] += 1 other_totals[name] += 1 dates = [day.isoformat() for day in daterange(start, through)] coverage = {} if backfill: coverage["initialize_backfill_through"] = backfill["window"]["end"] if through >= QUERY_CUTOVER: coverage["request_traffic_from"] = QUERY_CUTOVER.isoformat() historical_clients = {client["id"]: client for client in backfill.get("clients", [])} if backfill else {} clients = [] for group, label in CLIENT_GROUPS: counts = capability_counts[group] historical = historical_clients.get(group, {}) backfilled_support = capability_backfill_support(capability_backfill, group, start, through) current = protocol_series(named_daily[group], dates, "request") observations = counts["observations"] current_support = { feature: observations and counts[feature] / observations > CAPABILITY_PROPORTION_THRESHOLD for feature in CAPABILITY_FEATURES } historical_support = historical.get("capability_support", {}) clients.append( { "id": group, "label": label, "source_names": sorted(set(historical.get("source_names", [])) | group_names[group]), "capability_support_60d": { feature: bool( current_support[feature] or feature in backfilled_support or ( feature in HISTORICAL_CAPABILITY_FEATURES and historical_support.get(feature) ) ) for feature in CAPABILITY_FEATURES }, "traffic": merge_traffic(report_rows(historical.get("traffic", []), start, through), current), } ) included_other = sorted(name for name, calls in other_totals.items() if calls >= OTHER_MINIMUM_TOOL_CALLS) other_daily_aggregate: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int)) for stamp in dates: for name in included_other: for version, calls in other_daily[name][stamp].items(): other_daily_aggregate[stamp][version] += calls historical_other = backfill.get("everything_else", {}) if backfill else {} current_other = protocol_series(other_daily_aggregate, dates, "request") return { "schema_version": 2, "generated_at": datetime.now(timezone.utc).isoformat(), "window": {"start": start.isoformat(), "end": through.isoformat()}, "coverage": coverage, "policy": { "modern_protocol_version": MODERN_PROTOCOL, "valid_protocol_versions": list(VALID_PROTOCOLS), "capability_proportion_threshold": CAPABILITY_PROPORTION_THRESHOLD, "elicitation_historical_source": "initialize.capabilities.elicitation", "elicitation_request_source": "clientCapabilities.elicitation", "elicitation_url_historical_source": "initialize.capabilities.elicitation.url", "elicitation_url_request_source": "clientCapabilities.elicitation.url", "mcp_apps_historical_source": "initialize.capabilities.extensions.io.modelcontextprotocol/ui", "mcp_apps_request_source": "clientCapabilities.extensions.io.modelcontextprotocol/ui", **( { "capability_backfill_path": CAPABILITY_BACKFILL_PATH, "skills_observation_source": "successful client-originated skills/list transport metrics", } if capability_backfill else {} ), "historical_capability_limit": list(HISTORICAL_CAPABILITY_FEATURES), "mcp_remote_policy": "excluded", "everything_else_minimum_tool_calls": OTHER_MINIMUM_TOOL_CALLS, "everything_else_historical_qualification": "legacy tool calls in immutable initialize backfill window", "everything_else_request_qualification": "valid-protocol tool calls in report window", }, "clients": clients, "everything_else": { "source_names": sorted(set(historical_other.get("source_names", [])) | set(included_other)), "traffic": merge_traffic( report_rows(historical_other.get("traffic", []), start, through), current_other, ), }, } def initial_start(rows: list[dict[str, str]], state: dict[str, Any] | None, overlap: int) -> date: completed = date.fromisoformat(state["completed_through"]) if state else max(parse_time(row["last_seen"]).date() for row in rows) return completed - timedelta(days=overlap) def run(args: argparse.Namespace) -> int: api = HfApi() target = api.repo_info(args.target_repo, repo_type="dataset") source = api.repo_info(args.source_repo, repo_type="dataset") rows = load_raw(args.target_repo, target.sha) previous = load_state(args.target_repo, target.sha) through = date.fromisoformat(args.through) if args.through else date.today() - timedelta(days=1) start = date.fromisoformat(args.since) if args.since else initial_start(rows, previous, args.overlap_days) if args.max_days: through = min(through, start + timedelta(days=args.max_days - 1)) if start > through: print(f"nothing to process: start={start}, through={through}") return 0 fs = HfFileSystem() partitions = source_paths(fs, args.source_repo, source.sha, daterange(start, through)) counters: dict[str, int] = defaultdict(int) events = read_events( fs, (path for paths in partitions.values() for path in paths), counters, args.source_repo, source.sha, ) state, updates = merge(rows, events) raw, dedup = sorted_raw(state), deduplicate(state.values()) report = dashboard_report( fs, args.source_repo, source.sha, through, args.report_days, load_backfill(args.target_repo, target.sha), load_capability_backfill(args.target_repo, target.sha), ) manifest = { "format": 1, "generated_at": datetime.now(timezone.utc).isoformat(), "pipeline_revision": target.sha, "previous_target_revision": target.sha, "source_repo": args.source_repo, "source_revision": source.sha, "completed_through": through.isoformat(), "overlap_days": args.overlap_days, "max_days": args.max_days, "partitions": {day: len(paths) for day, paths in partitions.items()}, "source_rows": counters["source_rows"], "initialize_rows": counters["initialize_rows"], "invalid_json": counters["invalid_json"], "updates": updates, "raw_records": len(raw), "deduplicated_records": len(dedup), "dashboard": {"path": REPORT_PATH, "window_start": report["window"]["start"], "window_end": report["window"]["end"]}, } print(json.dumps(manifest, indent=2, sort_keys=True)) if args.dry_run: return 0 with tempfile.TemporaryDirectory() as directory: directory = Path(directory) raw_file, dedup_file, state_file, readme_file, report_file = ( directory / "raw.parquet", directory / "deduplicated.parquet", directory / "state.json", directory / "README.md", directory / "dashboard-v1.json", ) write_parquet(raw_file, raw, ["name", "version", "capabilities", "last_seen"]) write_parquet(dedup_file, dedup, ["name", "versions", "capabilities", "last_seen"]) state_file.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") readme_file.write_text(README) report_file.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"Update MCP clients through {through}", commit_description=f"Source: {args.source_repo}@{source.sha}\n\nPartitions: {start} through {through}; {counters['source_rows']:,} rows scanned.", operations=[ CommitOperationAdd(path_in_repo=RAW_PATH, path_or_fileobj=raw_file), CommitOperationAdd(path_in_repo=DEDUP_PATH, path_or_fileobj=dedup_file), CommitOperationAdd(path_in_repo=STATE_PATH, path_or_fileobj=state_file), CommitOperationAdd(path_in_repo=REPORT_PATH, path_or_fileobj=report_file), CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=readme_file), ], ) print(f"published https://huggingface.co/datasets/{args.target_repo}/commit/{commit.oid}") return 0 def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--source-repo", default=SOURCE_REPO) parser.add_argument("--target-repo", default=TARGET_REPO) parser.add_argument("--since", help="first source date (YYYY-MM-DD)") parser.add_argument("--through", help="last complete source date (YYYY-MM-DD)") parser.add_argument("--overlap-days", type=int, default=1) parser.add_argument("--max-days", type=int, default=5, help="hard cap on source dates per run (0 means unlimited)") parser.add_argument("--report-days", type=int, default=60, help="completed UTC dates in the dashboard report") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() if args.overlap_days < 0 or args.max_days < 0 or args.report_days < 1: parser.error("--overlap-days and --max-days must be non-negative; --report-days must be positive") try: return run(args) except Exception as error: print(f"pipeline failed: {error}", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())