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.0
    License
    Apache-2.0
    Last updated
    11 days ago
    Downloads
    6K

    #MoonBit MCP SDK

    Type-safe Model Context Protocol SDK for MoonBit.

    Version: 0.17.5 · 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 and local $ref/$defs are supported.

    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 work is still in progress: the validator has an explicit partial 2020-12 profile; arbitrary remote/dynamic/unevaluated schemas, remaining typed-value precision and normative edge cases remain open. See the conformance evidence and migration notes before relying on a complete-protocol guarantee.

    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

    moon add colmugx/mcp

    For this development revision, use the workspace and its independent external/json-schema submodule. The validator dependency must be published and a standalone build verified before releasing this SDK revision; the existing published SDK is not evidence that these workspace changes are already available through the registry.

    #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 {
    match @mcp.MCPClient::connect_http(
    url="http://localhost:4240/mcp",
    name="demo-client",
    version="1.0.0",
    ) {
    Ok(client) => {
    // Optional one-shot discovery of server identity/capabilities.
    ignore(client.discover())
    match client.list_tools() {
    Ok(result) => for tool in result.tools { println(tool.name) }
    Err(e) => println(e.message())
    }
    client.close()
    }
    Err(e) => println("connect failed: \{e.message()}")
    }
    }

    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 => {
    ignore(host.connect_stdio(name="local", cmd="moon", args=["run", "server"], group~))
    ignore(host.connect_http(name="remote", url="http://localhost:4240/mcp"))
    match host.list_tools() {
    Ok(result) => for tool in result.tools { println(tool.name) } // local.echo
    Err(e) => println(e.message())
    }
    ignore(host.call_tool("local.echo", arguments="{\"text\":\"hello\"}"))
    host.close_all()
    })
    }

    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
    Migration 0.152025-11-25 → 2026-07-28 migration, node by node
    Migration 0.14Breaking changes from 0.13.x

    #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.

    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