Repository navigation
feat: gamification & leaderboard system #2405
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 14 commits
4457d6c
5164b11
954c9eb
3fd342f
bccb7ae
9ef1ac1
0ca87c3
81d3522
7c9334a
5564e25
98ea8ae
4313ce5
0288024
3fcf615
f33aa36
af5f0ab
409228a
3e648d5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| /** | ||
| * MCP Gamification Tools — leaderboard, badges, levels, sharing. | ||
| * | ||
| * @module mcp-server/tools/gamificationTools | ||
| */ | ||
|
|
||
| import { z } from "zod"; | ||
|
|
||
| export const gamificationTools = [ | ||
| { | ||
| name: "gamification_leaderboard", | ||
| description: "Get leaderboard rankings for a scope (global, weekly, monthly, tokens_shared).", | ||
| inputSchema: z.object({ | ||
| scope: z.enum(["global", "weekly", "monthly", "tokens_shared"]).default("global"), | ||
| limit: z.number().min(1).max(100).default(50), | ||
| }), | ||
| handler: async (args: { scope: string; limit: number }) => { | ||
| const { getTopN } = await import("../../../src/lib/gamification/leaderboard"); | ||
| const entries = await getTopN(args.scope as any, args.limit); | ||
| return { entries }; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_rank", | ||
| description: "Get rank for an API key in a leaderboard scope.", | ||
| inputSchema: z.object({ | ||
| apiKeyId: z.string(), | ||
| scope: z.enum(["global", "weekly", "monthly", "tokens_shared"]).default("global"), | ||
| }), | ||
| handler: async (args: { apiKeyId: string; scope: string }) => { | ||
| const { getRank } = await import("../../../src/lib/gamification/leaderboard"); | ||
| const rank = await getRank(args.apiKeyId, args.scope as any); | ||
| return { rank }; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_profile", | ||
| description: "Get XP, level, and badges for an API key.", | ||
| inputSchema: z.object({ | ||
| apiKeyId: z.string(), | ||
| }), | ||
| handler: async (args: { apiKeyId: string }) => { | ||
| const { getXp, getBadges } = await import("../../../src/lib/db/gamification"); | ||
| const { calculateLevel, getLevelTitle, getLevelTier } = | ||
| await import("../../../src/lib/gamification/xp"); | ||
| const { getStreak } = await import("../../../src/lib/gamification/streaks"); | ||
|
|
||
| const xp = getXp(args.apiKeyId); | ||
| const badges = getBadges(args.apiKeyId); | ||
| const streak = await getStreak(args.apiKeyId); | ||
| const level = xp ? calculateLevel(xp.totalXp) : 1; | ||
|
|
||
| return { | ||
| totalXp: xp?.totalXp || 0, | ||
| level, | ||
| title: getLevelTitle(level), | ||
| tier: getLevelTier(level), | ||
| streak: streak.currentStreak, | ||
| longestStreak: streak.longestStreak, | ||
| badges: badges.map((b) => ({ id: b.badgeId, unlockedAt: b.unlockedAt })), | ||
| }; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_badges", | ||
| description: "List all badge definitions or earned badges for an API key.", | ||
| inputSchema: z.object({ | ||
| apiKeyId: z.string().optional(), | ||
| category: z.string().optional(), | ||
| }), | ||
| handler: async (args: { apiKeyId?: string; category?: string }) => { | ||
| const { getBadgeDefinitions, getBadges } = await import("../../../src/lib/db/gamification"); | ||
|
|
||
| if (args.apiKeyId) { | ||
| const badges = getBadges(args.apiKeyId); | ||
| return { earned: badges }; | ||
| } | ||
|
|
||
| const definitions = getBadgeDefinitions(args.category); | ||
| return { definitions }; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_transfer", | ||
| description: "Transfer tokens between API keys.", | ||
| inputSchema: z.object({ | ||
| fromApiKeyId: z.string(), | ||
| toApiKeyId: z.string(), | ||
| amount: z.number().positive(), | ||
| reason: z.string().optional(), | ||
| }), | ||
| handler: async (args: { | ||
| fromApiKeyId: string; | ||
| toApiKeyId: string; | ||
| amount: number; | ||
| reason?: string; | ||
| }) => { | ||
| const { transferTokens } = await import("../../../src/lib/gamification/sharing"); | ||
| const result = await transferTokens( | ||
| args.fromApiKeyId, | ||
| args.toApiKeyId, | ||
| args.amount, | ||
| args.reason | ||
| ); | ||
| return result; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_invite", | ||
| description: "Create an invite token for server connection.", | ||
| inputSchema: z.object({ | ||
| apiKeyId: z.string(), | ||
| serverUrl: z.string().optional(), | ||
| maxUses: z.number().positive().default(1), | ||
| }), | ||
| handler: async (args: { apiKeyId: string; serverUrl?: string; maxUses: number }) => { | ||
| const { createInvite } = await import("../../../src/lib/gamification/invites"); | ||
| const result = await createInvite(args.apiKeyId, args.serverUrl, args.maxUses); | ||
| return result; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_servers", | ||
| description: "List connected community servers.", | ||
| inputSchema: z.object({}), | ||
| handler: async () => { | ||
| const { listServers } = await import("../../../src/lib/gamification/servers"); | ||
| return { servers: await listServers() }; | ||
| }, | ||
| }, | ||
| { | ||
| name: "gamification_anomalies", | ||
| description: "Get flagged anomalous XP activity (admin only).", | ||
| inputSchema: z.object({}), | ||
| handler: async () => { | ||
| const { getAnomalies } = await import("../../../src/lib/gamification/antiCheat"); | ||
| return { anomalies: await getAnomalies() }; | ||
| }, | ||
| }, | ||
| ]; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| "use client"; | ||
|
|
||
| import { useState, useEffect, useCallback } from "react"; | ||
|
|
||
| interface BadgeUnlockEvent { | ||
| badgeId: string; | ||
| badgeName: string; | ||
| badgeIcon: string; | ||
| badgeRarity: string; | ||
| } | ||
|
|
||
| const RARITY_COLORS: Record<string, string> = { | ||
| common: "border-gray-500 bg-gray-800", | ||
| uncommon: "border-green-500 bg-green-900/30", | ||
| rare: "border-blue-500 bg-blue-900/30", | ||
| legendary: "border-yellow-500 bg-yellow-900/30", | ||
| }; | ||
|
|
||
| export function BadgeToast({ apiKeyId }: { apiKeyId: string }) { | ||
| const [toasts, setToasts] = useState<BadgeUnlockEvent[]>([]); | ||
|
|
||
| const addToast = useCallback((event: BadgeUnlockEvent) => { | ||
| setToasts((prev) => [...prev, event]); | ||
| // Auto-dismiss after 5s | ||
| setTimeout(() => { | ||
| setToasts((prev) => prev.slice(1)); | ||
| }, 5000); | ||
| }, []); | ||
|
|
||
| useEffect(() => { | ||
| const es = new EventSource(`/api/gamification/notifications?apiKeyId=${apiKeyId}`); | ||
|
|
||
| es.addEventListener("badge_unlock", (event) => { | ||
| try { | ||
| const data = JSON.parse(event.data) as BadgeUnlockEvent; | ||
| addToast(data); | ||
| } catch { | ||
| // ignore parse errors | ||
| } | ||
| }); | ||
|
|
||
| es.onerror = () => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WARNING: No reconnect logic for EventSource — permanent disconnect on error When The leaderboard page ( |
||
| es.close(); | ||
| }; | ||
|
|
||
| return () => es.close(); | ||
| }, [apiKeyId, addToast]); | ||
|
|
||
| if (toasts.length === 0) return null; | ||
|
|
||
| return ( | ||
| <div className="fixed top-4 right-4 z-50 flex flex-col gap-2"> | ||
| {toasts.map((toast, i) => ( | ||
| <div | ||
| key={`${toast.badgeId}-${i}`} | ||
| className={`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg animate-slide-in ${RARITY_COLORS[toast.badgeRarity] || RARITY_COLORS.common}`} | ||
| > | ||
| <span className="text-2xl">🏆</span> | ||
| <div> | ||
| <div className="font-semibold text-white">Badge Unlocked!</div> | ||
| <div className="text-sm text-text-muted">{toast.badgeName}</div> | ||
| </div> | ||
| </div> | ||
| ))} | ||
| </div> | ||
| ); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| "use client"; | ||
|
|
||
| import { useState, useEffect } from "react"; | ||
| import { Card } from "@/shared/components"; | ||
|
|
||
| interface Anomaly { | ||
| apiKeyId: string; | ||
| xpLastHour: number; | ||
| zScore: number; | ||
| } | ||
|
|
||
| export default function GamificationAdminPage() { | ||
| const [anomalies, setAnomalies] = useState<Anomaly[]>([]); | ||
| const [loading, setLoading] = useState(true); | ||
|
|
||
| useEffect(() => { | ||
| const fetchAnomalies = async () => { | ||
| try { | ||
| const res = await fetch("/api/gamification/anomalies"); | ||
| const data = await res.json(); | ||
| setAnomalies(data.anomalies || []); | ||
| } catch { | ||
| // ignore fetch errors | ||
| } finally { | ||
| setLoading(false); | ||
| } | ||
| }; | ||
| fetchAnomalies(); | ||
| const interval = setInterval(fetchAnomalies, 30000); | ||
| return () => clearInterval(interval); | ||
| }, []); | ||
|
|
||
| return ( | ||
| <div className="flex flex-col gap-6"> | ||
| <div> | ||
| <h1 className="text-2xl font-bold">Gamification Admin</h1> | ||
| <p className="text-sm text-text-muted mt-1">Monitor anomalies and system health</p> | ||
| </div> | ||
|
|
||
| <Card> | ||
| <h2 className="text-lg font-semibold mb-3">Flagged Anomalies</h2> | ||
| {loading ? ( | ||
| <div className="text-text-muted">Loading...</div> | ||
| ) : anomalies.length === 0 ? ( | ||
| <div className="text-text-muted">No anomalies detected</div> | ||
| ) : ( | ||
| <div className="overflow-x-auto"> | ||
| <table className="w-full text-sm"> | ||
| <thead> | ||
| <tr className="border-b border-border"> | ||
| <th className="text-left p-2 font-medium text-text-muted">API Key</th> | ||
| <th className="text-right p-2 font-medium text-text-muted">XP (1h)</th> | ||
| <th className="text-right p-2 font-medium text-text-muted">Z-Score</th> | ||
| <th className="text-center p-2 font-medium text-text-muted">Status</th> | ||
| </tr> | ||
| </thead> | ||
| <tbody> | ||
| {anomalies.map((a) => ( | ||
| <tr key={a.apiKeyId} className="border-b border-border/50 last:border-b-0"> | ||
| <td className="p-2 font-mono text-xs">{a.apiKeyId.slice(0, 16)}...</td> | ||
| <td className="p-2 text-right">{a.xpLastHour.toLocaleString()}</td> | ||
| <td className="p-2 text-right text-red-400">{a.zScore.toFixed(2)}</td> | ||
| <td className="p-2 text-center"> | ||
| <span className="px-2 py-0.5 text-xs bg-red-500/20 text-red-400 rounded-full"> | ||
| Suspicious | ||
| </span> | ||
| </td> | ||
| </tr> | ||
| ))} | ||
| </tbody> | ||
| </table> | ||
| </div> | ||
| )} | ||
| </Card> | ||
| </div> | ||
| ); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
WARNING:
setTimeoutis never cleared on unmount — causes state update on unmounted componentIf
BadgeToastunmounts while toasts are still visible (e.g., user navigates away), thesetTimeoutcallback at line 25 will still fire after 5 seconds and callsetToasts()on an unmounted component. This causes a React warning and potential memory leak.Return a cleanup function from
addToastor useuseRefto track timeouts and clear them in theuseEffectcleanup.