### Minimal STDIO Server Setup Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/kotlin-sdk-server/Module.md Sets up a basic server that handles 'hello' tool requests over standard input/output. Ensure System.in and System.out are available. ```kotlin val server = Server( serverInfo = Implementation(name = "demo-server", version = "1.0.0"), options = ServerOptions( capabilities = ServerCapabilities( tools = ServerCapabilities.Tools(listChanged = true) ) ) ) { addTool( name = "hello", description = "Greets the caller by name" ) { request -> val name = request.params.arguments?.get("name")?.jsonPrimitive?.content ?: "there" CallToolResult( content = listOf(TextContent("Hello, $name!")), isError = false, ) } } val transport = StdioServerTransport( System.`in`.asSource().buffered(), System.out.asSink().buffered() ) server.createSession(transport) ``` -------------------------------- ### Minimal STDIO Client Setup Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/kotlin-sdk-client/Module.md Demonstrates the basic setup for a client using STDIO transport for CLI interoperability. It initializes the client with basic information and capabilities, then performs a call to list tools and execute a tool. ```kotlin val client = mcpClient( clientInfo = Implementation(name = "demo-client", version = "1.0.0"), clientOptions = ClientOptions( capabilities = ClientCapabilities( tools = ClientCapabilities.Tools(), resources = ClientCapabilities.Resources(subscribe = true) ) ), transport = StdioClientTransport( System.`in`.asSource().buffered(), System.out.asSink().buffered() ) ) val tools = client.listTools() val result = client.callTool("hello", mapOf("name" to "Kotlin")) println(result.content) ``` -------------------------------- ### Install SSE and MCP Endpoints with Ktor Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Use `Application.mcp { }` to automatically install SSE and ContentNegotiation, then register MCP endpoints at '/'. Do not install ContentNegotiation separately. ```kotlin embeddedServer(CIO, port = 3000) { install(SSE) routing { route("/api/mcp") { mcp { MyServer() } } } }.start(wait = true) ``` -------------------------------- ### Registering a Server with Prompt Capabilities Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Initializes a Server instance with specific capabilities, including prompt management. This setup is required before adding prompt handlers. ```kotlin import io.modelcontextprotocol.kotlin.sdk.server.Server import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities fun main() { val server = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( prompts = ServerCapabilities.Prompts(listChanged = true) ) ) ) } ``` -------------------------------- ### Install Linux using WSL Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Use this command to install the default Ubuntu distribution of Linux on Windows via WSL. Restart your machine after execution. ```powershell wsl --install ``` -------------------------------- ### Create MCP Server with a Simple Tool Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md This snippet demonstrates how to set up an MCP server using Ktor. It defines a basic server implementation, adds a tool that responds with 'Hello, world!', and starts the server on a specified port. ```kotlin import io.ktor.server.cio.CIO import io.ktor.server.engine.embeddedServer import io.modelcontextprotocol.kotlin.sdk.server.Server import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions import io.modelcontextprotocol.kotlin.sdk.server.mcpStreamableHttp import io.modelcontextprotocol.kotlin.sdk.types.CallToolResult import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities import io.modelcontextprotocol.kotlin.sdk.types.TextContent import io.modelcontextprotocol.kotlin.sdk.types.ToolSchema import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put fun main(args: Array) { val port = args.firstOrNull()?.toIntOrNull() ?: 3000 val mcpServer = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( tools = ServerCapabilities.Tools(listChanged = true) ) ) ) mcpServer.addTool( name = "example-tool", description = "An example tool", inputSchema = ToolSchema( properties = buildJsonObject { put("input", buildJsonObject { put("type", "string") }) } ) ) { request -> CallToolResult(content = listOf(TextContent("Hello, world!"))) } embeddedServer(CIO, host = "127.0.0.1", port = port) { mcpStreamableHttp { mcpServer } }.start(wait = true) } ``` -------------------------------- ### Minimal Ktor SSE MCP Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/docs/moduledoc.md Provides an example of setting up a minimal Ktor SSE server to expose MCP tools, including defining an 'echo' tool that returns the input text. ```kotlin fun Application.module() { mcp { Server( serverInfo = Implementation("sample-server", "1.0.0"), options = ServerOptions(ServerCapabilities( tools = ServerCapabilities.Tools(listChanged = true), resources = ServerCapabilities.Resources(listChanged = true, subscribe = true), )), ) { addTool(name = "echo", description = "Echo text back") { request -> val text = request.params.arguments?.get("text")?.jsonPrimitive?.content ?: "" CallToolResult(content = listOf(TextContent("You said: $text"))) } } } } ``` -------------------------------- ### Install a specific Linux distribution using WSL Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb To install a Linux distribution other than the default Ubuntu, append the `-d` flag followed by the distribution name to the install command. Ensure the distribution is available in the Microsoft Store. ```powershell wsl --install -d ``` -------------------------------- ### Build and Run Kotlinlang MCP Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlinlang-mcp-server/README.md Set Algolia credentials as environment variables and then run the Gradle build to start the server. The server defaults to http://localhost:8080/mcp. ```shell export ALGOLIA_APP_ID=... export ALGOLIA_API_KEY=... export ALGOLIA_INDEX_NAME=... ./gradlew run ``` -------------------------------- ### Gradle Setup for MCP Client or Server Only (JVM) Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Use \"kotlin-sdk-client\" or \"kotlin-sdk-server\" if you only require client or server APIs respectively. Replace \"$mcpVersion\" with the latest version. ```kotlin dependencies { implementation("io.modelcontextprotocol:kotlin-sdk-client:$mcpVersion") implementation("io.modelcontextprotocol:kotlin-sdk-server:$mcpVersion") } ``` -------------------------------- ### List files matching a pattern Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb The 'll' command lists files. Use a wildcard like '/etc/hello*' to filter the output to files starting with 'hello'. ```bash ll /etc/hello* ``` -------------------------------- ### Create Ktor HTTP Client Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Initialize a Ktor HTTP client, installing the Server-Sent Events (SSE) plugin and a Logging plugin. The logger is configured to display HTTP requests and responses in collapsible HTML details. ```kotlin val httpClient = HttpClient { install(SSE) install(Logging) { level = LogLevel.ALL logger = object : Logger { override fun log(message: String) { val messageType = if (message.contains("REQUEST")) "Request" else "Response" DISPLAY(HTML("
HTTP $messageType
$message
")) } } } } ``` -------------------------------- ### Complete Client-Server Communication Test in Kotlin Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/kotlin-sdk-testing/Module.md This example demonstrates a full client-server communication test using in-memory transports. It covers setting up the server and client, establishing a connection, configuring request handlers, executing client operations, and verifying results. Ensure proper resource cleanup in production tests. ```kotlin @OptIn(ExperimentalMcpApi::class) @Test fun testClientServerCommunication(): Unit = runBlocking { val server = Server( Implementation(name = "test server", version = "1.0"), ServerOptions(capabilities = ServerCapabilities(resources = ServerCapabilities.Resources())) ) val (clientTransport, serverTransport) = ChannelTransport.createLinkedPair() val client = Client(clientInfo = Implementation(name = "test client", version = "1.0")) val serverSessionResult = CompletableDeferred() listOf( launch { client.connect(clientTransport) }, launch { serverSessionResult.complete(server.createSession(serverTransport)) } ).joinAll() val serverSession = serverSessionResult.await() serverSession.setRequestHandler(Method.Defined.Initialize) { _, _ -> InitializeResult( protocolVersion = LATEST_PROTOCOL_VERSION, capabilities = ServerCapabilities( resources = ServerCapabilities.Resources(null, null), tools = ServerCapabilities.Tools(null) ), serverInfo = Implementation(name = "test", version = "1.0") ) } serverSession.setRequestHandler(Method.Defined.ResourcesList) { _, _ -> ListResourcesResult( resources = listOf(Resource(uri = "/foo/bar", name = "foo-bar-resource")) ) } // Test client operations client.listResources() shouldNotBeNull { this.resources shouldHaveSize 1 } // Clean up resources client.close() server.close() } ``` -------------------------------- ### Locate Binary, Source, and Manual Files with whereis Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Use the `whereis` command to find the binary, source, and manual files for a given command name. This is useful for understanding where application components are installed on the system. ```bash whereis apache2 ``` -------------------------------- ### Run Ktor Server without Authentication Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/simple-streamable-server/README.md Build and run the Ktor server. The server starts on http://localhost:3001/mcp by default. You can pass a port number as an argument to change it. ```shell ./gradlew run ``` ```shell ./gradlew run --args="8080" ``` -------------------------------- ### Gradle Setup for MCP Kotlin SDK (JVM) Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Add the Maven Central repository and the MCP SDK dependency to your JVM project's Gradle build file. Replace \"$mcpVersion\" with the latest version. ```kotlin repositories { mavenCentral() } dependencies { // See the badge above for the latest version implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") } ``` -------------------------------- ### Configure CORS for Browser Clients Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Installs the Ktor CORS plugin to allow MCP-specific headers for browser-based clients. Restrict origins in production environments. ```kotlin install(CORS) { anyHost() // restrict to specific origins in production allowMethod(HttpMethod.Options) allowMethod(HttpMethod.Get) allowMethod(HttpMethod.Post) allowMethod(HttpMethod.Delete) allowNonSimpleContentTypes = true allowHeader("Mcp-Session-Id") allowHeader("Mcp-Protocol-Version") exposeHeader("Mcp-Session-Id") exposeHeader("Mcp-Protocol-Version") } ``` -------------------------------- ### Multiplatform Gradle Setup for MCP Kotlin SDK Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Add the MCP SDK as a common dependency in your Kotlin Multiplatform project's commonMain source set. Replace \"$mcpVersion\" with the latest version. ```kotlin commonMain { dependencies { // Works as a common dependency as well as the platform one implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") } } ``` -------------------------------- ### Ktor WebSocket Server Integration Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/kotlin-sdk-server/Module.md Integrates MCP into a Ktor application using WebSockets. This setup wires message handling over a single bidirectional connection. ```kotlin fun Application.module() { mcpWebSocket { Server( serverInfo = Implementation("ktor-ws", "1.0.0"), options = ServerOptions(ServerCapabilities(tools = ServerCapabilities.Tools())) ) } } ``` -------------------------------- ### Ktor SSE Server Integration Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/kotlin-sdk-server/Module.md Integrates MCP into a Ktor application using Server-Sent Events (SSE). This setup enables prompt and resource capabilities with list change notifications. ```kotlin fun Application.module() { mcp { Server( serverInfo = Implementation("ktor-sse", "1.0.0"), options = ServerOptions( ServerCapabilities( prompts = ServerCapabilities.Prompts(listChanged = true), resources = ServerCapabilities.Resources(listChanged = true, subscribe = true), ) ) ) { addPrompt( name = "welcome", description = "Explain how to use the server" ) { GetPromptResult( description = "Welcome to the MCP server", messages = listOf(CreateMessageResult.Message(TextContent("Try listing tools first"))) ) } } } } ``` -------------------------------- ### Registering and Calling Tools Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Illustrates how to set up a server with a tool that echoes user-provided text arguments. Tools can accept JSON arguments and return results, potentially including streaming logs or progress. Ensure sensitive operations have human oversight. ```kotlin import io.modelcontextprotocol.kotlin.sdk.server.Server import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions import io.modelcontextprotocol.kotlin.sdk.types.CallToolResult import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities import io.modelcontextprotocol.kotlin.sdk.types.TextContent import kotlinx.serialization.json.jsonPrimitive fun main() { val server = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( tools = ServerCapabilities.Tools(listChanged = true) ) ) ) server.addTool( name = "echo", description = "Return whatever the user sent back to them" ) { request -> val text = request.arguments?.get("text")?.jsonPrimitive?.content ?: "(empty)" CallToolResult(content = listOf(TextContent(text = "Echo: $text"))) } } ``` -------------------------------- ### Registering and Serving Resources Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Demonstrates how to initialize a server and add a resource handler. The resource handler returns text content for a given URI. Set resource subscription and list change capabilities as needed. ```kotlin import io.modelcontextprotocol.kotlin.sdk.server.Server import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceResult import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities import io.modelcontextprotocol.kotlin.sdk.types.TextResourceContents fun main() { val server = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( resources = ServerCapabilities.Resources(subscribe = true, listChanged = true) ) ) ) server.addResource( uri = "note://release/latest", name = "Release notes", description = "Last deployment summary", mimeType = "text/markdown" ) { request -> ReadResourceResult( contents = listOf( TextResourceContents( text = "Ship 42 reached production successfully.", uri = request.uri, mimeType = "text/markdown" ) ) ) } } ``` -------------------------------- ### Configure Client with Sampling Capability Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Demonstrates how to initialize a client with the sampling capability enabled. If tool use is not supported, omit 'tools' from the sampling capabilities. ```kotlin val client = Client( clientInfo = Implementation("demo-client", "1.0.0"), options = ClientOptions( capabilities = ClientCapabilities( sampling = buildJsonObject { putJsonObject("tools") { } }, // drop tools if you don't support tool use ), ), ) client.setRequestHandler(Method.Defined.SamplingCreateMessage) { request, _ -> val content = request.messages.lastOrNull()?.content val prompt = if (content is TextContent) content.text else "your topic" CreateMessageResult( model = "gpt-4o-mini", role = Role.Assistant, content = TextContent(text = "Here is a short note about $prompt"), ) } ``` -------------------------------- ### Create and Connect MCP Client Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md This snippet shows how to initialize an MCP client, configure an HTTP client with SSE, and establish a connection to an MCP server. It then lists available tools on the server. ```kotlin import io.ktor.client.HttpClient import io.ktor.client.plugins.sse.SSE import io.modelcontextprotocol.kotlin.sdk.client.Client import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport import io.modelcontextprotocol.kotlin.sdk.types.Implementation import kotlinx.coroutines.runBlocking fun main(args: Array) = runBlocking { val url = args.firstOrNull() ?: "http://localhost:3000/mcp" val httpClient = HttpClient { install(SSE) } val client = Client( clientInfo = Implementation( name = "example-client", version = "1.0.0" ) ) val transport = StreamableHttpClientTransport( client = httpClient, url = url ) // Connect to server client.connect(transport) // List available tools val tools = client.listTools().tools println(tools) } ``` -------------------------------- ### Build and Connect with MCP Inspector Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/weather-stdio-server/README.md Build the fat JAR of the server and then connect to it using the MCP Inspector. Ensure you have built the JAR first. ```shell ./gradlew build npx @modelcontextprotocol/inspector -- java -jar samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar ``` -------------------------------- ### Create MCP Client Instance Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Instantiate the MCP client with basic client information, including its name and version. ```kotlin val mcpClient = Client( clientInfo = Implementation( name = "my-client", version = "1.0.0" ) ) ``` -------------------------------- ### Run the Weather STDIO Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/weather-stdio-server/README.md Build and run the server using Gradle. The server communicates via standard input and output. ```shell ./gradlew run ``` -------------------------------- ### Minimal WebSocket MCP Client Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/docs/moduledoc.md Demonstrates how to create a minimal WebSocket client to connect to an MCP server, list available tools, and call a tool. ```kotlin val client = mcpClient( clientInfo = Implementation("sample-client", "1.0.0"), clientOptions = ClientOptions(ClientCapabilities(tools = ClientCapabilities.Tools())), transport = WebSocketClientTransport("ws://localhost:8080/mcp") ) val tools = client.listTools() val result = client.callTool("echo", mapOf("text" to "Hello, MCP!")) println(result.content) ``` -------------------------------- ### Set up Streamable HTTP Server Endpoint Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Shows how to embed a Ktor server and mount the MCP streamable HTTP endpoint. The path can be customized, and the default is '/mcp'. ```kotlin embeddedServer(CIO, port = 3000) { mcpStreamableHttp(path = "/api/mcp") { MyServer() } }.start(wait = true) ``` -------------------------------- ### List Available Tools Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Retrieve and display a list of available tools from the MCP server. For each tool, print its title, name, description, input/output schemas, icons, annotations, and execution details. ```kotlin runBlocking { val listToolsResult = mcpClient.listTools() for (tool in listToolsResult.tools) { println( """ |🔨Title: ${tool.title} (${tool.name}) | |Description: ${tool.description} | |Input schema: ${tool.inputSchema} |Output schema: ${tool.outputSchema} |Icons: ${tool.icons?.joinToString(", ")} |Annotations: ${tool.annotations} |Execution: ${tool.execution} | """.trimMargin() ) } } ``` -------------------------------- ### Docker Build and Run Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlinlang-mcp-server/README.md Build a Docker image for the kotlinlang-mcp-server and run it, exposing the default port and setting necessary Algolia environment variables. The server runs on port 8080 by default. ```shell docker build -t kotlinlang-mcp-server . docker run \ -p 8080:8080 \ -e ALGOLIA_APP_ID=... \ -e ALGOLIA_API_KEY=... \ -e ALGOLIA_INDEX_NAME=... \ kotlinlang-mcp-server ``` -------------------------------- ### Run Static Analysis Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Perform static code analysis using Detekt. ```bash ./gradlew detekt ``` -------------------------------- ### Run Ktor Server with Authentication Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/simple-streamable-server/README.md Build and run the Ktor server with authentication enabled. The token is read from the MCP_AUTH_TOKEN environment variable. Clients must include an Authorization: Bearer header. ```shell MCP_AUTH_TOKEN=my-secret ./gradlew run --args="--auth" ``` -------------------------------- ### Client-Side Root Management Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md This snippet shows how a client can advertise its capabilities, specifically managing roots (authorized file system paths). It demonstrates adding a root and notifying the server of changes. ```kotlin val client = Client( clientInfo = Implementation("demo-client", "1.0.0"), options = ClientOptions( capabilities = ClientCapabilities(roots = ClientCapabilities.Roots(listChanged = true)), ), ) client.addRoot( uri = "file:///Users/demo/projects", name = "Projects", ) client.sendRootsListChanged() ``` -------------------------------- ### Run Kotlin MCP Server with SSE (Plain Configuration) Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-server/README.md Build and run the Kotlin MCP server using Gradle, exposing capabilities via plain SSE configuration on port 3001. Note: This mode may have known issues. ```shell ./gradlew run --args="--sse-server 3001" ``` -------------------------------- ### Run Client Authentication Conformance Tests Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute the client authentication suite of MCP conformance tests, covering 20 OAuth scenarios. Requires Node.js and npx. ```bash ./conformance-test/run-conformance.sh client-auth ``` -------------------------------- ### Run Client Conformance Tests Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute the client core suite of MCP conformance tests, including initialization, tool calls, elicitation, and SSE retries. Requires Node.js and npx. ```bash ./conformance-test/run-conformance.sh client ``` -------------------------------- ### Run All Conformance Tests Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute all MCP specification conformance test suites sequentially. Requires Node.js and npx. ```bash ./conformance-test/run-conformance.sh all ``` -------------------------------- ### Connect with MCP Inspector Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/simple-streamable-server/README.md Connect to the running server using the MCP Inspector. Select Streamable HTTP transport and enter the server address. ```shell npx @modelcontextprotocol/inspector ``` -------------------------------- ### Write to a protected file using echo Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb This command attempts to write 'hello world' to a file named 'helloworld.txt' in the '/etc' directory. It demonstrates a common scenario where a standard user will encounter a 'permission denied' error due to the protected nature of the '/etc' folder. ```bash echo hello world > /etc/helloworld.txt ``` -------------------------------- ### Run Kotlin MCP Server with SSE (Ktor Plugin) Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-server/README.md Build and run the Kotlin MCP server using Gradle, exposing capabilities via SSE using the Ktor plugin on port 3002. This mode is for HTTP-based clients. ```shell ./gradlew run --args="--sse-server-ktor 3002" ``` -------------------------------- ### Run Kotlin MCP Client with Python Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-client/README.md Connect to a Python-based MCP server by providing the path to its script file when running the Gradle task. ```shell ./gradlew run --args="path/to/server.py" ``` -------------------------------- ### Print Coverage Summary Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Display a summary of code coverage. ```bash ./gradlew koverLog ``` -------------------------------- ### Run 'sudo su' to become root Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Use the 'sudo su' command to gain superuser privileges. The prompt changes from '$' to '#' and the username changes to 'root'. ```bash sudo su ``` -------------------------------- ### Add Dependencies and Imports Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Add the necessary dependencies for the Kotlin SDK Client, Ktor client, and Kotlinx.coroutines. Import required classes for HTTP client, SSE, logging, and MCP client types. ```python %use coroutines (1.10.2) %use ktor-client (0.3.0-98) USE { dependencies( "io.modelcontextprotocol:kotlin-sdk-client-jvm:0.10.0", ) } ``` ```kotlin import io.ktor.client.HttpClient import io.ktor.client.plugins.logging.* import io.ktor.client.plugins.sse.SSE import io.modelcontextprotocol.kotlin.sdk.client.Client import io.modelcontextprotocol.kotlin.sdk.client.StreamableHttpClientTransport import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.TextContent ``` -------------------------------- ### Display file content Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb The 'cat' command displays the content of a file. Use it to view the content of '/etc/helloworld.txt'. ```bash cat /etc/helloworld.txt ``` -------------------------------- ### Adding a Prompt Handler to the Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Defines a new prompt named 'code-review' with arguments and a handler function. The handler processes the 'diff' argument to generate a review request. ```kotlin import io.modelcontextprotocol.kotlin.sdk.types.GetPromptResult import io.modelcontextprotocol.kotlin.sdk.types.Implementation import io.modelcontextprotocol.kotlin.sdk.types.PromptArgument import io.modelcontextprotocol.kotlin.sdk.types.PromptMessage import io.modelcontextprotocol.kotlin.sdk.types.Role import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities import io.modelcontextprotocol.kotlin.sdk.types.TextContent import io.modelcontextprotocol.kotlin.sdk.server.Server import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions fun main() { val server = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( prompts = ServerCapabilities.Prompts(listChanged = true) ) ) ) server.addPrompt( name = "code-review", description = "Ask the model to review a diff", arguments = listOf( PromptArgument(name = "diff", description = "Unified diff", required = true), ) ) { request -> GetPromptResult( description = "Quick code review helper", messages = listOf( PromptMessage( role = Role.User, content = TextContent(text = "Review this change:\n${request.arguments?.get("diff")}"), ), ), ) } } ``` -------------------------------- ### Run Kotlin MCP Client with JVM Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-client/README.md Connect to a Java-based MCP server by providing the path to its JAR file when running the Gradle task. ```shell ./gradlew run --args="path/to/server.jar" ``` -------------------------------- ### Implement Server-Side Pagination Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md This snippet demonstrates how to implement pagination for list operations on the server. It handles requests for listing resources and returns paginated results with a `nextCursor`. ```kotlin val server = Server( serverInfo = Implementation("example-server", "1.0.0"), options = ServerOptions( capabilities = ServerCapabilities( resources = ServerCapabilities.Resources(), ), ) ) val session = server.createSession( StdioServerTransport( inputStream = System.`in`.asSource().buffered(), outputStream = System.out.asSink().buffered() ) ) val resources = listOf( Resource(uri = "note://1", name = "Note 1", description = "First"), Resource(uri = "note://2", name = "Note 2", description = "Second"), Resource(uri = "note://3", name = "Note 3", description = "Third"), ) val pageSize = 2 session.setRequestHandler(Method.Defined.ResourcesList) { request, _ -> val start = request.params?.cursor?.toIntOrNull() ?: 0 val page = resources.drop(start).take(pageSize) val next = if (start + page.size < resources.size) (start + page.size).toString() else null ListResourcesResult( resources = page, nextCursor = next, ) } ``` -------------------------------- ### List File Details with ll Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb The `ll` command (often an alias for `ls -alF`) provides a detailed listing of files and directories, including permissions, ownership, size, and modification date. Use it to inspect the contents of a directory. ```bash ll /etc/apache2 ``` -------------------------------- ### Run Kotlin MCP Server with STDIO Mode Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-server/README.md Build and run the Kotlin MCP server using Gradle with the default STDIO transport mode. This is suitable for process-based clients. ```shell ./gradlew run ``` ```shell ./gradlew run --args="--stdio" ``` -------------------------------- ### Run Kotlin MCP Client with Node.js Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-client/README.md Connect to a Node.js-based MCP server by providing the path to its JavaScript file when running the Gradle task. ```shell ./gradlew run --args="path/to/build/index.js" ``` -------------------------------- ### Implement Completion Suggestions Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Declare the completions capability and handle completion requests to provide ranked argument suggestions. Supports pagination with `total` and `hasMore` fields. ```kotlin val server = Server( serverInfo = Implementation( name = "example-server", version = "1.0.0" ), options = ServerOptions( capabilities = ServerCapabilities( completions = ServerCapabilities.Completions, ), ) ) val session = server.createSession( StdioServerTransport( inputStream = System.`in`.asSource().buffered(), outputStream = System.out.asSink().buffered() ) ) session.setRequestHandler(Method.Defined.CompletionComplete) { request, _ -> val options = listOf("kotlin", "compose", "coroutine") val matches = options.filter { it.startsWith(request.argument.value.lowercase()) } CompleteResult( completion = CompleteResult.Completion( values = matches.take(3), total = matches.size, hasMore = matches.size > 3, ), ) } ``` -------------------------------- ### Run Server Conformance Tests Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute only the server suite of MCP conformance tests. Requires Node.js and npx. ```bash ./conformance-test/run-conformance.sh server ``` -------------------------------- ### Connect MCP Inspector to STDIO Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-server/README.md Connect the MCP Inspector tool to the running STDIO server. Ensure the inspector configuration file is correctly specified. ```shell npx @modelcontextprotocol/inspector --config samples/kotlin-mcp-server/mcp-inspector-config.json --server stdio-server ``` -------------------------------- ### Connect MCP Inspector to SSE (Plain Configuration) Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-server/README.md Connect the MCP Inspector tool to the running SSE server configured without the Ktor plugin. Ensure the correct server identifier is used. ```shell npx @modelcontextprotocol/inspector --config samples/kotlin-mcp-server/mcp-inspector-config.json --server sse-server ``` -------------------------------- ### Check Public API Compatibility Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Verify public API compatibility before committing changes. ```bash ./gradlew apiCheck ``` -------------------------------- ### MCP Kotlin SDK Dependencies Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/docs/moduledoc.md Shows how to include the MCP Kotlin SDK in your project, either by using the all-in-one bundle or by selecting specific modules like client or server. ```kotlin dependencies { // All-in-one bundle implementation("io.modelcontextprotocol:kotlin-sdk:") // Or pick sides explicitly implementation("io.modelcontextprotocol:kotlin-sdk-client:") implementation("io.modelcontextprotocol:kotlin-sdk-server:") } ``` -------------------------------- ### Connect MCP Inspector to Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlinlang-mcp-server/README.md Launch the MCP Inspector and configure it to use Streamable HTTP transport, pointing to the server's URL. The default server URL is http://localhost:8080/mcp. ```shell npx @modelcontextprotocol/inspector ``` -------------------------------- ### Connect MCP Inspector to SSE (Ktor Plugin) Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlin-mcp-server/README.md Connect the MCP Inspector tool to the running SSE server that uses the Ktor plugin. Verify the server address and configuration. ```shell npx @modelcontextprotocol/inspector --config samples/kotlin-mcp-server/mcp-inspector-config.json --server sse-ktor-server ``` -------------------------------- ### Claude Desktop Integration Configuration Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/weather-stdio-server/README.md Add this JSON configuration to your Claude Desktop settings to integrate the weather server. Ensure the path to the JAR is absolute. ```json { "mcpServers": { "weather": { "command": "java", "args": [ "-jar", "/absolute/path/to/samples/weather-stdio-server/build/libs/weather-stdio-server-0.1.0-all.jar" ] } } } ``` -------------------------------- ### Run MCP Inspector Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md This command launches the MCP Inspector, a tool for testing and interacting with MCP servers. It provides a UI to connect to a server and inspect its functionality. ```bash npx -y @modelcontextprotocol/inspector ``` -------------------------------- ### Build a Tool Call Request Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/kotlin-sdk-core/Module.md Constructs a `CallToolRequest` using DSL helpers for fluent message building. Ensure the `CallToolRequest` type is imported. ```kotlin val request = CallToolRequest { name = "summarize" arguments = mapOf("text" to "Hello MCP") } ``` -------------------------------- ### Run Single Test Method Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute a specific test method within the JVM core module. ```bash ./gradlew :kotlin-sdk-core:jvmTest --tests "*.ProtocolTest.should preserve existing meta when adding progress token" ``` -------------------------------- ### Run Reboot Command with Sudo Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Execute the 'reboot' command with superuser privileges using the 'sudo' prefix. This is useful for system-level operations that require elevated permissions. ```bash sudo reboot ``` -------------------------------- ### Purge a Package with apt purge Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb The `apt purge` command uninstalls a package and removes all its associated configuration files. Use this command for a complete cleanup of a package and its settings. ```bash apt purge ``` -------------------------------- ### Exit root session Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Run the 'exit' command to return to your standard user session from the root account. The prompt reverts to '$'. ```bash exit ``` -------------------------------- ### Generate XML Coverage Report Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Generate a code coverage report in XML format. ```bash ./gradlew koverXmlReport ``` -------------------------------- ### MCP Client Configuration Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/kotlinlang-mcp-server/README.md Configure an MCP client to connect to the Kotlinlang server using Streamable HTTP transport. Specify the server URL in the client's configuration. ```json { "mcpServers": { "kotlinlang": { "url": "http://localhost:8080/mcp" } } } ``` -------------------------------- ### Implement Structured Logging Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Declare the logging capability to stream structured log notifications to the client. Clients can set the minimum log level, and the server emits `notifications/message`. ```kotlin val server = Server( serverInfo = Implementation("example-server", "1.0.0"), options = ServerOptions( capabilities = ServerCapabilities( logging = ServerCapabilities.Logging, ), ) ) val session = server.createSession( StdioServerTransport( inputStream = System.`in`.asSource().buffered(), outputStream = System.out.asSink().buffered() ) ) session.sendLoggingMessage( LoggingMessageNotification( LoggingMessageNotificationParams( level = LoggingLevel.Info, logger = "startup", data = buildJsonObject { put("message", "Server started") }, ), ), ) ``` -------------------------------- ### Run Lint Check Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute the ktlint check to ensure code style compliance. ```bash ./gradlew ktlintCheck ``` -------------------------------- ### Call Tool and Process JSON Results in Kotlin Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb This snippet demonstrates how to call a tool named 'microsoft_docs_search' with a 'query' argument and then parse the JSON results returned in the tool's content. It iterates through the results, extracting and printing the title, content, and content URL. ```kotlin runBlocking { val toolCallResult = mcpClient.callTool( name = "microsoft_docs_search", arguments = mapOf("query" to "Linux") ) for (content in toolCallResult.content) { (content as? TextContent).let { Json.parseToJsonElement(it?.text.orEmpty()).jsonObject.get("results")?.jsonArray?.forEach { result -> val item = result as JsonObject println( """ |Title: ${item["title"]} | |Content: ${item["content"]} |Content URL: ${item["contentUrl"]} """.trimMargin() ) } } } } ``` -------------------------------- ### MCP Conformance Test Script Usage Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/conformance-test/README.md The main script for running MCP conformance tests. It accepts a command and optional extra arguments which are forwarded to the conformance runner. ```bash ./conformance-test/run-conformance.sh [extra-args...] ``` -------------------------------- ### Connect MCP Client to Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb Connect the MCP client to a remote MCP server using StreamableHttpClientTransport. After connecting, print the server version and capabilities. ```kotlin runBlocking { mcpClient.connect( StreamableHttpClientTransport( client = httpClient, url = "https://learn.microsoft.com/api/mcp" ) ) println("✅ Server version: ${mcpClient.serverVersion}") println("✅ Server capabilities: ${mcpClient.serverCapabilities}") } ``` -------------------------------- ### Ktor Dependencies for MCP Client and Server Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/README.md Declare Ktor client or server engine dependencies explicitly, as the MCP SDK does not include them transitively. Replace \"$ktorVersion\" and \"$mcpVersion\" with the latest versions. ```kotlin dependencies { // MCP client with Ktor implementation("io.ktor:ktor-client-cio:$ktorVersion") implementation("io.modelcontextprotocol:kotlin-sdk-client:$mcpVersion") // MCP server with Ktor implementation("io.ktor:ktor-server-netty:$ktorVersion") implementation("io.modelcontextprotocol:kotlin-sdk-server:$mcpVersion") } ``` -------------------------------- ### Run Single Test Class Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/CLAUDE.md Execute tests for a specific class within the JVM module. ```bash ./gradlew :kotlin-sdk-server:jvmTest --tests "io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransportTest" ``` -------------------------------- ### Verify current user ID Source: https://github.com/modelcontextprotocol/kotlin-sdk/blob/main/samples/notebooks/McpClient.ipynb The 'id' command is used to display the current user's identity and group memberships. This is useful for verifying which user context a command is being run under, especially when troubleshooting permission issues. ```bash id ```