Skip to content

Commit 72a8983

Browse files
committed
Expand module documentation with detailed examples, structured sections, and knit snippets
1 parent 0596ffa commit 72a8983

File tree

4 files changed

+283
-79
lines changed

4 files changed

+283
-79
lines changed

docs/moduledoc.md

Lines changed: 49 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
# MCP Kotlin SDK
22

3-
Kotlin SDK for the Model Context Protocol (MCP).
4-
This is a Kotlin Multiplatform library that helps you build MCP clients and servers that speak the same protocol and
5-
share the same types.
6-
The SDK focuses on clarity, small building blocks, and first‑class coroutine support.
3+
Kotlin Multiplatform implementation of the Model Context Protocol (MCP). The SDK focuses on clear, explicit APIs,
4+
small building blocks, and first-class coroutine support so clients and servers share the same well-typed messages and
5+
transports.
76

8-
Use the umbrella `kotlin-sdk` artifact when you want a single dependency that brings the core types plus both client and
9-
server toolkits. If you only need one side, depend on `kotlin-sdk-client` or `kotlin-sdk-server` directly.
10-
11-
Gradle (Kotlin DSL):
7+
Use the umbrella `kotlin-sdk` artifact to bring in everything at once, or depend on the focused modules directly:
128

139
```kotlin
1410
dependencies {
15-
// Convenience bundle with everything you need to start
11+
// All-in-one bundle
1612
implementation("io.modelcontextprotocol:kotlin-sdk:<version>")
1713

18-
// Or pick modules explicitly
14+
// Or pick sides explicitly
1915
implementation("io.modelcontextprotocol:kotlin-sdk-client:<version>")
2016
implementation("io.modelcontextprotocol:kotlin-sdk-server:<version>")
2117
}
@@ -25,79 +21,73 @@ dependencies {
2521

2622
## Module kotlin-sdk-core
2723

28-
Foundational, platform‑agnostic pieces:
24+
Foundation shared by both sides:
2925

30-
- Protocol data model and JSON serialization (kotlinx.serialization)
31-
- Request/response and notification types used by both sides of MCP
32-
- Coroutine‑friendly protocol engine and utilities
33-
- Transport abstractions shared by client and server
26+
- Protocol data model for MCP requests, results, notifications, capabilities, and content types.
27+
- `McpJson` (kotlinx.serialization) with MCP-friendly defaults plus helpers for converting native values to JSON.
28+
- Transport abstractions (`Transport`, `AbstractTransport`, `WebSocketMcpTransport`) and streaming `ReadBuffer`.
29+
- `Protocol` base class that handles JSON-RPC framing, correlation, progress tokens, and capability assertions.
3430

35-
You typically do not use `core` directly in application code; it is pulled in by the client/server modules. Use it
36-
explicitly if you only need the protocol types or plan to implement a custom transport.
31+
Use `core` when you need the raw types or want to author a custom transport. Public APIs are explicit to keep the shared
32+
surface stable across platforms.
3733

3834
---
3935

4036
## Module kotlin-sdk-client
4137

42-
High‑level client API for connecting to an MCP server and invoking its tools, prompts, and resources. Ships with several
43-
transports:
38+
High-level client for connecting to MCP servers and invoking their features:
4439

45-
- WebSocketClientTransport – low latency, full‑duplex
46-
- SSEClientTransport – Server‑Sent Events over HTTP
47-
- StdioClientTransport – CLI‑friendly stdio bridge
48-
- StreamableHttpClientTransport – simple HTTP streaming
40+
- `Client` runtime (or `mcpClient` helper) performs the MCP handshake and exposes `serverCapabilities`,
41+
`serverVersion`, and `serverInstructions`.
42+
- Typed operations for tools, prompts, resources, completion, logging, roots, sampling, and elicitation with capability
43+
enforcement.
44+
- Transports: `StdioClientTransport`, `SSEClientTransport`, `WebSocketClientTransport`, and `StreamableHttpClientTransport`,
45+
plus Ktor client extensions for quick wiring.
4946

50-
A minimal client:
47+
Minimal WebSocket client:
5148

5249
```kotlin
53-
val client = Client(
54-
clientInfo = Implementation(name = "sample-client", version = "1.0.0")
50+
val client = mcpClient(
51+
clientInfo = Implementation("sample-client", "1.0.0"),
52+
clientOptions = ClientOptions(ClientCapabilities(tools = ClientCapabilities.Tools())),
53+
transport = WebSocketClientTransport("ws://localhost:8080/mcp")
5554
)
5655

57-
client.connect(WebSocketClientTransport("ws://localhost:8080/mcp"))
58-
5956
val tools = client.listTools()
60-
val result = client.callTool(
61-
name = "echo",
62-
arguments = mapOf("text" to "Hello, MCP!")
63-
)
57+
val result = client.callTool("echo", mapOf("text" to "Hello, MCP!"))
58+
println(result.content)
6459
```
6560

6661
---
6762

6863
## Module kotlin-sdk-server
6964

70-
Lightweight server toolkit for hosting MCP tools, prompts, and resources. It provides a small, composable API and
71-
ready‑to‑use transports:
65+
Server toolkit for exposing MCP tools, prompts, and resources:
7266

73-
- StdioServerTransport – integrates well with CLIs and editors
74-
- SSE/WebSocket helpers for Ktor – easy HTTP deployment
67+
- `Server` runtime coordinates sessions, initialization flow, and capability enforcement with registries for tools,
68+
prompts, resources, and templates.
69+
- Transports: `StdioServerTransport` for CLI/editor bridges; Ktor extensions (`mcp` for SSE + POST back-channel and
70+
`mcpWebSocket` for WebSocket) for HTTP hosting.
71+
- Built-in notifications for list changes and resource subscriptions when capabilities enable them.
7572

76-
Register tools and run over stdio:
73+
Minimal Ktor SSE server:
7774

7875
```kotlin
79-
80-
val server = Server(
81-
serverInfo = Implementation(name = "sample-server", version = "1.0.0"),
82-
options = ServerOptions(ServerCapabilities())
83-
)
84-
85-
server.addTool(
86-
name = "echo",
87-
description = "Echoes the provided text"
88-
) { request ->
89-
// Build and return a CallToolResult from request.arguments
90-
// (see CallToolResult and related types in kotlin-sdk-core)
91-
/* ... */
76+
fun Application.module() {
77+
mcp {
78+
Server(
79+
serverInfo = Implementation("sample-server", "1.0.0"),
80+
options = ServerOptions(ServerCapabilities(
81+
tools = ServerCapabilities.Tools(listChanged = true),
82+
resources = ServerCapabilities.Resources(listChanged = true, subscribe = true),
83+
)),
84+
) {
85+
addTool(name = "echo", description = "Echo text back") { request ->
86+
CallToolResult(content = listOf(TextContent("You said: ${request.params.arguments["text"]}")))
87+
}
88+
}
89+
}
9290
}
93-
94-
// Bridge the protocol over stdio
95-
val transport = StdioServerTransport(
96-
inputStream = kotlinx.io.files.Path("/dev/stdin").source(),
97-
outputStream = kotlinx.io.files.Path("/dev/stdout").sink()
98-
)
99-
// Start transport and wire it with the server using provided helpers in the SDK.
10091
```
10192

102-
For HTTP deployments, use the Ktor extensions included in the module to expose an MCP WebSocket or SSE endpoint with a
103-
few lines of code.
93+
Pick the module that matches your role, or use the umbrella artifact to get both sides with the shared core.

kotlin-sdk-client/Module.md

Lines changed: 71 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,74 @@
1-
# Module kotlin-sdk-client
1+
# kotlin-sdk-client
22

3-
The Model Context Protocol (MCP) Kotlin SDK client module provides a multiplatform implementation for connecting to and
4-
interacting with MCP servers.
3+
`kotlin-sdk-client` is the multiplatform MCP client for Kotlin. It handles the MCP handshake, enforces capabilities, and
4+
gives you typed APIs to call tools, prompts, resources, completions, and logging endpoints on MCP servers. It reuses
5+
protocol types from `kotlin-sdk-core` and ships with transports for CLI and Ktor-based networking.
56

6-
## Features
7+
## What the module provides
78

8-
- Cross-platform support for JVM, WASM, JS, and Native
9-
- Built-in support for multiple transport protocols (stdio, SSE, WebSocket)
10-
- Type-safe API for resource management and server interactions
9+
- **Client runtime**: The `Client` class (or `mcpClient` helper) wraps initialization, capability checks, and
10+
request/notification plumbing. After connecting, it exposes `serverCapabilities`, `serverVersion`, and
11+
`serverInstructions`.
12+
- **Typed operations**: Convenience functions like `listTools`, `callTool`, `listResources`, `readResource`,
13+
`listPrompts`, `complete`, `setLoggingLevel`, and subscription helpers for resources.
14+
- **Capability enforcement**: Methods fail fast if the server does not advertise the needed capability; optional
15+
strictness mirrors the protocol options used by the server SDK.
16+
- **Transports**: Ready-to-use implementations for STDIO (CLI interoperability), Ktor SSE (`SSEClientTransport` with
17+
POST back-channel), Ktor WebSocket, and Streamable HTTP for environments that prefer request/response streaming.
18+
- **Ktor client integration**: Extension helpers wire MCP over Ktor client engines with minimal setup for SSE,
19+
Streamable HTTP, or WebSocket.
20+
21+
## Typical client setup
22+
23+
1. Declare client capabilities with `ClientOptions` (e.g., tools, prompts, resources, logging, roots, sampling,
24+
elicitation).
25+
2. Create a transport suitable for your environment.
26+
3. Connect using `mcpClient` or instantiate `Client` and call `connect(transport)`.
27+
4. Use typed APIs to interact with the server; results and errors use the shared MCP types.
28+
29+
### Minimal STDIO client
30+
31+
```kotlin
32+
val client = mcpClient(
33+
clientInfo = Implementation(name = "demo-client", version = "1.0.0"),
34+
clientOptions = ClientOptions(
35+
capabilities = ClientCapabilities(
36+
tools = ClientCapabilities.Tools(),
37+
resources = ClientCapabilities.Resources(subscribe = true),
38+
)
39+
),
40+
transport = StdioClientTransport(System.`in`.source(), System.out.sink())
41+
)
42+
43+
val tools = client.listTools()
44+
val result = client.callTool("hello", mapOf("name" to "Kotlin"))
45+
println(result.content)
46+
```
47+
48+
### Ktor-based transports
49+
50+
- **SSE** (streaming GET + POST back-channel): create `SSEClientTransport(baseUrl, httpClient)`; sessions are keyed by
51+
`sessionId` managed by the SDK.
52+
- **WebSocket**: use `WebSocketClientTransport(url, httpClient)` to get bidirectional messaging in one connection.
53+
- **Streamable HTTP**: `StreamableHttpClientTransport` enables MCP over streaming HTTP where WebSockets are unavailable.
54+
55+
## Feature usage highlights
56+
57+
- **Tools**: `callTool` accepts raw maps or `CallToolRequest`; metadata keys are validated per MCP rules.
58+
- **Prompts & completion**: `getPrompt`, `listPrompts`, and `complete` wrap common prompt flows.
59+
- **Resources**: `listResources`, `listResourceTemplates`, `readResource`, and `subscribeResource` cover discovery,
60+
templating, and updates (when the server allows subscriptions).
61+
- **Roots**: If enabled, register local roots with `addRoot`/`addRoots`; the client responds to `RootsList` requests
62+
from the server.
63+
- **Notifications**: Built-in handlers cover initialization, cancellation, progress, and roots list changes; you can
64+
register more handlers via the underlying `Protocol` API.
65+
66+
## Diagnostics and lifecycle
67+
68+
- Capability assertions prevent calling endpoints the server does not expose; errors surface with clear messages.
69+
- Logging uses `KotlinLogging`; enable DEBUG to inspect transport and handshake behavior.
70+
- `close()` tears down the transport and cancels in-flight requests.
71+
72+
Use this module whenever you need an MCP-aware Kotlin client—whether embedding in a CLI over STDIO or talking to remote
73+
servers via Ktor SSE/WebSocket/streamable HTTP transports. Public APIs are explicit so downstream users can rely on
74+
stable, well-typed surface areas across platforms.

kotlin-sdk-core/Module.md

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,47 @@
1-
# Module kotlin-sdk-core
1+
# kotlin-sdk-core
22

3-
The MCP Kotlin SDK Core module provides fundamental functionality for interacting with Model Context Protocol (MCP).
4-
This module serves as the foundation for building MCP-enabled applications in Kotlin.
3+
`kotlin-sdk-core` is the foundation of the MCP Kotlin SDK. It contains protocol message types, JSON handling, and
4+
transport abstractions used by both client and server modules. No platform-specific code lives here; everything is
5+
designed for Kotlin Multiplatform with explicit API mode enabled.
56

7+
## What the module provides
8+
9+
- **Protocol model**: Complete MCP data classes for requests, results, notifications, capabilities, tools, prompts,
10+
resources, logging, completion, sampling, elicitation, and roots. DSL helpers (`*.dsl.kt`) let you build messages
11+
fluently without repeating boilerplate.
12+
- **JSON utilities**: A shared `McpJson` configuration (kotlinx.serialization) with MCP-friendly settings (ignore
13+
unknown keys, no class discriminator). Helpers for converting maps to `JsonElement`, `EmptyJsonObject`, and
14+
encoding/decoding JSON-RPC envelopes.
15+
- **Transport abstractions**: `Transport` and `AbstractTransport` define the message pipeline, callbacks, and error
16+
handling. `WebSocketMcpTransport` adds a shared WebSocket implementation for both client and server sides, and
17+
`ReadBuffer` handles streaming JSON-RPC framing.
18+
- **Protocol engine**: The `Protocol` base class manages request/response correlation, notifications, progress tokens,
19+
and capability assertions. Higher-level modules extend it to become `Client` and `Server`.
20+
- **Errors and safety**: Common exception types (`McpException`, parsing errors) plus capability enforcement hooks
21+
ensure callers cannot use endpoints the peer does not advertise.
22+
23+
## Typical usage
24+
25+
- Import MCP types to define capabilities and message payloads for your own transports or custom integrations.
26+
- Extend `Protocol` if you need a bespoke peer role while reusing correlation logic and JSON-RPC helpers.
27+
- Use the DSL builders to construct well-typed requests (tools, prompts, resources, logging, completion) instead of
28+
crafting raw JSON.
29+
30+
### Example: building a tool call request
31+
32+
```kotlin
33+
val request = CallToolRequest {
34+
name = "summarize"
35+
arguments = mapOf("text" to "Hello MCP")
36+
}
37+
```
38+
39+
### Example: parsing a JSON-RPC message
40+
41+
```kotlin
42+
val message: JSONRPCMessage = McpJson.decodeFromString(jsonString)
43+
```
44+
45+
Use this module when you need the raw building blocks of MCP—types, JSON config, and transport base classes—whether to
46+
embed in another runtime, author new transports, or contribute higher-level features in the client/server modules. The
47+
APIs are explicit to keep the shared surface stable for downstream users.

0 commit comments

Comments
 (0)