Sign in

    mcp

    Type-safe MCP SDK in MoonBit with server/client support and dual transport (STDIO/HTTP)

    mcp
    modelcontextprotocol
    Download zip
    Author
    Version
    0.18.2
    License
    Apache-2.0
    Last updated
    11 hours ago
    Downloads
    6K

    #MoonBit MCP SDK

    Type-safe Model Context Protocol SDK for MoonBit.

    Version: 0.18.1 · Protocol: 2026-07-28 (stateless) · License: Apache-2.0

    #Protocol support and scope

    The SDK targets MCP 2026-07-28 with stateless per-request metadata and MRTR. This branch includes complete content/tool/resource/prompt wire models, completion, sampling and form/URL elicitation models, trusted request context, cooperative cancellation, cache metadata preservation, and registry-aware HTTP header validation. Registering features controls the capabilities advertised by discovery; an empty registry must be enabled explicitly.

    Tool input/output validation now compiles schemas once at registration and rejects invalid arguments before executing handlers. Successful structured output is validated when an output schema is declared. Closed objects, precise numeric constraints, local and preloaded external $ref, $id/anchors, dynamic references, unevaluated constraints, and standard-vocabulary custom dialects are supported. Pass schema_resources to tool_definition for external documents; registration never fetches them over the network.

    Elicitation forms are validated before interaction and accepted content is checked against an owned schema snapshot. The server independently verifies MRTR response keys, result types, and form constraints from authenticated continuation state; the client bounds retries without a final unconsumable interaction.

    JSON-RPC ids and peer error codes now retain exact integer literals beyond Int32 and binary64. String ids, large numeric ids, duplicate checks, subscriptions and cancellation share consistent routing without truncation.

    Conformance is evidence-based, not an unconditional complete-protocol guarantee. The validator's standard suite reaches 1301/1301, but optional format assertions and general ECMA-262 patterns remain outside its supported profile. MCP transport/runtime evidence and host responsibilities are tracked separately in the conformance matrix and migration notes. The error API uses MoonBit checked errors rather than Result-valued failure returns.

    Bearer tokens, server-side authentication hooks, and protected-resource metadata are supported. OAuth authorization client lifecycle, PKCE, dynamic client registration, and token refresh management are not included.

    #Installation

    Install the published SDK and its async runtime dependency in your MoonBit project:

    moon add colmugx/mcp@0.18.0 moon add moonbitlang/async@0.21.0

    Development can use the workspace's independent external/json-schema submodule. The SDK currently declares colmugx/json-schema@0.1.4; workspace and historical registry-only verification evidence are recorded separately in the conformance notes.

    #Quick Start

    #Server

    async fn main {
    @mcp.MCPServer::MCPServer("demo-server", "1.0.0")
    .tool("echo", "Echo text", Json::object({ "type": "object" }), fn(_context, args) {
    let text = match args {
    Object(obj) =>
    match obj.get("text") {
    Some(String(value)) => value
    _ => ""
    }
    _ => ""
    }
    Ok(@mcp.ToolResult::text(text))
    })
    .run_stdio()
    }

    Use .run_http(port=4240, path="/mcp") for Streamable HTTP.

    #Client

    async fn main {
    let client = @mcp.MCPClient::connect_http(
    url="http://localhost:4240/mcp",
    name="demo-client",
    version="1.0.0",
    )
    defer client.close()
    // Optional one-shot discovery of server identity/capabilities.
    ignore(client.discover())
    let result = client.list_tools()
    for tool in result.tools { println(tool.name) }
    }

    Connection and operation APIs return their success values directly and raise MCPError on failure. Use try ... catch for local recovery; async cancellation remains an async error. Business handler callbacks still return explicit Result values. See the client error-handling guide. For local subprocess servers, use MCPClient::connect_stdio(cmd~, args?, name~, version~, extra_env?, group~).

    #Host

    async fn main {
    let host = @mcp.MCPHost::MCPHost(name="my-host", version="1.0.0")
    @async.with_task_group(group => {
    defer host.close_all()
    ignore(host.connect_stdio(name="local", cmd="moon", args=["run", "server"], group~))
    ignore(host.connect_http(name="remote", url="http://localhost:4240/mcp"))
    let result = host.list_tools()
    for tool in result.tools { println(tool.name) } // local.echo
    ignore(host.call_tool("local.echo", arguments="{\"text\":\"hello\"}"))
    })
    }

    Host tool names are qualified as connection.tool so multiple servers can expose the same tool name without collision.

    #Documentation

    DocumentDescription
    QuickstartServer, client, and host setup
    Protocol TypesJSON-RPC, errors, and MCP types
    Server GuideHigh-level server API and runtime behavior
    Transport ReferenceAdvanced transport internals
    Client GuideConnections, MRTR input handlers, notifications, and legacy compatibility
    ArchitectureProtocol, runtime, transport, application layers
    Host GuideMCPHost named connections and routing
    Conformance notesProtocol coverage, remaining gaps, and compatibility notes
    ChangelogRelease history and breaking changes

    #API Direction

    The default public path is intentionally small:

    • MCPServer for serving tools, resources, and prompts.
    • MCPClient for one server connection.
    • MCPHost for multiple named server connections.
    • colmugx/mcp/client/legacy for talking to 2025-11-25-era servers (LegacyClient).

    Transports and request builders are advanced/internal details. Existing low-level imports may still be useful for SDK contributors, but application code should prefer the high-level APIs above.

    #License

    Apache-2.0

    Annotations

    Protocol types

    CacheScope

    Protocol types

    CallToolResult

    using @colmugx/mcp/protocol/types { type ToolResult as CallToolResult }

    CancellationToken

    Request-local cooperative cancellation, shared with its transport and task owner.

    ClientCapabilities

    Protocol types

    CompleteRequestParams

    Protocol types

    CompletionArgument

    Protocol types

    CompletionContext

    Protocol types

    CompletionReference

    Protocol types

    CompletionRegistry

    Server

    CompletionResult

    Complete wire result, including open completion fields and result metadata. total keeps the exact integer literal (pinned schema: integer); a Double total cannot represent the count losslessly.

    ContentBlock

    Protocol types

    ContentMetadata

    Protocol types

    CreateMessageRequest

    Protocol types

    CreateMessageResult

    Protocol types

    DiscoverResult

    Protocol types

    ElicitationAction

    Protocol types

    ElicitationCapabilities

    Protocol types

    ElicitationRequest

    Protocol types

    ElicitationResult

    Protocol types

    ElicitationValue

    Protocol types

    GetPromptResult

    Protocol types

    Icon

    Protocol types

    IconTheme

    Protocol types

    InputRequestEntry

    Protocol types

    InputRequestKind

    Protocol types

    JsonInteger

    Protocol types

    JsonNumber

    Protocol types

    JsonRpcRequest

    Protocol types

    JsonSchema

    Protocol core

    ListPromptsResult

    Client and Host

    ListResourcesResult

    Client and Host

    ListToolsResult

    Client and Host

    MCPClient

    Client and Host

    MCPError

    Protocol types

    MCPHost

    Client and Host

    MCPServer

    Server

    ModelHint

    Protocol types

    ModelPreferences

    Protocol types

    ParamDef

    Protocol tool types

    Params

    Protocol core

    Principal

    Identity established by a trusted server-side authenticator, never by request metadata.

    ProgressNotification

    Protocol types

    ProgressReporter

    Reports progress through the current request's transport; direct dispatch defaults to a no-op.

    ProgressToken

    Protocol types

    PromptArgument

    Protocol types

    PromptCapabilities

    Protocol types

    PromptDefinition

    Protocol types

    PromptMessage

    Protocol types

    ReadResourceResult

    Client and Host

    RequestCancelled

    RequestContext

    Runtime data stays separate from tool/prompt business arguments, including on MRTR retry.

    RequestId

    Protocol types

    ResourceCapabilities

    Protocol types

    ResourceContents

    Protocol types

    ResourceData

    Protocol types

    ResourceDefinition

    Protocol types

    ResourceLinkData

    Protocol types

    ResourceReadResult

    Protocol types

    ResourceTemplateDefinition

    Protocol types

    ResultMetadata

    Protocol types

    Role

    Protocol types

    RootCapabilities

    Protocol types

    SamplingCapabilities

    Protocol types

    SamplingContent

    Protocol types

    SamplingContentBlock

    Protocol types

    SamplingContext

    Protocol types

    SamplingMessage

    Protocol types

    ServerCapabilities

    Protocol types

    ServerInfo

    Protocol types

    Tool

    Protocol tool types

    ToolAnnotations

    Protocol types

    ToolCallOutcome

    Protocol tool types

    ToolCapabilities

    Protocol types

    ToolChoice

    Protocol types

    ToolChoiceMode

    Protocol types

    ToolDefinition

    Protocol types

    ToolError

    Protocol core

    ToolResultContent

    Protocol types

    ToolUseContent

    Protocol types

    TransportError

    Protocol types

    get_number

    fn get_number(json : Json, key : String) -> Result[Double,
    ToolResult
    ]

    Extract number from JSON, returning error ToolResult on failure

    get_optional_number

    fn get_optional_number(json : Json, key : String) -> Result[Double?,
    ToolResult
    ]

    Extract optional number from JSON

    get_optional_string

    fn get_optional_string(json : Json, key : String) -> Result[String?,
    ToolResult
    ]

    Extract optional string from JSON

    get_string

    fn get_string(json : Json, key : String) -> Result[String,
    ToolResult
    ]

    Extract string from JSON, returning error ToolResult on failure

    parse_json

    fn parse_json(source : StringView) -> Json raise
    MCPError

    Preserve decimal literals at wire boundaries and when constructing schemas. Core JSON can preserve large integers while still rounding long decimals.

    Source Files