Convert R objects to JSON-compatible format for MCP
Source:R/type-conversion-to-json.R
to_mcp_json.Rd
Converts various R objects to a JSON-compatible format, preserving type information where possible. Handles special types like dates, factors, matrices, and special numeric values (Inf, -Inf, NaN).
Usage
to_mcp_json(
x,
auto_unbox = TRUE,
size_limit = 1e+06,
custom_serializers = list()
)
Details
The function handles the following R types:
Basic types: NULL, logical, numeric, character, integer
Special numeric values: Inf, -Inf, NaN
Date/time types: Date, POSIXct, POSIXlt
Complex numbers
Raw vectors (binary data)
Factors (with levels preserved)
Matrices and arrays (with dimensions)
Data frames
Lists (recursive conversion)
S3 and S4 objects
Formulas and language objects
Environments (replaced with markers)
Examples
# Basic types
to_mcp_json(list(a = 1, b = "hello"))
#> $a
#> [x] 1
#>
#> $b
#> [x] "hello"
#>
to_mcp_json(c(TRUE, FALSE, NA))
#> [1] TRUE FALSE NA
# Special numeric values
to_mcp_json(c(1, Inf, -Inf, NaN))
#> $values
#> [1] "1" "Inf" "-Inf" "NaN"
#>
#> $special_indices
#> [1] 2 3 4
#>
#> $`_mcp_type`
#> [1] "numeric_vector_special"
#>
# Dates and times
to_mcp_json(Sys.Date())
#> $values
#> [1] "2025-06-20"
#>
#> $`_mcp_type`
#> [1] "Date"
#>
to_mcp_json(Sys.time())
#> $values
#> [1] "2025-06-20T17:54:51"
#>
#> $timezone
#> [1] "UTC"
#>
#> $`_mcp_type`
#> [1] "POSIXct"
#>
# Data frames
to_mcp_json(data.frame(x = 1:3, y = letters[1:3]))
#> $x
#> [1] 1 2 3
#>
#> $y
#> [1] "a" "b" "c"
#>
#> attr(,"_mcp_type")
#> [1] "data.frame"
#> attr(,"_mcp_nrow")
#> [1] 3
# Complex types
to_mcp_json(matrix(1:6, nrow = 2))
#> $data
#> [1] 1 2 3 4 5 6
#>
#> $dim
#> [1] 2 3
#>
#> $dimnames
#> NULL
#>
#> $`_mcp_type`
#> [1] "matrix"
#>
to_mcp_json(factor(c("a", "b", "a")))
#> $levels
#> [1] "a" "b"
#>
#> $values
#> [1] 1 2 1
#>
#> $`_mcp_type`
#> [1] "factor"
#>
to_mcp_json(3 + 4i)
#> $real
#> [1] 3
#>
#> $imaginary
#> [1] 4
#>
#> $`_mcp_type`
#> [1] "complex"
#>