|
6 | 6 |
|
7 | 7 | from dotenv import load_dotenv |
8 | 8 | from fastmcp import FastMCP |
9 | | -from pydantic import BaseModel, Field |
| 9 | +from pydantic import BaseModel, Field, model_validator |
| 10 | +from pydantic import ValidationError as PydanticValidationError |
10 | 11 |
|
11 | 12 | from services.hyperliquid_services import HyperliquidServices |
12 | | -from services.validators import ValidationError, validate_order_inputs |
| 13 | +from services.validators import ValidationError, validate_coin, validate_order_inputs |
13 | 14 |
|
14 | 15 | # Load environment variables |
15 | 16 | load_dotenv() |
@@ -84,6 +85,53 @@ def initialize_service(): |
84 | 85 | logger.info(f"Service initialized for account: {account_info}") |
85 | 86 |
|
86 | 87 |
|
| 88 | +class CandlesSnapshotParams(BaseModel): |
| 89 | + """Bulk candles snapshot request parameters""" |
| 90 | + |
| 91 | + coins: list[str] = Field(..., min_length=1, description="List of trading pairs") |
| 92 | + interval: str = Field( |
| 93 | + ..., description="Candlestick interval supported by HyperLiquid" |
| 94 | + ) |
| 95 | + start_time: int | None = Field( |
| 96 | + default=None, |
| 97 | + description="Start timestamp in milliseconds", |
| 98 | + ) |
| 99 | + end_time: int | None = Field( |
| 100 | + default=None, |
| 101 | + description="End timestamp in milliseconds", |
| 102 | + ) |
| 103 | + days: int | None = Field( |
| 104 | + default=None, |
| 105 | + gt=0, |
| 106 | + description="Fetch recent N days (mutually exclusive with start/end)", |
| 107 | + ) |
| 108 | + limit: int | None = Field( |
| 109 | + default=None, |
| 110 | + gt=0, |
| 111 | + le=5000, |
| 112 | + description="Maximum number of candles per coin (latest N records)", |
| 113 | + ) |
| 114 | + |
| 115 | + @model_validator(mode="after") |
| 116 | + def validate_time_params(self): |
| 117 | + if self.days is not None and ( |
| 118 | + self.start_time is not None or self.end_time is not None |
| 119 | + ): |
| 120 | + raise ValueError("days cannot be used together with start_time or end_time") |
| 121 | + |
| 122 | + if self.days is None and self.start_time is None: |
| 123 | + raise ValueError("start_time is required when days is not provided") |
| 124 | + |
| 125 | + if ( |
| 126 | + self.start_time is not None |
| 127 | + and self.end_time is not None |
| 128 | + and self.start_time >= self.end_time |
| 129 | + ): |
| 130 | + raise ValueError("start_time must be less than end_time") |
| 131 | + |
| 132 | + return self |
| 133 | + |
| 134 | + |
87 | 135 | # Account Management Tools |
88 | 136 |
|
89 | 137 |
|
@@ -369,6 +417,103 @@ async def get_orderbook(coin: str, depth: int = 20) -> dict[str, Any]: |
369 | 417 | return await hyperliquid_service.get_orderbook(coin, depth) |
370 | 418 |
|
371 | 419 |
|
| 420 | +@mcp.tool |
| 421 | +async def get_candles_snapshot( |
| 422 | + coins: list[str], |
| 423 | + interval: str, |
| 424 | + start_time: int | None = None, |
| 425 | + end_time: int | None = None, |
| 426 | + days: int | None = None, |
| 427 | + limit: int | None = None, |
| 428 | +) -> dict[str, Any]: |
| 429 | + """ |
| 430 | + Fetch candlestick (OHLCV) data for multiple coins in one request |
| 431 | +
|
| 432 | + Args: |
| 433 | + coins: List of trading pairs (e.g., ["BTC", "ETH"]) |
| 434 | + interval: Candlestick interval supported by HyperLiquid (e.g., "1m", "1h") |
| 435 | + start_time: Start timestamp in milliseconds (required when days not provided) |
| 436 | + end_time: End timestamp in milliseconds (defaults to now when omitted) |
| 437 | + days: Number of recent days to fetch (mutually exclusive with start/end) |
| 438 | + limit: Optional max number of candles per coin (latest N samples) |
| 439 | + """ |
| 440 | + |
| 441 | + initialize_service() |
| 442 | + |
| 443 | + try: |
| 444 | + params = CandlesSnapshotParams( |
| 445 | + coins=coins, |
| 446 | + interval=interval, |
| 447 | + start_time=start_time, |
| 448 | + end_time=end_time, |
| 449 | + days=days, |
| 450 | + limit=limit, |
| 451 | + ) |
| 452 | + except PydanticValidationError as validation_error: |
| 453 | + return { |
| 454 | + "success": False, |
| 455 | + "error": f"Invalid input: {validation_error.errors()}", |
| 456 | + "error_code": "VALIDATION_ERROR", |
| 457 | + } |
| 458 | + except ValueError as validation_error: |
| 459 | + return { |
| 460 | + "success": False, |
| 461 | + "error": f"Invalid input: {str(validation_error)}", |
| 462 | + "error_code": "VALIDATION_ERROR", |
| 463 | + } |
| 464 | + |
| 465 | + # Validate each coin using existing validator for consistency |
| 466 | + for coin in params.coins: |
| 467 | + try: |
| 468 | + validate_coin(coin) |
| 469 | + except ValidationError as validation_error: |
| 470 | + return { |
| 471 | + "success": False, |
| 472 | + "error": f"Invalid input: {str(validation_error)}", |
| 473 | + "error_code": "VALIDATION_ERROR", |
| 474 | + } |
| 475 | + |
| 476 | + service_result = await hyperliquid_service.get_candles_snapshot_bulk( |
| 477 | + coins=params.coins, |
| 478 | + interval=params.interval, |
| 479 | + start_time=params.start_time, |
| 480 | + end_time=params.end_time, |
| 481 | + days=params.days, |
| 482 | + ) |
| 483 | + |
| 484 | + if not service_result.get("success"): |
| 485 | + return service_result |
| 486 | + |
| 487 | + candles_data = service_result.get("data", {}) |
| 488 | + applied_limit = params.limit or None |
| 489 | + |
| 490 | + if applied_limit is not None: |
| 491 | + limited_data = {} |
| 492 | + for coin, candles in candles_data.items(): |
| 493 | + if not isinstance(candles, list): |
| 494 | + limited_data[coin] = candles |
| 495 | + continue |
| 496 | + limited_data[coin] = candles[-applied_limit:] |
| 497 | + candles_data = limited_data |
| 498 | + |
| 499 | + response: dict[str, Any] = { |
| 500 | + "success": True, |
| 501 | + "data": candles_data, |
| 502 | + "interval": service_result.get("interval"), |
| 503 | + "start_time": service_result.get("start_time"), |
| 504 | + "end_time": service_result.get("end_time"), |
| 505 | + "requested_coins": params.coins, |
| 506 | + } |
| 507 | + |
| 508 | + if applied_limit is not None: |
| 509 | + response["limit_per_coin"] = applied_limit |
| 510 | + |
| 511 | + if service_result.get("coin_errors"): |
| 512 | + response["coin_errors"] = service_result["coin_errors"] |
| 513 | + |
| 514 | + return response |
| 515 | + |
| 516 | + |
372 | 517 | @mcp.tool |
373 | 518 | async def get_funding_history(coin: str, days: int = 7) -> dict[str, Any]: |
374 | 519 | """ |
@@ -636,6 +781,23 @@ def start_server(): |
636 | 781 | ) |
637 | 782 | logger.info(f"Logs will be written to: {log_path}") |
638 | 783 |
|
| 784 | + # Log all registered tools BEFORE starting server |
| 785 | + if hasattr(mcp, "_tool_manager") and hasattr(mcp._tool_manager, "_tools"): |
| 786 | + tools_dict = mcp._tool_manager._tools |
| 787 | + tool_names = sorted(tools_dict.keys()) |
| 788 | + |
| 789 | + print("\n" + "=" * 60) |
| 790 | + print(f"✅ {len(tool_names)} MCP Tools Registered:") |
| 791 | + print("=" * 60) |
| 792 | + |
| 793 | + for i, tool_name in enumerate(tool_names, 1): |
| 794 | + marker = "🆕" if tool_name == "get_candles_snapshot" else " " |
| 795 | + print(f"{marker} {i:2d}. {tool_name}") |
| 796 | + |
| 797 | + print("=" * 60 + "\n") |
| 798 | + else: |
| 799 | + print("\n⚠️ Cannot verify tool registration\n") |
| 800 | + |
639 | 801 | asyncio.run(run_as_server()) |
640 | 802 | except Exception as e: |
641 | 803 | logger.error(f"Failed to start server: {e}") |
|
0 commit comments