|
| 1 | +import dev.johnoreilly.climatetrace.data.ClimateTraceRepository |
| 2 | +import dev.johnoreilly.climatetrace.di.initKoin |
| 3 | +import io.ktor.server.application.* |
| 4 | +import io.ktor.server.cio.* |
| 5 | +import io.ktor.server.engine.* |
| 6 | +import io.ktor.server.routing.* |
| 7 | +import io.ktor.server.sse.* |
| 8 | +import io.ktor.util.collections.* |
| 9 | +import io.ktor.utils.io.streams.* |
| 10 | +import io.modelcontextprotocol.kotlin.sdk.* |
| 11 | +import io.modelcontextprotocol.kotlin.sdk.server.Server |
| 12 | +import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions |
| 13 | +import io.modelcontextprotocol.kotlin.sdk.server.SseServerTransport |
| 14 | +import io.modelcontextprotocol.kotlin.sdk.server.StdioServerTransport |
| 15 | +import kotlinx.coroutines.Job |
| 16 | +import kotlinx.coroutines.runBlocking |
| 17 | +import kotlinx.io.asSink |
| 18 | +import kotlinx.io.buffered |
| 19 | +import kotlinx.serialization.json.JsonObject |
| 20 | +import kotlinx.serialization.json.JsonPrimitive |
| 21 | +import kotlinx.serialization.json.jsonPrimitive |
| 22 | + |
| 23 | + |
| 24 | +private val koin = initKoin(enableNetworkLogs = true).koin |
| 25 | + |
| 26 | +fun configureServer(): Server { |
| 27 | + val climateTraceRepository = koin.get<ClimateTraceRepository>() |
| 28 | + |
| 29 | + val server = Server( |
| 30 | + Implementation( |
| 31 | + name = "mcp-kotlin PeopleInSpace server", |
| 32 | + version = "1.0.0" |
| 33 | + ), |
| 34 | + ServerOptions( |
| 35 | + capabilities = ServerCapabilities( |
| 36 | + prompts = ServerCapabilities.Prompts(listChanged = true), |
| 37 | + resources = ServerCapabilities.Resources(subscribe = true, listChanged = true), |
| 38 | + tools = ServerCapabilities.Tools(listChanged = true) |
| 39 | + ) |
| 40 | + ) |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | + server.addTool( |
| 45 | + name = "get-countries", |
| 46 | + description = "List of countries" |
| 47 | + ) { |
| 48 | + val countries = climateTraceRepository.fetchCountries() |
| 49 | + CallToolResult( |
| 50 | + content = |
| 51 | + countries.map { TextContent("${it.name}, ${it.alpha3}") } |
| 52 | + ) |
| 53 | + } |
| 54 | + |
| 55 | + server.addTool( |
| 56 | + name = "get-emissions", |
| 57 | + description = "List emission info for a particular country", |
| 58 | + inputSchema = Tool.Input( |
| 59 | + properties = JsonObject( |
| 60 | + mapOf( |
| 61 | + "countryCode" to JsonPrimitive("string"), |
| 62 | + "year" to JsonPrimitive("date"), |
| 63 | + |
| 64 | + ) |
| 65 | + ), |
| 66 | + required = listOf("countryCode") |
| 67 | + ) |
| 68 | + |
| 69 | + ) { request -> |
| 70 | + val countryCode = request.arguments["countryCode"] |
| 71 | + val year = request.arguments["year"] |
| 72 | + if (countryCode == null || year == null) { |
| 73 | + return@addTool CallToolResult( |
| 74 | + content = listOf(TextContent("The 'countryCode' and `year` parameters are required.")) |
| 75 | + ) |
| 76 | + } |
| 77 | + |
| 78 | + val countryEmissionInfo = climateTraceRepository.fetchCountryEmissionsInfo( |
| 79 | + countryCode.jsonPrimitive.content, |
| 80 | + year.jsonPrimitive.content |
| 81 | + ) |
| 82 | + CallToolResult( |
| 83 | + content = |
| 84 | + countryEmissionInfo.map { TextContent(it.emissions.co2.toString()) } |
| 85 | + ) |
| 86 | + } |
| 87 | + |
| 88 | + return server |
| 89 | +} |
| 90 | + |
| 91 | +/** |
| 92 | + * Runs an MCP (Model Context Protocol) server using standard I/O for communication. |
| 93 | + * |
| 94 | + * This function initializes a server instance configured with predefined tools and capabilities. |
| 95 | + * It sets up a transport mechanism using standard input and output for communication. |
| 96 | + * Once the server starts, it listens for incoming connections, processes requests, |
| 97 | + * and executes the appropriate tools. The server shuts down gracefully upon receiving |
| 98 | + * a close event. |
| 99 | + */ |
| 100 | +fun `run mcp server using stdio`() { |
| 101 | + val server = configureServer() |
| 102 | + val transport = StdioServerTransport( |
| 103 | + System.`in`.asInput(), |
| 104 | + System.out.asSink().buffered() |
| 105 | + ) |
| 106 | + |
| 107 | + runBlocking { |
| 108 | + server.connect(transport) |
| 109 | + val done = Job() |
| 110 | + server.onClose { |
| 111 | + done.complete() |
| 112 | + } |
| 113 | + done.join() |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +/** |
| 118 | + * Launches an SSE (Server-Sent Events) MCP (Model Context Protocol) server on the specified port. |
| 119 | + * This server enables clients to connect via SSE for real-time communication and provides endpoints |
| 120 | + * for handling specific messages. |
| 121 | + * |
| 122 | + * @param port The port number on which the SSE server should be started. |
| 123 | + */ |
| 124 | +fun `run sse mcp server`(port: Int): Unit = runBlocking { |
| 125 | + val servers = ConcurrentMap<String, Server>() |
| 126 | + |
| 127 | + val server = configureServer() |
| 128 | + embeddedServer(CIO, host = "0.0.0.0", port = port) { |
| 129 | + install(SSE) |
| 130 | + routing { |
| 131 | + sse("/sse") { |
| 132 | + val transport = SseServerTransport("/message", this) |
| 133 | + |
| 134 | + servers[transport.sessionId] = server |
| 135 | + |
| 136 | + server.onClose { |
| 137 | + servers.remove(transport.sessionId) |
| 138 | + } |
| 139 | + |
| 140 | + server.connect(transport) |
| 141 | + } |
| 142 | + post("/message") { |
| 143 | + val sessionId: String = call.request.queryParameters["sessionId"]!! |
| 144 | + val transport = servers[sessionId]?.transport as? SseServerTransport |
| 145 | + if (transport == null) { |
| 146 | + call.respond("Session not found", null) |
| 147 | + return@post |
| 148 | + } |
| 149 | + |
| 150 | + transport.handlePostMessage(call) |
| 151 | + } |
| 152 | + } |
| 153 | + }.start(wait = true) |
| 154 | +} |
0 commit comments