deribit-mcp 1.0.0

MCP (Model Context Protocol) server for Deribit trading platform
Documentation
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
//! Authenticated `Account` tool family.
//!
//! All tools in this module have [`ToolClass::Account`] and require
//! credentials configured via `DERIBIT_CLIENT_ID` /
//! `DERIBIT_CLIENT_SECRET` (ADR-0004). The first call drives the
//! upstream `AuthManager`'s OAuth client-credentials flow lazily and
//! caches the token (v0.2-01).
//!
//! v0.2-02 ships:
//!
//! - `get_account_summary` — balance / equity / margin for a currency.
//! - `get_positions` — open positions, optionally filtered by currency
//!   / kind / subaccount.
//! - `get_subaccounts` — subaccount list with optional portfolio.
//!
//! v0.2-03 adds historical-activity tools:
//!
//! - `get_transaction_log` — account transaction log for a window.
//! - `get_deposits` — recent deposits for a currency.
//! - `get_withdrawals` — recent withdrawals for a currency.
//!
//! v0.2-04 adds order + user-trades history:
//!
//! - `get_open_orders_by_currency` — open orders for a currency,
//!   optionally filtered by kind / type.
//! - `get_open_orders_by_instrument` — open orders for one
//!   instrument.
//! - `get_user_trades_by_currency` — user trades over an id /
//!   timestamp window.
//! - `get_user_trades_by_instrument` — user trades for an
//!   instrument over a sequence-number window.
//!
//! [`ToolClass::Account`]: super::ToolClass::Account

use std::sync::Arc;

use rmcp::model::Tool;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::schema::{parse_input as parse, schema_for};
use super::{ToolClass, ToolEntry, ToolHandlerFn, ToolRegistry};
use crate::context::AdapterContext;
use crate::error::AdapterError;

/// Register every `Account` tool with the registry.
pub fn register(registry: &mut ToolRegistry) {
    registry.insert(get_account_summary_tool());
    registry.insert(get_positions_tool());
    registry.insert(get_subaccounts_tool());
    // v0.2-03 — historical activity.
    registry.insert(get_transaction_log_tool());
    registry.insert(get_deposits_tool());
    registry.insert(get_withdrawals_tool());
    // v0.2-04 — orders + user-trades history.
    registry.insert(get_open_orders_by_currency_tool());
    registry.insert(get_open_orders_by_instrument_tool());
    registry.insert(get_user_trades_by_currency_tool());
    registry.insert(get_user_trades_by_instrument_tool());
}

// ----- get_account_summary ------------------------------------------

/// `get_account_summary` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetAccountSummaryInput {
    /// Currency to summarise (`BTC`, `ETH`, `USDC`, …).
    pub currency: String,
    /// Include the per-currency `summaries[]` (id, email, account type, …).
    /// Defaults to `false` upstream.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extended: Option<bool>,
}

fn get_account_summary_tool() -> ToolEntry {
    let schema = schema_for::<GetAccountSummaryInput>();
    let descriptor = Tool::new(
        "get_account_summary",
        "Account balance / equity / margin for a single currency.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_account_summary(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_account_summary(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: GetAccountSummaryInput = parse(input)?;
    let result = ctx
        .http
        .get_account_summary(&input.currency, input.extended)
        .await?;
    Ok(serde_json::to_value(&result)?)
}

// ----- get_positions ------------------------------------------------

/// `get_positions` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetPositionsInput {
    /// Optional currency filter (`BTC`, `ETH`, …). When omitted the
    /// upstream returns positions across every currency.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    /// Optional instrument-kind filter: `future`, `option`, `spot`,
    /// `future_combo`, `option_combo`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// Optional subaccount id to scope the query to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subaccount_id: Option<i32>,
}

fn get_positions_tool() -> ToolEntry {
    let schema = schema_for::<GetPositionsInput>();
    let descriptor = Tool::new(
        "get_positions",
        "Open positions, optionally filtered by currency / kind / subaccount.",
        schema,
    );
    let handler: ToolHandlerFn = Arc::new(|ctx, input| Box::pin(handle_get_positions(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_positions(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let input: GetPositionsInput = parse(input)?;
    let result = ctx
        .http
        .get_positions(
            input.currency.as_deref(),
            input.kind.as_deref(),
            input.subaccount_id,
        )
        .await?;
    Ok(serde_json::to_value(&result)?)
}

// ----- get_subaccounts ----------------------------------------------

/// `get_subaccounts` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetSubaccountsInput {
    /// When `true`, include each subaccount's portfolio in the
    /// response. Defaults to `false` upstream.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub with_portfolio: Option<bool>,
}

fn get_subaccounts_tool() -> ToolEntry {
    let schema = schema_for::<GetSubaccountsInput>();
    let descriptor = Tool::new(
        "get_subaccounts",
        "List subaccounts, optionally including portfolio per subaccount.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_subaccounts(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_subaccounts(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let input: GetSubaccountsInput = parse(input)?;
    let result = ctx.http.get_subaccounts(input.with_portfolio).await?;
    Ok(serde_json::to_value(&result)?)
}

// ----- get_transaction_log ------------------------------------------

/// `get_transaction_log` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetTransactionLogInput {
    /// Currency to scope the log to (`BTC`, `ETH`, …).
    pub currency: String,
    /// Window start, Unix epoch milliseconds.
    pub start_timestamp: u64,
    /// Window end, Unix epoch milliseconds.
    pub end_timestamp: u64,
    /// Optional substring search across the log entries.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    /// Maximum entries to return (upstream caps the page size).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub count: Option<u64>,
    /// Optional subaccount id to scope the log to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subaccount_id: Option<u64>,
    /// Continuation token from a previous page (returned in
    /// upstream `continuation` field).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub continuation: Option<u64>,
}

fn get_transaction_log_tool() -> ToolEntry {
    let schema = schema_for::<GetTransactionLogInput>();
    let descriptor = Tool::new(
        "get_transaction_log",
        "Account transaction log for a currency over a window, with optional pagination.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_transaction_log(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_transaction_log(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: GetTransactionLogInput = parse(input)?;
    let request = deribit_http::model::transaction::TransactionLogRequest {
        currency: input.currency,
        start_timestamp: input.start_timestamp,
        end_timestamp: input.end_timestamp,
        query: input.query,
        count: input.count,
        subaccount_id: input.subaccount_id,
        continuation: input.continuation,
    };
    let result = ctx.http.get_transaction_log(request).await?;
    Ok(serde_json::to_value(&result)?)
}

// ----- get_deposits / get_withdrawals -------------------------------

/// Pagination + currency input shared by `get_deposits` and
/// `get_withdrawals` (the upstream signatures are identical).
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct PaginatedCurrencyInput {
    /// Currency to scope the query to (`BTC`, `ETH`, …).
    pub currency: String,
    /// Page size; defaults to upstream's default (10) when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub count: Option<u32>,
    /// Page offset; defaults to 0 when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

fn get_deposits_tool() -> ToolEntry {
    let schema = schema_for::<PaginatedCurrencyInput>();
    let descriptor = Tool::new(
        "get_deposits",
        "Recent deposits for a currency, paginated.",
        schema,
    );
    let handler: ToolHandlerFn = Arc::new(|ctx, input| Box::pin(handle_get_deposits(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_deposits(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let input: PaginatedCurrencyInput = parse(input)?;
    let result = ctx
        .http
        .get_deposits(&input.currency, input.count, input.offset)
        .await?;
    Ok(serde_json::to_value(&result)?)
}

fn get_withdrawals_tool() -> ToolEntry {
    let schema = schema_for::<PaginatedCurrencyInput>();
    let descriptor = Tool::new(
        "get_withdrawals",
        "Recent withdrawals for a currency, paginated.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_withdrawals(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_withdrawals(ctx: &AdapterContext, input: Value) -> Result<Value, AdapterError> {
    let input: PaginatedCurrencyInput = parse(input)?;
    let result = ctx
        .http
        .get_withdrawals(&input.currency, input.count, input.offset)
        .await?;
    Ok(serde_json::to_value(&result)?)
}

// ----- get_open_orders_by_currency / by_instrument ------------------

/// `get_open_orders_by_currency` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetOpenOrdersByCurrencyInput {
    /// Currency (`BTC`, `ETH`, …).
    pub currency: String,
    /// Optional instrument-kind filter: `future`, `option`, `spot`,
    /// `future_combo`, `option_combo`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// Optional order-type filter (`limit`, `stop_limit`, `take_limit`,
    /// `market`, `stop_market`, `take_market`, `market_limit`,
    /// `trailing_stop`, `all`).
    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
    pub order_type: Option<String>,
}

fn get_open_orders_by_currency_tool() -> ToolEntry {
    let schema = schema_for::<GetOpenOrdersByCurrencyInput>();
    let descriptor = Tool::new(
        "get_open_orders_by_currency",
        "Open orders for a currency, optionally filtered by kind and type.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_open_orders_by_currency(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_open_orders_by_currency(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: GetOpenOrdersByCurrencyInput = parse(input)?;
    let result = ctx
        .http
        .get_open_orders_by_currency(
            &input.currency,
            input.kind.as_deref(),
            input.order_type.as_deref(),
        )
        .await?;
    Ok(serde_json::to_value(&result)?)
}

/// `get_open_orders_by_instrument` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetOpenOrdersByInstrumentInput {
    /// Instrument identifier (`BTC-PERPETUAL`, …).
    pub instrument_name: String,
    /// Optional order-type filter (same vocabulary as
    /// `get_open_orders_by_currency`'s `type` argument).
    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
    pub order_type: Option<String>,
}

fn get_open_orders_by_instrument_tool() -> ToolEntry {
    let schema = schema_for::<GetOpenOrdersByInstrumentInput>();
    let descriptor = Tool::new(
        "get_open_orders_by_instrument",
        "Open orders for a single instrument, optionally filtered by type.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_open_orders_by_instrument(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_open_orders_by_instrument(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: GetOpenOrdersByInstrumentInput = parse(input)?;
    let result = ctx
        .http
        .get_open_orders_by_instrument(&input.instrument_name, input.order_type.as_deref())
        .await?;
    Ok(serde_json::to_value(&result)?)
}

// ----- get_user_trades_by_currency ----------------------------------

/// `get_user_trades_by_currency` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetUserTradesByCurrencyInput {
    /// Currency (`BTC`, `ETH`, …). Forwarded to the upstream as a
    /// closed-set `Currency` enum.
    pub currency: String,
    /// Optional instrument-kind filter: `future`, `option`, `spot`,
    /// `future_combo`, `option_combo`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    /// First trade id to return (string per upstream spec).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_id: Option<String>,
    /// Last trade id to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_id: Option<String>,
    /// Page size (1..=1000; upstream default 10).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub count: Option<u32>,
    /// Earliest timestamp to filter on (epoch ms).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_timestamp: Option<u64>,
    /// Latest timestamp to filter on (epoch ms).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_timestamp: Option<u64>,
    /// Sort direction: `asc` or `desc`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sorting: Option<String>,
    /// When `true`, include archived trades.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub historical: Option<bool>,
    /// Optional subaccount id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subaccount_id: Option<u32>,
}

fn get_user_trades_by_currency_tool() -> ToolEntry {
    let schema = schema_for::<GetUserTradesByCurrencyInput>();
    let descriptor = Tool::new(
        "get_user_trades_by_currency",
        "User trades for a currency over an id / timestamp window with sort + historical opt-in.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_user_trades_by_currency(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_user_trades_by_currency(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: GetUserTradesByCurrencyInput = parse(input)?;

    if let Some(count) = input.count {
        validate_count_range(count)?;
    }

    let currency = parse_currency(&input.currency)?;
    let kind = input.kind.as_deref().map(parse_kind).transpose()?;
    let sorting = input.sorting.as_deref().map(parse_sorting).transpose()?;

    let request = deribit_http::model::request::trade::TradesRequest {
        currency,
        kind,
        start_id: input.start_id,
        end_id: input.end_id,
        count: input.count,
        start_timestamp: input.start_timestamp,
        end_timestamp: input.end_timestamp,
        sorting,
        historical: input.historical,
        subaccount_id: input.subaccount_id,
    };
    let result = ctx.http.get_user_trades_by_currency(request).await?;
    Ok(serde_json::to_value(&result)?)
}

/// Convert a user-supplied currency string into the upstream
/// `Currency` closed-set enum.
fn parse_currency(s: &str) -> Result<deribit_http::model::Currency, AdapterError> {
    serde_json::from_value(serde_json::Value::String(s.to_uppercase())).map_err(|err| {
        AdapterError::Validation {
            field: "currency".to_string(),
            message: err.to_string(),
        }
    })
}

/// Convert a user-supplied kind string into the upstream
/// `InstrumentKind` enum.
fn parse_kind(s: &str) -> Result<deribit_http::model::InstrumentKind, AdapterError> {
    serde_json::from_value(serde_json::Value::String(s.to_lowercase())).map_err(|err| {
        AdapterError::Validation {
            field: "kind".to_string(),
            message: err.to_string(),
        }
    })
}

/// Convert a user-supplied `sorting` string into the upstream
/// `SortDirection` enum.
fn parse_sorting(s: &str) -> Result<deribit_http::model::SortDirection, AdapterError> {
    serde_json::from_value(serde_json::Value::String(s.to_lowercase())).map_err(|err| {
        AdapterError::Validation {
            field: "sorting".to_string(),
            message: err.to_string(),
        }
    })
}

/// Reject `count` values outside the documented `1..=1000` range
/// before the request hits the upstream HTTP client. The upstream
/// would surface this as an opaque API error; rejecting here gives
/// the LLM a structured `AdapterError::Validation { field: "count" }`
/// instead.
fn validate_count_range(count: u32) -> Result<(), AdapterError> {
    if (1..=1000).contains(&count) {
        Ok(())
    } else {
        Err(AdapterError::Validation {
            field: "count".to_string(),
            message: format!("expected 1..=1000, got {count}"),
        })
    }
}

// ----- get_user_trades_by_instrument --------------------------------

/// `get_user_trades_by_instrument` input.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct GetUserTradesByInstrumentInput {
    /// Instrument identifier (`BTC-PERPETUAL`, …).
    pub instrument_name: String,
    /// First trade sequence number to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_seq: Option<u64>,
    /// Last trade sequence number to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_seq: Option<u64>,
    /// Page size (1..=1000; upstream default 10).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub count: Option<u32>,
    /// When `true`, include archived trades.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_old: Option<bool>,
    /// Sort direction: `asc` or `desc`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sorting: Option<String>,
}

fn get_user_trades_by_instrument_tool() -> ToolEntry {
    let schema = schema_for::<GetUserTradesByInstrumentInput>();
    let descriptor = Tool::new(
        "get_user_trades_by_instrument",
        "User trades for a single instrument over a sequence-number window.",
        schema,
    );
    let handler: ToolHandlerFn =
        Arc::new(|ctx, input| Box::pin(handle_get_user_trades_by_instrument(ctx, input)));
    ToolEntry {
        descriptor,
        class: ToolClass::Account,
        handler,
    }
}

async fn handle_get_user_trades_by_instrument(
    ctx: &AdapterContext,
    input: Value,
) -> Result<Value, AdapterError> {
    let input: GetUserTradesByInstrumentInput = parse(input)?;
    if let Some(count) = input.count {
        validate_count_range(count)?;
    }
    let result = ctx
        .http
        .get_user_trades_by_instrument(
            &input.instrument_name,
            input.start_seq,
            input.end_seq,
            input.count,
            input.include_old,
            input.sorting.as_deref(),
        )
        .await?;
    Ok(serde_json::to_value(&result)?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_account_tools_register_under_account_class() {
        for entry in [
            get_account_summary_tool(),
            get_positions_tool(),
            get_subaccounts_tool(),
            get_transaction_log_tool(),
            get_deposits_tool(),
            get_withdrawals_tool(),
            get_open_orders_by_currency_tool(),
            get_open_orders_by_instrument_tool(),
            get_user_trades_by_currency_tool(),
            get_user_trades_by_instrument_tool(),
        ] {
            assert_eq!(entry.class, ToolClass::Account);
        }
    }

    #[test]
    fn register_populates_full_account_set() {
        let mut registry = ToolRegistry::new();
        register(&mut registry);
        let listed = registry.list();
        let names: Vec<&str> = listed.iter().map(|t| t.name.as_ref()).collect();
        for expected in [
            "get_account_summary",
            "get_deposits",
            "get_open_orders_by_currency",
            "get_open_orders_by_instrument",
            "get_positions",
            "get_subaccounts",
            "get_transaction_log",
            "get_user_trades_by_currency",
            "get_user_trades_by_instrument",
            "get_withdrawals",
        ] {
            assert!(
                names.contains(&expected),
                "missing tool {expected}; got {names:?}"
            );
        }
        assert_eq!(registry.len(), 10);
    }

    #[test]
    fn open_orders_by_currency_input_renames_type_field() {
        // The MCP schema field is named `type` (matching upstream),
        // even though the Rust field uses `order_type` to avoid the
        // reserved word. Round-trip a payload with `type` to pin the
        // mapping.
        let v = serde_json::json!({"currency": "BTC", "type": "limit"});
        let parsed: GetOpenOrdersByCurrencyInput = serde_json::from_value(v).expect("parse");
        assert_eq!(parsed.order_type.as_deref(), Some("limit"));
    }

    #[test]
    fn user_trades_by_instrument_input_accepts_required_only() {
        let v = serde_json::json!({"instrument_name": "BTC-PERPETUAL"});
        let parsed: GetUserTradesByInstrumentInput = serde_json::from_value(v).expect("parse");
        assert!(parsed.start_seq.is_none());
        assert!(parsed.end_seq.is_none());
    }

    #[test]
    fn transaction_log_input_requires_window() {
        let err =
            parse::<GetTransactionLogInput>(serde_json::json!({"currency": "BTC"})).unwrap_err();
        assert!(matches!(err, AdapterError::Validation { .. }));
    }

    #[test]
    fn paginated_input_accepts_required_only() {
        let parsed: PaginatedCurrencyInput =
            serde_json::from_value(serde_json::json!({"currency": "BTC"})).expect("parse");
        assert!(parsed.count.is_none());
        assert!(parsed.offset.is_none());
    }

    #[test]
    fn account_summary_input_requires_currency() {
        let err = parse::<GetAccountSummaryInput>(serde_json::json!({})).unwrap_err();
        match err {
            AdapterError::Validation { field, .. } => assert_eq!(field, "arguments"),
            other => panic!("unexpected: {other:?}"),
        }
    }

    #[test]
    fn positions_input_accepts_no_filters() {
        let parsed: GetPositionsInput =
            serde_json::from_value(serde_json::json!({})).expect("parse");
        assert!(parsed.currency.is_none());
        assert!(parsed.kind.is_none());
        assert!(parsed.subaccount_id.is_none());
    }

    #[test]
    fn subaccounts_input_accepts_no_arguments() {
        let parsed: GetSubaccountsInput =
            serde_json::from_value(serde_json::json!({})).expect("parse");
        assert!(parsed.with_portfolio.is_none());
    }

    #[test]
    fn parse_currency_rejects_out_of_vocab() {
        let err = parse_currency("DOGE").unwrap_err();
        match err {
            AdapterError::Validation { field, .. } => assert_eq!(field, "currency"),
            other => panic!("unexpected: {other:?}"),
        }
    }

    #[test]
    fn parse_kind_rejects_out_of_vocab() {
        let err = parse_kind("perpetual").unwrap_err();
        match err {
            AdapterError::Validation { field, .. } => assert_eq!(field, "kind"),
            other => panic!("unexpected: {other:?}"),
        }
    }

    #[test]
    fn parse_sorting_rejects_out_of_vocab() {
        let err = parse_sorting("random").unwrap_err();
        match err {
            AdapterError::Validation { field, .. } => assert_eq!(field, "sorting"),
            other => panic!("unexpected: {other:?}"),
        }
    }

    #[test]
    fn parse_currency_accepts_lowercase() {
        let parsed = parse_currency("btc").expect("ok");
        assert!(matches!(parsed, deribit_http::model::Currency::Btc));
    }

    #[test]
    fn validate_count_rejects_zero_and_over_1000() {
        assert!(matches!(
            validate_count_range(0).unwrap_err(),
            AdapterError::Validation { ref field, .. } if field == "count"
        ));
        assert!(matches!(
            validate_count_range(1001).unwrap_err(),
            AdapterError::Validation { ref field, .. } if field == "count"
        ));
    }

    #[test]
    fn validate_count_accepts_boundary_values() {
        assert!(validate_count_range(1).is_ok());
        assert!(validate_count_range(1000).is_ok());
    }
}