226 lines
12 KiB
Python
226 lines
12 KiB
Python
"""Stateless, read-only MCP endpoint for reviewed BoomCast metadata."""
|
|
import hashlib
|
|
import json
|
|
from datetime import timedelta
|
|
from urllib.parse import urlsplit
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.core.cache import cache
|
|
from django.db.models import Count
|
|
from django.db.models.functions import TruncDate
|
|
from django.http import JsonResponse
|
|
from django.utils import timezone
|
|
from django.utils.dateparse import parse_date
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
from .h3_utils import cell_from_coordinates
|
|
from .models import Event, PendingEvent
|
|
|
|
PROTOCOL_VERSION = "2025-06-18"
|
|
TOOLS = [
|
|
{"name": "submissions_list", "description": "Page through reviewed submissions only. Review outcome is approved; denied records are deleted by the review workflow.", "inputSchema": {"type": "object", "properties": {"date_from": {"type": "string", "format": "date"}, "date_to": {"type": "string", "format": "date"}, "classification": {"type": "string"}, "review_outcome": {"type": "string", "enum": ["approved"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "offset": {"type": "integer", "minimum": 0, "maximum": 10000}}, "additionalProperties": False}},
|
|
{"name": "submissions_get", "description": "Get one reviewed submission by Event ID; pending IDs are inaccessible.", "inputSchema": {"type": "object", "properties": {"id": {"type": "integer", "minimum": 1}}, "required": ["id"], "additionalProperties": False}},
|
|
{"name": "submissions_stats", "description": "Reviewed submission counts by day, predicted class, and confirmed review outcome.", "inputSchema": {"type": "object", "properties": {"date_from": {"type": "string", "format": "date"}, "date_to": {"type": "string", "format": "date"}, "classification": {"type": "string"}, "review_outcome": {"type": "string", "enum": ["approved"]}}, "additionalProperties": False}},
|
|
{"name": "pending_summary", "description": "Only aggregate count and counts by predicted class for pending review; no individual records.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
|
|
]
|
|
|
|
|
|
def _error(code, message, request_id=None):
|
|
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
|
|
|
|
|
|
def _reply(request_id, result):
|
|
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
|
|
|
|
|
def _prediction(record):
|
|
payload = record.classifier_response if isinstance(record.classifier_response, dict) else {}
|
|
predictions = payload.get("predictions", [])
|
|
if not isinstance(predictions, list):
|
|
return []
|
|
clean = []
|
|
for item in predictions[:10]:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
label, score = item.get("class"), item.get("score")
|
|
if isinstance(label, str) and len(label) <= 255 and isinstance(score, (int, float)) and not isinstance(score, bool) and 0 <= score <= 1:
|
|
clean.append({"class": label, "score": score})
|
|
return clean
|
|
|
|
|
|
def _label(record):
|
|
prediction = _prediction(record)
|
|
return prediction[0]["class"] if prediction else "unclassified"
|
|
|
|
|
|
def _summary(event):
|
|
return {"id": event.pk, "occurrence_at": event.captured_at.isoformat() if event.captured_at else None,
|
|
"submitted_at": event.submitted_at.isoformat() if event.submitted_at else None,
|
|
"reviewed_at": event.approved_at.isoformat(), "source_type": event.source_type,
|
|
"predicted_classification": _label(event), "review_outcome": "approved",
|
|
"confirmed_classification": None}
|
|
|
|
|
|
def _detail(event):
|
|
result = _summary(event)
|
|
result.update({"predictions": _prediction(event), "occurrences": event.occurrences,
|
|
"occurrence_time_approximate": event.occurrence_time_approximate,
|
|
"generalized_location_h3": event.h3_cell or cell_from_coordinates(event.latitude, event.longitude) or None})
|
|
return result
|
|
|
|
|
|
def _filters(args):
|
|
start, end = args.get("date_from"), args.get("date_to")
|
|
if start is not None:
|
|
if not isinstance(start, str) or not parse_date(start) or parse_date(start).isoformat() != start:
|
|
raise ValueError("date_from must be YYYY-MM-DD")
|
|
start = parse_date(start)
|
|
if end is not None:
|
|
if not isinstance(end, str) or not parse_date(end) or parse_date(end).isoformat() != end:
|
|
raise ValueError("date_to must be YYYY-MM-DD")
|
|
end = parse_date(end)
|
|
if start and end and (end < start or end - start > timedelta(days=366)):
|
|
raise ValueError("date range must be ordered and at most 366 days")
|
|
if not end:
|
|
end = min(timezone.localdate(), start + timedelta(days=366)) if start else timezone.localdate()
|
|
if not start:
|
|
start = end - timedelta(days=366)
|
|
outcome = args.get("review_outcome")
|
|
if outcome is not None and outcome != "approved":
|
|
raise ValueError("review_outcome must be approved")
|
|
classification = args.get("classification")
|
|
if classification is not None and (not isinstance(classification, str) or not 1 <= len(classification) <= 255):
|
|
raise ValueError("classification must be a nonempty label")
|
|
queryset = Event.objects.all()
|
|
if start:
|
|
queryset = queryset.filter(approved_at__date__gte=start)
|
|
if end:
|
|
queryset = queryset.filter(approved_at__date__lte=end)
|
|
if classification:
|
|
queryset = queryset.filter(classifier_response__predictions__0__class=classification)
|
|
return queryset
|
|
|
|
|
|
def _validate(name, args):
|
|
schema = next((item["inputSchema"] for item in TOOLS if item["name"] == name), None)
|
|
if schema is None:
|
|
raise ValueError("Unknown tool")
|
|
if not isinstance(args, dict) or set(args) - set(schema["properties"]) or set(schema.get("required", [])) - set(args):
|
|
raise ValueError("Invalid tool arguments")
|
|
for key in ("limit", "offset", "id"):
|
|
if key in args and (type(args[key]) is not int or args[key] < (1 if key != "offset" else 0) or args[key] > (100 if key == "limit" else 10000 if key == "offset" else 2147483647)):
|
|
raise ValueError(f"Invalid {key}")
|
|
|
|
|
|
def _call(name, args):
|
|
_validate(name, args)
|
|
if name == "pending_summary":
|
|
counts = {}
|
|
for pending in PendingEvent.objects.only("classifier_response").iterator(chunk_size=500):
|
|
label = _label(pending)
|
|
counts[label] = counts.get(label, 0) + 1
|
|
return {"total": sum(counts.values()), "by_predicted_classification": counts}
|
|
if name == "submissions_get":
|
|
event = Event.objects.filter(pk=args["id"]).first()
|
|
if event is None:
|
|
raise LookupError("Reviewed submission not found")
|
|
return _detail(event)
|
|
queryset = _filters(args)
|
|
if name == "submissions_list":
|
|
limit, offset = args.get("limit", 25), args.get("offset", 0)
|
|
return {"total": queryset.count(), "limit": limit, "offset": offset,
|
|
"items": [_summary(item) for item in queryset.order_by("-approved_at", "-pk")[offset:offset + limit]]}
|
|
if name == "submissions_stats":
|
|
days = list(queryset.annotate(day=TruncDate("approved_at")).values("day").annotate(count=Count("pk")).order_by("day")[:367])
|
|
classes = {}
|
|
for event in queryset.only("classifier_response").iterator(chunk_size=500):
|
|
label = _label(event)
|
|
classes[label] = classes.get(label, 0) + 1
|
|
return {"total": sum(classes.values()), "by_day": [{"date": row["day"].isoformat(), "count": row["count"]} for row in days],
|
|
"by_predicted_classification": classes, "by_review_outcome": {"approved": sum(classes.values())},
|
|
"confirmed_classification_available": False}
|
|
raise ValueError("Unknown tool")
|
|
|
|
|
|
def _principal(request):
|
|
header = request.headers.get("Authorization", "")
|
|
if not header.startswith("Bearer "):
|
|
return None
|
|
token = header[7:].strip()
|
|
if not token.startswith("bmcp_") or len(token) > 120:
|
|
return None
|
|
from .models import McpAccessToken
|
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
|
credential = McpAccessToken.objects.select_related("user").filter(token_hash=digest, revoked_at__isnull=True).first()
|
|
if not credential or not credential.user.is_active:
|
|
return None
|
|
return credential.user
|
|
|
|
|
|
@csrf_exempt
|
|
def mcp_endpoint(request):
|
|
if request.method != "POST":
|
|
response = JsonResponse({"detail": "POST only"}, status=405)
|
|
response["Allow"] = "POST"
|
|
return response
|
|
origin = request.headers.get("Origin")
|
|
if origin:
|
|
parsed = urlsplit(origin)
|
|
if parsed.scheme not in ("http", "https") or parsed.netloc != request.get_host():
|
|
return JsonResponse({"detail": "Origin not allowed"}, status=403)
|
|
user = _principal(request)
|
|
if user is None:
|
|
response = JsonResponse({"detail": "MCP Bearer token required"}, status=401)
|
|
response["WWW-Authenticate"] = 'Bearer realm="BoomCast MCP"'
|
|
return response
|
|
if not user.has_perm("fireworks_detect.view_event") or not user.has_perm("fireworks_detect.view_pendingevent"):
|
|
return JsonResponse({"detail": "Review read permissions required"}, status=403)
|
|
key = f"boomcast-mcp:{user.pk}"
|
|
if not cache.add(key, 1, 60):
|
|
try:
|
|
count = cache.incr(key)
|
|
except ValueError:
|
|
cache.set(key, 1, 60)
|
|
count = 1
|
|
if count > 120:
|
|
response = JsonResponse({"detail": "Rate limit exceeded"}, status=429)
|
|
response["Retry-After"] = "60"
|
|
return response
|
|
if (request.META.get("CONTENT_LENGTH") or "").isdigit() and int(request.META["CONTENT_LENGTH"]) > 65536:
|
|
return JsonResponse(_error(-32600, "Request too large"), status=413)
|
|
if len(request.body) > 65536:
|
|
return JsonResponse(_error(-32600, "Request too large"), status=413)
|
|
try:
|
|
message = json.loads(request.body)
|
|
except (ValueError, UnicodeDecodeError):
|
|
return JsonResponse(_error(-32700, "Invalid JSON"), status=400)
|
|
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
|
|
return JsonResponse(_error(-32600, "Invalid request"), status=400)
|
|
request_id, method = message.get("id"), message["method"]
|
|
if method == "notifications/initialized" and "id" not in message:
|
|
from django.http import HttpResponse
|
|
return HttpResponse(status=202)
|
|
if "id" not in message or not (isinstance(request_id, (str, int)) and not isinstance(request_id, bool)):
|
|
return JsonResponse(_error(-32600, "Request ID required"), status=400)
|
|
if method == "initialize":
|
|
result = {"protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}}, "serverInfo": {"name": "boomcast-readonly", "version": "1.0.0"}}
|
|
elif method == "tools/list":
|
|
result = {"tools": TOOLS}
|
|
elif method == "tools/call":
|
|
params = message.get("params")
|
|
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
|
|
return JsonResponse(_error(-32602, "Invalid tool call", request_id))
|
|
try:
|
|
output = _call(params["name"], params.get("arguments", {}))
|
|
except ValueError as error:
|
|
result = {"content": [{"type": "text", "text": str(error)}], "isError": True}
|
|
except LookupError:
|
|
result = {"content": [{"type": "text", "text": "Reviewed submission not found"}], "isError": True}
|
|
else:
|
|
result = {"content": [{"type": "text", "text": json.dumps(output, ensure_ascii=False)}], "structuredContent": output}
|
|
else:
|
|
return JsonResponse(_error(-32601, "Method not found", request_id))
|
|
response = JsonResponse(_reply(request_id, result))
|
|
response["Cache-Control"] = "no-store"
|
|
return response
|