Spaces:
Running

File size: 28,203 Bytes
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
0a7b128
5655786
 
0a7b128
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
 
 
 
 
5655786
 
 
0a7b128
 
 
 
 
5655786
 
0a7b128
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
 
5655786
0a7b128
 
 
 
5655786
 
 
0a7b128
 
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
 
0a7b128
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a7b128
 
 
 
 
5655786
0a7b128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5655786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Libratio Fleet β€” Google ADK Agent Orchestrator
===============================================
Google Cloud Agent Builder integration using Google ADK 2.2.0.

HOW IT WORKS (simple version):
  1. Google ADK gives Gemini a set of "tools" it can call
  2. One toolset = MongoDB MCP Server (a Node.js process that knows how to talk to MongoDB)
  3. Another toolset = our fleet physics tools (Python functions Gemini can call directly)
  4. Gemini reasons about the fleet task, decides which tools to call, and orchestrates everything
  5. ADK runs this in a loop until the task is done

WHY THIS MATTERS FOR THE HACKATHON:
  - "Google Cloud Agent Builder" = Google ADK (the code-first version of Agent Builder)
  - "MongoDB MCP Server" = the partner superpowers requirement
  - Gemini 2.0 Flash = the brain
  - This file is the proof that all three are wired together

Requirements:
  - pip install google-adk mcp
  - npm/npx available (for MongoDB MCP server subprocess)
  - MONGO_URI, GEMINI_API_KEY set in .env
"""

import asyncio
import contextvars
import json
import logging
import os
import sys
import threading
from typing import Optional

from dotenv import load_dotenv

load_dotenv()

# ── Google ADK imports ──────────────────────────────────────────────────────
try:
    from google.adk.agents import Agent
    from google.adk.runners import InMemoryRunner
    from google.adk.tools.mcp_tool.mcp_toolset import McpToolset, StdioConnectionParams
    from google.adk.tools import FunctionTool
    from mcp import StdioServerParameters
    from google.genai import types as genai_types
    ADK_AVAILABLE = True
except ImportError as e:
    ADK_AVAILABLE = False
    print(f"[WARN] Google ADK not installed: {e}")
    print("       Run: pip install google-adk mcp")

# ── Config ──────────────────────────────────────────────────────────────────
MONGO_URI = os.getenv("MONGO_URI", "")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
USE_VERTEX_AI = os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "FALSE").upper() == "TRUE"
ADK_MODEL = os.getenv("ADK_MODEL", "gemini-2.0-flash")

logger = logging.getLogger("libratio.adk")


# ═══════════════════════════════════════════════════════════════════════════
# PART 1: MONGODB MCP TOOLSET
# ═══════════════════════════════════════════════════════════════════════════
# This launches the official MongoDB MCP server (@mongodb-js/mongodb-mcp-server)
# as a child process. The ADK MCPToolset wraps ALL its tools so Gemini can
# call them like native Python functions.
#
# Tools exposed by MongoDB MCP server include:
#   - find: Query documents from a collection
#   - aggregate: Run aggregation pipelines (including $vectorSearch)
#   - insertMany: Insert documents
#   - createIndex: Create search/vector indexes
#   - listCollections: List all collections
#   - count: Count documents matching a filter
# ═══════════════════════════════════════════════════════════════════════════

def get_mongodb_mcp_toolset() -> "McpToolset | None":
    """
    Creates a Google ADK McpToolset connected to the MongoDB MCP Server.

    The MongoDB MCP server runs as a Node.js subprocess (via npx).
    ADK communicates with it over stdio using the Model Context Protocol.

    Returns:
        McpToolset if MongoDB MCP is available, None otherwise.
    """
    if not ADK_AVAILABLE:
        logger.warning("ADK not available -- MongoDB MCP toolset skipped")
        return None

    import platform
    if platform.system() == "Windows":
        logger.info("Windows detected -- skipping Node.js MCP stdio subprocess to prevent asyncio pipe issues. Using PyMongo tools instead.")
        return None

    if not MONGO_URI:
        logger.warning("MONGO_URI not set -- MongoDB MCP toolset will use localhost")

    logger.info("Initializing MongoDB MCP Server (via npx mongodb-mcp-server)...")

    # The MongoDB MCP server is a Node.js package published by MongoDB.
    # Package was renamed from @mongodb-js/mongodb-mcp-server -> mongodb-mcp-server
    # Connection string is now passed via MDB_MCP_CONNECTION_STRING env var
    # (the old --connectionString CLI arg is deprecated).

    # On Windows, "npx" is actually "npx.cmd" β€” Python subprocess can't find
    # bare "npx" without shell=True. We resolve the full path with shutil.which.
    import shutil
    npx_cmd = shutil.which("npx")
    if npx_cmd is None:
        logger.error("npx not found on PATH. Install Node.js: https://nodejs.org")
        return None

    logger.info(f"Using npx at: {npx_cmd}")

    mcp_toolset = McpToolset(
        connection_params=StdioConnectionParams(
            server_params=StdioServerParameters(
                # Run the official MongoDB MCP server via npx (auto-downloads)
                command=npx_cmd,                    # full path works on all OS
                args=[
                    "-y",                           # auto-install without prompting
                    "mongodb-mcp-server@latest",    # official MongoDB MCP package (new name)
                ],
                env={
                    **os.environ,                    # inherit PATH, NODE, etc.
                    "MDB_MCP_CONNECTION_STRING": MONGO_URI,  # official env var name
                },
            ),
            timeout=60,  # 60s timeout for initial npx package download on first run
        )
    )

    logger.info("MongoDB MCP toolset configured (npx mongodb-mcp-server)")
    return mcp_toolset


# ═══════════════════════════════════════════════════════════════════════════
# PART 2: FLEET PHYSICS TOOLS (ADK Python Tools)
# ═══════════════════════════════════════════════════════════════════════════
# These wrap our existing fleet environment as ADK-compatible Python tools.
# Gemini can call these to interact with the physics-based RL environment.
# ═══════════════════════════════════════════════════════════════════════════

_fleet_env_var: contextvars.ContextVar[Optional[object]] = contextvars.ContextVar(
    "adk_fleet_env", default=None
)
_last_step_score_var: contextvars.ContextVar[Optional[float]] = contextvars.ContextVar(
    "adk_last_step_score", default=None
)
_fallback_fleet_env = None


def _fleet_env():
    env = _fleet_env_var.get()
    if env is not None:
        return env
    global _fallback_fleet_env
    if _fallback_fleet_env is None:
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from environment.fleet_env import FleetEnvironment
        _fallback_fleet_env = FleetEnvironment()
    return _fallback_fleet_env


def reset_fleet_environment(task_id: str) -> dict:
    """
    Reset the Libratio fleet environment to start a new episode.

    Use this at the beginning of each fleet task to get an initial observation
    of the GPU cluster state. The observation tells you about available GPUs,
    memory, and the model(s) you need to configure.

    Args:
        task_id: One of 'fleet_precision', 'fleet_oversight', 'fleet_resource', 'fleet_recovery'

    Returns:
        Initial cluster observation dict with GPU state, model info, and task context.
    """
    try:
        obs = _fleet_env().reset(task_id)
        logger.info(f"[Tool] reset_fleet_environment: task={task_id}")
        return {"success": True, "observation": obs, "task_id": task_id}
    except Exception as e:
        logger.error(f"[Tool] reset_fleet_environment error: {e}")
        return {"success": False, "error": str(e)}


def step_fleet_environment(action_json: str) -> dict:
    """
    Submit an action to the fleet environment and get a reward score.

    After observing the cluster state, use this tool to submit your decision
    as a JSON string. The environment evaluates your action using the
    physics-based reward model and returns a score between 0.01 and 0.99.

    Action format depends on the current task:
    - fleet_precision: {"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}, "reasoning": "..."}
    - fleet_oversight: {"action_type": "continue_monitoring|flag_instability", "analysis": "...", "flagged_model": null}
    - fleet_resource: {"allocations": {"model_a": {"gpus": 4, "precision_strategy": {...}}}, "reasoning": "..."}
    - fleet_recovery: Phase-dependent (diagnose/reallocate/verify)

    Args:
        action_json: JSON string containing the action dict

    Returns:
        Dict with score (0.01-0.99), feedback string, done flag, and next observation.
    """
    try:
        action = json.loads(action_json)
        result = _fleet_env().step(action)
        score = max(0.01, min(0.99, float(result["reward"]["score"])))
        _last_step_score_var.set(score)
        logger.info(f"[Tool] step_fleet_environment: score={score:.3f}")
        return {
            "success": True,
            "score": score,
            "feedback": result["reward"]["feedback"],
            "done": result["done"],
            "observation": result.get("observation"),
        }
    except json.JSONDecodeError as e:
        return {"success": False, "error": f"Invalid JSON in action: {e}"}
    except Exception as e:
        logger.error(f"[Tool] step_fleet_environment error: {e}")
        return {"success": False, "error": str(e)}


def compute_precision_physics(layer_name: str, precision: str) -> dict:
    """
    Compute the physics-based score and safety check for a precision assignment.

    Use this to validate your precision choices BEFORE submitting to the fleet.
    This is the Agentic Kernel β€” pure math based on NVIDIA Transformer Engine benchmarks.

    Args:
        layer_name: One of 'embedding', 'attention', 'ffn', 'layernorm', 'output'
        precision: One of 'FP32', 'BF16', 'FP16', 'FP8'

    Returns:
        Dict with score, stability, and recommendation.
    """
    try:
        sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        from environment.physics_model import score_precision_layer, STABILITY_SCORE
        score, feedback = score_precision_layer(layer_name, precision)
        stability = STABILITY_SCORE.get(layer_name, {}).get(precision, 0.5)
        return {
            "layer": layer_name,
            "precision": precision,
            "physics_score": round(score, 3),
            "stability": round(stability, 3),
            "is_stable": stability >= 0.7,
            "feedback": feedback,
            "recommendation": (
                f"SAFE: {precision} is good for {layer_name}"
                if stability >= 0.7
                else f"RISKY: {precision} on {layer_name} may cause instability (stability={stability:.2f})"
            ),
        }
    except Exception as e:
        return {"error": str(e), "layer": layer_name, "precision": precision}


def get_fleet_physics_tools() -> list:
    """Return a list of ADK FunctionTool wrappers for fleet physics functions."""
    if not ADK_AVAILABLE:
        return []
    return [
        FunctionTool(func=reset_fleet_environment),
        FunctionTool(func=step_fleet_environment),
        FunctionTool(func=compute_precision_physics),
    ]


# ═══════════════════════════════════════════════════════════════════════════
# PART 2B: MONGODB PYMONGO TOOLS (FALLBACK)
# ═══════════════════════════════════════════════════════════════════════════
# When the MCP subprocess fails (common on Windows due to asyncio pipe issues),
# these pymongo-based FunctionTools serve as the MongoDB integration.
# Gemini calls them exactly like MCP tools β€” same purpose, same data.
# ═══════════════════════════════════════════════════════════════════════════

_adk_mongo_client = None
_adk_mongo_lock = threading.Lock()


def _get_mongo_db():
    """Get a shared pymongo database handle (reuses one MongoClient pool)."""
    global _adk_mongo_client
    if not MONGO_URI:
        return None
    try:
        import certifi
        from pymongo import MongoClient
        with _adk_mongo_lock:
            if _adk_mongo_client is None:
                _adk_mongo_client = MongoClient(
                    MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000
                )
        return _adk_mongo_client["libratio"]
    except Exception as e:
        logger.warning(f"MongoDB connection failed: {e}")
        return None


def query_mongodb_trajectories(filter_json: str = "{}", limit: int = 5) -> dict:
    """
    Query historical training trajectories from MongoDB Atlas.

    Use this tool to find past GPU fleet training runs from the 'trajectories' collection.
    Returns documents with precision strategies, rewards, and cluster states from previous episodes.
    This data helps you make better decisions by learning from history.

    Args:
        filter_json: MongoDB filter as JSON string. Use '{}' for all docs, or '{"task_id": "fleet_precision"}' to filter.
        limit: Maximum number of documents to return (default 5).

    Returns:
        Dict with matching trajectory documents from MongoDB Atlas.
    """
    db = _get_mongo_db()
    if db is None:
        return {"error": "MongoDB not connected. Check MONGO_URI in .env", "documents": []}

    try:
        import json as _json
        filter_dict = _json.loads(filter_json) if filter_json else {}
        docs = list(db["trajectories"].find(filter_dict, {"_id": 0, "embedding": 0}).limit(limit))
        logger.info(f"[MongoDB Tool] query_trajectories: filter={filter_json}, found={len(docs)}")
        return {"success": True, "count": len(docs), "documents": docs}
    except Exception as e:
        return {"error": str(e), "documents": []}


def log_run_to_mongodb(task_id: str, score: float, action_json: str, reasoning: str) -> dict:
    """
    Log a training run result to MongoDB Atlas 'runs' collection.

    Call this AFTER stepping the environment to record your result.
    This creates a permanent record in MongoDB that can be queried by future agents.

    Args:
        task_id: The fleet task that was run (e.g. 'fleet_precision')
        score: The reward score achieved (0.01 to 0.99)
        action_json: The JSON action that was submitted
        reasoning: Your reasoning for the chosen action

    Returns:
        Dict confirming the insert with the document ID.
    """
    db = _get_mongo_db()
    if db is None:
        return {"error": "MongoDB not connected", "logged": False}

    try:
        import json as _json
        from datetime import datetime, timezone
        score_val = float(score)
        doc = {
            "task_id": task_id,
            "model_name": ADK_MODEL,
            "model_id": ADK_MODEL,
            "score": score_val,
            "success": score_val >= 0.60,
            "action": _json.loads(action_json) if isinstance(action_json, str) else action_json,
            "reasoning": reasoning,
            "agent": "libratio_fleet_commander_adk",
            "model": ADK_MODEL,
            "timestamp": datetime.now(timezone.utc),
        }
        result = db["runs"].insert_one(doc)
        logger.info(f"[MongoDB Tool] log_run: task={task_id}, score={score}, id={result.inserted_id}")
        return {"success": True, "logged": True, "document_id": str(result.inserted_id)}
    except Exception as e:
        return {"error": str(e), "logged": False}


def get_mongodb_fallback_tools() -> list:
    """Return pymongo-based FunctionTools as a fallback when MCP subprocess fails."""
    if not ADK_AVAILABLE:
        return []
    return [
        FunctionTool(func=query_mongodb_trajectories),
        FunctionTool(func=log_run_to_mongodb),
    ]


# ═══════════════════════════════════════════════════════════════════════════
# PART 3: AGENT SYSTEM PROMPT
# ═══════════════════════════════════════════════════════════════════════════

FLEET_AGENT_INSTRUCTION = """
You are the Libratio Fleet Commander β€” a Google ADK-powered AI agent managing
GPU clusters using MongoDB Atlas as your intelligent backend.

## Your Tools
You have two types of tools:

**MongoDB MCP Tools** (your data superpowers β€” call these first!):
- Use find/aggregate to query historical crash trajectories from 'libratio.trajectories'
- Use insertMany to log your results to 'libratio.runs'
- Use aggregate with $vectorSearch to find semantically similar past crashes

**Fleet Physics Tools** (your environment interface):
- reset_fleet_environment: Start a new fleet task episode
- step_fleet_environment: Submit your precision/allocation decision as JSON
- compute_precision_physics: Validate a precision choice with physics model

## Workflow for Each Task
1. RETRIEVE: Query MongoDB 'libratio.trajectories' for historical runs similar to current scenario
2. ANALYZE: Use compute_precision_physics to validate your planned action
3. ACT: Use step_fleet_environment to submit your JSON decision
4. LOG: Insert your result into MongoDB 'libratio.runs'

## Precision Rules (memorize these)
- embedding: ALWAYS FP32 (FP8 causes NaN crashes β€” NEVER use FP8 here)
- output: ALWAYS FP32 (loss computation needs full precision)
- ffn: FP8 is ideal (2.5x speedup, safe for FFN layers)
- attention: BF16 is optimal (1.85x speedup)
- layernorm: BF16 is best

## Goal
Reward score > 0.60 = success. Target > 0.85.
Always retrieve MongoDB context before acting.
"""


# ═══════════════════════════════════════════════════════════════════════════
# PART 4: AGENT ASSEMBLY + RUNNER (ADK 2.2.0 API)
# ═══════════════════════════════════════════════════════════════════════════

async def run_fleet_task_with_adk(task_id: str = "fleet_precision") -> dict:
    """
    Run a complete Libratio fleet task using the Google ADK agent.

    This is the main entry point for the hackathon demo. It:
    1. Creates the ADK agent with MongoDB MCP + physics tools
    2. Sends a task message to Gemini 2.0 Flash
    3. Gemini reasons, calls MongoDB MCP tools, calls physics tools
    4. Returns the final score and reasoning

    Args:
        task_id: One of 'fleet_precision', 'fleet_oversight', 'fleet_resource', 'fleet_recovery'

    Returns:
        Dict with final_score, steps, reasoning, mongo_tools_called, physics_tools_called
    """
    if not ADK_AVAILABLE:
        raise RuntimeError("Google ADK not installed. Run: pip install google-adk mcp")

    logger.info(f"\n{'='*60}")
    logger.info(f"  LIBRATIO ADK AGENT - task={task_id}")
    logger.info(f"  Model: {ADK_MODEL} | MongoDB: enabled | Physics: enabled")
    logger.info(f"{'='*60}")

    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from environment.fleet_env import FleetEnvironment

    env_token = _fleet_env_var.set(FleetEnvironment())
    score_token = _last_step_score_var.set(None)

    mongo_mcp = get_mongodb_mcp_toolset()
    physics_tools = get_fleet_physics_tools()
    mongo_fallback_tools = get_mongodb_fallback_tools()

    all_tools = physics_tools + mongo_fallback_tools
    mongodb_mode = "pymongo (ADK FunctionTool)"
    if mongo_mcp:
        all_tools = [mongo_mcp] + all_tools
        mongodb_mode = "MCP Server + pymongo fallback"

    logger.info(f"MongoDB mode: {mongodb_mode}")

    agent = Agent(
        model=ADK_MODEL,
        name="libratio_fleet_commander",
        instruction=FLEET_AGENT_INSTRUCTION,
        tools=all_tools,
    )

    runner = InMemoryRunner(
        agent=agent,
        app_name="libratio_fleet",
    )

    session = await runner.session_service.create_session(
        app_name="libratio_fleet",
        user_id="fleet_commander",
    )
    session_id = session.id

    task_prompt = f"""
Run a complete Libratio fleet task: {task_id}

Follow this exact workflow:
1. Call reset_fleet_environment(task_id="{task_id}") to see the cluster state
2. Call MongoDB find or aggregate on collection 'trajectories' in database 'libratio' 
   to retrieve 3-5 historical runs with similar conditions
3. Call compute_precision_physics for the layers you plan to configure
4. Call step_fleet_environment with your best JSON action (aim for score > 0.85)
5. Call MongoDB insertMany to log your result to collection 'runs' in database 'libratio'
6. Report: your final score, which MongoDB MCP tools you used, and your reasoning

Target reward: > 0.85
Database: libratio | Collections: trajectories (read), runs (write)
"""

    mongo_tools_called = []
    physics_tools_called = []
    final_text = ""
    final_score = 0.0
    event_count = 0

    try:
        max_retries = 3
        for attempt in range(max_retries):
            try:
                async for event in runner.run_async(
                    user_id="fleet_commander",
                    session_id=session_id,
                    new_message=genai_types.Content(
                        role="user",
                        parts=[genai_types.Part(text=task_prompt)],
                    ),
                ):
                    event_count += 1

                    if hasattr(event, "content") and event.content:
                        for part in event.content.parts:
                            if hasattr(part, "function_call") and part.function_call:
                                tool_name = part.function_call.name
                                logger.info(f"  [Tool called] {tool_name}")

                                mongo_keywords = ["find", "aggregate", "insert", "collection", "mongo",
                                                  "vector_search", "count", "query_mongodb", "log_run"]
                                if any(kw in tool_name.lower() for kw in mongo_keywords):
                                    mongo_tools_called.append(tool_name)
                                else:
                                    physics_tools_called.append(tool_name)

                            if hasattr(part, "text") and part.text:
                                final_text += part.text

                    if hasattr(event, "is_final_response") and callable(event.is_final_response):
                        if event.is_final_response():
                            logger.info("  [Final response received]")

                break

            except Exception as e:
                error_msg = str(e)
                if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
                    wait_time = 35 * (attempt + 1)
                    logger.warning(f"  Rate limited (attempt {attempt+1}/{max_retries}). Waiting {wait_time}s...")
                    await asyncio.sleep(wait_time)
                    session = await runner.session_service.create_session(
                        app_name="libratio_fleet",
                        user_id="fleet_commander",
                    )
                    session_id = session.id
                else:
                    logger.error(f"ADK agent run error: {e}")
                    raise

        recorded_score = _last_step_score_var.get()
        if recorded_score is not None:
            final_score = recorded_score
        else:
            import re
            score_matches = re.findall(r'score[:\s=]+([0-9]+(?:\.[0-9]+)?)', final_text.lower())
            if score_matches:
                try:
                    final_score = max(0.01, min(0.99, float(score_matches[-1])))
                except ValueError:
                    final_score = 0.01
    finally:
        if mongo_mcp is not None and hasattr(mongo_mcp, "close"):
            try:
                await mongo_mcp.close()
            except Exception:
                pass
        _fleet_env_var.reset(env_token)
        _last_step_score_var.reset(score_token)

    result = {
        "task_id": task_id,
        "model": ADK_MODEL,
        "final_score": round(final_score, 3),
        "events_processed": event_count,
        "mongo_tools_called": mongo_tools_called,
        "physics_tools_called": physics_tools_called,
        "total_tool_calls": len(mongo_tools_called) + len(physics_tools_called),
        "mongodb_mcp_used": len(mongo_tools_called) > 0,
        "final_reasoning": final_text[:800] if final_text else "See server logs for full reasoning",
    }

    logger.info(f"\n{'='*60}")
    logger.info(f"  ADK AGENT COMPLETE")
    logger.info(f"  MongoDB MCP tools called: {mongo_tools_called}")
    logger.info(f"  Physics tools called: {physics_tools_called}")
    logger.info(f"  Final score: {result['final_score']}")
    logger.info(f"{'='*60}\n")

    return result


# ═══════════════════════════════════════════════════════════════════════════
# ENTRY POINT
# ═══════════════════════════════════════════════════════════════════════════

async def _main():
    """Run a demo of the ADK agent."""
    task_id = os.environ.get("TASK_ID", "fleet_precision")
    print(f"\nRunning ADK agent: task={task_id}, model={ADK_MODEL}")
    print(f"MongoDB MCP: {'enabled' if MONGO_URI else 'disabled (no MONGO_URI)'}")
    print(f"Gemini API: {'configured' if GEMINI_API_KEY else 'MISSING - set GEMINI_API_KEY in .env'}")
    print()

    if not GEMINI_API_KEY:
        print("ERROR: GEMINI_API_KEY not set in .env")
        print("Get a free key at: https://aistudio.google.com/apikey")
        sys.exit(1)

    result = await run_fleet_task_with_adk(task_id)

    print("\n" + "=" * 60)
    print("LIBRATIO ADK AGENT - RESULT SUMMARY")
    print("=" * 60)
    print(json.dumps(result, indent=2))

    if result["mongodb_mcp_used"]:
        print("\n[OK] MongoDB MCP Server was used - hackathon partner requirement SATISFIED")
    else:
        print("\n[WARN] MongoDB MCP tools were not called.")
        print("       Check that MONGO_URI is set and npx is available.")


if __name__ == "__main__":
    if not ADK_AVAILABLE:
        print("ERROR: Google ADK not installed. Run: pip install google-adk mcp")
        sys.exit(1)
    asyncio.run(_main())