Sign in

    jsonrpc

    A small, transport-agnostic JSON-RPC 2.0 endpoint library.

    json-rpc
    json-rpc2
    jsonrpc
    jsonrpc2
    Download zip
    Version
    0.3.0
    License
    Apache-2.0
    Last updated
    4 months ago
    Downloads
    57

    #shiguri-01/jsonrpc

    A small JSON-RPC 2.0 endpoint library for MoonBit.

    The core package works with complete JSON-RPC messages. Transport packages and application code decide how messages are framed and delivered.

    #Install

    moon add shiguri-01/jsonrpc

    #Packages

    • shiguri-01/jsonrpc: core endpoint
    • shiguri-01/jsonrpc/session: optional transport-neutral session helper
    • shiguri-01/jsonrpc/stdio: native-only stdin/stdout transport

    See src/README.mbt.md for core package usage, src/session/README.mbt.md for the session helper, and src/stdio/README.mbt.md for the stdio transport.

    Runnable examples are in examples/README.mbt.md.

    #Core Endpoint

    shiguri-01/jsonrpc is the core JSON-RPC 2.0 endpoint package.

    The core package works with complete JSON-RPC messages. Transports such as stdio, WebSocket, and HTTP stay outside the core.

    #Usage

    ///|
    #warnings("-unnecessary_annotation")
    struct EchoParams {
    message : String
    } derive(FromJson)

    ///|
    struct EchoResult {
    message : String
    } derive(ToJson)

    ///|
    #warnings("-unused_async-unused_error_type")
    async fn echo(params : EchoParams) -> EchoResult raise @jsonrpc.RpcError {
    { message: params.message }
    }

    ///|
    /// Demonstrate building an endpoint and creating JSON-RPC documents.
    pub async fn usage() -> Unit {
    let endpoint = @jsonrpc.EndpointBuilder()
    .handle("echo", @jsonrpc.typed(echo))
    .build()

    let received = endpoint.receive_text(
    (
    #|{"jsonrpc":"2.0","method":"echo","params":{"message":"hello"},"id":1}
    ),
    )

    let request = endpoint.request("workspace/configuration")

    let notification = endpoint.notify("window/logMessage", params=null)

    // In an application, write these JSON values to your transport.
    ignore(received)
    ignore(request)
    ignore(notification)
    }

    Send received.outgoing, request, or notification through your transport. Responses for local requests appear in ReceiveResult.completed.

    Configuration or application-owned data can be captured by the handler.

    ///|
    struct Config {
    prefix : String
    }

    ///|
    #warnings("-unused_async")
    async fn greet(config : Config, params : Json?) -> Json raise @jsonrpc.RpcError {
    guard params is Some(Object({ "name": String(name), .. })) else {
    raise @jsonrpc.invalid_params()
    }
    Json::string("\{config.prefix}, \{name}")
    }

    ///|
    /// Demonstrate capturing application configuration in a handler.
    pub fn configured_usage() -> Unit raise @jsonrpc.EndpointError {
    let config : Config = { prefix: "hello" }

    let endpoint = @jsonrpc.EndpointBuilder()
    .handle("greet", async fn(params) -> Json raise @jsonrpc.RpcError {
    greet(config, params)
    })
    .build()

    // Reuse the endpoint from the transport loop that drives your application.
    ignore(endpoint)
    }

    See ../examples/README.mbt.md for runnable examples.

    Handler

    type Handler = async (Json?) -> Json raise RpcError

    Low-level JSON-RPC method handler.

    The argument is the request params member, or None when params is absent. Return a JSON-RPC result value, or raise RpcError to send a JSON-RPC error response for calls with an id.

    EndpointError

    pub(all) suberror EndpointError {
    DuplicatePendingId(Id)
    DuplicateMethod(String)
    ReservedMethod(String)
    InvalidMethod(String)
    } derive(Eq,
    Debug
    )

    Error raised while constructing local requests or endpoint method tables.

    RequestError

    type RequestError derive(Eq,
    Debug
    )

    Request parsing failure plus any valid id that could still be detected.

    RpcError

    pub(all) suberror RpcError {
    RpcError(Int, String)
    RpcErrorWithData(Int, String, Json)
    } derive(Eq,
    Debug
    )

    Error returned by a method handler.
    impl ToJson for RpcError

    CompletedRequest

    pub(all) struct CompletedRequest {
    id : Id
    method_name : String
    result : Result[Json, RpcError]
    } derive(Eq,
    Debug
    )

    Result for a locally issued request completed by an incoming response.

    Endpoint

    pub struct Endpoint {
    // private fields
    }

    One side of a JSON-RPC connection.

    Endpoint::notify

    fn Endpoint::notify(_self : Endpoint, rpc_method : String, params? : Json) -> Json raise EndpointError

    Create a JSON-RPC notification document.

    Notifications do not allocate an id and cannot produce a completed local request.

    Endpoint::receive_json

    async fn Endpoint::receive_json(self : Endpoint, value : Json) -> ReceiveResult

    Handle an already parsed JSON value.

    Endpoint::receive_text

    async fn Endpoint::receive_text(self : Endpoint, input : String) -> ReceiveResult

    Handle a raw JSON document.

    Endpoint::request

    fn Endpoint::request(self : Endpoint, rpc_method : String, params? : Json, id? : Id) -> Json raise EndpointError

    Create a JSON-RPC request and register its id as pending.

    If id is omitted, the endpoint allocates an integer id. The returned JSON value is the request document to send through a transport.

    EndpointBuilder

    pub struct EndpointBuilder {
    // private fields
    }
    fn EndpointBuilder::EndpointBuilder() -> EndpointBuilder

    Builder for a JSON-RPC endpoint method table.

    EndpointBuilder::build

    Build the runtime endpoint.

    EndpointBuilder::handle

    fn EndpointBuilder::handle(self : EndpointBuilder, name : String, handler : async (Json?) -> Json raise RpcError) -> EndpointBuilder

    Register a method handler on the builder.

    Validation errors are accumulated and reported by build, so calls can be chained while preserving all registration attempts.
    pub(all) enum Id {
    String(String)
    Number(Int)
    } derive(Eq, Hash,
    Debug
    )

    JSON-RPC request id used for local request correlation.
    impl ToJson for Id

    MessageKind

    type MessageKind derive(Eq,
    Debug
    )

    Pending

    ReceiveResult

    pub(all) struct ReceiveResult {
    outgoing : Array[Json]
    completed : Array[CompletedRequest]
    unexpected : Array[Json]
    } derive(Eq,
    Debug
    )

    Result of receiving one JSON-RPC document.

    outgoing contains response documents to send, completed contains local requests matched by responses, and unexpected contains response-like documents that did not match any pending request.

    Request

    Parsed request data used internally by the dispatcher.

    Response

    type Response derive(Eq,
    Debug
    )

    INTERNAL_ERROR_CODE

    let INTERNAL_ERROR_CODE : Int

    JSON-RPC 2.0 error code for unexpected server failures.

    INVALID_PARAMS_CODE

    let INVALID_PARAMS_CODE : Int

    JSON-RPC 2.0 error code for invalid method parameters.

    INVALID_REQUEST_CODE

    let INVALID_REQUEST_CODE : Int

    JSON-RPC 2.0 error code for structurally invalid requests.

    METHOD_NOT_FOUND_CODE

    let METHOD_NOT_FOUND_CODE : Int

    JSON-RPC 2.0 error code for unknown methods.

    PARSE_ERROR_CODE

    let PARSE_ERROR_CODE : Int

    JSON-RPC 2.0 error code for parse failures.

    batch

    fn batch(items : Array[Json]) -> Json

    Create a JSON-RPC batch document from request or response documents.

    internal_error

    fn internal_error(message? : String) -> RpcError

    Standard "Internal error" error.

    invalid_params

    fn invalid_params(message? : String) -> RpcError

    Standard "Invalid params" error.

    typed

    fn[P :
    FromJson
    , R : ToJson] typed(run : async (P) -> R raise RpcError) -> (async (Json?) -> Json raise RpcError)

    Convert a typed async MoonBit function into a low-level JSON-RPC handler.

    The generated handler decodes params as P, calls run, and converts the result to JSON. Parameter decode failures are reported as RpcErrorWithData with JSON-RPC INVALID_PARAMS_CODE.

    Powered by MoonBit

    Site sourceReport issuePackagesBuild queueSkillsStatistics

    © 2026 mooncakes.io