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
//! Configuration surface — CLI + env + `.env` loader.
//!
//! Priority order (first wins):
//! 1. CLI flags
//! 2. Process environment
//! 3. `.env` file via `dotenvy`
//! 4. Built-in defaults

use clap::Parser;
use std::net::SocketAddr;
use std::path::PathBuf;

/// Resolved configuration for `deribit-mcp`.
#[derive(Debug, Clone)]
pub struct Config {
    /// Deribit API endpoint (testnet by default).
    pub endpoint: String,
    /// Client ID for OAuth flow.
    pub client_id: Option<String>,
    /// Client secret for OAuth flow (env/`.env` only).
    pub client_secret: Option<String>,
    /// Enable trading tools (off by default).
    pub allow_trading: bool,
    /// Max order notional in USD (unlimited by default).
    pub max_order_usd: Option<u64>,
    /// MCP transport: `stdio` or `http` (stdio default).
    pub transport: Transport,
    /// HTTP listen address (only used if transport is HTTP).
    pub http_listen: SocketAddr,
    /// HTTP bearer token for auth (optional, env/`.env` only).
    pub http_bearer_token: Option<String>,
    /// Log format: `text` or `json`.
    pub log_format: LogFormat,
    /// Upstream transport selection for `Trading` tool dispatch
    /// (`http` default, `fix` opt-in via v0.6).
    pub order_transport: OrderTransport,
}

/// MCP transport selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transport {
    /// Standard input/output (default).
    Stdio,
    /// HTTP/SSE.
    Http,
}

/// Log output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogFormat {
    /// Human-readable text (default for stdio).
    Text,
    /// JSON structured logs (default for http).
    Json,
}

/// Upstream transport for `Trading` tool dispatch.
///
/// `Http` is the default and matches the v0.1..v0.5 behaviour:
/// every `place_order` / `edit_order` / `cancel_order` /
/// `cancel_all_*` call hits the Deribit REST API via the
/// `deribit-http` client. `Fix` opts the trading family into the
/// lazy FIX-session path landed in v0.6-02 / v0.6-03.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrderTransport {
    /// REST over HTTP (default; v0.1..v0.5 behaviour).
    Http,
    /// FIX 4.4 over TCP via `deribit-fix`. Requires `--allow-trading`.
    Fix,
}

/// Map a `DERIBIT_NETWORK=testnet|mainnet` value to the full
/// endpoint URL. Returns `None` for unrecognised values so the
/// caller falls through to the next resolution layer rather than
/// silently picking the default.
fn network_to_endpoint(value: &str) -> Option<String> {
    match value.trim().to_ascii_lowercase().as_str() {
        "testnet" | "test" => Some("https://test.deribit.com".to_string()),
        "mainnet" | "main" | "production" | "prod" => Some("https://www.deribit.com".to_string()),
        _ => None,
    }
}

impl OrderTransport {
    /// Parse the user-facing string form (`http` / `fix`). Used by
    /// both the CLI parser and the env-var parser so the two stay
    /// in lockstep.
    fn parse(s: &str) -> Option<Self> {
        match s {
            "http" => Some(Self::Http),
            "fix" => Some(Self::Fix),
            _ => None,
        }
    }
}

impl Config {
    /// Load configuration from CLI args, env, and `.env` file.
    ///
    /// # Errors
    ///
    /// Returns error if parsing fails (invalid addresses, numbers, etc).
    pub fn load() -> anyhow::Result<Self> {
        let args = Args::parse();

        // Load `.env` file first (doesn't override existing env vars).
        if let Some(ref env_file) = args.env_file {
            dotenvy::from_path(env_file).ok(); // Ignore if file doesn't exist.
        } else if std::path::Path::new(".env").exists() {
            dotenvy::dotenv().ok();
        }

        // Resolve each setting in priority order: CLI, env, default.
        //
        // Endpoint resolution layers, top wins:
        //   1. `--testnet` / `--mainnet` CLI flags.
        //   2. `DERIBIT_NETWORK=testnet|mainnet` — readable
        //      symbolic toggle, useful for compose / k8s configs.
        //   3. `DERIBIT_ENDPOINT=<full URL>` — escape hatch for
        //      proxies and forks.
        //   4. Default: testnet (ADR-0009).
        let endpoint = args
            .endpoint()
            .or_else(|| {
                std::env::var("DERIBIT_NETWORK")
                    .ok()
                    .and_then(|v| network_to_endpoint(&v))
            })
            .or_else(|| std::env::var("DERIBIT_ENDPOINT").ok())
            .unwrap_or_else(|| "https://test.deribit.com".to_string());

        let client_id = args
            .client_id
            .clone()
            .or_else(|| std::env::var("DERIBIT_CLIENT_ID").ok());

        let client_secret = std::env::var("DERIBIT_CLIENT_SECRET").ok();

        let allow_trading = args.allow_trading
            || std::env::var("DERIBIT_ALLOW_TRADING")
                .map(|v| v == "1")
                .unwrap_or(false);

        let max_order_usd = args.max_order_usd.or_else(|| {
            std::env::var("DERIBIT_MAX_ORDER_USD")
                .ok()
                .and_then(|v| v.parse().ok())
        });

        let transport = args
            .transport()
            .or_else(|| {
                std::env::var("DERIBIT_MCP_TRANSPORT")
                    .ok()
                    .and_then(|v| match v.as_str() {
                        "stdio" => Some(Transport::Stdio),
                        "http" => Some(Transport::Http),
                        _ => None,
                    })
            })
            .unwrap_or(Transport::Stdio);

        let http_listen = args
            .listen
            .or_else(|| {
                std::env::var("DERIBIT_HTTP_LISTEN")
                    .ok()
                    .and_then(|v| v.parse().ok())
            })
            .unwrap_or_else(|| {
                "127.0.0.1:8723"
                    .parse()
                    .expect("invalid default listen addr")
            });

        // Treat an empty string as unset. `.env` files from
        // docker-compose stacks tend to ship `KEY=` lines for
        // optional settings; without this filter the empty string
        // would activate the bearer-token middleware and 401 every
        // request.
        let http_bearer_token = std::env::var("DERIBIT_HTTP_BEARER_TOKEN")
            .ok()
            .filter(|v| !v.is_empty());

        let order_transport = args
            .order_transport()
            .or_else(|| {
                std::env::var("DERIBIT_ORDER_TRANSPORT")
                    .ok()
                    .and_then(|v| OrderTransport::parse(&v))
            })
            .unwrap_or(OrderTransport::Http);

        // Exhaustive match — the compiler refuses to compile this
        // block once a new `OrderTransport` variant is added, forcing
        // a reviewer to decide whether the new transport needs the
        // same gating.
        match order_transport {
            OrderTransport::Fix if !allow_trading => {
                anyhow::bail!(
                    "`--order-transport=fix` (or DERIBIT_ORDER_TRANSPORT=fix) requires \
                     `--allow-trading` (or DERIBIT_ALLOW_TRADING=1) — without trading \
                     the FIX session would never be reached"
                );
            }
            OrderTransport::Fix | OrderTransport::Http => {}
        }

        #[allow(clippy::unnecessary_lazy_evaluations)]
        let log_format = args
            .log_format()
            .or_else(|| {
                std::env::var("DERIBIT_LOG_FORMAT")
                    .ok()
                    .and_then(|v| match v.as_str() {
                        "text" => Some(LogFormat::Text),
                        "json" => Some(LogFormat::Json),
                        _ => None,
                    })
            })
            .unwrap_or_else(|| match transport {
                Transport::Stdio => LogFormat::Text,
                Transport::Http => LogFormat::Json,
            });

        Ok(Self {
            endpoint,
            client_id,
            client_secret,
            allow_trading,
            max_order_usd,
            transport,
            http_listen,
            http_bearer_token,
            log_format,
            order_transport,
        })
    }
}

/// CLI arguments parsed via `clap`.
#[derive(Debug, Parser)]
#[command(name = "deribit-mcp")]
#[command(about = "Model Context Protocol server for Deribit")]
#[command(version)]
struct Args {
    /// Deribit endpoint: use --testnet (default) or --mainnet.
    #[arg(long, help = "Use testnet endpoint (default)")]
    testnet: bool,

    /// Use mainnet endpoint instead of testnet.
    #[arg(long, help = "Use mainnet endpoint")]
    mainnet: bool,

    /// Deribit client ID (or DERIBIT_CLIENT_ID env var).
    #[arg(long, help = "Client ID for OAuth")]
    client_id: Option<String>,

    /// Enable trading tools (off by default).
    #[arg(long, help = "Enable trading tools")]
    allow_trading: bool,

    /// Max order notional in USD (unlimited by default).
    #[arg(long, help = "Max order notional in USD")]
    max_order_usd: Option<u64>,

    /// MCP transport: stdio (default) or http.
    #[arg(long, help = "Transport: stdio or http")]
    transport: Option<String>,

    /// HTTP listen address (only for http transport).
    #[arg(long, help = "HTTP listen address")]
    listen: Option<SocketAddr>,

    /// Log format: text or json.
    #[arg(long, help = "Log format: text or json")]
    log_format: Option<String>,

    /// Upstream transport for trading tools: http (default) or fix.
    #[arg(long, help = "Order transport: http or fix")]
    order_transport: Option<String>,

    /// Path to `.env` file (default: `./.env` if exists).
    #[arg(long, help = "Path to .env file")]
    env_file: Option<PathBuf>,
}

impl Args {
    /// Parse CLI arguments.
    fn parse() -> Self {
        <Self as Parser>::parse()
    }

    /// Resolve endpoint from testnet/mainnet flags.
    fn endpoint(&self) -> Option<String> {
        if self.mainnet {
            Some("https://www.deribit.com".to_string())
        } else if self.testnet {
            Some("https://test.deribit.com".to_string())
        } else {
            None
        }
    }

    /// Parse transport flag.
    fn transport(&self) -> Option<Transport> {
        self.transport.as_ref().and_then(|t| match t.as_str() {
            "stdio" => Some(Transport::Stdio),
            "http" => Some(Transport::Http),
            _ => None,
        })
    }

    /// Parse log format flag.
    fn log_format(&self) -> Option<LogFormat> {
        self.log_format.as_ref().and_then(|f| match f.as_str() {
            "text" => Some(LogFormat::Text),
            "json" => Some(LogFormat::Json),
            _ => None,
        })
    }

    /// Parse order-transport flag.
    fn order_transport(&self) -> Option<OrderTransport> {
        self.order_transport
            .as_ref()
            .and_then(|t| OrderTransport::parse(t))
    }
}

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

    #[test]
    fn log_format_matches_transport() {
        // Text for stdio, JSON for http (default when not specified).
        let stdio_default = match Transport::Stdio {
            Transport::Stdio => LogFormat::Text,
            Transport::Http => LogFormat::Json,
        };
        let http_default = match Transport::Http {
            Transport::Stdio => LogFormat::Text,
            Transport::Http => LogFormat::Json,
        };
        assert_eq!(stdio_default, LogFormat::Text);
        assert_eq!(http_default, LogFormat::Json);
    }

    /// Reproduce the `OrderTransport::Fix` requires-trading guard
    /// from `Config::load` directly: the guard runs against locally
    /// resolved values so it can be exercised without
    /// `Config::load`'s CLI-arg path. Mirrors the production
    /// `match` so adding a new `OrderTransport` variant fails to
    /// compile in both places.
    fn fix_requires_trading_guard(
        order_transport: OrderTransport,
        allow_trading: bool,
    ) -> Result<(), &'static str> {
        match order_transport {
            OrderTransport::Fix if !allow_trading => Err(
                "`--order-transport=fix` (or DERIBIT_ORDER_TRANSPORT=fix) requires `--allow-trading`",
            ),
            OrderTransport::Fix | OrderTransport::Http => Ok(()),
        }
    }

    #[test]
    fn fix_without_allow_trading_is_rejected() {
        assert!(fix_requires_trading_guard(OrderTransport::Fix, false).is_err());
    }

    #[test]
    fn fix_with_allow_trading_is_accepted() {
        fix_requires_trading_guard(OrderTransport::Fix, true).unwrap();
    }

    #[test]
    fn http_default_does_not_require_trading() {
        fix_requires_trading_guard(OrderTransport::Http, false).unwrap();
    }

    #[test]
    fn network_env_var_resolves_to_endpoint() {
        assert_eq!(
            network_to_endpoint("testnet").as_deref(),
            Some("https://test.deribit.com")
        );
        assert_eq!(
            network_to_endpoint("MAINNET").as_deref(),
            Some("https://www.deribit.com")
        );
        assert_eq!(
            network_to_endpoint(" Test ").as_deref(),
            Some("https://test.deribit.com")
        );
        assert_eq!(
            network_to_endpoint("production").as_deref(),
            Some("https://www.deribit.com")
        );
        assert_eq!(network_to_endpoint("staging"), None);
        assert_eq!(network_to_endpoint(""), None);
    }

    #[test]
    fn order_transport_parse_round_trip() {
        assert_eq!(OrderTransport::parse("http"), Some(OrderTransport::Http));
        assert_eq!(OrderTransport::parse("fix"), Some(OrderTransport::Fix));
        assert_eq!(OrderTransport::parse("HTTP"), None);
        assert_eq!(OrderTransport::parse(""), None);
        assert_eq!(OrderTransport::parse("rest"), None);
    }
}