-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
4615 lines (4118 loc) · 208 KB
/
Copy pathserver.py
File metadata and controls
4615 lines (4118 loc) · 208 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MCP Server: EU AI Act Compliance Checker
Scans projects to detect AI model usage and verify EU AI Act compliance
"""
import ast
import asyncio
import os
import re
import json
import time
import hashlib
import secrets
import logging
import tempfile
import contextvars
from pathlib import Path
from typing import Annotated, Dict, List, Any, Optional
from pydantic import Field
from datetime import datetime, timedelta, timezone
from enum import Enum
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import TextContent
from gdpr_module import GDPRChecker, GDPR_TEMPLATES, GDPR_REQUIREMENTS
logger = logging.getLogger(__name__)
# --- API Key Management (Paywall Step 2) ---
API_KEYS_PATH = Path(__file__).parent / "api_keys.json"
API_KEYS_DATA_PATH = Path(__file__).parent / "data" / "api_keys.json"
ARTICLES_DB_PATH = Path(__file__).parent / "data" / "eu_ai_act_articles.json"
def _load_articles_db() -> Dict[str, Any]:
"""Load and cache the EU AI Act articles knowledge base."""
try:
data = json.loads(ARTICLES_DB_PATH.read_text())
return {a["article"]: a for a in data.get("articles", [])}
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return {}
_ARTICLES_DB: Dict[str, Any] = _load_articles_db()
class ApiKeyManager:
"""Loads and validates API keys from both api_keys.json files.
Supports two formats:
- Root api_keys.json: {"keys": [{"key": "...", "email": "...", ...}]}
- data/api_keys.json: {"mcp_pro_...": {"email": "...", "active": true, ...}}
"""
def __init__(self, path: Path = API_KEYS_PATH, data_path: Path = API_KEYS_DATA_PATH):
self._path = path
self._data_path = data_path
self._keys: Dict[str, Dict] = {}
self._loaded_at: float = 0
self._reload()
def _reload(self):
"""Reload keys from both files (cached for 60s)."""
merged: Dict[str, Dict] = {}
for path in [self._path, self._data_path]:
try:
data = json.loads(path.read_text())
# List format: {"keys": [{"key": "...", ...}]}
for entry in data.get("keys", []):
merged[entry["key"]] = entry
# Dict format: {"api_key_value": {"tier": "pro", ...}}
for api_key, info in data.items():
if api_key == "keys":
continue
if isinstance(info, dict):
info["key"] = api_key
merged[api_key] = info
except (FileNotFoundError, json.JSONDecodeError, KeyError):
pass
self._keys = merged
self._loaded_at = time.time()
def verify(self, key: str) -> Optional[Dict]:
"""Verify an API key. Returns key info if valid+active, None otherwise.
Reloads from disk every 60s to pick up new keys without restart."""
if time.time() - self._loaded_at > 60:
self._reload()
entry = self._keys.get(key)
if entry and entry.get("active"):
plan = entry.get("plan", entry.get("tier", "free"))
return {"email": entry.get("email", ""), "plan": plan}
return None
def get_entry(self, key: str) -> Dict:
"""Get the full entry for an API key (for usage stats)."""
if time.time() - self._loaded_at > 60:
self._reload()
return self._keys.get(key, {})
def _atomic_write(self, path: Path, data: dict):
"""Write JSON data atomically via temp file + rename to prevent corruption."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=2)
os.replace(tmp, path)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def increment_scans(self, key: str):
"""Increment scans_total for an API key and persist to data file."""
if time.time() - self._loaded_at > 60:
self._reload()
entry = self._keys.get(key)
if not entry:
return
entry["scans_total"] = entry.get("scans_total", 0) + 1
entry["last_scan"] = datetime.now(timezone.utc).isoformat()
# Persist to data file (canonical source for paywall_api.py compatibility)
try:
data = json.loads(self._data_path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
data = {}
if key in data:
data[key]["scans_total"] = entry["scans_total"]
data[key]["last_scan"] = entry["last_scan"]
self._atomic_write(self._data_path, data)
def register_key(self, email: str, plan: str = "free") -> Dict:
"""Register a new API key. Writes to data/api_keys.json.
Returns the created entry with the generated key."""
api_key = f"ak_{secrets.token_hex(20)}"
entry = {
"plan": plan,
"active": True,
"created_at": datetime.now(timezone.utc).isoformat(),
"email": email,
"scans_total": 0,
}
# Load existing data file, add new key, write back
data = {}
try:
data = json.loads(self._data_path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
pass
data[api_key] = entry
self._atomic_write(self._data_path, data)
# Refresh in-memory cache
self._reload()
return {"key": api_key, **entry}
_api_key_manager = ApiKeyManager()
# --- Rate Limiting (Paywall Step 1) ---
FREE_TIER_DAILY_LIMIT = 10
class RateLimiter:
"""IP rate limiter with file persistence. 10 requests per calendar day (UTC) per IP.
Counters survive server restarts via JSON file. Resets automatically when the UTC date changes."""
# Shared with paywall_api.py so free-tier limits are enforced across both MCP and REST
_PERSIST_PATH = Path(__file__).parent / "data" / "rate_limits.json"
def __init__(self, max_requests: int = FREE_TIER_DAILY_LIMIT):
self.max_requests = max_requests
self._clients: Dict[str, Dict] = {} # {ip: {"count": int, "date": str}}
self._last_cleanup: float = time.time()
self._load()
def _load(self):
"""Load persisted rate limits from disk."""
try:
if self._PERSIST_PATH.exists():
data = json.loads(self._PERSIST_PATH.read_text())
today = self._today()
self._clients = {ip: e for ip, e in data.items() if e.get("date") == today}
except (json.JSONDecodeError, OSError):
self._clients = {}
def _save(self):
"""Persist current rate limits to disk (atomic write)."""
try:
self._PERSIST_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = self._PERSIST_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(self._clients))
tmp.rename(self._PERSIST_PATH)
except OSError:
pass
@staticmethod
def _today() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d")
def check(self, ip: str) -> tuple[bool, int]:
"""Check if IP is allowed. Returns (allowed, remaining)."""
today = self._today()
# Periodic cleanup every hour to prevent memory leak from expired entries
now = time.time()
if now - self._last_cleanup > 3600:
self.cleanup()
self._last_cleanup = now
entry = self._clients.get(ip)
if entry is None or entry["date"] != today:
self._clients[ip] = {"count": 1, "date": today}
self._save()
return True, self.max_requests - 1
if entry["count"] >= self.max_requests:
return False, 0
entry["count"] += 1
self._save()
return True, self.max_requests - entry["count"]
def cleanup(self):
"""Remove expired entries (old dates) to prevent memory leak."""
today = self._today()
expired = [ip for ip, e in self._clients.items() if e["date"] != today]
for ip in expired:
del self._clients[ip]
if expired:
self._save()
_rate_limiter = RateLimiter()
# Context variable: remaining scans for the current request (set by middleware, read by _add_banner)
_scan_remaining: contextvars.ContextVar = contextvars.ContextVar('scan_remaining', default=None)
# Context variable: current plan for the request ('free', 'pro', 'certified', 'marketplace')
# Sentinel default distinguishes "middleware set free" from "middleware never ran (stdio)"
_PLAN_NOT_SET = "__not_set__"
_current_plan: contextvars.ContextVar = contextvars.ContextVar('current_plan', default=_PLAN_NOT_SET)
# Context variable: client IP for the current request (set by middleware, read by register_free_key)
_client_ip: contextvars.ContextVar = contextvars.ContextVar('client_ip', default='unknown')
# Context variable: transport type — 'mcp_jsonrpc' for MCP tools/call, 'api_rest' for /api/ endpoints
_transport_type: contextvars.ContextVar = contextvars.ContextVar('transport_type', default='unknown')
# Context variable: client hint from User-Agent (e.g. 'claude-desktop', 'cursor', 'unknown')
_client_hint: contextvars.ContextVar = contextvars.ContextVar('client_hint', default='unknown')
# Context variable: MCP session ID (Streamable HTTP spec — differentiates sessions behind proxy)
_mcp_session_id: contextvars.ContextVar = contextvars.ContextVar('mcp_session_id', default='')
# Module-level fallback for ContextVars that don't propagate across FastMCP's
# anyio task groups (streamable-http transport dispatches tools in separate tasks).
# Single-worker uvicorn: safe for low-concurrency MCP traffic.
_fallback_ip: str = "unknown"
_fallback_transport: str = "unknown"
_fallback_client_hint: str = "unknown"
_fallback_mcp_session_id: str = ""
# Keepalive detection: track tools_list frequency per IP to distinguish
# automated gateway polling from genuine user discovery sessions.
_tools_list_timestamps: dict[str, list[float]] = {}
_KEEPALIVE_WINDOW_S = 3600 # 1 hour window
_KEEPALIVE_THRESHOLD = 8 # >8 tools_list/hour = automated polling
def _is_automated_polling(ip: str) -> bool:
"""Detect if tools_list calls from this IP are automated keepalives."""
import time
now = time.time()
if ip not in _tools_list_timestamps:
_tools_list_timestamps[ip] = []
ts_list = _tools_list_timestamps[ip]
ts_list.append(now)
# Prune old entries
cutoff = now - _KEEPALIVE_WINDOW_S
_tools_list_timestamps[ip] = [t for t in ts_list if t > cutoff]
return len(_tools_list_timestamps[ip]) > _KEEPALIVE_THRESHOLD
_fallback_plan: str = "free"
_fallback_scan_remaining: int | None = None
# Per-IP plan cache: avoids race condition where a certified-key request
# overwrites _fallback_plan before a concurrent free-tier tool function reads it.
# Dict[ip, plan_str] — cleared on each middleware entry for the same IP.
import threading
_ip_plan_lock = threading.Lock()
_ip_plan_map: dict[str, str] = {}
def _get_client_ip() -> str:
"""Get client IP with fallback to module-level variable when ContextVar doesn't propagate."""
ip = _client_ip.get()
if ip != "unknown":
return ip
return _fallback_ip
def _get_transport() -> str:
"""Get transport type with fallback."""
t = _transport_type.get()
if t != "unknown":
return t
return _fallback_transport
def _get_client_hint_val() -> str:
"""Get client hint with fallback."""
h = _client_hint.get()
if h != "unknown":
return h
return _fallback_client_hint
def _get_mcp_session_id() -> str:
"""Get MCP session ID with fallback."""
s = _mcp_session_id.get()
return s if s else _fallback_mcp_session_id
def _get_plan() -> str:
"""Get current plan with fallback.
ContextVar propagation: HTTP middleware sets _current_plan + _fallback_plan.
FastMCP dispatches tools in separate anyio tasks where ContextVars don't
propagate, so HTTP tool calls fall through to per-IP plan map.
Stdio transport never runs middleware, so ContextVar stays _PLAN_NOT_SET
and _fallback_plan may be stale — default to 'free' in that case.
"""
p = _current_plan.get()
if p != _PLAN_NOT_SET:
return p
if _fallback_transport in ("mcp_jsonrpc", "api_rest"):
# Use per-IP plan map to avoid race conditions between concurrent
# certified and free-tier requests sharing _fallback_plan.
ip = _get_client_ip()
with _ip_plan_lock:
plan = _ip_plan_map.get(ip)
if plan is not None:
return plan
return _fallback_plan
return "free"
def _get_scan_remaining() -> int | None:
"""Get remaining scans with fallback."""
r = _scan_remaining.get()
if r is not None:
return r
return _fallback_scan_remaining
# --- Email validation ---
_EMAIL_RE = re.compile(
r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?"
r"(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$"
)
_DISPOSABLE_DOMAINS = frozenset({
"mailinator.com", "guerrillamail.com", "guerrillamail.net", "tempmail.com",
"throwaway.email", "yopmail.com", "sharklasers.com", "guerrillamailblock.com",
"grr.la", "dispostable.com", "mailnesia.com", "maildrop.cc", "trashmail.com",
"trashmail.me", "trashmail.net", "10minutemail.com", "temp-mail.org",
"fakeinbox.com", "tempail.com", "tempr.email", "discard.email",
"discardmail.com", "mailcatch.com", "nada.email", "getnada.com",
# RFC 2606 reserved domains — never valid for real registration
"example.com", "example.org", "example.net",
"test.com", "test.org", "test.net",
})
def _sanitize_email(email: str) -> str:
"""Extract a clean email from common LLM-mangled inputs."""
if not email:
return email
email = email.strip()
for prefix in ("mailto:", "email:", "Email:"):
if email.lower().startswith(prefix.lower()):
email = email[len(prefix):].strip()
email = email.strip("<>\"'`() ")
match = re.search(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', email)
if match:
return match.group(0)
return email
def _validate_email(email: str) -> str | None:
"""Validate email format and reject disposable domains.
Returns None if valid, or an error message string.
"""
if not email or len(email) > 254:
logging.getLogger("mcp.register").warning(
"email validation failed: empty_or_too_long | len=%d | preview=%s",
len(email) if email else 0, repr(email[:30]) if email else "None")
return "Please provide a valid email address."
if not _EMAIL_RE.match(email):
import hashlib
email_hash = hashlib.sha256(email.encode()).hexdigest()[:8]
logging.getLogger("mcp.register").warning(
"email validation failed: bad_format | hash=%s | len=%d | has_at=%s | preview_domain=%s",
email_hash, len(email), "@" in email,
email.rsplit("@", 1)[-1][:20] if "@" in email else "no_at")
return (
"Invalid email format. Please provide a real email address "
"(e.g. name@domain.com), not a placeholder."
)
domain = email.rsplit("@", 1)[-1].lower()
if domain in _DISPOSABLE_DOMAINS:
return "Disposable email addresses are not accepted. Please use a permanent email."
return None
# --- IP classification for clean funnel metrics ---
_INTERNAL_CIDRS = (
"10.", "192.168.", "127.", "172.16.", "172.17.", "172.18.", "172.19.",
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.", "172.25.",
"172.26.", "172.27.", "172.28.", "172.29.", "172.30.", "172.31.",
"198.51.100.", # RFC 5737 TEST-NET-2
"203.0.113.", # RFC 5737 TEST-NET-3
"::1",
)
_INFRA_IPS = frozenset({
"57.131.27.61", # local server
"51.91.99.178", # OVH server
"90.105.196.22", # shareholder
"2001:41d0:2005:100::6fd", # OVH IPv6
})
# Hetzner (5.78.x), Linode, DigitalOcean, AWS datacenter prefixes → crawler
_DATACENTER_PREFIXES = (
"5.78.", "5.161.", "5.180.", # Hetzner
"160.79.", "172.104.", "172.105.", "139.162.", # Linode
"104.248.", "134.209.", "157.245.", "161.35.", # DigitalOcean
"35.", "52.", "54.", "18.", # AWS (broad)
"93.184.216.", # IANA example.com (test probes)
)
_ANTHROPIC_GATEWAY_PREFIXES = ("160.79.106.",)
def _detect_client_hint(scope) -> str:
"""Infer MCP client type from User-Agent header.
Returns: 'claude-desktop', 'cursor', 'continue', 'cline', 'browser', or 'unknown'.
"""
ua = _get_header(scope, b"user-agent") if isinstance(scope, dict) else None
if not ua:
return "unknown"
ua_lower = ua.lower()
if "claude" in ua_lower or "anthropic" in ua_lower:
return "claude-desktop"
if "cursor" in ua_lower:
return "cursor"
if "continue" in ua_lower:
return "continue"
if "cline" in ua_lower:
return "cline"
if "mozilla" in ua_lower or "chrome" in ua_lower or "safari" in ua_lower:
return "browser"
return "unknown"
# --- Unique external MCP client tracking ---
_UNIQUE_CLIENTS_PATH = Path(__file__).parent / "data" / "unique_mcp_clients.json"
def _track_unique_client(ip: str, source: str, client_hint: str, mcp_session: str = ""):
"""Track unique external MCP clients per day. Counts 'external', 'gateway', and 'stdio' sources."""
if source not in ("external", "gateway", "stdio"):
return
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
try:
data = json.loads(_UNIQUE_CLIENTS_PATH.read_text()) if _UNIQUE_CLIENTS_PATH.exists() else {}
except (json.JSONDecodeError, OSError):
data = {}
if today not in data:
data[today] = {"ips": [], "count": 0, "client_hints": {}}
import hashlib
ident = ip if ip != "unknown" else f"stdio-pid-{os.getpid()}"
if mcp_session:
ident = f"{ident}:{mcp_session}"
ip_hash = hashlib.sha256(ident.encode()).hexdigest()[:12]
if ip_hash not in data[today]["ips"]:
data[today]["ips"].append(ip_hash)
data[today]["count"] = len(data[today]["ips"])
hint_counts = data[today]["client_hints"]
hint_counts[client_hint] = hint_counts.get(client_hint, 0) + 1
# Keep only last 30 days
cutoff = (datetime.now(timezone.utc) - timedelta(days=30)).strftime("%Y-%m-%d")
data = {k: v for k, v in data.items() if k >= cutoff}
try:
_UNIQUE_CLIENTS_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = _UNIQUE_CLIENTS_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(data, indent=2, default=str))
tmp.rename(_UNIQUE_CLIENTS_PATH)
except OSError:
pass
_KNOWN_MCP_CLIENTS = frozenset({"claude-desktop", "cursor", "continue", "cline"})
def _is_anthropic_gateway(ip: str) -> bool:
"""Check if IP belongs to the Anthropic MCP gateway subnet (Linode 160.79.106.x)."""
return any(ip.startswith(p) for p in _ANTHROPIC_GATEWAY_PREFIXES)
def _classify_ip(ip: str, client_hint: str = "unknown") -> str:
"""Classify IP as 'internal', 'crawler', 'gateway', or 'external'.
- internal: private ranges, RFC 5737 test nets, known infra IPs
- gateway: Anthropic MCP gateway IPs (protocol keepalives, may proxy real users)
- crawler: known datacenter IP prefixes (Hetzner, Linode, etc.)
- external: everything else (potential real users)
"""
if not ip:
return "internal"
if ip == "unknown":
return "stdio"
if ip in _INFRA_IPS:
return "internal"
for prefix in _INTERNAL_CIDRS:
if ip.startswith(prefix):
return "internal"
if _is_anthropic_gateway(ip):
return "gateway"
for prefix in _DATACENTER_PREFIXES:
if ip.startswith(prefix):
return "crawler"
return "external"
# --- Tool call telemetry (funnel visibility: which tool, CTA included, plan) ---
_TOOL_CALL_LOG_PATH = Path(__file__).parent / "data" / "tool_calls.jsonl"
_SCAN_TOOLS = {
"scan_project", "check_compliance", "generate_report",
"gdpr_scan_project", "gdpr_check_compliance", "gdpr_generate_report",
"combined_compliance_report",
}
def _write_tool_call_entry(entry: dict):
try:
_TOOL_CALL_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(_TOOL_CALL_LOG_PATH, "a") as f:
f.write(json.dumps(entry, default=str) + "\n")
except Exception:
import logging
logging.getLogger("mcp.telemetry").exception(
"_write_tool_call_entry failed for %s", entry.get("tool"))
def _log_tool_call(tool_name: str, cta_included: bool = False, plan: str = None,
ip: str = None, extra: dict = None):
"""Append tool call events for funnel diagnostics.
Funnel step naming (standardized — matches web analytics event names):
mcp_scan_completed — any successful scan/check/report tool
cta_register_free_key_viewed — CTA text included in response
cta_register_free_key_clicked — register_free_key tool invoked
free_key_activation — register_free_key succeeded
pricing_view — get_pricing tool called
Scan tools with a CTA emit BOTH mcp_scan_completed and
cta_register_free_key_viewed so drop-off between the two is measurable.
Callers passing funnel_step explicitly in `extra` suppress auto-tagging.
"""
resolved_ip = ip or _get_client_ip()
hint = _get_client_hint_val()
source = _classify_ip(resolved_ip, hint)
resolved_plan = plan or _get_plan()
is_protocol_keepalive = tool_name.startswith("__connection_")
is_genuine_external = (
source in ("external", "crawler", "gateway")
and resolved_plan not in ("certified",)
and resolved_ip not in ("testclient", "unknown", "127.0.0.1", "93.184.216.34")
and not is_protocol_keepalive
)
mcp_session = _get_mcp_session_id()
id_seed = f"{resolved_ip}:{hint}:{mcp_session}" if mcp_session else f"{resolved_ip}:{hint}"
client_id = hashlib.sha256(id_seed.encode()).hexdigest()[:12]
base = {
"ts": datetime.now(timezone.utc).isoformat(),
"tool": tool_name,
"plan": resolved_plan,
"cta_included": cta_included,
"cta_variant": _fallback_cta_variant if cta_included else None,
"ip": resolved_ip,
"source": source,
"transport": _get_transport(),
"client_hint": hint,
"client_id": client_id,
"is_genuine_external": is_genuine_external,
"is_protocol_keepalive": is_protocol_keepalive,
"schema_version": _SCHEMA_VERSION,
}
if mcp_session:
base["mcp_session_id"] = mcp_session
if extra:
base.update(extra)
explicit_step = base.get("funnel_step")
if explicit_step:
_write_tool_call_entry(base)
return
is_scan = tool_name in _SCAN_TOOLS
if is_scan:
scan_entry = dict(base)
scan_entry["funnel_step"] = "mcp_scan_completed"
_write_tool_call_entry(scan_entry)
if cta_included:
cta_entry = dict(base)
cta_entry["funnel_step"] = "cta_register_free_key_viewed"
cta_entry["funnel_step_legacy"] = "cta_shown"
_write_tool_call_entry(cta_entry)
return
if cta_included:
base["funnel_step"] = "cta_register_free_key_viewed"
base["funnel_step_legacy"] = "cta_shown"
_write_tool_call_entry(base)
# --- Registration logging ---
_REGISTRATION_LOG_PATH = Path(__file__).parent / "data" / "registration_log.jsonl"
def _record_registration(email: str, source: str, ip: str, api_key: str,
scan_id: Optional[str] = None):
"""Append a registration event to registration_log.jsonl for funnel tracking."""
import hashlib
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"email_hash": hashlib.sha256(email.lower().strip().encode()).hexdigest()[:16],
"source": source, # "mcp_tool", "api_direct", "cli", "mcp_phonehome", "mcp_tool_local_fallback"
"ip": ip,
"api_key_prefix": api_key[:12] + "..." if api_key else None,
"scan_id": scan_id,
}
try:
_REGISTRATION_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(_REGISTRATION_LOG_PATH, "a") as f:
f.write(json.dumps(entry, default=str) + "\n")
except Exception as exc:
import logging
logging.getLogger("mcp.registration").error("_record_registration failed: %s", exc)
def _require_plan(min_plan: str, tool_name: str) -> Optional[dict]:
"""Return a friendly upgrade message if the current plan is insufficient, None if OK."""
order = {"free": 0, "pro": 1, "paid_scan": 1, "marketplace": 1, "certified": 2}
current = _get_plan()
if order.get(current, 0) >= order.get(min_plan, 0):
return None
_TOOL_INFO = {
"generate_compliance_roadmap": {
"plan": "pro", "price": "29 EUR/month",
"teaser": "You'd get a week-by-week action plan prioritized by legal criticality × effort, deadline-aware for August 2, 2026.",
},
"generate_annex4_package": {
"plan": "pro", "price": "29 EUR/month",
"teaser": "You'd get an auditor-ready ZIP with all 8 official Annex IV sections and a SHA-256 manifest.",
},
"certify_compliance_report": {
"plan": "certified", "price": "99 EUR/month",
"teaser": "You'd get an Ed25519-signed report with an RFC 3161 timestamp and a public verification URL for auditors.",
},
}
info = _TOOL_INFO.get(tool_name, {"plan": min_plan, "price": "", "teaser": ""})
plan_label = info["plan"].capitalize()
return {
"upgrade_required": True,
"tool": tool_name,
"required_plan": info["plan"],
"current_plan": current,
"message": (
f"{tool_name} is a {plan_label} feature ({info['price']}). "
f"{info['teaser']}"
),
"how_to_unlock": "Add your API key via the X-Api-Key header when connecting to the MCP server.",
"upgrade_url": "https://arkforge.tech/en/pricing.html?utm_source=mcp_cta&utm_medium=tool_output",
"get_key": "https://arkforge.tech/en/pricing.html?utm_source=mcp_cta&utm_medium=tool_output",
}
# --- Scan history logging (shared with paywall_api.py) ---
_SCAN_HISTORY_PATH = Path(__file__).parent / "data" / "scan_history.json"
def _record_mcp_scan(api_key: Optional[str], ip: str, tool_name: str,
result: str = "attempt", duration_ms: int = None):
"""Record an MCP tool call to scan_history.json for visibility.
Args:
result: "attempt" (middleware pre-exec), "ok", "error:<reason>"
duration_ms: wall-clock time of the tool execution (post-exec only)
"""
# Skip recording when tool_name is unknown (test probes, malformed requests)
if tool_name == "unknown":
return
try:
history = json.loads(_SCAN_HISTORY_PATH.read_text()) if _SCAN_HISTORY_PATH.exists() else []
except (json.JSONDecodeError, OSError):
history = []
# Session hash: IP + date → stable ID for correlating multi-step flows
import hashlib
day_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
session_hash = hashlib.sha256(f"{ip}:{day_str}".encode()).hexdigest()[:12]
client_hint = _get_client_hint_val()
ip_source = _classify_ip(ip, client_hint)
# Track unique external MCP clients
_track_unique_client(ip, ip_source, client_hint, _get_mcp_session_id())
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"api_key": api_key[:12] + "..." if api_key else None,
"ip": ip,
"source": ip_source,
"transport": _get_transport(),
"client_hint": client_hint,
"plan": "pro" if api_key else "free",
"scan_type": f"mcp_{tool_name}",
"session_id": session_hash,
"frameworks_detected": [],
"files_scanned": 0,
"result": result,
}
if duration_ms is not None:
entry["duration_ms"] = duration_ms
history.append(entry)
if len(history) > 1000:
history = history[-1000:]
try:
tmp = _SCAN_HISTORY_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(history, indent=2, default=str))
tmp.rename(_SCAN_HISTORY_PATH)
except OSError:
import logging
logging.getLogger("mcp.scan_history").exception("_record_mcp_scan write failed for %s", tool_name)
_UNIQUE_CLIENTS_PATH = Path(__file__).parent / "data" / "unique_mcp_clients.json"
_PHONE_HOME_URL = "https://trust.arkforge.tech/api/mcp-scan-ping"
def _stdio_phone_home(tool_name: str, scan_id: str = None,
models_found: int = 0, files_scanned: int = 0):
"""Fire-and-forget ping to track stdio usage. Non-blocking, fail-silent."""
transport = _get_transport()
if transport not in ("stdio", "unknown"):
return
import threading
def _ping():
try:
import urllib.request
payload = json.dumps({
"tool": tool_name,
"transport": "stdio",
"scan_id": scan_id or "",
"models_found": models_found,
"files_scanned": files_scanned,
"v": _SCHEMA_VERSION,
}).encode()
req = urllib.request.Request(
_PHONE_HOME_URL,
data=payload,
headers={
"Content-Type": "application/json",
"User-Agent": "ArkForge-MCP-Scanner/2.0.33",
},
method="POST",
)
urllib.request.urlopen(req, timeout=5)
except Exception:
pass
threading.Thread(target=_ping, daemon=True).start()
def _compute_funnel_metrics() -> dict:
"""Compute corrected conversion funnel metrics.
Uses unique users (not raw ListTools) as denominator, and tracks
scan_project_success_rate from scan_history.json outcomes.
"""
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
# --- Unique users from unique_mcp_clients.json ---
try:
clients = json.loads(_UNIQUE_CLIENTS_PATH.read_text())
except (FileNotFoundError, json.JSONDecodeError):
clients = {}
today_data = clients.get(today, {})
unique_users_today = today_data.get("count", 0)
unique_users_7d = sum(
v.get("count", 0) for k, v in clients.items()
if k >= (datetime.now(timezone.utc) - timedelta(days=7)).strftime("%Y-%m-%d")
)
# --- Tool calls from tool_calls.jsonl ---
ext_tool_calls_today = 0
ext_tool_calls_7d = 0
ext_tool_callers_today = set()
ext_tool_callers_7d = set()
discovery_today = 0
genuine_discovery_today = 0
genuine_discovery_7d = 0
cutoff_7d = (datetime.now(timezone.utc) - timedelta(days=7)).isoformat()
today_prefix = today + "T"
try:
with open(_TOOL_CALL_LOG_PATH) as f:
for line in f:
try:
e = json.loads(line)
except (json.JSONDecodeError, ValueError):
continue
ts = e.get("ts", "")
source = e.get("source", "")
tool = e.get("tool", "")
ip = e.get("ip", "")
if source not in ("external", "crawler", "gateway"):
continue
is_connection = tool.startswith("__connection_")
if is_connection:
if "tools_list" in tool:
is_polling = e.get("is_automated_polling", False)
if ts >= today_prefix:
discovery_today += 1
if not is_polling:
genuine_discovery_today += 1
if ts >= cutoff_7d and not is_polling:
genuine_discovery_7d += 1
continue
if ts >= today_prefix:
ext_tool_calls_today += 1
ext_tool_callers_today.add(ip)
if ts >= cutoff_7d:
ext_tool_calls_7d += 1
ext_tool_callers_7d.add(ip)
except FileNotFoundError:
pass
# --- scan_project success rate from scan_history.json ---
scan_attempts = 0
scan_successes = 0
scan_errors = 0
ext_scan_attempts = 0
ext_scan_successes = 0
try:
history = json.loads(_SCAN_HISTORY_PATH.read_text()) if _SCAN_HISTORY_PATH.exists() else []
for entry in history:
result = entry.get("result", "")
if result == "attempt":
scan_attempts += 1
if entry.get("source") in ("external", "gateway"):
ext_scan_attempts += 1
elif result == "ok":
scan_successes += 1
if entry.get("source") in ("external", "gateway"):
ext_scan_successes += 1
elif result.startswith("error"):
scan_errors += 1
except (json.JSONDecodeError, FileNotFoundError):
pass
completed = scan_successes + scan_errors
success_rate = round(scan_successes / completed, 3) if completed > 0 else None
reconnection_ratio = round(discovery_today / unique_users_today, 1) if unique_users_today > 0 else None
conversion_rate = round(len(ext_tool_callers_7d) / unique_users_7d, 3) if unique_users_7d > 0 else None
return {
"unique_users_today": unique_users_today,
"unique_users_7d": unique_users_7d,
"discovery_requests_today": discovery_today,
"genuine_discovery_today": genuine_discovery_today,
"genuine_discovery_7d": genuine_discovery_7d,
"reconnection_ratio": reconnection_ratio,
"ext_tool_calls_today": ext_tool_calls_today,
"ext_tool_calls_7d": ext_tool_calls_7d,
"ext_tool_callers_today": len(ext_tool_callers_today),
"ext_tool_callers_7d": len(ext_tool_callers_7d),
"conversion_rate_7d": conversion_rate,
"scan_project_success_rate": success_rate,
"scan_attempts_total": scan_attempts,
"scan_successes_total": scan_successes,
"scan_errors_total": scan_errors,
"ext_scan_attempts": ext_scan_attempts,
"ext_scan_successes": ext_scan_successes,
"computed_at": datetime.now(timezone.utc).isoformat(),
}
def _get_header(scope, name: bytes) -> Optional[str]:
"""Extract a header value from ASGI scope."""
for header_name, header_val in scope.get("headers", []):
if header_name == name:
return header_val.decode()
return None
def _extract_api_key(scope) -> Optional[str]:
"""Extract API key from X-API-Key header or Authorization: Bearer."""
key = _get_header(scope, b"x-api-key")
if key:
return key
auth = _get_header(scope, b"authorization")
if auth and auth.startswith("Bearer "):
return auth[7:]
return None
def _scan_repo_url(repo_url: str) -> tuple:
"""Shallow-clone a repo and run the EU AI Act scan on it.
Blocking (git clone + filesystem scan) — call via asyncio.to_thread.
Returns (http_status, response_body)."""
import subprocess
import shutil
clone_dir = tempfile.mkdtemp(prefix="scan_")
try:
subprocess.run(
["git", "clone", "--depth", "1", repo_url, clone_dir],
check=True, capture_output=True, text=True, timeout=60,
)
checker = EUAIActChecker(clone_dir)
scan_result = checker.scan_project()
compliance = checker.check_compliance("limited")
scan_result["report"] = checker.generate_report(scan_result, compliance)
except subprocess.CalledProcessError as e:
return 400, {"error": f"Cannot clone repo: {(e.stderr or '')[:200]}"}
except subprocess.TimeoutExpired:
return 408, {"error": "Git clone timed out (60s limit)"}
finally:
shutil.rmtree(clone_dir, ignore_errors=True)
return 200, {"scan_result": {"plan": "trust_layer", "repo_url": repo_url, **scan_result}}
class RateLimitMiddleware:
"""ASGI middleware: rate-limits MCP tools/call requests per client IP.
Handles /api/verify-key endpoint. Pro API keys bypass rate limiting."""
def __init__(self, app):
self.app = app
async def _json_response(self, send, status: int, body: dict, extra_headers: list = None):
"""Send a JSON HTTP response with optional extra headers."""
resp = json.dumps(body).encode()
headers = [
[b"content-type", b"application/json"],
[b"content-length", str(len(resp)).encode()],
]
if extra_headers:
headers.extend(extra_headers)
await send({
"type": "http.response.start",
"status": status,
"headers": headers,
})
await send({"type": "http.response.body", "body": resp})
@staticmethod
def _rate_limit_headers(remaining: int) -> list:
"""Build X-RateLimit-Remaining and X-RateLimit-Reset headers."""
from datetime import timedelta
now_dt = datetime.now(timezone.utc)
midnight = (now_dt + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
reset = int((midnight - now_dt).total_seconds())
return [
[b"x-ratelimit-remaining", str(remaining).encode()],
[b"x-ratelimit-reset", str(reset).encode()],
]
async def __call__(self, scope, receive, send):
global _fallback_ip, _fallback_transport, _fallback_client_hint
global _fallback_plan, _fallback_scan_remaining
if scope["type"] != "http":
await self.app(scope, receive, send)
return
path = scope.get("path", "")
# --- /health endpoint (GET) — lightweight liveness probe ---
if path in ("/health", "/api/health") and scope.get("method") in ("GET", "HEAD"):
await self._json_response(send, 200, {"status": "ok", "service": "mcp-eu-ai-act"})
return
# Set transport for REST API paths
if path.startswith("/api/"):
_transport_type.set("api_rest")
_client_hint.set(_detect_client_hint(scope))
# --- /api/usage endpoint (GET) — free tier usage status ---
if path == "/api/usage" and scope.get("method") == "GET":
ip = _get_header(scope, b"x-real-ip")
if not ip:
xff = _get_header(scope, b"x-forwarded-for")
if xff: