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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env -S uv run
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.10"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "datasets",
|
| 6 |
+
# "huggingface_hub",
|
| 7 |
+
# ]
|
| 8 |
+
# ///
|
| 9 |
+
"""
|
| 10 |
+
Extract unique MCP client combinations (name, version, capabilities) from evalstate/hf-mcp-logs dataset.
|
| 11 |
+
Only processes "initialize" method calls - ignores "session_delete" events which lack complete client information.
|
| 12 |
+
Tracks most recent "last seen" timestamp for each unique client configuration.
|
| 13 |
+
Uses batched streaming for efficient I/O on large datasets (~7M rows).
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
# Process all data and save to local file
|
| 17 |
+
python3.10 extract_mcp_clients.py -o clients.ndjson
|
| 18 |
+
|
| 19 |
+
# Push to Hugging Face Hub (creates/updates evalstate/mcp-clients dataset)
|
| 20 |
+
python3.10 extract_mcp_clients.py --push-to-hub
|
| 21 |
+
|
| 22 |
+
# Push to a specific split (for scheduled pipelines)
|
| 23 |
+
python3.10 extract_mcp_clients.py --push-to-hub --split raw
|
| 24 |
+
|
| 25 |
+
# Process a sample for testing
|
| 26 |
+
python3.10 extract_mcp_clients.py --limit 10000 -o sample.ndjson
|
| 27 |
+
|
| 28 |
+
Output fields:
|
| 29 |
+
- name: MCP client name (e.g., "Cursor", "Anthropic/ClaudeAI", "chat-ui-mcp")
|
| 30 |
+
- version: Client version
|
| 31 |
+
- capabilities: Client capabilities (JSON object or null)
|
| 32 |
+
- last_seen: Most recent timestamp when this client was seen
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import argparse
|
| 36 |
+
import json
|
| 37 |
+
import sys
|
| 38 |
+
from datetime import datetime
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
|
| 41 |
+
from datasets import Dataset, Features, Value
|
| 42 |
+
from huggingface_hub import HfApi
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def normalize_capabilities(caps):
|
| 46 |
+
"""Normalize capabilities for comparison."""
|
| 47 |
+
if caps is None:
|
| 48 |
+
return None
|
| 49 |
+
if isinstance(caps, str):
|
| 50 |
+
# Parse stringified JSON if needed
|
| 51 |
+
if caps == '{}':
|
| 52 |
+
return {}
|
| 53 |
+
try:
|
| 54 |
+
return json.loads(caps)
|
| 55 |
+
except Exception:
|
| 56 |
+
return caps
|
| 57 |
+
return caps
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def create_dataset_from_clients(clients_list, features=None):
|
| 61 |
+
"""Create a Hugging Face Dataset from the clients list."""
|
| 62 |
+
if features is None:
|
| 63 |
+
features = Features({
|
| 64 |
+
'name': Value('string'),
|
| 65 |
+
'version': Value('string'),
|
| 66 |
+
'capabilities': Value('null'), # Will be inferred
|
| 67 |
+
'last_seen': Value('string'),
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
# Convert to records format for Dataset
|
| 71 |
+
records = []
|
| 72 |
+
for client in clients_list:
|
| 73 |
+
record = {
|
| 74 |
+
'name': client['name'],
|
| 75 |
+
'version': client['version'],
|
| 76 |
+
'capabilities': client['capabilities'],
|
| 77 |
+
'last_seen': client['last_seen'],
|
| 78 |
+
}
|
| 79 |
+
records.append(record)
|
| 80 |
+
|
| 81 |
+
return Dataset.from_list(records, features=features)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def push_to_hub(clients_list, repo_id, split=None, token=None, private=False):
|
| 85 |
+
"""Push the clients dataset to Hugging Face Hub."""
|
| 86 |
+
# Create dataset from clients
|
| 87 |
+
dataset = create_dataset_from_clients(clients_list)
|
| 88 |
+
|
| 89 |
+
# Determine split for push
|
| 90 |
+
if split:
|
| 91 |
+
print(f"Pushing dataset to https://huggingface.co/datasets/{repo_id} (split: {split})", file=sys.stderr)
|
| 92 |
+
else:
|
| 93 |
+
print(f"Pushing dataset to https://huggingface.co/datasets/{repo_id}", file=sys.stderr)
|
| 94 |
+
|
| 95 |
+
# Push to hub with optional split
|
| 96 |
+
dataset.push_to_hub(
|
| 97 |
+
repo_id=repo_id,
|
| 98 |
+
split=split,
|
| 99 |
+
token=token,
|
| 100 |
+
private=private,
|
| 101 |
+
commit_message=f"Update MCP clients dataset ({datetime.now().strftime('%Y-%m-%d %H:%M')})",
|
| 102 |
+
)
|
| 103 |
+
print(f"Successfully pushed {len(clients_list):,} clients to {repo_id}", file=sys.stderr)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def main():
|
| 107 |
+
parser = argparse.ArgumentParser(
|
| 108 |
+
description="Extract unique MCP clients with last seen timestamp from evalstate/hf-mcp-logs",
|
| 109 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 110 |
+
epilog="""
|
| 111 |
+
Examples:
|
| 112 |
+
# Process all data and save to local file
|
| 113 |
+
%(prog)s -o clients.ndjson
|
| 114 |
+
|
| 115 |
+
# Push to Hugging Face Hub (requires authentication: `hf auth login`)
|
| 116 |
+
%(prog)s --push-to-hub
|
| 117 |
+
|
| 118 |
+
# Push to a specific split (ideal for scheduled jobs/pipelines)
|
| 119 |
+
%(prog)s --push-to-hub --split raw
|
| 120 |
+
|
| 121 |
+
# Process with limit (for testing)
|
| 122 |
+
%(prog)s --limit 10000 -o sample.ndjson
|
| 123 |
+
|
| 124 |
+
# Push to a private repo
|
| 125 |
+
%(prog)s --push-to-hub --private
|
| 126 |
+
"""
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument("-o", "--output", help="Output file path (default: stdout)")
|
| 129 |
+
parser.add_argument("--limit", type=int,
|
| 130 |
+
help="Limit processing to N rows (useful for testing)")
|
| 131 |
+
parser.add_argument("--format", choices=["ndjson", "csv"], default="ndjson",
|
| 132 |
+
help="Output format (default: ndjson)")
|
| 133 |
+
parser.add_argument("--batch-size", type=int, default=1000,
|
| 134 |
+
help="Batch size for streaming (default: 1000). Larger values may "
|
| 135 |
+
"improve I/O efficiency but use more memory.")
|
| 136 |
+
parser.add_argument("--push-to-hub", action="store_true",
|
| 137 |
+
help="Push the resulting dataset to Hugging Face Hub")
|
| 138 |
+
parser.add_argument("--split", default=None,
|
| 139 |
+
help="Split name when pushing to Hub (e.g., 'raw' for scheduled pipelines)")
|
| 140 |
+
parser.add_argument("--repo-id", default="evalstate/mcp-clients",
|
| 141 |
+
help="HF Hub repository ID (default: evalstate/mcp-clients)")
|
| 142 |
+
parser.add_argument("--token", default=None,
|
| 143 |
+
help="HF token (defaults to HF_TOKEN env var or cached token)")
|
| 144 |
+
parser.add_argument("--private", action="store_true",
|
| 145 |
+
help="Create/push to a private repository")
|
| 146 |
+
args = parser.parse_args()
|
| 147 |
+
|
| 148 |
+
# Dictionary to track unique (name, version, capabilities) -> data
|
| 149 |
+
unique_clients = {}
|
| 150 |
+
|
| 151 |
+
# Load dataset in streaming mode with batch processing
|
| 152 |
+
print(f"Loading dataset: evalstate/hf-mcp-logs (sessions split)", file=sys.stderr)
|
| 153 |
+
print(f"Using batch size: {args.batch_size}", file=sys.stderr)
|
| 154 |
+
|
| 155 |
+
from datasets import load_dataset
|
| 156 |
+
ds = load_dataset('evalstate/hf-mcp-logs', 'sessions', streaming=True)
|
| 157 |
+
# Access sessions split
|
| 158 |
+
sessions_ds = ds['sessions']
|
| 159 |
+
|
| 160 |
+
total_rows = 0
|
| 161 |
+
skipped_deletes = 0
|
| 162 |
+
skipped_other = 0
|
| 163 |
+
start_time = None
|
| 164 |
+
|
| 165 |
+
# Process in batches for better I/O efficiency
|
| 166 |
+
for batch in sessions_ds.iter(batch_size=args.batch_size):
|
| 167 |
+
batch_len = len(batch['name']) # All columns have same length
|
| 168 |
+
total_rows += batch_len
|
| 169 |
+
|
| 170 |
+
# Progress indicator every 100k rows
|
| 171 |
+
if total_rows % 100000 == 0:
|
| 172 |
+
if start_time is None:
|
| 173 |
+
start_time = datetime.now()
|
| 174 |
+
elapsed = (datetime.now() - start_time).total_seconds()
|
| 175 |
+
rate = total_rows / elapsed if elapsed > 0 else 0
|
| 176 |
+
print(f"Processed {total_rows:,} rows ({rate:.0f} rows/sec), "
|
| 177 |
+
f"found {len(unique_clients):,} unique clients, "
|
| 178 |
+
f"skipped {skipped_deletes:,} delete events...", file=sys.stderr)
|
| 179 |
+
|
| 180 |
+
if args.limit and total_rows > args.limit:
|
| 181 |
+
break
|
| 182 |
+
|
| 183 |
+
# Process each row in batch
|
| 184 |
+
# Batch is a dict where keys are column names and values are lists
|
| 185 |
+
for i in range(batch_len):
|
| 186 |
+
# Check methodName field - only process 'initialize' events
|
| 187 |
+
method_name = batch['methodName'][i] if 'methodName' in batch else None
|
| 188 |
+
|
| 189 |
+
# Skip session_delete events - they don't have meaningful client information
|
| 190 |
+
if method_name == 'session_delete':
|
| 191 |
+
skipped_deletes += 1
|
| 192 |
+
continue
|
| 193 |
+
|
| 194 |
+
# Only process initialize events
|
| 195 |
+
if method_name != 'initialize':
|
| 196 |
+
skipped_other += 1
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
name = batch['name'][i]
|
| 200 |
+
version = batch['version'][i]
|
| 201 |
+
capabilities = normalize_capabilities(batch['capabilities'][i])
|
| 202 |
+
time_str = batch['time'][i]
|
| 203 |
+
|
| 204 |
+
if not all([name, version, time_str]):
|
| 205 |
+
continue
|
| 206 |
+
|
| 207 |
+
# Create composite key for deduplication
|
| 208 |
+
# For capabilities, we need a hashable representation
|
| 209 |
+
if isinstance(capabilities, dict):
|
| 210 |
+
cap_key = json.dumps(capabilities, sort_keys=True)
|
| 211 |
+
else:
|
| 212 |
+
cap_key = str(capabilities) if capabilities is not None else None
|
| 213 |
+
|
| 214 |
+
key = (name, version, cap_key)
|
| 215 |
+
|
| 216 |
+
# Update if this entry is newer
|
| 217 |
+
if key not in unique_clients or time_str > unique_clients[key]['last_seen']:
|
| 218 |
+
unique_clients[key] = {
|
| 219 |
+
'name': name,
|
| 220 |
+
'version': version,
|
| 221 |
+
'capabilities': capabilities,
|
| 222 |
+
'last_seen': time_str
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
print(f"\nProcessing complete: {total_rows:,} rows processed", file=sys.stderr)
|
| 226 |
+
print(f"Skipped {skipped_deletes:,} session_delete events", file=sys.stderr)
|
| 227 |
+
if skipped_other > 0:
|
| 228 |
+
print(f"Skipped {skipped_other:,} other non-initialize events", file=sys.stderr)
|
| 229 |
+
print(f"Found {len(unique_clients):,} unique client configurations", file=sys.stderr)
|
| 230 |
+
|
| 231 |
+
# Sort by last_seen descending (most recent first)
|
| 232 |
+
sorted_clients = sorted(
|
| 233 |
+
unique_clients.values(),
|
| 234 |
+
key=lambda x: x['last_seen'],
|
| 235 |
+
reverse=True
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# Handle push to hub
|
| 239 |
+
if args.push_to_hub:
|
| 240 |
+
push_to_hub(sorted_clients, args.repo_id, split=args.split, token=args.token, private=args.private)
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
# Handle local output
|
| 244 |
+
if args.output:
|
| 245 |
+
out_file = open(args.output, 'w')
|
| 246 |
+
else:
|
| 247 |
+
out_file = sys.stdout
|
| 248 |
+
|
| 249 |
+
# Output results
|
| 250 |
+
if args.format == 'ndjson':
|
| 251 |
+
for client in sorted_clients:
|
| 252 |
+
# Ensure capabilities is output properly
|
| 253 |
+
if client['capabilities'] == '{}':
|
| 254 |
+
client['capabilities'] = {}
|
| 255 |
+
|
| 256 |
+
out_file.write(json.dumps(client) + '\n')
|
| 257 |
+
|
| 258 |
+
elif args.format == 'csv':
|
| 259 |
+
# Write CSV header
|
| 260 |
+
import csv
|
| 261 |
+
writer = csv.writer(out_file)
|
| 262 |
+
writer.writerow(['name', 'version', 'capabilities', 'last_seen'])
|
| 263 |
+
|
| 264 |
+
for client in sorted_clients:
|
| 265 |
+
# Convert capabilities to string for CSV
|
| 266 |
+
caps = client['capabilities']
|
| 267 |
+
if isinstance(caps, dict):
|
| 268 |
+
caps_str = json.dumps(caps)
|
| 269 |
+
elif caps is None:
|
| 270 |
+
caps_str = ''
|
| 271 |
+
else:
|
| 272 |
+
caps_str = str(caps)
|
| 273 |
+
|
| 274 |
+
writer.writerow([client['name'], client['version'], caps_str, client['last_seen']])
|
| 275 |
+
|
| 276 |
+
if args.output:
|
| 277 |
+
out_file.close()
|
| 278 |
+
print(f"Output written to: {args.output}", file=sys.stderr)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
if __name__ == '__main__':
|
| 282 |
+
main()
|