MCP Kotlin SDK Documentation

repository·main·Indexed 23 days ago

https://github.com/modelcontextprotocol/kotlin-sdk

A Kotlin Multiplatform implementation of the Model Context Protocol (MCP) for building clients and servers targeting JVM, Native, JS, and Wasm. It provides coroutine-friendly APIs and supports transports including stdio, SSE, and WebSockets. The SDK includes modules for client and server APIs, integration with Ktor, and support for MCP primitives such as Prompts, Resources, Tools, and Sampling.

Tokens
18.8K
Snippets
44
Records
84
Agent score
78%

What's inside MCP Kotlin SDK

  1. Overview of MCP Sample Implementations

    main

    The following table summarizes the available sample projects in the Kotlin MCP SDK repository, categorized by their type, transport mechanism, and supported MCP features:

    SampleTypeTransportMCP Features
    simple-streamable-serverServerStreamable HTTPTools, Resources, Prompts, Logging
    kotlinlang-mcp-serverServerStreamable HTTPTools
    kotlin-mcp-serverServerSTDIO, SSETools, Resources, Prompts
    weather-stdio-serverServerSTDIOTools
    kotlin-mcp-clientClientSTDIOTool discovery & invocation
    notebooksClient (Notebook)Streamable HTTPTool discovery & invocation
  2. Understand the MCP Kotlin SDK modules

    main

    The SDK is divided into three main modules:

    kotlin-sdk-core

    Shared foundation for both clients and servers. It includes:

    • The MCP protocol data model (requests, results, notifications, capabilities, etc.).
    • McpJson (based on kotlinx.serialization) for MCP-friendly JSON handling.
    • Transport abstractions like Transport, AbstractTransport, and WebSocketMcpTransport.
    • The Protocol base class for JSON-RPC framing, correlation, and capability assertions.

    kotlin-sdk-client

    High-level client implementation. It provides:

    • Client runtime (or mcpClient helper) to handle handshakes and expose server metadata.
    • Typed operations for tools, prompts, resources, completion, logging, roots, sampling, and elicitation.
    • Transports: StdioClientTransport, SseClientTransport, WebSocketClientTransport, and StreamableHttpClientTransport.

    kotlin-sdk-server

    Server-side toolkit. It provides:

    • Server runtime to coordinate sessions, initialization, and capability enforcement.
    • Registries for tools, prompts, resources, and templates.
    • Transports: StdioServerTransport (for CLI/editor bridges) and Ktor extensions (mcp for SSE + POST and mcpWebSocket for WebSockets).
  3. Understand Kotlin MCP Client capabilities

    main

    This sample client demonstrates the core lifecycle of an MCP client interacting with a server:

    1. Tool discovery: The client connects to the server, retrieves the list of available tools, and converts them into the format required by the Anthropic API.
    2. Tool invocation: During an interactive chat loop, if Claude requests a tool call, the client intercepts the request, invokes the corresponding tool on the MCP server, and returns the tool's output back to the model to continue the conversation.

    Note: The client uses STDIO transport, meaning it manages the MCP server as a subprocess.

  4. Core components of the kotlin-sdk-core module

    main

    The kotlin-sdk-core module provides the foundational building blocks for the MCP Kotlin SDK. It is designed for Kotlin Multiplatform and includes:

    • Protocol model: Data classes for all MCP entities (requests, results, notifications, capabilities, tools, prompts, resources, logging, completion, sampling, elicitation, and roots) along with DSL helpers.
    • JSON utilities: Shared McpJson configuration and helpers for map-to-JsonElement conversion and JSON-RPC encoding/decoding.
    • Transport abstractions: The Transport and AbstractTransport interfaces for message pipelines, plus WebSocketMcpTransport and ReadBuffer for streaming and WebSocket support.
    • Protocol engine: The Protocol base class, which handles request/response correlation, notifications, progress tokens, and capability assertions.
    • Errors and safety: Common exception types like McpException and capability enforcement hooks to prevent using unsupported endpoints.
  5. Overview of MCP Conformance Test Suites

    main

    The conformance testing is divided into three main suites:

    1. Server Suite

    Validates the Ktor-based conformance server against various MCP server scenarios, including:

    • Lifecycle: initialize, ping
    • Tools: Text, image, audio, embedded, progress, logging, error, sampling, elicitation, dynamic, reconnection, and JSON Schema 2020-12.
    • Resources: List, read-text, read-binary, templates, subscribe, and dynamic.
    • Prompts: Simple, with-args, with-image, with-embedded-resource, and dynamic.
    • Completions: complete handler.
    • Security: DNS rebinding protection.

    2. Client Core Suite

    Tests fundamental client capabilities:

    • initialize: Connect, list tools, and close.
    • tools_call: Connect, call add_numbers(a=5, b=3), and close.
    • elicitation-sep1034-client-defaults: Elicitation with applyDefaults capability.
    • sse-retry: Call test_reconnection and verify reconnection.

    3. Client Auth Suite

    Tests 20 total OAuth scenarios, including:

    • 17 OAuth Authorization Code scenarios.
    • 2 Client Credentials scenarios (jwt, basic).
    • 1 Cross-App Access scenario (SEP-990).

    Note: Auth scenarios use Ktor's HttpClient plugins directly and do not use the SDK's built-in auth support.

  6. Understand the kotlin-sdk-server lifecycle and capabilities

    main

    Capabilities

    Capabilities are declared via ServerOptions. They drive which handlers can be installed and whether the server emits list-change notifications. The server enforces these declarations; attempting to register an unsupported feature will throw an error.

    Lifecycle

    • Sessions: Managed by the Server class. You can attach transports and open sessions via createSession(transport). Multiple sessions can be active simultaneously.
    • Hooks: Use onConnect and onClose callbacks within a session to manage lifecycle events. (Note: onInitialized is deprecated; use session-level hooks instead).
    • Cleanup: Closing the server tears down transports and unsubscribes all sessions.
  7. Use Streamable HTTP Transport for remote deployments

    main

    The recommended choice for remote deployments is the Streamable HTTP Transport. It uses StreamableHttpClientTransport for clients and Ktor helpers mcpStreamableHttp() or mcpStatelessStreamableHttp() for servers. These helpers expose MCP over a single HTTP endpoint with optional JSON-only or SSE streaming responses and automatically install ContentNegotiation with McpJson (do not install it yourself).

    Both helpers accept a path parameter (defaulting to "/mcp") to mount the endpoint at a specific URL.

    embeddedServer(CIO, port = 3000) {
        mcpStreamableHttp(path = "/api/mcp") {
            MyServer()
        }
    }.start(wait = true)
  8. What are MCP Primitives?

    main

    The Model Context Protocol (MCP) relies on four core primitives to enable communication between servers and clients:

    • Prompts: Interactive templates for LLM interactions. Servers provide templates with optional arguments, and clients request/use them.
    • Resources: Contextual data for augmenting LLM context. Servers expose data sources (files, API responses, etc.), and clients read or subscribe to them.
    • Tools: Executable functions that the LLM can invoke. Servers define these functions, and clients call them to perform actions.
    • Sampling: Server-initiated LLM requests. Servers request completions from the client, and the client executes the LLM call and returns the results.
  9. Understand MCP Capabilities

    main

    Capabilities define the features supported by a server or client and are declared during initialization.

    Server Capabilities

    Servers declare these to inform clients what they can do:

    • prompts: Management and notifications for prompt templates (listChanged flag).
    • resources: Exposure, subscriptions, and update notifications (subscribe, listChanged flags).
    • tools: Discovery, execution, and list change notifications (listChanged flag).
    • logging: Streaming logs to the client console.
    • completions: Providing argument autocompletion suggestions.
    • experimental: Custom non-standard features.

    Client Capabilities

    Clients declare these to inform servers what they support:

    • sampling: Ability to execute model requests (LLM calls) on behalf of the server.
    • roots: Exposing root directories and notifying of changes (listChanged flag).
    • elicitation: Ability to display schema/form dialogs for structured input.
    • experimental: Custom non-standard features.
  10. Use SSE Transport for backwards compatibility

    main

    For compatibility with older MCP clients, you can use Server-Sent Events (SSE) via two Ktor helpers:

    1. Application.mcp { }: Automatically installs SSE and ContentNegotiation with McpJson, then registers MCP endpoints at /. Do not install ContentNegotiation yourself.
    2. Route.mcp { }: Registers MCP endpoints at the current route path. This requires you to call install(SSE) in the application first. This is useful for hosting MCP alongside other routes or under a path prefix.
    embeddedServer(CIO, port = 3000) {
        install(SSE)
        routing {
            route("/api/mcp") {
                mcp { MyServer() }
            }
        }
    }.start(wait = true)
  11. Use WebSocket Transport for low-latency connections

    main
    Use WebSocketClientTransport and its matching server utilities for full-duplex, low-latency connections. This is particularly useful when handling many notifications or long-running sessions behind a reverse proxy that supports WebSockets.