Skip to main content

lean_ctx/server/
tool_trait.rs

1use rmcp::ErrorData;
2use rmcp::model::{ContentBlock, Tool};
3use serde_json::{Map, Value};
4
5/// Internal handler-to-dispatch signal for an executed operation that failed.
6/// Unlike invalid arguments, its body can contain file excerpts and must pass
7/// the full content pipeline before becoming an MCP `isError` result.
8pub(crate) const TOOL_EXECUTION_ERROR: rmcp::model::ErrorCode = rmcp::model::ErrorCode(-32071);
9
10pub(crate) fn tool_execution_error(message: String) -> ErrorData {
11    ErrorData::new(TOOL_EXECUTION_ERROR, message, None)
12}
13
14/// Path arguments shared by MCP dispatch and the embedded Engine boundary.
15pub const PATH_LIKE_KEYS: &[&str] = &[
16    "path",
17    "project_root",
18    "root",
19    "file",
20    "directory",
21    "dir",
22    "target",
23    "source",
24    "destination",
25    "old_path",
26    "new_path",
27    "file_path",
28    "from",
29    "to",
30    "base_path",
31    "config_path",
32    "output",
33];
34
35/// Stable states exposed by `ctx_shell(background_action="status")`.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum BackgroundJobState {
38    Running,
39    Completed,
40    Failed,
41    Cancelled,
42}
43
44impl BackgroundJobState {
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::Running => "running",
48            Self::Completed => "completed",
49            Self::Failed => "failed",
50            Self::Cancelled => "cancelled",
51        }
52    }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct BackgroundDisplay {
57    pub header: String,
58    pub footer: Option<String>,
59}
60
61/// Protocol metadata that must survive output compression and archiving.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct BackgroundShellOutcome {
64    pub state: BackgroundJobState,
65    pub exit_code: Option<i32>,
66    pub job_id: String,
67    pub archive_id: Option<String>,
68    pub archive_truncated: Option<bool>,
69    pub captured_chars: Option<usize>,
70    pub archived_chars: Option<usize>,
71    pub summary: String,
72    pub is_error: bool,
73    pub display: Option<BackgroundDisplay>,
74}
75
76/// A background job lookup failed without evidence of a lifecycle state.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct BackgroundLookupError {
79    pub job_id: String,
80    pub code: String,
81    pub reason: String,
82}
83
84/// Outcome of a shell execution, carried alongside the rendered text so the
85/// MCP dispatch layer can surface failures in protocol metadata instead of
86/// only as an `[exit:N]` text footer (GitHub #389: clients had no programmatic
87/// way to detect ctx_shell failures and resorted to fragile regex matching).
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum ShellOutcome {
90    /// The command ran; carries its real exit code (0 = success).
91    Exit(i32),
92    /// The command never ran (allowlist/validation rejection, or a
93    /// precondition failure such as an unreadable/oversized input file).
94    Blocked,
95    /// A managed background job status. Unlike a foreground `Exit(1)`, a
96    /// terminal failed job is never reclassified as grep-like result data.
97    Background(BackgroundShellOutcome),
98    /// The requested background job is unknown or its retained verdict expired.
99    BackgroundLookupError(BackgroundLookupError),
100}
101
102impl ShellOutcome {
103    /// Whether this outcome must be reported as a tool error (`isError: true`).
104    pub fn is_error(&self) -> bool {
105        match self {
106            ShellOutcome::Exit(code) => *code != 0,
107            ShellOutcome::Blocked | ShellOutcome::BackgroundLookupError(_) => true,
108            ShellOutcome::Background(outcome) => outcome.is_error,
109        }
110    }
111
112    /// Structured payload for `CallToolResult.structuredContent`, so guards
113    /// can read state/exit/archive data instead of parsing output text.
114    /// Ordinary foreground success (exit 0) stays token-neutral; background
115    /// status always remains structured because clients may filter its text.
116    pub fn structured(&self) -> Option<serde_json::Value> {
117        match self {
118            ShellOutcome::Exit(0) => None,
119            ShellOutcome::Exit(code) => Some(serde_json::json!({ "exitCode": code })),
120            ShellOutcome::Blocked => Some(serde_json::json!({ "blocked": true })),
121            ShellOutcome::Background(outcome) => {
122                let mut fields = serde_json::Map::new();
123                fields.insert(
124                    "state".to_string(),
125                    serde_json::json!(outcome.state.as_str()),
126                );
127                fields.insert("jobId".to_string(), serde_json::json!(outcome.job_id));
128                fields.insert("summary".to_string(), serde_json::json!(outcome.summary));
129                if let Some(exit_code) = outcome.exit_code {
130                    fields.insert("exitCode".to_string(), serde_json::json!(exit_code));
131                }
132                if let Some(archive_id) = &outcome.archive_id {
133                    fields.insert("archiveId".to_string(), serde_json::json!(archive_id));
134                }
135                if let Some(archive_truncated) = outcome.archive_truncated {
136                    fields.insert(
137                        "archiveTruncated".to_string(),
138                        serde_json::json!(archive_truncated),
139                    );
140                }
141                if let Some(captured_chars) = outcome.captured_chars {
142                    fields.insert(
143                        "capturedChars".to_string(),
144                        serde_json::json!(captured_chars),
145                    );
146                }
147                if let Some(archived_chars) = outcome.archived_chars {
148                    fields.insert(
149                        "archivedChars".to_string(),
150                        serde_json::json!(archived_chars),
151                    );
152                }
153                Some(serde_json::Value::Object(fields))
154            }
155            ShellOutcome::BackgroundLookupError(error) => Some(serde_json::json!({
156                "jobId": error.job_id,
157                "errorCode": error.code,
158                "reason": error.reason,
159            })),
160        }
161    }
162
163    /// Whether this is a status body that the common pipeline must secure,
164    /// archive and render before delivery.
165    pub fn is_background_status(&self) -> bool {
166        matches!(
167            self,
168            ShellOutcome::Background(BackgroundShellOutcome {
169                display: Some(_),
170                ..
171            })
172        )
173    }
174
175    pub fn is_terminal_background_status(&self) -> bool {
176        matches!(
177            self,
178            ShellOutcome::Background(BackgroundShellOutcome {
179                state: BackgroundJobState::Completed
180                    | BackgroundJobState::Failed
181                    | BackgroundJobState::Cancelled,
182                display: Some(_),
183                ..
184            })
185        )
186    }
187}
188
189/// Result returned by an McpTool handler.
190pub struct ToolOutput {
191    pub text: String,
192    pub original_tokens: usize,
193    pub saved_tokens: usize,
194    pub mode: Option<String>,
195    /// Path associated with the tool call (for record_call_with_path).
196    pub path: Option<String>,
197    /// True when the tool mutated state that clients should know about
198    /// (e.g. dynamic tool categories changed).
199    pub changed: bool,
200    /// Set by shell-executing tools so dispatch can populate `isError` +
201    /// `structuredContent` on the MCP result (GitHub #389). `None` for tools
202    /// that don't run shell commands.
203    pub shell_outcome: Option<ShellOutcome>,
204    /// Override content blocks for non-text responses (e.g. images).
205    /// When set, dispatch uses these instead of wrapping `text` in TextContent.
206    pub content_blocks: Option<Vec<ContentBlock>>,
207}
208
209impl ToolOutput {
210    pub fn simple(text: String) -> Self {
211        Self {
212            text,
213            original_tokens: 0,
214            saved_tokens: 0,
215            mode: None,
216            path: None,
217            changed: false,
218            shell_outcome: None,
219            content_blocks: None,
220        }
221    }
222
223    /// Compact one-line summary for headers_only response verbosity.
224    pub fn to_header_line(&self, tool_name: &str) -> String {
225        let path_str = self.path.as_deref().unwrap_or("—");
226        let mode_str = self.mode.as_deref().unwrap_or("—");
227        let sent = self.original_tokens.saturating_sub(self.saved_tokens);
228        let pct = if self.original_tokens > 0 {
229            (self.saved_tokens as f64 / self.original_tokens as f64 * 100.0) as u32
230        } else {
231            0
232        };
233        format!("[{tool_name}: {path_str}, mode={mode_str}, {sent} tok sent, -{pct}%]")
234    }
235
236    pub fn with_savings(text: String, original: usize, saved: usize) -> Self {
237        Self {
238            text,
239            original_tokens: original,
240            saved_tokens: saved,
241            mode: None,
242            path: None,
243            changed: false,
244            shell_outcome: None,
245            content_blocks: None,
246        }
247    }
248
249    /// Construct a ToolOutput for image/binary content blocks.
250    /// Bypasses all text processing in the dispatch pipeline.
251    pub fn image(blocks: Vec<ContentBlock>, path: String) -> Self {
252        Self {
253            text: String::new(),
254            original_tokens: 0,
255            saved_tokens: 0,
256            mode: Some("image".to_string()),
257            path: Some(path),
258            changed: false,
259            shell_outcome: None,
260            content_blocks: Some(blocks),
261        }
262    }
263}
264
265/// Trait for a self-contained MCP tool. Each tool provides its own schema
266/// definition and handler, eliminating the possibility of schema/handler drift.
267///
268/// This trait is the plugin interface for LcpTools: any implementation can be
269/// registered at runtime via `ToolRegistry::register()`. Future plugin system
270/// will load implementations from shared libraries or subprocess bridges.
271///
272/// Handlers are synchronous because all existing tool handlers are sync.
273/// The async boundary (cache locks, session reads) is handled by the dispatch
274/// layer before calling `handle`.
275pub trait McpTool: Send + Sync {
276    /// Tool name as registered in the MCP protocol (e.g. "ctx_tree").
277    fn name(&self) -> &'static str;
278
279    /// MCP tool definition including JSON schema. This replaces the
280    /// corresponding entry in `granular_tool_defs()`.
281    fn tool_def(&self) -> Tool;
282
283    /// Execute the tool. Args are the raw JSON-RPC arguments.
284    /// `ctx` provides access to resolved paths and project state.
285    fn handle(&self, args: &Map<String, Value>, ctx: &ToolContext)
286    -> Result<ToolOutput, ErrorData>;
287
288    /// Whether *this* invocation yields a machine-readable payload (e.g. JSON)
289    /// that must reach the client byte-exact and parseable. When `true`, the
290    /// dispatch pipeline suppresses every human-oriented decoration
291    /// (auto-context briefing, verify footer, hints, checkpoints, deprecation
292    /// notices) and terse compression for this call, returning the pure body.
293    /// Keyed on `args` because most tools emit machine-readable output only for
294    /// an opt-in format flag (e.g. `format=json`); defaults to `false` (#990).
295    fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
296        false
297    }
298
299    /// Attestation that *this* invocation derives its output from the caller's
300    /// arguments and lean-ctx's own state only — it reads no project source,
301    /// provider or stored copy of one. Replay admission relies on it: an
302    /// output with no captured source set is replayed under protection only
303    /// when its tool attests this. The default is `false`: "no source was
304    /// observed" is not proof, an uninstrumented reader publishes none either.
305    /// Override only for a tool whose handler was read for exactly this.
306    fn attests_source_free(&self, _args: Option<&Map<String, Value>>) -> bool {
307        false
308    }
309
310    /// Declaration that *this* invocation reads every project source it
311    /// derives output from through the admitted readers
312    /// (`tools::ctx_read::read_file_*`), on the handler's own thread or on
313    /// workers started with `TaskSpine::spawn_thread` — so that each of them is
314    /// published into the call's source capture. Only then is a captured
315    /// source set the WHOLE set, and only then may it authorize reuse of the
316    /// result (idempotent replay, response cache, source-bound recovery copy).
317    ///
318    /// The default is `false`: a source set captured from a tool that does not
319    /// declare this may be partial (a raw `fs::read`, a thread without the
320    /// capture, a cached body served without a read) and counts as unknown.
321    /// Override only after reading every content path of the handler.
322    fn publishes_every_source(&self, _args: Option<&Map<String, Value>>) -> bool {
323        false
324    }
325}
326
327tokio::task_local! {
328    /// #1781: the cancellation token of the request currently being served,
329    /// scoped by `call_tool` around the whole guarded dispatch.
330    ///
331    /// A task-local rather than a field on the shared server: rmcp spawns one
332    /// task per request and hands each its own `child_token`, so concurrent
333    /// calls would otherwise overwrite one another's token — and cancelling the
334    /// wrong command is worse than not cancelling at all.
335    pub static REQUEST_CT: tokio_util::sync::CancellationToken;
336}
337
338/// Context passed to tool handlers. Contains pre-resolved values that
339/// many tools need, avoiding repeated async lock acquisition inside
340/// handlers. Extended with shared server state for tools that need
341/// cache/session access.
342///
343/// `Clone` exists for per-op delegation (#1088): a batch op with its own
344/// `path` clones the ctx and swaps in that op's resolved path.
345#[derive(Clone)]
346pub struct ToolContext {
347    pub project_root: String,
348    /// Session-scoped trusted roots (MCP `roots/list`, config `extra_roots`),
349    /// snapshotted from the session so sync handlers can honor them without an
350    /// async lock. Empty = single-root jail behaviour (#403).
351    pub extra_roots: Vec<String>,
352    pub minimal: bool,
353    /// Pre-resolved paths keyed by argument name (e.g. "path" -> "/abs/dir").
354    pub resolved_paths: std::collections::HashMap<String, String>,
355    /// CRP mode for compression-aware tools.
356    pub crp_mode: crate::tools::CrpMode,
357    /// Shared cache handle for tools that need read/write access.
358    pub cache: Option<crate::tools::SharedCache>,
359    /// Shared session handle for tools that need session access.
360    pub session: Option<std::sync::Arc<tokio::sync::RwLock<crate::core::session::SessionState>>>,
361    /// Tool call records for session-aware tools (e.g. ctx_session status).
362    pub tool_calls:
363        Option<std::sync::Arc<tokio::sync::RwLock<Vec<crate::core::protocol::ToolCallRecord>>>>,
364    /// Current agent identity for multi-agent tools.
365    pub agent_id: Option<std::sync::Arc<tokio::sync::RwLock<Option<String>>>>,
366    /// Active workflow run state.
367    pub workflow:
368        Option<std::sync::Arc<tokio::sync::RwLock<Option<crate::core::workflow::WorkflowRun>>>>,
369    /// Context ledger for handoff operations.
370    pub ledger:
371        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::context_ledger::ContextLedger>>>,
372    /// Client name (cursor, claude, etc.).
373    pub client_name: Option<std::sync::Arc<tokio::sync::RwLock<String>>>,
374    /// Optional MCP client role supplied by the session/request context.
375    /// Absent preserves the backward-compatible permissive default.
376    pub client_role: Option<String>,
377    /// Optional shell permission supplied by the session/request context.
378    /// `None` preserves the backward-compatible permissive default.
379    pub shell_access: Option<bool>,
380    /// Pipeline stats for metrics/proof tools.
381    pub pipeline_stats:
382        Option<std::sync::Arc<tokio::sync::RwLock<crate::core::pipeline::PipelineStats>>>,
383    /// Global call counter for context tools.
384    pub call_count: Option<std::sync::Arc<std::sync::atomic::AtomicUsize>>,
385    /// Autonomy state for search repeat detection.
386    pub autonomy: Option<std::sync::Arc<crate::core::autonomy::AutonomyState>>,
387    /// Errors from path resolution (PathJail rejection, secret path, etc.).
388    /// Keyed by argument name (e.g. "path" -> "path escapes project root: ...").
389    pub path_errors: std::collections::HashMap<String, String>,
390    /// Shared in-memory BM25 index cache for semantic search.
391    pub bm25_cache: Option<crate::core::bm25_cache::SharedBm25Cache>,
392    /// MCP progress notification sender for long-running operations.
393    pub progress_sender: Option<crate::server::progress::SharedProgressSender>,
394    /// Cancellation token for this request, when the transport supplies one
395    /// (#1781).
396    ///
397    /// A synchronous tool that waits on a child process cannot observe an
398    /// aborted call without it: the host stops waiting, but the wait loop keeps
399    /// running and holds its thread until its own cap expires. Tools that block
400    /// should consult this and return promptly when it fires.
401    pub cancel: Option<tokio_util::sync::CancellationToken>,
402}
403
404impl Default for ToolContext {
405    /// Minimal context: `project_root` empty, all shared-state handles `None`.
406    /// Single source for the one-shot CLI ctx (`cli::call_cmd::oneshot_ctx`) and
407    /// the `empty_ctx` test helper — adding a field no longer breaks either.
408    fn default() -> Self {
409        Self {
410            project_root: String::new(),
411            extra_roots: Vec::new(),
412            minimal: false,
413            resolved_paths: std::collections::HashMap::new(),
414            crp_mode: crate::tools::CrpMode::Off,
415            cache: None,
416            session: None,
417            tool_calls: None,
418            agent_id: None,
419            workflow: None,
420            ledger: None,
421            client_name: None,
422            client_role: None,
423            shell_access: None,
424            pipeline_stats: None,
425            call_count: None,
426            autonomy: None,
427            path_errors: std::collections::HashMap::new(),
428            bm25_cache: None,
429            progress_sender: None,
430            cancel: None,
431        }
432    }
433}
434
435impl ToolContext {
436    pub fn resolved_path(&self, arg: &str) -> Option<&str> {
437        self.resolved_paths.get(arg).map(String::as_str)
438    }
439
440    /// Returns the path resolution error for a given key, if any.
441    pub fn path_error(&self, key: &str) -> Option<&str> {
442        self.path_errors.get(key).map(String::as_str)
443    }
444
445    /// Sync path resolution using `project_root` + session `extra_roots`. Thin
446    /// wrapper over [`crate::core::path_resolve::resolve_tool_path_with_roots`]
447    /// for sync tool handlers.
448    pub fn resolve_path_sync(&self, path: &str) -> Result<String, String> {
449        crate::core::path_resolve::resolve_tool_path_with_roots(
450            Some(&self.project_root),
451            None,
452            path,
453            &self.extra_roots,
454        )
455    }
456
457    /// Default-deny write gate for the read-only tier (#475). Write-capable tool
458    /// handlers must call this with an already-resolved absolute path before
459    /// touching the filesystem; it errors if the path is inside a configured
460    /// `read_only_roots` subtree. A no-op (always `Ok`) when no read-only roots
461    /// are configured, so non-users pay nothing. Thin wrapper over the single
462    /// choke point [`crate::core::pathjail::enforce_writable`] — the low-level
463    /// atomic writers call the same function, so this is the ergonomic,
464    /// early-error layer, not the only line of defence.
465    pub fn ensure_writable(&self, resolved_path: &str) -> Result<(), String> {
466        crate::core::pathjail::enforce_writable(std::path::Path::new(resolved_path))
467    }
468}
469
470// ── Arg extraction helpers (mirror server/helpers.rs for standalone use) ──
471
472/// Extract a resolved path from context with differentiated error messages.
473/// Returns descriptive errors for: missing param, PathJail rejection, wrong type.
474pub fn require_resolved_path(
475    ctx: &ToolContext,
476    args: &Map<String, Value>,
477    key: &str,
478) -> Result<String, ErrorData> {
479    if let Some(path) = ctx.resolved_path(key) {
480        return Ok(path.to_string());
481    }
482    if let Some(err) = ctx.path_error(key) {
483        return Err(ErrorData::invalid_params(format!("{key}: {err}"), None));
484    }
485    if let Some(val) = args.get(key)
486        && !val.is_string()
487    {
488        let type_name = match val {
489            Value::Number(_) => "number",
490            Value::Bool(_) => "boolean",
491            Value::Array(_) => "array",
492            Value::Object(_) => "object",
493            Value::Null => "null",
494            Value::String(_) => unreachable!(),
495        };
496        return Err(ErrorData::invalid_params(
497            format!("{key} must be a string, got {type_name}"),
498            None,
499        ));
500    }
501    Err(ErrorData::invalid_params(
502        format!("{key} is required"),
503        None,
504    ))
505}
506
507pub fn get_str(args: &Map<String, Value>, key: &str) -> Option<String> {
508    args.get(key).and_then(|v| v.as_str()).map(String::from)
509}
510
511pub fn get_int(args: &Map<String, Value>, key: &str) -> Option<i64> {
512    args.get(key)
513        .and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok()))
514}
515
516/// Read a non-negative integer argument as `usize`.
517///
518/// Returns `None` for missing or negative values. This avoids the
519/// `negative_i64 as usize` wrap to `usize::MAX`, which previously let an agent
520/// trigger unbounded allocations (e.g. `top_k`, `limit`, `max_results`) → OOM.
521/// Callers should still apply a sensible upper cap on the result.
522pub fn get_usize(args: &Map<String, Value>, key: &str) -> Option<usize> {
523    get_int(args, key).and_then(|n| usize::try_from(n).ok())
524}
525
526pub fn get_bool(args: &Map<String, Value>, key: &str) -> Option<bool> {
527    args.get(key).and_then(serde_json::Value::as_bool)
528}
529
530pub fn get_f64(args: &Map<String, Value>, key: &str) -> Option<f64> {
531    args.get(key).and_then(serde_json::Value::as_f64)
532}
533
534pub fn get_str_array(args: &Map<String, Value>, key: &str) -> Option<Vec<String>> {
535    args.get(key).and_then(|v| v.as_array()).map(|arr| {
536        arr.iter()
537            .filter_map(|v| v.as_str().map(String::from))
538            .collect()
539    })
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545    use serde_json::json;
546
547    fn empty_ctx() -> ToolContext {
548        ToolContext::default()
549    }
550
551    #[test]
552    fn require_resolved_path_returns_resolved() {
553        let mut ctx = empty_ctx();
554        ctx.resolved_paths
555            .insert("path".to_string(), "/abs/file.rs".to_string());
556        let args: Map<String, Value> = Map::new();
557        let result = require_resolved_path(&ctx, &args, "path");
558        assert_eq!(result.unwrap(), "/abs/file.rs");
559    }
560
561    #[test]
562    fn require_resolved_path_surfaces_jail_error() {
563        let mut ctx = empty_ctx();
564        ctx.path_errors.insert(
565            "path".to_string(),
566            "path escapes project root /project".to_string(),
567        );
568        let args: Map<String, Value> = Map::new();
569        let result = require_resolved_path(&ctx, &args, "path");
570        assert!(result.is_err());
571        let err = result.unwrap_err();
572        let msg = format!("{err:?}");
573        assert!(msg.contains("escapes project root"), "got: {msg}");
574    }
575
576    #[test]
577    fn require_resolved_path_detects_non_string() {
578        let ctx = empty_ctx();
579        let mut args: Map<String, Value> = Map::new();
580        args.insert("path".to_string(), json!(42));
581        let result = require_resolved_path(&ctx, &args, "path");
582        assert!(result.is_err());
583        let err = result.unwrap_err();
584        let msg = format!("{err:?}");
585        assert!(msg.contains("must be a string, got number"), "got: {msg}");
586    }
587
588    #[test]
589    fn require_resolved_path_missing_param() {
590        let ctx = empty_ctx();
591        let args: Map<String, Value> = Map::new();
592        let result = require_resolved_path(&ctx, &args, "path");
593        assert!(result.is_err());
594        let err = result.unwrap_err();
595        let msg = format!("{err:?}");
596        assert!(msg.contains("path is required"), "got: {msg}");
597    }
598
599    #[test]
600    fn get_int_coerces_string_to_number() {
601        let mut args = Map::new();
602        args.insert("n".into(), json!("42"));
603        assert_eq!(super::get_int(&args, "n"), Some(42));
604    }
605
606    #[test]
607    fn get_int_native_number_still_works() {
608        let mut args = Map::new();
609        args.insert("n".into(), json!(7));
610        assert_eq!(super::get_int(&args, "n"), Some(7));
611    }
612
613    #[test]
614    fn get_int_invalid_string_returns_none() {
615        let mut args = Map::new();
616        args.insert("n".into(), json!("not_a_number"));
617        assert_eq!(super::get_int(&args, "n"), None);
618    }
619
620    #[test]
621    fn get_usize_coerces_string() {
622        let mut args = Map::new();
623        args.insert("n".into(), json!("100"));
624        assert_eq!(super::get_usize(&args, "n"), Some(100));
625    }
626
627    #[test]
628    fn get_usize_negative_string_returns_none() {
629        let mut args = Map::new();
630        args.insert("n".into(), json!("-5"));
631        assert_eq!(super::get_usize(&args, "n"), None);
632    }
633}