From c0b63cbfda4f31721f3bdddd0c05bc303eb78f8a Mon Sep 17 00:00:00 2001 From: k-aniket23 Date: Fri, 25 Apr 2025 15:23:30 +0530 Subject: [PATCH 1/2] base thing which was already working, nothing new --- .idea/artifacts/kotlin_sdk_jvm_0_4_0.xml | 6 + .idea/codeStyles/Project.xml | 10 + .idea/codeStyles/codeStyleConfig.xml | 5 + .idea/gradle.xml | 27 + .idea/kotlinc.xml | 2 +- .idea/misc.xml | 2 +- samples/kotlin-mcp-client/build.gradle.kts | 1 + .../sample/client/MCPClient.kt | 828 +++++++++++++++++- .../sample/client/main.kt | 42 +- ...idelines_nutritional_interventions_anc.txt | 158 ++++ .../sample/server/McpWeatherServer.kt | 88 +- .../sample/server/resources/one.txt | 1 + .../who_ANC_Guideline_Zinc_supplements.txt | 7 + ...idelines_nutritional_interventions_anc.txt | 158 ++++ 14 files changed, 1310 insertions(+), 25 deletions(-) create mode 100644 .idea/artifacts/kotlin_sdk_jvm_0_4_0.xml create mode 100644 .idea/codeStyles/Project.xml create mode 100644 .idea/codeStyles/codeStyleConfig.xml create mode 100644 samples/kotlin-mcp-server/src/main/kotlin/resources/who_guidelines_nutritional_interventions_anc.txt create mode 100644 samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt create mode 100644 samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Zinc_supplements.txt create mode 100644 samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt diff --git a/.idea/artifacts/kotlin_sdk_jvm_0_4_0.xml b/.idea/artifacts/kotlin_sdk_jvm_0_4_0.xml new file mode 100644 index 00000000..7ed3c4d6 --- /dev/null +++ b/.idea/artifacts/kotlin_sdk_jvm_0_4_0.xml @@ -0,0 +1,6 @@ + + + $PROJECT_DIR$/build/libs + + + \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 00000000..1bec35e5 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 00000000..79ee123c --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml index 2e197de9..d6c9e48b 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -13,6 +13,33 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml index c224ad56..c22b6fa9 100644 --- a/.idea/kotlinc.xml +++ b/.idea/kotlinc.xml @@ -1,6 +1,6 @@ - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 195deedd..9c7988a2 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -11,7 +11,7 @@ - + \ No newline at end of file diff --git a/samples/kotlin-mcp-client/build.gradle.kts b/samples/kotlin-mcp-client/build.gradle.kts index fc327d1a..3b7b59be 100644 --- a/samples/kotlin-mcp-client/build.gradle.kts +++ b/samples/kotlin-mcp-client/build.gradle.kts @@ -20,6 +20,7 @@ dependencies { implementation("io.modelcontextprotocol:kotlin-sdk:$mcpVersion") implementation("org.slf4j:slf4j-nop:$slf4jVersion") implementation("com.anthropic:anthropic-java:$anthropicVersion") + } tasks.test { diff --git a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt index 6221b471..6c12415d 100644 --- a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt +++ b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt @@ -18,7 +18,13 @@ import kotlin.jvm.optionals.getOrNull class MCPClient : AutoCloseable { // Configures using the `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` environment variables - private val anthropic = AnthropicOkHttpClient.fromEnv() +// private val anthropic = AnthropicOkHttpClient.fromEnv() +//// .apiKey(System.getenv("ANTHROPIC_API_KEY") ?: "your_api_key_here") +//// .build() + + private val anthropic = AnthropicOkHttpClient.builder() + .apiKey(System.getenv("ANTHROPIC_API_KEY") ) + .build() // Initialize MCP client private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")) @@ -30,6 +36,7 @@ class MCPClient : AutoCloseable { // List of tools offered by the server private lateinit var tools: List + private fun JsonObject.toJsonValue(): JsonValue { val mapper = ObjectMapper() val node = mapper.readTree(this.toString()) @@ -86,10 +93,19 @@ class MCPClient : AutoCloseable { } } + private val messages = mutableListOf() + // Process a user query and return a string response suspend fun processQuery(query: String): String { // Create an initial message with a user's query - val messages = mutableListOf( + +// val messages = mutableListOf( +// MessageParam.builder() +// .role(MessageParam.Role.USER) +// .content(query) +// .build() +// ) + messages.add( MessageParam.builder() .role(MessageParam.Role.USER) .content(query) @@ -104,11 +120,76 @@ class MCPClient : AutoCloseable { .build() ) +// val assistantReply = response.content().firstOrNull()?.text()?.getOrNull()?.text() + + +// val finalText = mutableListOf() +// response.content().forEach { content -> +// when { +// // Append text outputs from the response +// content.isText() -> finalText.add(content.text().getOrNull()?.text() ?: "") +// +// // If the response indicates a tool use, process it further +// content.isToolUse() -> { +// val toolName = content.toolUse().get().name() +// val toolArgs = +// content.toolUse().get()._input().convert(object : TypeReference>() {}) +// +// // Call the tool with provided arguments +// val result = mcp.callTool( +// name = toolName, +// arguments = toolArgs ?: emptyMap() +// ) +// finalText.add("[Calling tool $toolName with args $toolArgs]") +// +// // Add the tool result message to the conversation +// messages.add( +// MessageParam.builder() +// .role(MessageParam.Role.USER) +// .content( +// """ +// "type": "tool_result", +// "tool_name": $toolName, +// "result": ${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }} +// """.trimIndent() +// ) +// .build() +// ) +// +// // Retrieve an updated response after tool execution +// val aiResponse = anthropic.messages().create( +// messageParamsBuilder +// .messages(messages) +// .build() +// ) +// +// // Append the updated response to final text +// finalText.add(aiResponse.content().first().text().getOrNull()?.text() ?: "") +// } +// } +// } +// +// return finalText.joinToString("\n", prefix = "", postfix = "") +// } val finalText = mutableListOf() + response.content().forEach { content -> when { // Append text outputs from the response - content.isText() -> finalText.add(content.text().getOrNull()?.text() ?: "") + content.isText() -> { + val text = content.text().getOrNull()?.text() + if (!text.isNullOrBlank()) { + finalText.add(text) + + // Save assistant response to memory + messages.add( + MessageParam.builder() + .role(MessageParam.Role.ASSISTANT) + .content(text) + .build() + ) + } + } // If the response indicates a tool use, process it further content.isToolUse() -> { @@ -121,19 +202,22 @@ class MCPClient : AutoCloseable { name = toolName, arguments = toolArgs ?: emptyMap() ) + finalText.add("[Calling tool $toolName with args $toolArgs]") - // Add the tool result message to the conversation + // Add the tool_result to messages + val toolResultContent = """ + { + "type": "tool_result", + "tool_name": "$toolName", + "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" + } + """.trimIndent() + messages.add( MessageParam.builder() .role(MessageParam.Role.USER) - .content( - """ - "type": "tool_result", - "tool_name": $toolName, - "result": ${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }} - """.trimIndent() - ) + .content(toolResultContent) .build() ) @@ -144,16 +228,30 @@ class MCPClient : AutoCloseable { .build() ) - // Append the updated response to final text - finalText.add(aiResponse.content().first().text().getOrNull()?.text() ?: "") + val aiReply = aiResponse.content().firstOrNull()?.text()?.getOrNull()?.text() + if (!aiReply.isNullOrBlank()) { + finalText.add(aiReply) + + // Save assistant's new response after tool use + messages.add( + MessageParam.builder() + .role(MessageParam.Role.ASSISTANT) + .content(aiReply) + .build() + ) + } } } } +// println(messages) + return finalText.joinToString("\n", prefix = "", postfix = "") } - // Main chat loop for interacting with the user + + + // Main chat loop for interacting with the user suspend fun chatLoop() { println("\nMCP Client Started!") println("Type your queries or 'quit' to exit.") @@ -173,4 +271,704 @@ class MCPClient : AutoCloseable { anthropic.close() } } -} \ No newline at end of file +} + + +// +// +//package io.modelcontextprotocol.sample.client +// +//import com.anthropic.client.okhttp.AnthropicOkHttpClient +//import com.anthropic.core.JsonValue +//import com.anthropic.models.messages.* +//import com.fasterxml.jackson.core.type.TypeReference +//import com.fasterxml.jackson.databind.ObjectMapper +//import io.modelcontextprotocol.kotlin.sdk.Implementation +//import io.modelcontextprotocol.kotlin.sdk.TextContent +//import io.modelcontextprotocol.kotlin.sdk.client.Client +//import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport +//import kotlinx.coroutines.runBlocking +//import kotlinx.io.asSink +//import kotlinx.io.asSource +//import kotlinx.io.buffered +//import kotlinx.serialization.json.JsonObject +//import kotlin.jvm.optionals.getOrNull +// +//import io.modelcontextprotocol.kotlin.sdk.ReadResourceRequest +////import io.modelcontextprotocol.kotlin.sdk.ReadResourceResult +//import io.modelcontextprotocol.kotlin.sdk.TextResourceContents +// +//class MCPClient : AutoCloseable { +// +// private val anthropic = AnthropicOkHttpClient.builder() +// .apiKey(System.getenv("ANTHROPIC_API_KEY") ) +// .build() +// +// // Initialize MCP client +// private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")) +// +// private val messageParamsBuilder: MessageCreateParams.Builder = MessageCreateParams.builder() +// .model(Model.CLAUDE_3_5_SONNET_20241022) +// .maxTokens(1024) +// +// // List of tools offered by the server +// private lateinit var tools: List +// private var resourceContent: String? = null // Store resource content +// private val resourceUri = "file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt" +// private fun JsonObject.toJsonValue(): JsonValue { +// val mapper = ObjectMapper() +// val node = mapper.readTree(this.toString()) +// return JsonValue.fromJsonNode(node) +// } +// +// +//// private val resourceContents = mutableMapOf() +// +// +// // Connect to the server using the path to the server +// suspend fun connectToServer(serverScriptPath: String) { +// try { +// // Build the command based on the file extension of the server script +// val command = buildList { +// when (serverScriptPath.substringAfterLast(".")) { +// "js" -> add("node") +// "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3") +// "jar" -> addAll(listOf("java", "-jar")) +// else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file") +// } +// add(serverScriptPath) +// } +// +// // Start the server process +// val process = ProcessBuilder(command).start() +// +// // Setup I/O transport using the process streams +// val transport = StdioClientTransport( +// input = process.inputStream.asSource().buffered(), +// output = process.outputStream.asSink().buffered() +// ) +// +// // Connect the MCP client to the server using the transport +// mcp.connect(transport) +// +// // Request the list of available tools from the server +// val toolsResult = mcp.listTools() +// tools = toolsResult?.tools?.map { tool -> +// ToolUnion.ofTool( +// Tool.builder() +// .name(tool.name) +// .description(tool.description ?: "") +// .inputSchema( +// Tool.InputSchema.builder() +// .type(JsonValue.from(tool.inputSchema.type)) +// .properties(tool.inputSchema.properties.toJsonValue()) +// .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required)) +// .build() +// ) +// .build() +// ) +// } ?: emptyList() +// println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") +// +// +// +//// val resourcesResult = mcp.listResources() +//// println("🔍 Available Resources:") +//// resourcesResult?.resources?.forEach {resource -> +//// println("• ${resource.name} and uri = (${resource.uri})") +//// +//// if(resource.mimeType?.contains("text") == true){ +//// val readRequest = ReadResourceRequest(uri = resource.uri) +//// val readResult = mcp.readResource(readRequest) +//// val content = readResult?.contents +//// ?.filterIsInstance() +//// ?.joinToString("\n"){it.text} +//// +//// if(!content.isNullOrBlank()){ +//// resourceContents[resource.name] = content +//// println("Loaded resource '${resource.name}' (${content.length} characters)") +//// } +//// else{ +//// println("Couldnot read content of resource '${resource.name}'") +//// } +//// +//// } +//// } +// +// +//// val resourcesResult = mcp.listResources() +//// println(resourcesResult) +//// println("🔍 Found ${resourcesResult?.resources?.size ?: 0} total resources:") +//// resourcesResult?.resources?.forEach { resource -> +//// println("• ${resource.name} (URI: ${resource.uri}, MIME type: ${resource.mimeType})") +//// +////// Add this to see which files are being filtered out by the text check +//// if(resource.mimeType?.contains("text") != true) { +//// println(" ⚠️ Skipping: Not detected as text content (MIME type: ${resource.mimeType})") +//// } +//// +//// +////// Only process text resources +//// if (resource.mimeType?.contains("text") == true) { +//// val readRequest = ReadResourceRequest(uri = resource.uri) +//// println("readRequest ${readRequest}") +//// val readResult = mcp.readResource(readRequest) +////// println("readResult ${readResult}") +//// +//// val content = readResult?.contents +//// ?.filterIsInstance() +//// ?.joinToString("\n") { it.text } +//// +//// println(content) +//// +//// if (!content.isNullOrBlank()) { +//// resourceContents[resource.name] = content +//// println("✔ Loaded resource '${resource.name}' (${content.length} characters)") +//// } else { +//// println("⚠ Could not read content of resource '${resource.name}'") +//// } +//// } +//// +//// +//// } +// +// +// val resourcesResult = mcp.listResources() +// val resource = resourcesResult?.resources?.find { it.uri == resourceUri } +// println(resource?.uri ) +// println(resource?.mimeType ) +// if (resource != null) { +// println("Found resource: ${resource.name} (${resource.uri})") +// // Construct ReadResourceRequest +// val readRequest = ReadResourceRequest(uri = resource.uri) +// println("readRequest: ${readRequest}") +// val readResult = mcp.readResource(readRequest) +// println("readResult: ${readResult}") +// this.resourceContent = readResult?.contents +// ?.filterIsInstance() +// ?.joinToString("\n") { it.text } +// +// println("Resource Text Content:\n$resourceContent") +//// resourceContent = readResult?.contents?.firstOrNull()?.text +// if (resourceContent != null) { +// println("Successfully loaded resource content (${resourceContent?.length} characters)") +// } else { +// println("Warning: Could not read resource content for ${resource.uri}") +// } +// } else { +// println("Warning: Resource $resourceUri not found") +// } +// } catch (e: Exception) { +// println("Failed to connect to MCP server: $e") +// throw e +// } +// } +// +// +// +// +// private val messages = mutableListOf() +// +// // Process a user query and return a string response +// suspend fun processQuery(query: String): String { +// // Create an initial message with a user's query +// +//// val messages = mutableListOf( +//// MessageParam.builder() +//// .role(MessageParam.Role.USER) +//// .content(query) +//// .build() +//// ) +// +// val context = resourceContent?.let { +// // Truncate or summarize to avoid exceeding token limits +// // For simplicity, take the first 5000 characters (adjust as needed) +// val maxLength = 5000 +// if (it.length > maxLength) { +// it.substring(0, maxLength) + "... [Content truncated]" +// } else { +// it +// } +// } +// +//// val combinedContext = resourceContents.entries.joinToString("\n\n") { (name, text) -> +//// val snippet = if (text.length > 2000) text.take(2000) + "... [truncated]" else text +//// "From $name:\nsnippet" +//// } +//// +//// println("Context available:combinedContext != null}") +// println("Context length: ${context?.length ?: 0} characters") +//// +//// // Combine context and user query +// val fullQuery = if (context != null) { +// """ +// Context from WHO Nutritional Interventions Guidelines: +// $context +// +// User Query: +// $query +// """.trimIndent() +// } else { +// query +// } +// +//// val fullQuery = if (combinedContext.isNotBlank()) { +//// """ +//// Context from WHO Guidelines Resources: +//// $combinedContext +//// +//// User Query: +//// $query +//// """.trimIndent() +//// } else { +//// query +//// } +// +// +// +// messages.add( +// MessageParam.builder() +// .role(MessageParam.Role.USER) +// .content(fullQuery) +// .build() +// ) +// +// // Send the query to the Anthropic model and get the response +// val response = anthropic.messages().create( +// messageParamsBuilder +// .messages(messages) +// .tools(tools) +// .build() +// ) +// +// val finalText = mutableListOf() +// +// response.content().forEach { content -> +// when { +// // Append text outputs from the response +// content.isText() -> { +// val text = content.text().getOrNull()?.text() +// if (!text.isNullOrBlank()) { +// finalText.add(text) +// +// // Save assistant response to memory +// messages.add( +// MessageParam.builder() +// .role(MessageParam.Role.ASSISTANT) +// .content(text) +// .build() +// ) +// } +// } +// +// // If the response indicates a tool use, process it further +// content.isToolUse() -> { +// val toolName = content.toolUse().get().name() +// val toolArgs = +// content.toolUse().get()._input().convert(object : TypeReference>() {}) +// +// // Call the tool with provided arguments +// val result = mcp.callTool( +// name = toolName, +// arguments = toolArgs ?: emptyMap() +// ) +// +// finalText.add("[Calling tool $toolName with args $toolArgs]") +// +// // Add the tool_result to messages +// val toolResultContent = """ +// { +// "type": "tool_result", +// "tool_name": "$toolName", +// "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" +// } +// """.trimIndent() +// +// messages.add( +// MessageParam.builder() +// .role(MessageParam.Role.USER) +// .content(toolResultContent) +// .build() +// ) +// +// // Retrieve an updated response after tool execution +// val aiResponse = anthropic.messages().create( +// messageParamsBuilder +// .messages(messages) +// .build() +// ) +// +// val aiReply = aiResponse.content().firstOrNull()?.text()?.getOrNull()?.text() +// if (!aiReply.isNullOrBlank()) { +// finalText.add(aiReply) +// +// // Save assistant's new response after tool use +// messages.add( +// MessageParam.builder() +// .role(MessageParam.Role.ASSISTANT) +// .content(aiReply) +// .build() +// ) +// } +// } +// } +// } +// +// println(messages) +// +// return finalText.joinToString("\n", prefix = "", postfix = "") +// } +// +// +// +// // Main chat loop for interacting with the user +// suspend fun chatLoop() { +// println("\n==============================================") +// println("\nMCP Client Started!") +// println("Type your queries or 'quit' to exit.") +// println("\n==============================================") +// +// while (true) { +// print("\nQuery: ") +// val message = readLine() ?: break +// if (message.lowercase() == "quit") break +// val response = processQuery(message) +// println("\n$response") +// } +// } +// +// override fun close() { +// runBlocking { +// mcp.close() +// anthropic.close() +// } +// } +//} +// +//// +////package io.modelcontextprotocol.sample.client +//// +////import com.anthropic.client.okhttp.AnthropicOkHttpClient +////import com.anthropic.core.JsonValue +////import com.anthropic.models.messages.* +////import com.fasterxml.jackson.core.type.TypeReference +////import com.fasterxml.jackson.databind.ObjectMapper +////import io.modelcontextprotocol.kotlin.sdk.Implementation +////import io.modelcontextprotocol.kotlin.sdk.TextContent +////import io.modelcontextprotocol.kotlin.sdk.client.Client +////import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport +////import kotlinx.coroutines.runBlocking +////import kotlinx.io.asSink +////import kotlinx.io.asSource +////import kotlinx.io.buffered +////import kotlinx.serialization.json.JsonObject +////import kotlin.jvm.optionals.getOrNull +//// +////import io.modelcontextprotocol.kotlin.sdk.ReadResourceRequest +//////import io.modelcontextprotocol.kotlin.sdk.ReadResourceResult +////import io.modelcontextprotocol.kotlin.sdk.TextResourceContents +//// +////class MCPClient : AutoCloseable { +//// // Configures using the `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` environment variables +////// private val anthropic = AnthropicOkHttpClient.fromEnv() +//////// .apiKey(System.getenv("ANTHROPIC_API_KEY") ?: "your_api_key_here") +//////// .build() +//// +//// private val anthropic = AnthropicOkHttpClient.builder() +//// .apiKey(System.getenv("ANTHROPIC_API_KEY") ) +//// .build() +//// +//// // Initialize MCP client +//// private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")) +//// +//// private val messageParamsBuilder: MessageCreateParams.Builder = MessageCreateParams.builder() +//// .model(Model.CLAUDE_3_5_SONNET_20241022) +//// .maxTokens(1024) +//// +//// // List of tools offered by the server +//// private lateinit var tools: List +//// private var resourceContent: String? = null // Store resource content +//// // private val resourceUri = "file:///C://Users//developer//Downloads//kotlin-sdk//samples//weather-stdio-server//src//main//kotlin//io//modelcontextprotocol//sample//server//resources//who_guidelines_nutritional_interventions_anc.txt " +////// private val resourceUri = "file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt" +//// private fun JsonObject.toJsonValue(): JsonValue { +//// val mapper = ObjectMapper() +//// val node = mapper.readTree(this.toString()) +//// return JsonValue.fromJsonNode(node) +//// } +//// +//// +//// private val resourceContents = mutableMapOf() +//// +//// +//// // Connect to the server using the path to the server +//// suspend fun connectToServer(serverScriptPath: String) { +//// try { +//// // Build the command based on the file extension of the server script +//// val command = buildList { +//// when (serverScriptPath.substringAfterLast(".")) { +//// "js" -> add("node") +//// "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3") +//// "jar" -> addAll(listOf("java", "-jar")) +//// else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file") +//// } +//// add(serverScriptPath) +//// } +//// +//// // Start the server process +//// val process = ProcessBuilder(command).start() +//// +//// // Setup I/O transport using the process streams +//// val transport = StdioClientTransport( +//// input = process.inputStream.asSource().buffered(), +//// output = process.outputStream.asSink().buffered() +//// ) +//// +//// // Connect the MCP client to the server using the transport +//// mcp.connect(transport) +//// +//// // Request the list of available tools from the server +//// val toolsResult = mcp.listTools() +//// tools = toolsResult?.tools?.map { tool -> +//// ToolUnion.ofTool( +//// Tool.builder() +//// .name(tool.name) +//// .description(tool.description ?: "") +//// .inputSchema( +//// Tool.InputSchema.builder() +//// .type(JsonValue.from(tool.inputSchema.type)) +//// .properties(tool.inputSchema.properties.toJsonValue()) +//// .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required)) +//// .build() +//// ) +//// .build() +//// ) +//// } ?: emptyList() +//// println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") +//// +//// +//// val resourcesResult = mcp.listResources() +//// println(resourcesResult) +//// println("🔍 Found ${resourcesResult?.resources?.size ?: 0} total resources:") +//// resourcesResult?.resources?.forEach { resource -> +//// println("• ${resource.name} (URI: ${resource.uri}, MIME type: ${resource.mimeType})") +//// +//// +////// Add this to see which files are being filtered out by the text check +//// if(resource.mimeType?.contains("text") == true) { +//// println(" ⚠️ Skipping: Not detected as text content (MIME type: ${resource.mimeType})") +//// } +//// +//// +////// Only process text resources +//// +////// / if (resource.mimeType?.contains("text") == true) { +////// val readRequest = ReadResourceRequest(uri = resource.uri) +////// println("readRequest ${readRequest}") +////// +////// val readResult = mcp.readResource(readRequest) +//////// return readResult?.contents +////// println("readResult ${readResult}") +////// if (readResult == null) { +////// println("❌ readResource returned null for ${resource.uri}") +////// } else { +////// println("✅ readResource success: $readResult") +////// } +////// +////// val content = readResult?.contents +////// ?.filterIsInstance() +////// ?.joinToString("\n") { it.text } +////// +////// println(content) +////// +////// if (!content.isNullOrBlank()) { +////// resourceContents[resource.name] = content +////// println("✔ Loaded resource '${resource.name}' (${content.length} characters)") +////// } else { +////// println("⚠ Could not read content of resource '${resource.name}'") +////// } +//// +//// if (resource != null) { +//// println("Found resource: ${resource.name} (${resource.uri})") +//// // Construct ReadResourceRequest +//// val readRequest = ReadResourceRequest(uri = resource.uri) +//// println("readRequest: ${readRequest}") +//// println("Before calling readResource()") +//// val readResult = mcp.readResource(readRequest) +//// println("After calling readResource()") +//// println("readResult: ${readResult}") +//// this.resourceContent = readResult?.contents +//// ?.filterIsInstance() +//// ?.joinToString("\n") { it.text } +//// +//// // println("Resource Text Content:\n$resourceContent") +//// // resourceContent = readResult?.contents?.firstOrNull()?.text +//// if (resourceContent != null) { +//// println("Successfully loaded resource content (${resourceContent?.length} characters)") +//// } else { +//// println("Warning: Could not read resource content for ${resource.uri}") +//// } +//// } else { +//// println("Warning: Resource not found") +//// } +//// } +//// +//// +//// } catch (e: Exception) { +//// println("Failed to connect to MCP server: $e") +//// throw e +//// } +//// } +//// +//// +//// +//// +//// private val messages = mutableListOf() +//// +//// // Process a user query and return a string response +//// suspend fun processQuery(query: String): String { +//// // Create an initial message with a user's query +//// +//// +//// +//// val combinedContext = resourceContents.entries.joinToString("\n\n") { (name, text) -> +//// val snippet = if (text.length > 2000) text.take(2000) + "... [truncated]" else text +//// "From $name:$snippet" +//// } +//// +////// println("Context available:combinedContext != null}") +//// println("Context available: ${combinedContext.isNotBlank()}") +//// println("Context length: ${combinedContext?.length ?: 0} characters") +//// +//// +//// val fullQuery = if (combinedContext.isNotBlank()) { +//// """ +//// Context from WHO Guidelines Resources: +//// $combinedContext +//// +//// User Query: +//// $query +//// """.trimIndent() +//// } else { +//// query +//// } +//// +//// +//// +//// messages.add( +//// MessageParam.builder() +//// .role(MessageParam.Role.USER) +//// .content(fullQuery) +//// .build() +//// ) +//// +//// // Send the query to the Anthropic model and get the response +//// val response = anthropic.messages().create( +//// messageParamsBuilder +//// .messages(messages) +//// .tools(tools) +//// .build() +//// ) +//// +//// val finalText = mutableListOf() +//// +//// response.content().forEach { content -> +//// when { +//// // Append text outputs from the response +//// content.isText() -> { +//// val text = content.text().getOrNull()?.text() +//// if (!text.isNullOrBlank()) { +//// finalText.add(text) +//// +//// // Save assistant response to memory +//// messages.add( +//// MessageParam.builder() +//// .role(MessageParam.Role.ASSISTANT) +//// .content(text) +//// .build() +//// ) +//// } +//// } +//// +//// // If the response indicates a tool use, process it further +//// content.isToolUse() -> { +//// val toolName = content.toolUse().get().name() +//// val toolArgs = +//// content.toolUse().get()._input().convert(object : TypeReference>() {}) +//// +//// // Call the tool with provided arguments +//// val result = mcp.callTool( +//// name = toolName, +//// arguments = toolArgs ?: emptyMap() +//// ) +//// +//// finalText.add("[Calling tool $toolName with args $toolArgs]") +//// +//// // Add the tool_result to messages +//// val toolResultContent = """ +//// { +//// "type": "tool_result", +//// "tool_name": "$toolName", +//// "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" +//// } +//// """.trimIndent() +//// +//// messages.add( +//// MessageParam.builder() +//// .role(MessageParam.Role.USER) +//// .content(toolResultContent) +//// .build() +//// ) +//// +//// // Retrieve an updated response after tool execution +//// val aiResponse = anthropic.messages().create( +//// messageParamsBuilder +//// .messages(messages) +//// .build() +//// ) +//// +//// val aiReply = aiResponse.content().firstOrNull()?.text()?.getOrNull()?.text() +//// if (!aiReply.isNullOrBlank()) { +//// finalText.add(aiReply) +//// +//// // Save assistant's new response after tool use +//// messages.add( +//// MessageParam.builder() +//// .role(MessageParam.Role.ASSISTANT) +//// .content(aiReply) +//// .build() +//// ) +//// } +//// } +//// } +//// } +//// +//// println(messages) +//// +//// return finalText.joinToString("\n", prefix = "", postfix = "") +//// } +//// +//// +//// +//// // Main chat loop for interacting with the user +//// suspend fun chatLoop() { +//// println("\n==============================================") +//// println("\nMCP Client Started!") +//// println("Type your queries or 'quit' to exit.") +//// println("\n==============================================") +//// +//// while (true) { +//// print("\nQuery: ") +//// val message = readLine() ?: break +//// if (message.lowercase() == "quit") break +//// val response = processQuery(message) +//// println("\n$response") +//// } +//// } +//// +//// override fun close() { +//// runBlocking { +//// mcp.close() +//// anthropic.close() +//// } +//// } +////} \ No newline at end of file diff --git a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt index 6d761806..dbe2a2dd 100644 --- a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt +++ b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt @@ -2,12 +2,40 @@ package io.modelcontextprotocol.sample.client import kotlinx.coroutines.runBlocking +//fun main(args: Array) = runBlocking { +// if (args.isEmpty()) throw IllegalArgumentException("Usage: java -jar /build/libs/kotlin-mcp-client-0.1.0-all.jar ") +// val serverPath = args.first() +// val client = MCPClient() +// client.use { +// client.connectToServer(serverPath) +// println("starting mcp client") +// client.chatLoop() +// } +//} + + fun main(args: Array) = runBlocking { - if (args.isEmpty()) throw IllegalArgumentException("Usage: java -jar /build/libs/kotlin-mcp-client-0.1.0-all.jar ") - val serverPath = args.first() - val client = MCPClient() - client.use { - client.connectToServer(serverPath) - client.chatLoop() + if (args.isEmpty()) { + println("Please provide the path to the MCP server script as a command-line argument.") + return@runBlocking + } + + val serverScriptPath = args[0] + MCPClient().use { client -> + try { + client.connectToServer(serverScriptPath) + client.chatLoop() + } catch (e: Exception) { + println("Error: ${e.message}") + e.printStackTrace() + } } -} \ No newline at end of file +} + + +//fun main() = runBlocking { +// val client = MCPClient() +// client.connectToServer(System.getenv("SERVER_PATH")!!) +// client.chatLoop() +//} + diff --git a/samples/kotlin-mcp-server/src/main/kotlin/resources/who_guidelines_nutritional_interventions_anc.txt b/samples/kotlin-mcp-server/src/main/kotlin/resources/who_guidelines_nutritional_interventions_anc.txt new file mode 100644 index 00000000..61b8338d --- /dev/null +++ b/samples/kotlin-mcp-server/src/main/kotlin/resources/who_guidelines_nutritional_interventions_anc.txt @@ -0,0 +1,158 @@ +A. Nutritional interventions + + +Background + + +Pregnancy requires a healthy diet that includes an adequate intake of energy, protein, vitamins and minerals to meet maternal and fetal needs. However, for many pregnant women, dietary intake of vegetables, meat, dairy products and fruit is often insufficient to meet these needs, particularly in lowand middle-income countries (LMICs) where multiple nutritional deficiencies often co-exist. In resourcepoor countries in sub-Saharan Africa, south-central and south-east Asia, maternal undernutrition is highly prevalent and is recognized as a key determinant of poor perinatal outcomes (31). However, obesity and overweight is also associated with poor pregnancy outcomes and many women in a variety of settings gain excessive weight during pregnancy. While obesity has historically been a condition associated with affluence, there is some evidence to suggest a shift in the burden of overweight and obesity from advantaged to disadvantaged populations (32). Anaemia is associated with iron, folate and vitamin A deficiencies. It is estimated to affect 38.2% of pregnant women globally, with the highest prevalence in the WHO regions of South-East Asia (48.7%) and Africa (46.3%), medium prevalence in the Eastern Mediterranean Region (38.9%) and the lowest prevalence in the WHO regions of the Western Pacific (24.3%), the Americas (24.9%) and Europe (25.8%) (33). Major contributory factors to anaemia include parasitic infections such as malaria, hookworm and schistosomiasis, in areas where these infections are endemic. In addition, chronic infections such as tuberculosis (TB) and HIV, and haemoglobinopathies such as sickle-cell disease, contribute to the prevalence of anaemia. It is estimated that 0.8 million pregnant women globally have severe anaemia (defined as a blood haemoglobin concentration < 70 g/L) (33). In pregnancy, severe anaemia is associated with an increased risk of maternal and infant mortality (34). It is estimated that about half of the anaemia found in pregnant women is amenable to iron supplementation (33); however, this may be quite variable and is likely to be much lower in malaria-endemic areas. In addition to causing anaemia, iron deficiency adversely affects the use of energy sources by muscles and, thus, physical capacity and work performance, and also adversely affects immune status and morbidity from infections (35). Folate (vitamin B9) deficiency, in addition to anaemia it is also linked to fetal neural tube defects (36). Vitamin A deficiency affects about 19 million pregnant women, mostly in Africa and South-East Asia, causing night blindness (37). Calcium deficiency is associated with an increased risk of pre-eclampsia (38), and deficiencies of other vitamins and minerals, such as vitamin E, C, B6 and zinc, have also been postulated to play a role in pre-eclampsia. Zinc deficiency is associated with impaired immunity (39). Vitamin C intake enhances iron absorption from the gut; however, zinc, iron and other mineral supplements may compete for absorption, and it is unclear whether such interactions have health consequences (39). For the ANC guideline, the GDG evaluated the evidence on various vitamin and mineral supplements that might theoretically lead to improved maternal and perinatal outcomes. In addition, as both undernourishment and overnourishment may have negative consequences for pregnant women and their babies, the GDG also evaluated evidence on the effects of various dietary interventions to reduce the impact of these conditions. Caffeine is possibly the most widely used psychoactive substance in the world (40), and the GDG also evaluated evidence on the impact, if any, of caffeine restriction during pregnancy. + + +Women’s values +A scoping review of what women want from ANC and what outcomes they value informed the ANC guideline (13). Evidence showed that women from high-, medium- and low-resource settings valued having a positive pregnancy experience, the components of which included the provision of effective clinical practices (interventions and tests, including nutritional supplements), relevant and timely information (including dietary and nutritional advice) and psychosocial and emotional support, by knowledgeable, supportive and respectful health-care practitioners, to optimize maternal and newborn health (high confidence in the evidence). + + + + +A.1: Dietary interventions + + + A1.1: Counselling on healthy eating and physical activity + + +RECOMMENDATION A.1.1: Counselling about healthy eating and keeping physically active during pregnancy is recommended for pregnant women to stay healthy and to prevent excessive weight gain during pregnancy. (Recommended) + + +Remarks • A healthy diet contains adequate energy, protein, vitamins and minerals, obtained through the consumption of a variety of foods, including green and orange vegetables, meat, fish, beans, nuts, whole grains and fruit (41). • Stakeholders may wish to consider culturally appropriate healthy eating and exercise interventions to prevent excessive weight gain in pregnancy, particularly for populations with a high prevalence of overweight and obesity, depending on resources and women’s preferences. Interventions should be woman-centred and delivered in a non-judgemental manner, and developed to ensure appropriate weight gain (see further information in points below). • A healthy lifestyle includes aerobic physical activity and strength-conditioning exercise aimed at maintaining a good level of fitness throughout pregnancy, without trying to reach peak fitness level or train for athletic competition. Women should choose activities with minimal risk of loss of balance and fetal trauma (42). • Most normal gestational weight gain occurs after 20 weeks of gestation and the definition of “normal” is subject to regional variations, but should take into consideration pre-pregnant body mass index (BMI). According to the Institute of Medicine classification (43), women who are underweight at the start of pregnancy (i.e. BMI < 18.5 kg/m2 ) should aim to gain 12.5–18 kg, women who are normal weight at the start of pregnancy (i.e. BMI 18.5–24.9 kg/m2 ) should aim to gain 11.5–16 kg, overweight women (i.e. BMI 25–29.9 kg/m2 ) should aim to gain 7–11.5 kg, and obese women(i.e. BMI > 30 kg/m2 ) should aim to gain 5–9 kg. • Most evidence on healthy eating and exercise interventions comes from high-income countries (HICs), and the GDG noted that that there are at least 40 ongoing trials in HICs in this field. The GDG noted that research is needed on the effects, feasibility and acceptability of healthy eating and exercise interventions in LMICs. • Pregnancy may be an optimal time for behaviour change interventions among populations with a high prevalence of overweight and obesity, and the longer-term impact of these interventions on women, children and partners needs investigation. • The GDG noted that a strong training package is needed for practitioners, including standardized guidance on nutrition. This guidance should be evidence-based, sustainable, reproducible, accessible and adaptable to different cultural settings. + + + + + + +Summary of evidence and considerations + + + Effects of diet and exercise interventions compared with no diet and exercise interventions (EB Table A.1.1) + + + The evidence on the effects of healthy eating and exercise interventions was derived from a Cochrane review that included 65 randomized controlled trials (RCTs), mostly conducted in HICs (44). Thirty-four trials recruited women from the general population (i.e. women of a wide range of BMIs at baseline), 24 trials recruited overweight and/or obese women and seven recruited women defined as being at high risk of gestational diabetes. In total, 49 RCTs involving 11 444 women contributed data to the review’s meta-analyses. Diet interventions were defined as a special selection of food or energy intake to which a participant was restricted, which were most commonly “healthy eating” types of diets. Exercise interventions were defined by reviewers as any activity requiring physical effort, carried out to sustain or improve health or fitness, and these were either prescribed/unsupervised (e.g. 30 minutes of daily walking), supervised (e.g. a weekly supervised group exercise class) or both. These interventions were usually compared with “standard ANC” and aimed to prevent excessive gestational weight gain (EGWG). Most trials recruited women between 10 and 20 weeks of gestation. There was substantial variation in the number of contacts (i.e. counselling/exercise sessions), type of intervention and method of delivery. Data were grouped according to the type of intervention (i.e. diet only, exercise only, diet and exercise counselling, diet and supervised exercise) and the average effects across trials were estimated using the random effects model. Separate analyses were performed according to type of intervention and the risk of weight-related complications. Most data in the overall analyses were derived from trials of combined diet and exercise interventions. Maternal outcomes High-certainty evidence shows that women receiving diet and/or exercise interventions as part of ANC to prevent EGWG are less likely to experience EGWG (24 trials, 7096 women; relative risk [RR]: 0.80, 95% confidence interval [CI]: 0.73–0.87; absolute effect of 91 fewer women with EGWG per 1000 on average). Subgroup analyses were consistent with these findings. High-certainty evidence shows that diet and/or exercise interventions have little or no effect on preeclampsia risk (15 trials, 5330 women; RR: 0.95, 95% CI: 0.77–1.16). However, moderate-certainty evidence indicates that diet and/or exercise interventions probably prevent hypertension in pregnancy (11 trials, 5162 women; RR: 0.70, 95% CI: 0.51–0.96). Low-certainty evidence suggests that diet and/or exercise interventions may have little or no effect on caesarean section (28 trials, 7534 women; RR: 0.95, 95% CI: 0.88–1.03); however, low-certainty evidence from the diet and exercise counselling subgroup of trials suggests that reductions in caesarean section rates may be possible with this intervention (9 trials, 3406 women; RR: 0.87, 95% CI: 0.75–1.01). Moderate-certainty evidence indicates that diet and/or exercise interventions probably make little or no difference to induction of labour (8 trials, 3832 women; RR: 1.06, 95% CI: 0.94–1.19). Low-certainty evidence suggests that diet and/ or exercise interventions may reduce the risk of gestational diabetes mellitus (GDM) (19 trials, 7279 women; RR: 0.82, 95% CI: 0.67–1.01). Fetal and neonatal outcomes Moderate-certainty evidence suggests that diet and/or exercise interventions probably prevent neonatal macrosomia (27 trials, 8598 women; RR: 0.93, 95% CI: 0.86–1.02), particularly in overweight and obese women receiving diet and exercise counselling interventions (9 trials, 3252 neonates; RR: 0.85, 95% CI: 0.73–1.00). However, moderatecertainty evidence indicates that diet and exercise interventions probably have little or no effect on neonatal hypoglycaemia (4 trials, 2601 neonates; RR: 0.95, 95% CI: 0.76–1.18) or shoulder dystocia (4 trials, 3253 neonates; RR: 1.02, 95% CI: 0.57–1.83). Low-certainty evidence suggests that neonatal respiratory morbidity may occur less frequently with diet and exercise counselling interventions than controls, particularly among overweight and obese women (2 studies, 2256 women; RR: 0.47, 95% CI: 0.26–0.85). Low-certainty evidence suggests that diet and/or exercise interventions may have little or no effect on preterm birth (16 trials, 5923 women; RR: 0.91, 95% CI: 0.68–1.22), and the evidence on low-birth-weight neonates is very uncertain. Perinatal mortality was not reported in the review. Chapter 3. Evidence and recommendations 17 Additional considerations n High-certainty evidence from the review also shows that low gestational weight gain is more likely to occur with these interventions (11 trials, 4422 women; RR: 1.14, CI: 1.02–1.27); the clinical relevance of this finding is not known. n The effects, acceptability and feasibility of diet and exercise interventions in LMICs has not been established. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Cost implications of diet and exercise interventions for health services are highly variable. For example, supervised diet and exercise interventions can have high associated costs, mainly due to staff costs for time spent supervising, while counselling interventions might have relatively low costs. For pregnant women, the interventions might also have resource implications in terms of transport costs, time off work and child-minding costs, particularly if the intervention requires additional antenatal visits. Equity Most of the evidence came from trials conducted in HICs. Recent studies have reported a shift in the burden of overweight and obesity from advantaged to disadvantaged populations (32). Such a trend increases the risk of associated pregnancy complications, as well as cardiometabolic problems, among pregnant women from disadvantaged populations. These risks might be further exacerbated among women in low-resource community settings, as these settings may not be equipped to deal with complications. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Therefore, these types of interventions are more likely to be acceptable if the interventions are delivered in an unhurried and supportive way, which may also facilitate better engagement with ANC services. Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility In a number of LMIC settings, providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). + + + + + + + + + + + + + + + + + + + + + + + + + + + + +A.1.2: Nutrition education on energy and protein intake + + +RECOMMENDATION A.1.2: In undernourished populations, nutrition education on increasing daily energy and protein intake is recommended for pregnant women to reduce the risk of lowbirth-weight neonates. (Context-specific recommendation) + + +Remarks • Undernourishment is usually defined by a low BMI (i.e. being underweight). For adults, a 20–39% prevalence of underweight women is considered a high prevalence of underweight and 40% or higher is considered a very high prevalence (46). Mid-upper arm circumference (MUAC) may also be useful to identify protein–energy malnutrition in individual pregnant women and to determine its prevalence in this population (31). However, the optimal cut-off points may need to be determined for individual countries based on context-specific cost–benefit analyses (31). • Anthropometric characteristics of the general population are changing, and this needs to be taken into account by regularly reassessing the prevalence of undernutrition to ensure that the intervention remains relevant. • The GDG noted that a strong training package is needed for practitioners, including standardized guidance on nutrition. This guidance should be evidence-based, sustainable, reproducible, accessible and adaptable to different cultural settings. • Stakeholders might wish to consider alternative delivery platforms (e.g. peer counsellors, media reminders) and task shifting for delivery of this intervention. • Areas that are highly food insecure or those with little access to a variety of foods may wish to consider additional complementary interventions, such as distribution of balanced protein and energy supplements (see Recommendation A.1.3). Summary of evidence and considerations Effects of nutritional education to increase energy and protein intake versus no nutritional education intervention (EB Table A.1.2) Evidence on the effects of nutritional education was derived from a Cochrane review (47). Five trials conducted between 1975 and 2013 in Bangladesh, Greece and the USA, involving 1090 pregnant women, contributed data to this comparison. Nutritional education interventions were delivered one-to-one or in group classes and included education to improve the “quality” of diet, increase energy and protein intake, or improve knowledge of the nutritional value of different foods, including energy, protein, vitamins and iron. The Bangladesh study also involved cookery demonstrations. Maternal outcomes Evidence on gestational weight gain was of very low certainty. There was no other evidence available on maternal outcomes in the review for this comparison. Fetal and neonatal outcomes Low-certainty evidence shows that antenatal dietary education may reduce low-birth-weight neonates (300 women; RR: 0.04, 95% CI: 0.01–0.14), but may have little or no effect on small-for-gestational-age (SGA) neonates (2 trials, 449 women; RR: 0.46, 95% CI: 0.21–0.98), stillbirths (1 trial, 431 women; RR: 0.37, 95% CI: 0.07–1.90) or neonatal deaths (1 trial, 448 women; RR: 1.28, 95% CI: 0.35–4.72). Evidence on preterm birth was judged to be of very low certainty. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Resource costs are variable and mainly related to staffing and counselling time. Equity In many LMICs, pregnancy outcomes and ANC coverage are worse among women who are poor, least educated and residing in rural areas (29). Many low-income countries still struggle with widespread poverty and hunger, particularly among rural populations (48). Findings from a study of antenatal food supplementation and micronutrient supplements in rural Bangladesh suggest that food supplementation interventions might be associated with better ANC adherence among women with Chapter 3. Evidence and recommendations 19 less education but not among those with more education (49). Therefore, providing antenatal food supplements could help to address inequalities by improving maternal nutritional status and increasing ANC coverage among disadvantaged women. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Therefore, these types of interventions are more likely to be acceptable if the interventions are delivered in an unhurried and supportive way, which may also facilitate better engagement with ANC services. Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility In a number of LMIC settings, providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). + + + + + + + + + + + + + + + + +A.1.3: Energy and protein dietary supplements + + +RECOMMENDATION A.1.3: In undernourished populations, balanced energy and protein dietary supplementation is recommended for pregnant women to reduce the risk of stillbirths and smallfor-gestational-age neonates. (Context-specific recommendation) + + +Remarks • The GDG stressed that this recommendation is for populations or settings with a high prevalence of undernourished pregnant women, and not for individual pregnant women identified as being undernourished. • Undernourishment is usually defined by a low BMI (i.e. being underweight). For adults, a 20–39% prevalence of underweight women is considered a high prevalence of underweight and 40% or higher is considered a very high prevalence (46). MUAC may also be useful to identify protein–energy malnutrition in individual pregnant women and to determine its prevalence in this population (31). However, the optimal cut-off points may need to be determined for individual countries based on context-specific cost– benefit analyses (31). • Establishment of a quality assurance process is important to guarantee that balanced energy and protein food supplements are manufactured, packaged and stored in a controlled and uncontaminated environment. The cost and logistical implications associated with balanced energy and protein supplements might be mitigated by local production of supplements, provided that a quality assurance process is established. • A continual, adequate supply of supplements is required for programme success. This requires a clear understanding and investment in procurement and supply chain management. • Programmes should be designed and continually improved based on locally generated data and experiences. Examples relevant to this guideline include: – Improving delivery, acceptability and utilization of this intervention by pregnant women (i.e. overcoming supply and utilization barriers). – Distribution of balanced energy and protein supplements may not be feasible only through the local schedule of ANC visits; additional visits may need to be scheduled. The costs related to these additional visits should be considered. In the absence of antenatal visits, too few visits, or when the first visit comes too late, consideration should be given to alternative platforms for delivery (e.g. community health workers, task shifting in specific settings). – Values and preferences related to the types and amounts of balanced energy and protein supplements may vary. • Monitoring and evaluation should include evaluation of household-level storage facilities, spoilage, wastage, retailing, sharing and other issues related to food distribution. • Each country will need to understand the context-specific etiology of undernutrition at the national and sub-national levels. For instance, where seasonality is a predictor of food availability, the programme should consider this and adapt to the conditions as needed (e.g. provision of more or less food of different types in different seasons). In addition, a better understanding is needed of whether alternatives to energy and protein supplements – such as cash or vouchers, or improved local and national food production and distribution – can lead to better or equivalent results. • Anthropometric characteristics of the general population are changing, and this needs to be taken into account to ensure that only those women who are likely to benefit (i.e. only undernourished women) are included. • The GDG noted that it is not known whether there are risks associated with providing this intervention to women with a high BMI. Chapter 3. Evidence and recommendations 21 Summary of evidence and considerations Effects of balanced energy and protein supplements compared with no supplements or placebo (EB Table A.1.3) Evidence on the effects of balanced energy and protein supplements compared with no supplementation or placebo was derived from a Cochrane review (47). Twelve trials, involving 6705 women, were included in this comparison. Most data were derived from trials conducted in LMICs, including Burkina Faso, Colombia, Gambia, Ghana, India, Indonesia, South Africa and Taiwan, China. The balanced energy and protein supplements used were in various forms, including fortified beverages, biscuits and powders. Maternal outcomes The only maternal outcome reported for this comparison in the review, of those outcomes prioritized for this guideline, was pre-eclampsia. However, the evidence on this outcome, based on two small trials, was assessed as very uncertain. Fetal and neonatal outcomes Moderate-certainty evidence shows that balanced energy and protein supplementation probably reduces SGA neonates (7 trials, 4408 women; RR: 0.79, 95% CI: 0.69–0.90) and stillbirths (5 trials, 3408 women; RR: 0.60, 95% CI: 0.39–0.94), but probably has no effect on preterm birth (5 trials, 3384 women; RR: 0.96, 95% CI: 0.80–1.16). Lowcertainty evidence suggests that it may have little or no effect on neonatal deaths (5 trials, 3381 women; RR: 0.68, 95% CI: 0.43–1.07). Low birth weight was not reported for this comparison in the review. Additional considerations n In the review, mean birth weight (in grams) was reported and the findings favoured the balanced energy and protein supplementation group (11 trials, 5385 neonates; mean difference [MD]: 40.96, 95% CI: 4.66–77.26). This evidence was graded as moderate-quality evidence in the review (47). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources The cost of balanced energy and protein supplements is relatively high. There may also be cost implications with respect to transport, storage and training. Equity In many LMICs, pregnancy outcomes and ANC coverage are worse among women who are poor, least educated and residing in rural areas (29). Many low-income countries still struggle with widespread poverty and hunger, particularly among rural populations (48). Findings from a study of antenatal food supplementation and micronutrient supplements in rural Bangladesh suggest that food supplementation interventions might be associated with better ANC adherence among women with less education but not among those with more education (49). Therefore, providing antenatal food supplements could help to address inequalities by improving maternal nutritional status and increasing ANC coverage among disadvantaged women. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Therefore, these types of interventions are more likely to be acceptable if the interventions are delivered in an unhurried and supportive way, which may also facilitate better engagement with ANC services. Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility Providing balanced protein and energy supplements may be associated with logistical issues, as supplements are bulky and will require adequate transport and storage facilities to ensure continual supplies. Qualitative evidence from LMIC settings indicates that providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). + + + + + + + + + + + + + + + + + + + + + + + +A.1.4: High-protein supplements + + +RECOMMENDATION A.1.4: In undernourished populations, high-protein supplementation is not recommended for pregnant women to improve maternal and perinatal outcomes. (Not recommended) + + +Remarks • The GDG noted that there is insufficient evidence on the benefits, if any, of high-protein supplementation. • Further research on the effects of high-protein supplements in undernourished populations is not considered a research priority. Summary of evidence and considerations Effects of high-protein supplementation compared with controls (EB Table A.1.4) Evidence on the effects of high-protein supplementation was derived from the same Cochrane review as for Recommendations A.1.2 and A.1.3 (47). The review included one trial of high-protein supplementation compared with a micronutrient supplement conducted in the 1970s, involving 1051 low-income, black women in the USA. Maternal outcomes None of the outcomes prioritized for this guideline were reported for this comparison in the review. Fetal and neonatal outcomes High-certainty evidence shows that high-protein supplementation increases SGA neonates (1 trial, 505 neonates; RR: 1.58, 95% CI: 1.03–2.41). Moderate-certainty evidence indicates that highprotein supplementation probably has little or no effect on preterm birth (1 study, 505 women; RR: 1.14, 95% CI: 0.83–1.56). Low-certainty evidence suggests that high-protein supplementation may have little or no effect on stillbirths (1 trial, 529 babies; RR: 0.81, 95% CI: 0.31–2.15; certainty of evidence downgraded due to imprecision) and neonatal deaths (1 trial, 529 neonates; RR: 2.78, 95% CI: 0.75–10.36). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources The cost of high-protein supplements is relatively high. There may also be cost implications with respect to transport, storage and training. Equity In many LMICs, pregnancy outcomes and ANC coverage are worse among women who are poor, least educated and residing in rural areas (29). Many low-income countries still struggle with widespread poverty and hunger, particularly among rural populations (48). Therefore, providing antenatal food supplements could help to address inequalities by improving maternal nutritional status and increasing ANC coverage among disadvantaged women. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility Providing high-protein supplements may be associated with logistical issues, as supplements are bulky and will require adequate transport and storage facilities to ensure continual supplies. Qualitative evidence from LMIC settings indicates that providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). Chapter 3. Evidence and recommendations 23 + + + + +A.2: Iron and folic acid supplements + + +A.2.1: Daily iron and folic acid supplements + + +RECOMMENDATION A.2.1: Daily oral iron and folic acid supplementation with 30 mg to 60 mg of elemental irona and 400 µg (0.4 mg) folic acidb is recommended for pregnant women to prevent maternal anaemia, puerperal sepsis, low birth weight, and preterm birth.c (Recommended) + + +Remarks • This recommendation supersedes the 2012 WHO Guideline: daily iron and folic acid supplementation in pregnant women (36) and should be considered alongside Recommendation A.2.2 on intermittent iron. • In settings where anaemia in pregnant women is a severe public health problem (i.e. where at least 40% of pregnant women have a blood haemoglobin [Hb] concentration < 110 g/L), a daily dose of 60 mg of elemental iron is preferred over a lower dose. • In the first and third trimesters, the Hb threshold for diagnosing anaemia is 110 g/L; in the second trimester, the threshold is 105 g/L (50). • If a woman is diagnosed with anaemia during pregnancy, her daily elemental iron should be increased to 120 mg until her Hb concentration rises to normal (Hb 110 g/L or higher) (34, 51). Thereafter, she can resume the standard daily antenatal iron dose to prevent recurrence of anaemia. • Effective communication with pregnant women about diet and healthy eating – including providing information about food sources of vitamins and minerals, and dietary diversity – is an integral part of preventing anaemia and providing quality ANC. • Effective communication strategies are vital for improving the acceptability of, and adherence to, supplementation schemes. • Stakeholders may need to consider ways of reminding pregnant women to take their supplements and of assisting them to manage associated side-effects. • In areas with endemic infections that may cause anaemia through blood loss, increased red cell destruction or decreased red cell production, such as malaria and hookworm, measures to prevent, diagnose and treat these infections should be implemented. • Oral supplements are available as capsules or tablets (including soluble tablets, and dissolvable and modified-release tablets) (52). Establishment of a quality assurance process is important to guarantee that supplements are manufactured, packaged and stored in a controlled and uncontaminated environment (53). • A better understanding of the etiology of anaemia (e.g. malaria endemnicity, haemoglobinopathies) and the prevalence of risk factors is needed at the country level, to inform context-specific adaptations of this recommendation. • Standardized definitions of side-effects are needed to facilitate monitoring and evaluation. • Development and improvement of integrated surveillance systems are needed to link the assessment of anaemia and iron status at the country level to national and global surveillance systems. • To reach the most vulnerable populations and ensure a timely and continuous supply of supplements, stakeholders may wish to consider task shifting the provision of iron supplementation in community settings with poor access to health-care professionals (see Recommendation E.6.1, in section E: Health systems interventions to improve the utilization and quality of ANC). a The equivalent of 60 mg of elemental iron is 300 mg of ferrous sulfate hepahydrate, 180 mg of ferrous fumarate or 500 mg of ferrous gluconate. b Folic acid should be commenced as early as possible (ideally before conception) to prevent neural tube defects. c This recommendation supersedes the previous WHO recommendation found in the 2012 Guideline: daily iron and folic acid supplementation in pregnant women (36). WHO recommendations on antenatal care for a positive pregnancy experience 24 Summary of evidence and considerations Effects of any daily iron and folic acid supplements compared with no daily iron and folic acid supplements (EB Table A.2.1) The evidence on the effects of daily iron and/or folic acid was derived from a Cochrane review of 61 trials conducted in low-, middle- and high-income countries (54). Twenty-three trials were conducted in countries with some malaria risk, of which two reported malaria outcomes. Overall, 44 trials involving 43 274 women contributed data to the review’s meta-analyses. The trials compared daily oral iron supplementation, with or without folic acid or other vitamin and mineral supplements, with various control groups (folic acid only, placebo, no intervention, other vitamin and mineral supplements without iron or folic acid). Most of the evidence was derived from studies comparing iron supplementation with no iron supplementation. In most trials, women began taking supplements before 20 weeks of gestation and continued taking supplements until delivery. The most commonly used dose of elemental iron was 60 mg daily (range: 30–240 mg) and that of folic acid was 400 µg daily. Maternal outcomes Anaemia was reported in many different ways and at different time points during pregnancy and the puerperium. Low-certainty evidence shows that daily iron supplementation may reduce the risk of anaemia at term (defined as blood Hb concentration < 110 g/L at 37 weeks of gestation or later) (14 trials, 2199 women; RR: 0.30, 95% CI: 0.19–0.46) and severe postpartum anaemia (defined as Hb < 80 g/L) (8 trials, 1339 women; RR: 0.04, 95% CI: 0.01–0.28). Low-certainty evidence also shows that daily iron supplementation may increase maternal Hb concentrations at or near term (34 weeks of gestation or more) (19 trials, 3704 women; MD: 8.88 g/L higher, 95% CI: 6.96–10.8 g/L) and may increase the proportion of women with a high maternal Hb at or near term (Hb > 130 g/L at 34 weeks of gestation or later) (8 trials, 2156 women; RR: 3.07, 95% CI: 1.18–8.02). Regarding maternal morbidity, moderate-certainty evidence shows that daily iron supplementation probably reduces the risk of maternal puerperal infections (4 trials, 4374 women; RR: 0.68, 95% CI: 0.5–0.92). Low-certainty evidence shows that daily iron supplementation may have little or no effect on pre-eclampsia (4 trials, 1704 women; RR: 1.63, 95% CI: 0.87–3.07) and antepartum haemorrhage (2 trials, 1157 women; RR: 1.48, 95% CI: 0.51–4.31), and moderate-certainty evidence shows that it probably has little or no effect on postpartum haemorrhage (4 trials, 1488 women; RR: 0.93, 95% CI: 0.59–1.49). Evidence on other morbidity outcomes, including placental abruption and blood transfusions, is of very low certainty. Low-certainty evidence shows that daily iron supplementation may have little or no effect on maternal mortality (2 trials, 12 560 women; RR: 0.33, 95% CI: 0.01–8.19). Women’s satisfaction was evaluated in one small trial (49 women), which found little difference between daily iron and control groups. Side-effects: Moderate-certainty evidence indicates that daily iron supplementation probably has little or no effect on the risk of experiencing any side-effect (11 trials, 2425 women; RR: 1.29, 95% CI: 0.83–2.02), and that it may have little or no effect on constipation (4 trials, 1495 women; RR: 0.95, 95% CI: 0.62–1.43), heartburn (3 trials, 1323 women; RR: 1.19, 95% CI: 0.86–1.66) and vomiting (4 trials, 1392 women; RR: 0.88, 95% CI: 0.59–1.30). Evidence that daily iron has little or no effect on nausea is of low certainty (4 trials, 1377 women; RR: 1.21, 95% CI: 0.72–2.03). High-certainty evidence shows that diarrhoea is less common with daily iron supplements (3 trials, 1088 women; RR: 0.55, 95% CI: 0.32–0.93). Fetal and neonatal outcomes Low-certainty evidence shows that daily iron may reduce the risk of low-birth-weight neonates (< 2500 g) (11 trials, 17 613 neonates; RR: 0.84, 95% CI: 0.69–1.03). High-certainty evidence shows that it does not reduce the risk of preterm birth before 37 weeks of gestation (13 trials, 19 286 women; RR: 0.93, 95% CI: 0.84–1.03), but it does reduce the risk of very preterm birth (i.e. less than 34 weeks of gestation) (5 trials, 3749 women; RR: 0.51, 95% CI: 0.29–0.91). Low-certainty evidence suggests that daily iron may have little or no effect on congenital anomalies (4 trials, 14 636 neonates; RR: 0.88, 95% CI: 0.58–1.33). Moderate-certainty evidence indicates that daily iron probably has little or no effect on neonatal deaths (4 trials, 16 603 neonates; RR: 0.91, 95% CI: 0.71–1.18). Neonatal infections and SGA were not reviewed as outcomes + + + + + + +Additional considerations n Evidence from subgroups tended to be consistent with the overall findings for the main outcomes. More details can be found in the Web supplement (EB Table A.2.1). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Daily iron and folic acid supplements are relatively low cost, at less than 1 United States dollar (US$ 1) per pregnant woman (27). Equity Iron deficiency and parasitic infections are more common in LMICs and disadvantaged populations. Poor, rural and least-educated populations also experience the highest maternal, infant and child mortality (29). Increasing coverage of effective nutritional interventions to prevent anaemia, particularly among disadvantaged populations, might help to address maternal and newborn health inequalities. Acceptability Qualitative evidence suggests that the availability of iron supplements may actively encourage women to engage with ANC providers (low confidence in the evidence) (22). However, where there are additional costs associated with supplementation or where the supplements may be unavailable (because of resource constraints) women are less likely to engage with ANC services (high confidence in the evidence). Lower doses of iron may be associated with fewer side-effects and therefore may be more acceptable to women than higher doses. Feasibility Qualitative evidence about the views of health-care providers suggests that resource constraints, both in terms of the availability of the supplements and the lack of suitably trained staff to deliver them, may limit implementation (high confidence in the evidence) (45). a The equivalent of 120 mg of elemental iron is 600 mg of ferrous sulfate hepahydrate, 360 mg of ferrous fumarate or 1000 mg of ferrous gluconate. + + + + + A.2.2: Intermittent iron and folic acid supplements + + +RECOMMENDATION A.2.2: Intermittent oral iron and folic acid supplementation with 120 mg of elemental irona and 2800 µg (2.8 mg) of folic acid once weekly is recommended for pregnant women to improve maternal and neonatal outcomes if daily iron is not acceptable due to sideeffects, and in populations with an anaemia prevalence among pregnant women of less than 20%. (Context-specific recommendation) + + +Remarks • This recommendation supersedes the previous WHO recommendation in the 2012 Guideline: intermittent iron and folic acid supplementation in non-anaemic pregnant women (55) and should be considered alongside Recommendation A.1.1. • In general, anaemia prevalence of less than 20% is classified as a mild public health problem (33). • Before commencing intermittent iron supplementation, accurate measurement of maternal blood Hb concentrations is needed to confirm the absence of anaemia. Therefore, this recommendation may require a strong health system to facilitate accurate Hb measurement and to monitor anaemia status throughout pregnancy. • If a woman is diagnosed with anaemia (Hb < 110 g/L) during ANC, she should be given 120 mg of elemental iron and 400 µg (0.4 mg) of folic acid daily until her Hb concentration rises to normal (Hb 110 g/L or higher) (34, 51). Thereafter, she can continue with the standard daily antenatal iron and folic acid dose (or the intermittent regimen if daily iron is not acceptable due to side-effects) to prevent recurrence of anaemia. • Stakeholders may need to consider ways of reminding pregnant women to take their supplements on an intermittent basis and of assisting them to manage associated side-effects. WHO recommendations on antenatal care for a positive pregnancy experience 26 Summary of evidence and considerations Effects of intermittent iron and folic acid supplements compared with daily iron and folic acid supplements (EB Table A.2.2) The evidence on the effects of intermittent iron and folic acid was derived from a Cochrane review that included 27 trials from 15 countries; however, only 21 trials (involving 5490 women) contributed data to the review’s meta-analyses (56). All trials were conducted in LMICs with some degree of malaria risk (Argentina, Bangladesh, China, Guatemala, India, Indonesia, the Islamic Republic of Iran, Malawi, Malaysia, Mexico, Pakistan, Republic of Korea, Sri Lanka, Thailand and Viet Nam); however, only one trial specifically reported that it was conducted in a malaria-endemic area. Most of the intermittent iron regimens involved women taking weekly supplements, most commonly 120 mg elemental iron per week (range: 80–200 mg weekly), which was compared with daily regimens, most commonly 60 mg elemental iron daily (range: 40–120 mg daily). Where folic acid was also provided in the trials, it was administered weekly in the intermittent supplement groups (range: 400– 3500 µg weekly) compared with the usual standard daily dose for control groups. Maternal outcomes Anaemia was reported in different ways across trials. Low-certainty evidence suggests there may be little or no difference between intermittent and daily iron supplementation in the effect on anaemia at term (4 trials, 676 women; RR: 1.22, 95% CI: 0.84–1.80). Moderate-certainty evidence shows that anaemia at or near term (defined as a Hb of < 110 g/L at 34 weeks of gestation or later) probably occurs more frequently with intermittent than daily iron supplementation (8 trials, 1385 women; RR: 1.66, 95% CI: 1.09–2.53), and that intermittent iron supplementation is probably less likely to be associated with a Hb concentration of more than 130 g/L than daily iron (15 trials, 2616 women; RR: 0.53, 95% CI: 0.38–0.74). No events of severe anaemia occurred in either group in six trials reporting this outcome (1240 women). The evidence on mean Hb concentrations at or near term and severe postpartum anaemia is of very low certainty. Limited evidence on maternal morbidity from one small trial (110 women) was assessed as very uncertain. Maternal infections and maternal satisfaction were not evaluated in the review. Side-effects: Moderate-certainty evidence shows that intermittent iron supplementation is probably less commonly associated with nausea than daily iron supplementation (7 trials, 1034 women; RR: 0.60, 95% CI: 0.37–0.97). However, the evidence on other specific side-effects (constipation, diarrhoea, heartburn or vomiting) or any side-effect is of very low certainty. Fetal and neonatal outcomes Low-certainty evidence suggests that intermittent iron supplementation may have a similar effect to daily iron supplementation on low birth weight (< 2500 g) (8 trials, 1898 neonates; RR: 0.82, 95% CI: 0.50–1.22). However, the evidence on preterm birth and very preterm birth was assessed as very uncertain. Evidence on the relative effects of intermittent versus daily iron supplementation on neonatal mortality is also very uncertain. Neonatal infections and SGA outcomes were not included in the review. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Intermittent iron and folic acid supplementation might cost a little less than daily iron and folic acid supplementation due to the lower total weekly dose of iron. Equity Intermittent iron and folic acid supplementation may have less impact on health inequalities than daily iron and folic acid supplementation, as anaemia is more common in disadvantaged populations. Acceptability Qualitative evidence suggests that the availability of iron supplements may actively encourage women to engage with ANC providers (low confidence in the evidence) (22). However, where there are additional costs associated with supplementation or where the supplements may be unavailable (because of resource constraints) women are less likely to engage with ANC services (high confidence in the evidence). Women may find intermittent iron supplementation more acceptable than daily iron supplementation, particularly if they experience side-effects with daily iron supplements. Feasibility Intermittent iron may be more feasible in some lowresource settings if it costs less than daily iron. \ No newline at end of file diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt index 18fb37ad..0875b9f6 100644 --- a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt @@ -1,3 +1,7 @@ + + + + package io.modelcontextprotocol.sample.server import io.ktor.client.* @@ -16,6 +20,8 @@ import kotlinx.io.asSink import kotlinx.io.buffered import kotlinx.serialization.json.* +import java.io.File + // Main function to run the MCP server fun `run mcp server`() { // Base URL for the Weather API @@ -47,10 +53,17 @@ fun `run mcp server`() { version = "1.0.0" // Version of the implementation ), ServerOptions( - capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(listChanged = true)) + capabilities = ServerCapabilities( + tools = ServerCapabilities.Tools(listChanged = true), + resources = ServerCapabilities.Resources( subscribe = true,listChanged = true) + ) ) ) + + + + // Register a tool to fetch weather alerts by state server.addTool( name = "get_alerts", @@ -110,6 +123,76 @@ fun `run mcp server`() { CallToolResult(content = forecast.map { TextContent(it) }) } + + + + +// val textFilePath = "/C://Users//developer//Downloads//kotlin-sdk//samples//weather-stdio-server//src//main//kotlin//io//modelcontextprotocol//sample//server//resources//who_guidelines_nutritional_interventions_anc.txt" +// val resourceFolderPath = "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources" +// val resourceDir = File(resourceFolderPath) +// +// if(!resourceDir.exists() || !resourceDir.isDirectory){ +// throw RuntimeException("Resource directory not found: $resourceFolderPath") +// } +// +// resourceDir.listFiles{ file -> file.extension == "txt"}?.forEach{file -> +// val name = file.nameWithoutExtension.replace('_',' ').replaceFirstChar{it.uppercase()} +// val uri = "file://${file.absolutePath.replace("\\","/")}" +// val description = "Guideline section: $name" +// +// server.addResource( +// uri = uri, +// name = name, +// description = description, +// mimeType = "text/plain" +// ){ +// request -> +// val content = file.readText() +// println("content: ${content}") +// println("Serving resource: $name") +// ReadResourceResult( +// contents = listOf( +// TextResourceContents( +// text = content, +// uri = request.uri, +// mimeType = "text/plain" +// ) +// ) +// ) +// +// +// } +// } + +// +// val textFilePath = "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources\\who_guidelines_nutritional_interventions_anc.txt" +// val textFile = File(textFilePath) +// val resourceUri = "file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt" +// // Handle resources/list request +// server.addResource( +// uri = resourceUri, +// name = "WHO Nutritional Interventions Guidelines", +// description = "WHO guidelines on nutritional interventions for antenatal care", +// mimeType = "text/plain" +// ) { request -> +// if (!textFile.exists()) { +// throw RuntimeException("Resource file not found: $textFilePath") +// } +// val content = textFile.readText() +// println("content: ${content}") +// ReadResourceResult( +// contents = listOf( +// TextResourceContents( +// text = content, +// uri = request.uri, +// mimeType = "text/plain" +// ) +// ) +// ) +// } + + + // Create a transport using standard IO for server communication val transport = StdioServerTransport( System.`in`.asInput(), @@ -125,3 +208,6 @@ fun `run mcp server`() { done.join() } } + + + diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt new file mode 100644 index 00000000..a69ad967 --- /dev/null +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt @@ -0,0 +1 @@ +sjcweifjceefekfkekfpewlfpewfdlk \ No newline at end of file diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Zinc_supplements.txt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Zinc_supplements.txt new file mode 100644 index 00000000..0ca524f6 --- /dev/null +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Zinc_supplements.txt @@ -0,0 +1,7 @@ +A.5: Zinc supplements + + +RECOMMENDATION A.5: Zinc supplementation for pregnant women is only recommended in the context of rigorous research. (Context-specific recommendation – research) + + +Remarks • Many of the included studies were at risk of bias, which influenced the certainty of the review evidence on the effects of zinc supplementation. • The low-certainty evidence that zinc supplementation may reduce preterm birth warrants further investigation, as do the other outcomes for which the evidence is very uncertain (e.g. perinatal mortality, neonatal sepsis), particularly in zinc-deficient populations with no food fortification strategy in place. Further research should aim to clarify to what extent zinc supplementation competes with iron and/or calcium antenatal supplements for absorption. The GDG considered that food fortification may be a more cost–effective strategy and that more evidence is needed on the cost–effectiveness of food fortification strategies. Summary of evidence and considerations Effects of zinc supplements compared with no zinc supplements (EB Table A.5) The evidence was derived from a Cochrane review that included 21 trials involving more than 17 000 women (64). Most studies were conducted in LMICs, including Bangladesh, Chile, China, Egypt, Ghana, Indonesia, the Islamic Republic of Iran, Nepal, Pakistan, Peru and South Africa. Six trials were conducted in Denmark, the United Kingdom and the USA. Daily zinc supplementation was compared with no intervention or placebo. There was a wide variation among trials in terms of trial size (range: 56–4926 women), zinc dosage (range: 5–90 mg per day), nutritional and zinc status at trial entry, initiation and duration of supplementation (starting before conception in one trial, first or second trimester in the majority, or after 26 weeks of gestation in two trials, until delivery), and compliance with treatment. Maternal outcomes Moderate-certainty evidence indicates that zinc supplementation probably makes little or no difference to the risk of any maternal infections (3 trials, 1185 women; RR: 1.06; 95% CI: 0.74–1.53). The evidence on caesarean section, pre-eclampsia and side effects (maternal taste and smell dysfunction) is of very low certainty, and the review did not include anaemia, maternal mortality or maternal satisfaction as review outcomes. Fetal and neonatal outcomes Moderate-certainty evidence indicates that zinc supplementation probably makes little or no difference to the risk of having SGA (8 trials, 4252 newborns; RR: 1.02; 95% CI: 0.94–1.11) or low-birth weight neonates (14 trials, 5643 neonates; RR: 0.93, 95% CI: 0.78–1.12). However, low-certainty evidence suggests that zinc supplementation may reduce preterm birth (16 trials, 7637 women; RR: 0.86, 95% CI: 0.76–0.97), particularly in women with presumed low zinc intake or poor nutrition (14 trials, 7099 women; RR: 0.87, 95% CI: 0.77–0.98). Low-certainty evidence suggests that zinc sup ple ment ation may have little or no effect on congenital anomalies (6 trials, 1240 newborns; RR: 0.67, 95% CI: 0.33–1.34) and macrosomia (defined in the review as “high birth weight”; 5 trials, 2837 neonates; RR: 1.00, 95% CI: 0.84–1.18). Evidence on perinatal mortality and neonatal sepsis is of very low certainty. Additional considerations The trials were clinically heterogeneous, therefore it is unclear what dose and timing of zinc supplementation, if any, might lead to a possible reduction in preterm birth. There is little or no evidence on side effects of zinc supplementation. In addition, it is unclear to what extent zinc might compete with iron and/or calcium for absorption. Maternal anaemia was not evaluated in the review. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Zinc costs approximately US$ 1.30 for 100 tablets of 20 mg (i.e. less than US$ 3.00 for a 6-month supply based on a daily dose of 20 mg) (27). Chapter 3. Evidence and recommendations 31 Equity Effective interventions to improve maternal nutrition in disadvantaged populations could help to address health inequalities. A WHO report shows that inequalities in neonatal, infant and child mortality, as well as stunting prevalence, can be demonstrated according to economic status, education and place of residence in LMICs. The prevalence of stunting may be a good indicator of zinc deficiency in LMICs (39). Acceptability Qualitative evidence suggests that women in a variety of settings tend to view ANC as a source of knowledge and information and they generally appreciate any professional advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). Feasibility It may be more feasible to fortify food with zinc rather than to provide zinc as a single supplement, particularly in settings with a high prevalence of stunting in children \ No newline at end of file diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt new file mode 100644 index 00000000..61b8338d --- /dev/null +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt @@ -0,0 +1,158 @@ +A. Nutritional interventions + + +Background + + +Pregnancy requires a healthy diet that includes an adequate intake of energy, protein, vitamins and minerals to meet maternal and fetal needs. However, for many pregnant women, dietary intake of vegetables, meat, dairy products and fruit is often insufficient to meet these needs, particularly in lowand middle-income countries (LMICs) where multiple nutritional deficiencies often co-exist. In resourcepoor countries in sub-Saharan Africa, south-central and south-east Asia, maternal undernutrition is highly prevalent and is recognized as a key determinant of poor perinatal outcomes (31). However, obesity and overweight is also associated with poor pregnancy outcomes and many women in a variety of settings gain excessive weight during pregnancy. While obesity has historically been a condition associated with affluence, there is some evidence to suggest a shift in the burden of overweight and obesity from advantaged to disadvantaged populations (32). Anaemia is associated with iron, folate and vitamin A deficiencies. It is estimated to affect 38.2% of pregnant women globally, with the highest prevalence in the WHO regions of South-East Asia (48.7%) and Africa (46.3%), medium prevalence in the Eastern Mediterranean Region (38.9%) and the lowest prevalence in the WHO regions of the Western Pacific (24.3%), the Americas (24.9%) and Europe (25.8%) (33). Major contributory factors to anaemia include parasitic infections such as malaria, hookworm and schistosomiasis, in areas where these infections are endemic. In addition, chronic infections such as tuberculosis (TB) and HIV, and haemoglobinopathies such as sickle-cell disease, contribute to the prevalence of anaemia. It is estimated that 0.8 million pregnant women globally have severe anaemia (defined as a blood haemoglobin concentration < 70 g/L) (33). In pregnancy, severe anaemia is associated with an increased risk of maternal and infant mortality (34). It is estimated that about half of the anaemia found in pregnant women is amenable to iron supplementation (33); however, this may be quite variable and is likely to be much lower in malaria-endemic areas. In addition to causing anaemia, iron deficiency adversely affects the use of energy sources by muscles and, thus, physical capacity and work performance, and also adversely affects immune status and morbidity from infections (35). Folate (vitamin B9) deficiency, in addition to anaemia it is also linked to fetal neural tube defects (36). Vitamin A deficiency affects about 19 million pregnant women, mostly in Africa and South-East Asia, causing night blindness (37). Calcium deficiency is associated with an increased risk of pre-eclampsia (38), and deficiencies of other vitamins and minerals, such as vitamin E, C, B6 and zinc, have also been postulated to play a role in pre-eclampsia. Zinc deficiency is associated with impaired immunity (39). Vitamin C intake enhances iron absorption from the gut; however, zinc, iron and other mineral supplements may compete for absorption, and it is unclear whether such interactions have health consequences (39). For the ANC guideline, the GDG evaluated the evidence on various vitamin and mineral supplements that might theoretically lead to improved maternal and perinatal outcomes. In addition, as both undernourishment and overnourishment may have negative consequences for pregnant women and their babies, the GDG also evaluated evidence on the effects of various dietary interventions to reduce the impact of these conditions. Caffeine is possibly the most widely used psychoactive substance in the world (40), and the GDG also evaluated evidence on the impact, if any, of caffeine restriction during pregnancy. + + +Women’s values +A scoping review of what women want from ANC and what outcomes they value informed the ANC guideline (13). Evidence showed that women from high-, medium- and low-resource settings valued having a positive pregnancy experience, the components of which included the provision of effective clinical practices (interventions and tests, including nutritional supplements), relevant and timely information (including dietary and nutritional advice) and psychosocial and emotional support, by knowledgeable, supportive and respectful health-care practitioners, to optimize maternal and newborn health (high confidence in the evidence). + + + + +A.1: Dietary interventions + + + A1.1: Counselling on healthy eating and physical activity + + +RECOMMENDATION A.1.1: Counselling about healthy eating and keeping physically active during pregnancy is recommended for pregnant women to stay healthy and to prevent excessive weight gain during pregnancy. (Recommended) + + +Remarks • A healthy diet contains adequate energy, protein, vitamins and minerals, obtained through the consumption of a variety of foods, including green and orange vegetables, meat, fish, beans, nuts, whole grains and fruit (41). • Stakeholders may wish to consider culturally appropriate healthy eating and exercise interventions to prevent excessive weight gain in pregnancy, particularly for populations with a high prevalence of overweight and obesity, depending on resources and women’s preferences. Interventions should be woman-centred and delivered in a non-judgemental manner, and developed to ensure appropriate weight gain (see further information in points below). • A healthy lifestyle includes aerobic physical activity and strength-conditioning exercise aimed at maintaining a good level of fitness throughout pregnancy, without trying to reach peak fitness level or train for athletic competition. Women should choose activities with minimal risk of loss of balance and fetal trauma (42). • Most normal gestational weight gain occurs after 20 weeks of gestation and the definition of “normal” is subject to regional variations, but should take into consideration pre-pregnant body mass index (BMI). According to the Institute of Medicine classification (43), women who are underweight at the start of pregnancy (i.e. BMI < 18.5 kg/m2 ) should aim to gain 12.5–18 kg, women who are normal weight at the start of pregnancy (i.e. BMI 18.5–24.9 kg/m2 ) should aim to gain 11.5–16 kg, overweight women (i.e. BMI 25–29.9 kg/m2 ) should aim to gain 7–11.5 kg, and obese women(i.e. BMI > 30 kg/m2 ) should aim to gain 5–9 kg. • Most evidence on healthy eating and exercise interventions comes from high-income countries (HICs), and the GDG noted that that there are at least 40 ongoing trials in HICs in this field. The GDG noted that research is needed on the effects, feasibility and acceptability of healthy eating and exercise interventions in LMICs. • Pregnancy may be an optimal time for behaviour change interventions among populations with a high prevalence of overweight and obesity, and the longer-term impact of these interventions on women, children and partners needs investigation. • The GDG noted that a strong training package is needed for practitioners, including standardized guidance on nutrition. This guidance should be evidence-based, sustainable, reproducible, accessible and adaptable to different cultural settings. + + + + + + +Summary of evidence and considerations + + + Effects of diet and exercise interventions compared with no diet and exercise interventions (EB Table A.1.1) + + + The evidence on the effects of healthy eating and exercise interventions was derived from a Cochrane review that included 65 randomized controlled trials (RCTs), mostly conducted in HICs (44). Thirty-four trials recruited women from the general population (i.e. women of a wide range of BMIs at baseline), 24 trials recruited overweight and/or obese women and seven recruited women defined as being at high risk of gestational diabetes. In total, 49 RCTs involving 11 444 women contributed data to the review’s meta-analyses. Diet interventions were defined as a special selection of food or energy intake to which a participant was restricted, which were most commonly “healthy eating” types of diets. Exercise interventions were defined by reviewers as any activity requiring physical effort, carried out to sustain or improve health or fitness, and these were either prescribed/unsupervised (e.g. 30 minutes of daily walking), supervised (e.g. a weekly supervised group exercise class) or both. These interventions were usually compared with “standard ANC” and aimed to prevent excessive gestational weight gain (EGWG). Most trials recruited women between 10 and 20 weeks of gestation. There was substantial variation in the number of contacts (i.e. counselling/exercise sessions), type of intervention and method of delivery. Data were grouped according to the type of intervention (i.e. diet only, exercise only, diet and exercise counselling, diet and supervised exercise) and the average effects across trials were estimated using the random effects model. Separate analyses were performed according to type of intervention and the risk of weight-related complications. Most data in the overall analyses were derived from trials of combined diet and exercise interventions. Maternal outcomes High-certainty evidence shows that women receiving diet and/or exercise interventions as part of ANC to prevent EGWG are less likely to experience EGWG (24 trials, 7096 women; relative risk [RR]: 0.80, 95% confidence interval [CI]: 0.73–0.87; absolute effect of 91 fewer women with EGWG per 1000 on average). Subgroup analyses were consistent with these findings. High-certainty evidence shows that diet and/or exercise interventions have little or no effect on preeclampsia risk (15 trials, 5330 women; RR: 0.95, 95% CI: 0.77–1.16). However, moderate-certainty evidence indicates that diet and/or exercise interventions probably prevent hypertension in pregnancy (11 trials, 5162 women; RR: 0.70, 95% CI: 0.51–0.96). Low-certainty evidence suggests that diet and/or exercise interventions may have little or no effect on caesarean section (28 trials, 7534 women; RR: 0.95, 95% CI: 0.88–1.03); however, low-certainty evidence from the diet and exercise counselling subgroup of trials suggests that reductions in caesarean section rates may be possible with this intervention (9 trials, 3406 women; RR: 0.87, 95% CI: 0.75–1.01). Moderate-certainty evidence indicates that diet and/or exercise interventions probably make little or no difference to induction of labour (8 trials, 3832 women; RR: 1.06, 95% CI: 0.94–1.19). Low-certainty evidence suggests that diet and/ or exercise interventions may reduce the risk of gestational diabetes mellitus (GDM) (19 trials, 7279 women; RR: 0.82, 95% CI: 0.67–1.01). Fetal and neonatal outcomes Moderate-certainty evidence suggests that diet and/or exercise interventions probably prevent neonatal macrosomia (27 trials, 8598 women; RR: 0.93, 95% CI: 0.86–1.02), particularly in overweight and obese women receiving diet and exercise counselling interventions (9 trials, 3252 neonates; RR: 0.85, 95% CI: 0.73–1.00). However, moderatecertainty evidence indicates that diet and exercise interventions probably have little or no effect on neonatal hypoglycaemia (4 trials, 2601 neonates; RR: 0.95, 95% CI: 0.76–1.18) or shoulder dystocia (4 trials, 3253 neonates; RR: 1.02, 95% CI: 0.57–1.83). Low-certainty evidence suggests that neonatal respiratory morbidity may occur less frequently with diet and exercise counselling interventions than controls, particularly among overweight and obese women (2 studies, 2256 women; RR: 0.47, 95% CI: 0.26–0.85). Low-certainty evidence suggests that diet and/or exercise interventions may have little or no effect on preterm birth (16 trials, 5923 women; RR: 0.91, 95% CI: 0.68–1.22), and the evidence on low-birth-weight neonates is very uncertain. Perinatal mortality was not reported in the review. Chapter 3. Evidence and recommendations 17 Additional considerations n High-certainty evidence from the review also shows that low gestational weight gain is more likely to occur with these interventions (11 trials, 4422 women; RR: 1.14, CI: 1.02–1.27); the clinical relevance of this finding is not known. n The effects, acceptability and feasibility of diet and exercise interventions in LMICs has not been established. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Cost implications of diet and exercise interventions for health services are highly variable. For example, supervised diet and exercise interventions can have high associated costs, mainly due to staff costs for time spent supervising, while counselling interventions might have relatively low costs. For pregnant women, the interventions might also have resource implications in terms of transport costs, time off work and child-minding costs, particularly if the intervention requires additional antenatal visits. Equity Most of the evidence came from trials conducted in HICs. Recent studies have reported a shift in the burden of overweight and obesity from advantaged to disadvantaged populations (32). Such a trend increases the risk of associated pregnancy complications, as well as cardiometabolic problems, among pregnant women from disadvantaged populations. These risks might be further exacerbated among women in low-resource community settings, as these settings may not be equipped to deal with complications. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Therefore, these types of interventions are more likely to be acceptable if the interventions are delivered in an unhurried and supportive way, which may also facilitate better engagement with ANC services. Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility In a number of LMIC settings, providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). + + + + + + + + + + + + + + + + + + + + + + + + + + + + +A.1.2: Nutrition education on energy and protein intake + + +RECOMMENDATION A.1.2: In undernourished populations, nutrition education on increasing daily energy and protein intake is recommended for pregnant women to reduce the risk of lowbirth-weight neonates. (Context-specific recommendation) + + +Remarks • Undernourishment is usually defined by a low BMI (i.e. being underweight). For adults, a 20–39% prevalence of underweight women is considered a high prevalence of underweight and 40% or higher is considered a very high prevalence (46). Mid-upper arm circumference (MUAC) may also be useful to identify protein–energy malnutrition in individual pregnant women and to determine its prevalence in this population (31). However, the optimal cut-off points may need to be determined for individual countries based on context-specific cost–benefit analyses (31). • Anthropometric characteristics of the general population are changing, and this needs to be taken into account by regularly reassessing the prevalence of undernutrition to ensure that the intervention remains relevant. • The GDG noted that a strong training package is needed for practitioners, including standardized guidance on nutrition. This guidance should be evidence-based, sustainable, reproducible, accessible and adaptable to different cultural settings. • Stakeholders might wish to consider alternative delivery platforms (e.g. peer counsellors, media reminders) and task shifting for delivery of this intervention. • Areas that are highly food insecure or those with little access to a variety of foods may wish to consider additional complementary interventions, such as distribution of balanced protein and energy supplements (see Recommendation A.1.3). Summary of evidence and considerations Effects of nutritional education to increase energy and protein intake versus no nutritional education intervention (EB Table A.1.2) Evidence on the effects of nutritional education was derived from a Cochrane review (47). Five trials conducted between 1975 and 2013 in Bangladesh, Greece and the USA, involving 1090 pregnant women, contributed data to this comparison. Nutritional education interventions were delivered one-to-one or in group classes and included education to improve the “quality” of diet, increase energy and protein intake, or improve knowledge of the nutritional value of different foods, including energy, protein, vitamins and iron. The Bangladesh study also involved cookery demonstrations. Maternal outcomes Evidence on gestational weight gain was of very low certainty. There was no other evidence available on maternal outcomes in the review for this comparison. Fetal and neonatal outcomes Low-certainty evidence shows that antenatal dietary education may reduce low-birth-weight neonates (300 women; RR: 0.04, 95% CI: 0.01–0.14), but may have little or no effect on small-for-gestational-age (SGA) neonates (2 trials, 449 women; RR: 0.46, 95% CI: 0.21–0.98), stillbirths (1 trial, 431 women; RR: 0.37, 95% CI: 0.07–1.90) or neonatal deaths (1 trial, 448 women; RR: 1.28, 95% CI: 0.35–4.72). Evidence on preterm birth was judged to be of very low certainty. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Resource costs are variable and mainly related to staffing and counselling time. Equity In many LMICs, pregnancy outcomes and ANC coverage are worse among women who are poor, least educated and residing in rural areas (29). Many low-income countries still struggle with widespread poverty and hunger, particularly among rural populations (48). Findings from a study of antenatal food supplementation and micronutrient supplements in rural Bangladesh suggest that food supplementation interventions might be associated with better ANC adherence among women with Chapter 3. Evidence and recommendations 19 less education but not among those with more education (49). Therefore, providing antenatal food supplements could help to address inequalities by improving maternal nutritional status and increasing ANC coverage among disadvantaged women. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Therefore, these types of interventions are more likely to be acceptable if the interventions are delivered in an unhurried and supportive way, which may also facilitate better engagement with ANC services. Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility In a number of LMIC settings, providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). + + + + + + + + + + + + + + + + +A.1.3: Energy and protein dietary supplements + + +RECOMMENDATION A.1.3: In undernourished populations, balanced energy and protein dietary supplementation is recommended for pregnant women to reduce the risk of stillbirths and smallfor-gestational-age neonates. (Context-specific recommendation) + + +Remarks • The GDG stressed that this recommendation is for populations or settings with a high prevalence of undernourished pregnant women, and not for individual pregnant women identified as being undernourished. • Undernourishment is usually defined by a low BMI (i.e. being underweight). For adults, a 20–39% prevalence of underweight women is considered a high prevalence of underweight and 40% or higher is considered a very high prevalence (46). MUAC may also be useful to identify protein–energy malnutrition in individual pregnant women and to determine its prevalence in this population (31). However, the optimal cut-off points may need to be determined for individual countries based on context-specific cost– benefit analyses (31). • Establishment of a quality assurance process is important to guarantee that balanced energy and protein food supplements are manufactured, packaged and stored in a controlled and uncontaminated environment. The cost and logistical implications associated with balanced energy and protein supplements might be mitigated by local production of supplements, provided that a quality assurance process is established. • A continual, adequate supply of supplements is required for programme success. This requires a clear understanding and investment in procurement and supply chain management. • Programmes should be designed and continually improved based on locally generated data and experiences. Examples relevant to this guideline include: – Improving delivery, acceptability and utilization of this intervention by pregnant women (i.e. overcoming supply and utilization barriers). – Distribution of balanced energy and protein supplements may not be feasible only through the local schedule of ANC visits; additional visits may need to be scheduled. The costs related to these additional visits should be considered. In the absence of antenatal visits, too few visits, or when the first visit comes too late, consideration should be given to alternative platforms for delivery (e.g. community health workers, task shifting in specific settings). – Values and preferences related to the types and amounts of balanced energy and protein supplements may vary. • Monitoring and evaluation should include evaluation of household-level storage facilities, spoilage, wastage, retailing, sharing and other issues related to food distribution. • Each country will need to understand the context-specific etiology of undernutrition at the national and sub-national levels. For instance, where seasonality is a predictor of food availability, the programme should consider this and adapt to the conditions as needed (e.g. provision of more or less food of different types in different seasons). In addition, a better understanding is needed of whether alternatives to energy and protein supplements – such as cash or vouchers, or improved local and national food production and distribution – can lead to better or equivalent results. • Anthropometric characteristics of the general population are changing, and this needs to be taken into account to ensure that only those women who are likely to benefit (i.e. only undernourished women) are included. • The GDG noted that it is not known whether there are risks associated with providing this intervention to women with a high BMI. Chapter 3. Evidence and recommendations 21 Summary of evidence and considerations Effects of balanced energy and protein supplements compared with no supplements or placebo (EB Table A.1.3) Evidence on the effects of balanced energy and protein supplements compared with no supplementation or placebo was derived from a Cochrane review (47). Twelve trials, involving 6705 women, were included in this comparison. Most data were derived from trials conducted in LMICs, including Burkina Faso, Colombia, Gambia, Ghana, India, Indonesia, South Africa and Taiwan, China. The balanced energy and protein supplements used were in various forms, including fortified beverages, biscuits and powders. Maternal outcomes The only maternal outcome reported for this comparison in the review, of those outcomes prioritized for this guideline, was pre-eclampsia. However, the evidence on this outcome, based on two small trials, was assessed as very uncertain. Fetal and neonatal outcomes Moderate-certainty evidence shows that balanced energy and protein supplementation probably reduces SGA neonates (7 trials, 4408 women; RR: 0.79, 95% CI: 0.69–0.90) and stillbirths (5 trials, 3408 women; RR: 0.60, 95% CI: 0.39–0.94), but probably has no effect on preterm birth (5 trials, 3384 women; RR: 0.96, 95% CI: 0.80–1.16). Lowcertainty evidence suggests that it may have little or no effect on neonatal deaths (5 trials, 3381 women; RR: 0.68, 95% CI: 0.43–1.07). Low birth weight was not reported for this comparison in the review. Additional considerations n In the review, mean birth weight (in grams) was reported and the findings favoured the balanced energy and protein supplementation group (11 trials, 5385 neonates; mean difference [MD]: 40.96, 95% CI: 4.66–77.26). This evidence was graded as moderate-quality evidence in the review (47). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources The cost of balanced energy and protein supplements is relatively high. There may also be cost implications with respect to transport, storage and training. Equity In many LMICs, pregnancy outcomes and ANC coverage are worse among women who are poor, least educated and residing in rural areas (29). Many low-income countries still struggle with widespread poverty and hunger, particularly among rural populations (48). Findings from a study of antenatal food supplementation and micronutrient supplements in rural Bangladesh suggest that food supplementation interventions might be associated with better ANC adherence among women with less education but not among those with more education (49). Therefore, providing antenatal food supplements could help to address inequalities by improving maternal nutritional status and increasing ANC coverage among disadvantaged women. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Therefore, these types of interventions are more likely to be acceptable if the interventions are delivered in an unhurried and supportive way, which may also facilitate better engagement with ANC services. Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility Providing balanced protein and energy supplements may be associated with logistical issues, as supplements are bulky and will require adequate transport and storage facilities to ensure continual supplies. Qualitative evidence from LMIC settings indicates that providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). + + + + + + + + + + + + + + + + + + + + + + + +A.1.4: High-protein supplements + + +RECOMMENDATION A.1.4: In undernourished populations, high-protein supplementation is not recommended for pregnant women to improve maternal and perinatal outcomes. (Not recommended) + + +Remarks • The GDG noted that there is insufficient evidence on the benefits, if any, of high-protein supplementation. • Further research on the effects of high-protein supplements in undernourished populations is not considered a research priority. Summary of evidence and considerations Effects of high-protein supplementation compared with controls (EB Table A.1.4) Evidence on the effects of high-protein supplementation was derived from the same Cochrane review as for Recommendations A.1.2 and A.1.3 (47). The review included one trial of high-protein supplementation compared with a micronutrient supplement conducted in the 1970s, involving 1051 low-income, black women in the USA. Maternal outcomes None of the outcomes prioritized for this guideline were reported for this comparison in the review. Fetal and neonatal outcomes High-certainty evidence shows that high-protein supplementation increases SGA neonates (1 trial, 505 neonates; RR: 1.58, 95% CI: 1.03–2.41). Moderate-certainty evidence indicates that highprotein supplementation probably has little or no effect on preterm birth (1 study, 505 women; RR: 1.14, 95% CI: 0.83–1.56). Low-certainty evidence suggests that high-protein supplementation may have little or no effect on stillbirths (1 trial, 529 babies; RR: 0.81, 95% CI: 0.31–2.15; certainty of evidence downgraded due to imprecision) and neonatal deaths (1 trial, 529 neonates; RR: 2.78, 95% CI: 0.75–10.36). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources The cost of high-protein supplements is relatively high. There may also be cost implications with respect to transport, storage and training. Equity In many LMICs, pregnancy outcomes and ANC coverage are worse among women who are poor, least educated and residing in rural areas (29). Many low-income countries still struggle with widespread poverty and hunger, particularly among rural populations (48). Therefore, providing antenatal food supplements could help to address inequalities by improving maternal nutritional status and increasing ANC coverage among disadvantaged women. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). It also suggests that women may be less likely to engage with health services if advice is delivered in a hurried or didactic manner (high confidence in the evidence) (22). Qualitative evidence on health-care providers’ views of ANC suggests that they may be keen to offer general health-care advice and specific pregnancy-related information (low confidence in the evidence) but they sometimes feel they do not have the appropriate training and lack the resources and time to deliver the service in the informative, supportive and caring manner that women want (high confidence in the evidence) (45). Feasibility Providing high-protein supplements may be associated with logistical issues, as supplements are bulky and will require adequate transport and storage facilities to ensure continual supplies. Qualitative evidence from LMIC settings indicates that providers feel that a lack of resources may limit implementation of recommended interventions (high confidence in the evidence) (45). Chapter 3. Evidence and recommendations 23 + + + + +A.2: Iron and folic acid supplements + + +A.2.1: Daily iron and folic acid supplements + + +RECOMMENDATION A.2.1: Daily oral iron and folic acid supplementation with 30 mg to 60 mg of elemental irona and 400 µg (0.4 mg) folic acidb is recommended for pregnant women to prevent maternal anaemia, puerperal sepsis, low birth weight, and preterm birth.c (Recommended) + + +Remarks • This recommendation supersedes the 2012 WHO Guideline: daily iron and folic acid supplementation in pregnant women (36) and should be considered alongside Recommendation A.2.2 on intermittent iron. • In settings where anaemia in pregnant women is a severe public health problem (i.e. where at least 40% of pregnant women have a blood haemoglobin [Hb] concentration < 110 g/L), a daily dose of 60 mg of elemental iron is preferred over a lower dose. • In the first and third trimesters, the Hb threshold for diagnosing anaemia is 110 g/L; in the second trimester, the threshold is 105 g/L (50). • If a woman is diagnosed with anaemia during pregnancy, her daily elemental iron should be increased to 120 mg until her Hb concentration rises to normal (Hb 110 g/L or higher) (34, 51). Thereafter, she can resume the standard daily antenatal iron dose to prevent recurrence of anaemia. • Effective communication with pregnant women about diet and healthy eating – including providing information about food sources of vitamins and minerals, and dietary diversity – is an integral part of preventing anaemia and providing quality ANC. • Effective communication strategies are vital for improving the acceptability of, and adherence to, supplementation schemes. • Stakeholders may need to consider ways of reminding pregnant women to take their supplements and of assisting them to manage associated side-effects. • In areas with endemic infections that may cause anaemia through blood loss, increased red cell destruction or decreased red cell production, such as malaria and hookworm, measures to prevent, diagnose and treat these infections should be implemented. • Oral supplements are available as capsules or tablets (including soluble tablets, and dissolvable and modified-release tablets) (52). Establishment of a quality assurance process is important to guarantee that supplements are manufactured, packaged and stored in a controlled and uncontaminated environment (53). • A better understanding of the etiology of anaemia (e.g. malaria endemnicity, haemoglobinopathies) and the prevalence of risk factors is needed at the country level, to inform context-specific adaptations of this recommendation. • Standardized definitions of side-effects are needed to facilitate monitoring and evaluation. • Development and improvement of integrated surveillance systems are needed to link the assessment of anaemia and iron status at the country level to national and global surveillance systems. • To reach the most vulnerable populations and ensure a timely and continuous supply of supplements, stakeholders may wish to consider task shifting the provision of iron supplementation in community settings with poor access to health-care professionals (see Recommendation E.6.1, in section E: Health systems interventions to improve the utilization and quality of ANC). a The equivalent of 60 mg of elemental iron is 300 mg of ferrous sulfate hepahydrate, 180 mg of ferrous fumarate or 500 mg of ferrous gluconate. b Folic acid should be commenced as early as possible (ideally before conception) to prevent neural tube defects. c This recommendation supersedes the previous WHO recommendation found in the 2012 Guideline: daily iron and folic acid supplementation in pregnant women (36). WHO recommendations on antenatal care for a positive pregnancy experience 24 Summary of evidence and considerations Effects of any daily iron and folic acid supplements compared with no daily iron and folic acid supplements (EB Table A.2.1) The evidence on the effects of daily iron and/or folic acid was derived from a Cochrane review of 61 trials conducted in low-, middle- and high-income countries (54). Twenty-three trials were conducted in countries with some malaria risk, of which two reported malaria outcomes. Overall, 44 trials involving 43 274 women contributed data to the review’s meta-analyses. The trials compared daily oral iron supplementation, with or without folic acid or other vitamin and mineral supplements, with various control groups (folic acid only, placebo, no intervention, other vitamin and mineral supplements without iron or folic acid). Most of the evidence was derived from studies comparing iron supplementation with no iron supplementation. In most trials, women began taking supplements before 20 weeks of gestation and continued taking supplements until delivery. The most commonly used dose of elemental iron was 60 mg daily (range: 30–240 mg) and that of folic acid was 400 µg daily. Maternal outcomes Anaemia was reported in many different ways and at different time points during pregnancy and the puerperium. Low-certainty evidence shows that daily iron supplementation may reduce the risk of anaemia at term (defined as blood Hb concentration < 110 g/L at 37 weeks of gestation or later) (14 trials, 2199 women; RR: 0.30, 95% CI: 0.19–0.46) and severe postpartum anaemia (defined as Hb < 80 g/L) (8 trials, 1339 women; RR: 0.04, 95% CI: 0.01–0.28). Low-certainty evidence also shows that daily iron supplementation may increase maternal Hb concentrations at or near term (34 weeks of gestation or more) (19 trials, 3704 women; MD: 8.88 g/L higher, 95% CI: 6.96–10.8 g/L) and may increase the proportion of women with a high maternal Hb at or near term (Hb > 130 g/L at 34 weeks of gestation or later) (8 trials, 2156 women; RR: 3.07, 95% CI: 1.18–8.02). Regarding maternal morbidity, moderate-certainty evidence shows that daily iron supplementation probably reduces the risk of maternal puerperal infections (4 trials, 4374 women; RR: 0.68, 95% CI: 0.5–0.92). Low-certainty evidence shows that daily iron supplementation may have little or no effect on pre-eclampsia (4 trials, 1704 women; RR: 1.63, 95% CI: 0.87–3.07) and antepartum haemorrhage (2 trials, 1157 women; RR: 1.48, 95% CI: 0.51–4.31), and moderate-certainty evidence shows that it probably has little or no effect on postpartum haemorrhage (4 trials, 1488 women; RR: 0.93, 95% CI: 0.59–1.49). Evidence on other morbidity outcomes, including placental abruption and blood transfusions, is of very low certainty. Low-certainty evidence shows that daily iron supplementation may have little or no effect on maternal mortality (2 trials, 12 560 women; RR: 0.33, 95% CI: 0.01–8.19). Women’s satisfaction was evaluated in one small trial (49 women), which found little difference between daily iron and control groups. Side-effects: Moderate-certainty evidence indicates that daily iron supplementation probably has little or no effect on the risk of experiencing any side-effect (11 trials, 2425 women; RR: 1.29, 95% CI: 0.83–2.02), and that it may have little or no effect on constipation (4 trials, 1495 women; RR: 0.95, 95% CI: 0.62–1.43), heartburn (3 trials, 1323 women; RR: 1.19, 95% CI: 0.86–1.66) and vomiting (4 trials, 1392 women; RR: 0.88, 95% CI: 0.59–1.30). Evidence that daily iron has little or no effect on nausea is of low certainty (4 trials, 1377 women; RR: 1.21, 95% CI: 0.72–2.03). High-certainty evidence shows that diarrhoea is less common with daily iron supplements (3 trials, 1088 women; RR: 0.55, 95% CI: 0.32–0.93). Fetal and neonatal outcomes Low-certainty evidence shows that daily iron may reduce the risk of low-birth-weight neonates (< 2500 g) (11 trials, 17 613 neonates; RR: 0.84, 95% CI: 0.69–1.03). High-certainty evidence shows that it does not reduce the risk of preterm birth before 37 weeks of gestation (13 trials, 19 286 women; RR: 0.93, 95% CI: 0.84–1.03), but it does reduce the risk of very preterm birth (i.e. less than 34 weeks of gestation) (5 trials, 3749 women; RR: 0.51, 95% CI: 0.29–0.91). Low-certainty evidence suggests that daily iron may have little or no effect on congenital anomalies (4 trials, 14 636 neonates; RR: 0.88, 95% CI: 0.58–1.33). Moderate-certainty evidence indicates that daily iron probably has little or no effect on neonatal deaths (4 trials, 16 603 neonates; RR: 0.91, 95% CI: 0.71–1.18). Neonatal infections and SGA were not reviewed as outcomes + + + + + + +Additional considerations n Evidence from subgroups tended to be consistent with the overall findings for the main outcomes. More details can be found in the Web supplement (EB Table A.2.1). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Daily iron and folic acid supplements are relatively low cost, at less than 1 United States dollar (US$ 1) per pregnant woman (27). Equity Iron deficiency and parasitic infections are more common in LMICs and disadvantaged populations. Poor, rural and least-educated populations also experience the highest maternal, infant and child mortality (29). Increasing coverage of effective nutritional interventions to prevent anaemia, particularly among disadvantaged populations, might help to address maternal and newborn health inequalities. Acceptability Qualitative evidence suggests that the availability of iron supplements may actively encourage women to engage with ANC providers (low confidence in the evidence) (22). However, where there are additional costs associated with supplementation or where the supplements may be unavailable (because of resource constraints) women are less likely to engage with ANC services (high confidence in the evidence). Lower doses of iron may be associated with fewer side-effects and therefore may be more acceptable to women than higher doses. Feasibility Qualitative evidence about the views of health-care providers suggests that resource constraints, both in terms of the availability of the supplements and the lack of suitably trained staff to deliver them, may limit implementation (high confidence in the evidence) (45). a The equivalent of 120 mg of elemental iron is 600 mg of ferrous sulfate hepahydrate, 360 mg of ferrous fumarate or 1000 mg of ferrous gluconate. + + + + + A.2.2: Intermittent iron and folic acid supplements + + +RECOMMENDATION A.2.2: Intermittent oral iron and folic acid supplementation with 120 mg of elemental irona and 2800 µg (2.8 mg) of folic acid once weekly is recommended for pregnant women to improve maternal and neonatal outcomes if daily iron is not acceptable due to sideeffects, and in populations with an anaemia prevalence among pregnant women of less than 20%. (Context-specific recommendation) + + +Remarks • This recommendation supersedes the previous WHO recommendation in the 2012 Guideline: intermittent iron and folic acid supplementation in non-anaemic pregnant women (55) and should be considered alongside Recommendation A.1.1. • In general, anaemia prevalence of less than 20% is classified as a mild public health problem (33). • Before commencing intermittent iron supplementation, accurate measurement of maternal blood Hb concentrations is needed to confirm the absence of anaemia. Therefore, this recommendation may require a strong health system to facilitate accurate Hb measurement and to monitor anaemia status throughout pregnancy. • If a woman is diagnosed with anaemia (Hb < 110 g/L) during ANC, she should be given 120 mg of elemental iron and 400 µg (0.4 mg) of folic acid daily until her Hb concentration rises to normal (Hb 110 g/L or higher) (34, 51). Thereafter, she can continue with the standard daily antenatal iron and folic acid dose (or the intermittent regimen if daily iron is not acceptable due to side-effects) to prevent recurrence of anaemia. • Stakeholders may need to consider ways of reminding pregnant women to take their supplements on an intermittent basis and of assisting them to manage associated side-effects. WHO recommendations on antenatal care for a positive pregnancy experience 26 Summary of evidence and considerations Effects of intermittent iron and folic acid supplements compared with daily iron and folic acid supplements (EB Table A.2.2) The evidence on the effects of intermittent iron and folic acid was derived from a Cochrane review that included 27 trials from 15 countries; however, only 21 trials (involving 5490 women) contributed data to the review’s meta-analyses (56). All trials were conducted in LMICs with some degree of malaria risk (Argentina, Bangladesh, China, Guatemala, India, Indonesia, the Islamic Republic of Iran, Malawi, Malaysia, Mexico, Pakistan, Republic of Korea, Sri Lanka, Thailand and Viet Nam); however, only one trial specifically reported that it was conducted in a malaria-endemic area. Most of the intermittent iron regimens involved women taking weekly supplements, most commonly 120 mg elemental iron per week (range: 80–200 mg weekly), which was compared with daily regimens, most commonly 60 mg elemental iron daily (range: 40–120 mg daily). Where folic acid was also provided in the trials, it was administered weekly in the intermittent supplement groups (range: 400– 3500 µg weekly) compared with the usual standard daily dose for control groups. Maternal outcomes Anaemia was reported in different ways across trials. Low-certainty evidence suggests there may be little or no difference between intermittent and daily iron supplementation in the effect on anaemia at term (4 trials, 676 women; RR: 1.22, 95% CI: 0.84–1.80). Moderate-certainty evidence shows that anaemia at or near term (defined as a Hb of < 110 g/L at 34 weeks of gestation or later) probably occurs more frequently with intermittent than daily iron supplementation (8 trials, 1385 women; RR: 1.66, 95% CI: 1.09–2.53), and that intermittent iron supplementation is probably less likely to be associated with a Hb concentration of more than 130 g/L than daily iron (15 trials, 2616 women; RR: 0.53, 95% CI: 0.38–0.74). No events of severe anaemia occurred in either group in six trials reporting this outcome (1240 women). The evidence on mean Hb concentrations at or near term and severe postpartum anaemia is of very low certainty. Limited evidence on maternal morbidity from one small trial (110 women) was assessed as very uncertain. Maternal infections and maternal satisfaction were not evaluated in the review. Side-effects: Moderate-certainty evidence shows that intermittent iron supplementation is probably less commonly associated with nausea than daily iron supplementation (7 trials, 1034 women; RR: 0.60, 95% CI: 0.37–0.97). However, the evidence on other specific side-effects (constipation, diarrhoea, heartburn or vomiting) or any side-effect is of very low certainty. Fetal and neonatal outcomes Low-certainty evidence suggests that intermittent iron supplementation may have a similar effect to daily iron supplementation on low birth weight (< 2500 g) (8 trials, 1898 neonates; RR: 0.82, 95% CI: 0.50–1.22). However, the evidence on preterm birth and very preterm birth was assessed as very uncertain. Evidence on the relative effects of intermittent versus daily iron supplementation on neonatal mortality is also very uncertain. Neonatal infections and SGA outcomes were not included in the review. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Intermittent iron and folic acid supplementation might cost a little less than daily iron and folic acid supplementation due to the lower total weekly dose of iron. Equity Intermittent iron and folic acid supplementation may have less impact on health inequalities than daily iron and folic acid supplementation, as anaemia is more common in disadvantaged populations. Acceptability Qualitative evidence suggests that the availability of iron supplements may actively encourage women to engage with ANC providers (low confidence in the evidence) (22). However, where there are additional costs associated with supplementation or where the supplements may be unavailable (because of resource constraints) women are less likely to engage with ANC services (high confidence in the evidence). Women may find intermittent iron supplementation more acceptable than daily iron supplementation, particularly if they experience side-effects with daily iron supplements. Feasibility Intermittent iron may be more feasible in some lowresource settings if it costs less than daily iron. \ No newline at end of file From fea51ec83ac60a1162ffe525b4ee73860cf956b7 Mon Sep 17 00:00:00 2001 From: k-aniket23 Date: Mon, 28 Apr 2025 11:21:49 +0530 Subject: [PATCH 2/2] Providing multiple resources(.txt files) as context to AI systems --- .../sample/client/MCPClient.kt | 785 ++---------------- .../sample/client/main.kt | 52 +- .../sample/server/McpWeatherServer.kt | 111 +-- .../sample/server/resources/one.txt | 1 - .../who_ANC_Guideline_Calcium_supplements.txt | 7 + ...ho_ANC_Guideline_Vitamin_A_Supplements.txt | 7 + 6 files changed, 130 insertions(+), 833 deletions(-) delete mode 100644 samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt create mode 100644 samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Calcium_supplements.txt create mode 100644 samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Vitamin_A_Supplements.txt diff --git a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt index 6c12415d..dc5fdf26 100644 --- a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt +++ b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/MCPClient.kt @@ -16,11 +16,14 @@ import kotlinx.io.buffered import kotlinx.serialization.json.JsonObject import kotlin.jvm.optionals.getOrNull +import java.nio.file.Files +import java.nio.file.Paths + +import java.io.File +import io.modelcontextprotocol.kotlin.sdk.ReadResourceRequest +import io.modelcontextprotocol.kotlin.sdk.TextResourceContents + class MCPClient : AutoCloseable { - // Configures using the `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` environment variables -// private val anthropic = AnthropicOkHttpClient.fromEnv() -//// .apiKey(System.getenv("ANTHROPIC_API_KEY") ?: "your_api_key_here") -//// .build() private val anthropic = AnthropicOkHttpClient.builder() .apiKey(System.getenv("ANTHROPIC_API_KEY") ) @@ -36,17 +39,19 @@ class MCPClient : AutoCloseable { // List of tools offered by the server private lateinit var tools: List - private fun JsonObject.toJsonValue(): JsonValue { val mapper = ObjectMapper() val node = mapper.readTree(this.toString()) return JsonValue.fromJsonNode(node) } - // Connect to the server using the path to the server + + + private val resourceContents: MutableMap = mutableMapOf() + suspend fun connectToServer(serverScriptPath: String) { try { - // Build the command based on the file extension of the server script + // Build command to start server val command = buildList { when (serverScriptPath.substringAfterLast(".")) { "js" -> add("node") @@ -57,19 +62,19 @@ class MCPClient : AutoCloseable { add(serverScriptPath) } - // Start the server process + // Start server process val process = ProcessBuilder(command).start() - // Setup I/O transport using the process streams + // Setup transport val transport = StdioClientTransport( input = process.inputStream.asSource().buffered(), output = process.outputStream.asSink().buffered() ) - // Connect the MCP client to the server using the transport + // Connect MCP client mcp.connect(transport) - // Request the list of available tools from the server + // List tools val toolsResult = mcp.listTools() tools = toolsResult?.tools?.map { tool -> ToolUnion.ofTool( @@ -86,7 +91,31 @@ class MCPClient : AutoCloseable { .build() ) } ?: emptyList() + println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") + +// // List all resources + val resourcesResult = mcp.listResources() + val resources = resourcesResult?.resources ?: emptyList() + + println("Found ${resources.size} resources from server.") + + for (resource in resources) { + println("Loading resource: ${resource.name} (${resource.uri})") + val readRequest = ReadResourceRequest(uri = resource.uri) + val readResult = mcp.readResource(readRequest) + + val content = readResult?.contents + ?.filterIsInstance() + ?.joinToString("\n") { it.text } + if (content != null) { + resourceContents[resource.uri] = content + println("Successfully loaded resource (${content.length} characters) for URI: ${resource.uri}") + } else { + println("Warning: No content found for resource: ${resource.uri}") + } + } + } catch (e: Exception) { println("Failed to connect to MCP server: $e") throw e @@ -99,12 +128,18 @@ class MCPClient : AutoCloseable { suspend fun processQuery(query: String): String { // Create an initial message with a user's query -// val messages = mutableListOf( -// MessageParam.builder() -// .role(MessageParam.Role.USER) -// .content(query) -// .build() -// ) +// / Prepend resources as SYSTEM message if they are loaded + if (resourceContents.isNotEmpty()) { + val combinedResourceText = resourceContents.values.joinToString("\n\n") + messages.add( + MessageParam.builder() + .role(MessageParam.Role.ASSISTANT) // system role for context + .content("Reference Resources:\n$combinedResourceText") + .build() + ) + } + + messages.add( MessageParam.builder() .role(MessageParam.Role.USER) @@ -207,12 +242,12 @@ class MCPClient : AutoCloseable { // Add the tool_result to messages val toolResultContent = """ - { - "type": "tool_result", - "tool_name": "$toolName", - "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" - } - """.trimIndent() + { + "type": "tool_result", + "tool_name": "$toolName", + "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" + } + """.trimIndent() messages.add( MessageParam.builder() @@ -244,14 +279,12 @@ class MCPClient : AutoCloseable { } } -// println(messages) - return finalText.joinToString("\n", prefix = "", postfix = "") } - // Main chat loop for interacting with the user + // Main chat loop for interacting with the user suspend fun chatLoop() { println("\nMCP Client Started!") println("Type your queries or 'quit' to exit.") @@ -272,703 +305,3 @@ class MCPClient : AutoCloseable { } } } - - -// -// -//package io.modelcontextprotocol.sample.client -// -//import com.anthropic.client.okhttp.AnthropicOkHttpClient -//import com.anthropic.core.JsonValue -//import com.anthropic.models.messages.* -//import com.fasterxml.jackson.core.type.TypeReference -//import com.fasterxml.jackson.databind.ObjectMapper -//import io.modelcontextprotocol.kotlin.sdk.Implementation -//import io.modelcontextprotocol.kotlin.sdk.TextContent -//import io.modelcontextprotocol.kotlin.sdk.client.Client -//import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport -//import kotlinx.coroutines.runBlocking -//import kotlinx.io.asSink -//import kotlinx.io.asSource -//import kotlinx.io.buffered -//import kotlinx.serialization.json.JsonObject -//import kotlin.jvm.optionals.getOrNull -// -//import io.modelcontextprotocol.kotlin.sdk.ReadResourceRequest -////import io.modelcontextprotocol.kotlin.sdk.ReadResourceResult -//import io.modelcontextprotocol.kotlin.sdk.TextResourceContents -// -//class MCPClient : AutoCloseable { -// -// private val anthropic = AnthropicOkHttpClient.builder() -// .apiKey(System.getenv("ANTHROPIC_API_KEY") ) -// .build() -// -// // Initialize MCP client -// private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")) -// -// private val messageParamsBuilder: MessageCreateParams.Builder = MessageCreateParams.builder() -// .model(Model.CLAUDE_3_5_SONNET_20241022) -// .maxTokens(1024) -// -// // List of tools offered by the server -// private lateinit var tools: List -// private var resourceContent: String? = null // Store resource content -// private val resourceUri = "file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt" -// private fun JsonObject.toJsonValue(): JsonValue { -// val mapper = ObjectMapper() -// val node = mapper.readTree(this.toString()) -// return JsonValue.fromJsonNode(node) -// } -// -// -//// private val resourceContents = mutableMapOf() -// -// -// // Connect to the server using the path to the server -// suspend fun connectToServer(serverScriptPath: String) { -// try { -// // Build the command based on the file extension of the server script -// val command = buildList { -// when (serverScriptPath.substringAfterLast(".")) { -// "js" -> add("node") -// "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3") -// "jar" -> addAll(listOf("java", "-jar")) -// else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file") -// } -// add(serverScriptPath) -// } -// -// // Start the server process -// val process = ProcessBuilder(command).start() -// -// // Setup I/O transport using the process streams -// val transport = StdioClientTransport( -// input = process.inputStream.asSource().buffered(), -// output = process.outputStream.asSink().buffered() -// ) -// -// // Connect the MCP client to the server using the transport -// mcp.connect(transport) -// -// // Request the list of available tools from the server -// val toolsResult = mcp.listTools() -// tools = toolsResult?.tools?.map { tool -> -// ToolUnion.ofTool( -// Tool.builder() -// .name(tool.name) -// .description(tool.description ?: "") -// .inputSchema( -// Tool.InputSchema.builder() -// .type(JsonValue.from(tool.inputSchema.type)) -// .properties(tool.inputSchema.properties.toJsonValue()) -// .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required)) -// .build() -// ) -// .build() -// ) -// } ?: emptyList() -// println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") -// -// -// -//// val resourcesResult = mcp.listResources() -//// println("🔍 Available Resources:") -//// resourcesResult?.resources?.forEach {resource -> -//// println("• ${resource.name} and uri = (${resource.uri})") -//// -//// if(resource.mimeType?.contains("text") == true){ -//// val readRequest = ReadResourceRequest(uri = resource.uri) -//// val readResult = mcp.readResource(readRequest) -//// val content = readResult?.contents -//// ?.filterIsInstance() -//// ?.joinToString("\n"){it.text} -//// -//// if(!content.isNullOrBlank()){ -//// resourceContents[resource.name] = content -//// println("Loaded resource '${resource.name}' (${content.length} characters)") -//// } -//// else{ -//// println("Couldnot read content of resource '${resource.name}'") -//// } -//// -//// } -//// } -// -// -//// val resourcesResult = mcp.listResources() -//// println(resourcesResult) -//// println("🔍 Found ${resourcesResult?.resources?.size ?: 0} total resources:") -//// resourcesResult?.resources?.forEach { resource -> -//// println("• ${resource.name} (URI: ${resource.uri}, MIME type: ${resource.mimeType})") -//// -////// Add this to see which files are being filtered out by the text check -//// if(resource.mimeType?.contains("text") != true) { -//// println(" ⚠️ Skipping: Not detected as text content (MIME type: ${resource.mimeType})") -//// } -//// -//// -////// Only process text resources -//// if (resource.mimeType?.contains("text") == true) { -//// val readRequest = ReadResourceRequest(uri = resource.uri) -//// println("readRequest ${readRequest}") -//// val readResult = mcp.readResource(readRequest) -////// println("readResult ${readResult}") -//// -//// val content = readResult?.contents -//// ?.filterIsInstance() -//// ?.joinToString("\n") { it.text } -//// -//// println(content) -//// -//// if (!content.isNullOrBlank()) { -//// resourceContents[resource.name] = content -//// println("✔ Loaded resource '${resource.name}' (${content.length} characters)") -//// } else { -//// println("⚠ Could not read content of resource '${resource.name}'") -//// } -//// } -//// -//// -//// } -// -// -// val resourcesResult = mcp.listResources() -// val resource = resourcesResult?.resources?.find { it.uri == resourceUri } -// println(resource?.uri ) -// println(resource?.mimeType ) -// if (resource != null) { -// println("Found resource: ${resource.name} (${resource.uri})") -// // Construct ReadResourceRequest -// val readRequest = ReadResourceRequest(uri = resource.uri) -// println("readRequest: ${readRequest}") -// val readResult = mcp.readResource(readRequest) -// println("readResult: ${readResult}") -// this.resourceContent = readResult?.contents -// ?.filterIsInstance() -// ?.joinToString("\n") { it.text } -// -// println("Resource Text Content:\n$resourceContent") -//// resourceContent = readResult?.contents?.firstOrNull()?.text -// if (resourceContent != null) { -// println("Successfully loaded resource content (${resourceContent?.length} characters)") -// } else { -// println("Warning: Could not read resource content for ${resource.uri}") -// } -// } else { -// println("Warning: Resource $resourceUri not found") -// } -// } catch (e: Exception) { -// println("Failed to connect to MCP server: $e") -// throw e -// } -// } -// -// -// -// -// private val messages = mutableListOf() -// -// // Process a user query and return a string response -// suspend fun processQuery(query: String): String { -// // Create an initial message with a user's query -// -//// val messages = mutableListOf( -//// MessageParam.builder() -//// .role(MessageParam.Role.USER) -//// .content(query) -//// .build() -//// ) -// -// val context = resourceContent?.let { -// // Truncate or summarize to avoid exceeding token limits -// // For simplicity, take the first 5000 characters (adjust as needed) -// val maxLength = 5000 -// if (it.length > maxLength) { -// it.substring(0, maxLength) + "... [Content truncated]" -// } else { -// it -// } -// } -// -//// val combinedContext = resourceContents.entries.joinToString("\n\n") { (name, text) -> -//// val snippet = if (text.length > 2000) text.take(2000) + "... [truncated]" else text -//// "From $name:\nsnippet" -//// } -//// -//// println("Context available:combinedContext != null}") -// println("Context length: ${context?.length ?: 0} characters") -//// -//// // Combine context and user query -// val fullQuery = if (context != null) { -// """ -// Context from WHO Nutritional Interventions Guidelines: -// $context -// -// User Query: -// $query -// """.trimIndent() -// } else { -// query -// } -// -//// val fullQuery = if (combinedContext.isNotBlank()) { -//// """ -//// Context from WHO Guidelines Resources: -//// $combinedContext -//// -//// User Query: -//// $query -//// """.trimIndent() -//// } else { -//// query -//// } -// -// -// -// messages.add( -// MessageParam.builder() -// .role(MessageParam.Role.USER) -// .content(fullQuery) -// .build() -// ) -// -// // Send the query to the Anthropic model and get the response -// val response = anthropic.messages().create( -// messageParamsBuilder -// .messages(messages) -// .tools(tools) -// .build() -// ) -// -// val finalText = mutableListOf() -// -// response.content().forEach { content -> -// when { -// // Append text outputs from the response -// content.isText() -> { -// val text = content.text().getOrNull()?.text() -// if (!text.isNullOrBlank()) { -// finalText.add(text) -// -// // Save assistant response to memory -// messages.add( -// MessageParam.builder() -// .role(MessageParam.Role.ASSISTANT) -// .content(text) -// .build() -// ) -// } -// } -// -// // If the response indicates a tool use, process it further -// content.isToolUse() -> { -// val toolName = content.toolUse().get().name() -// val toolArgs = -// content.toolUse().get()._input().convert(object : TypeReference>() {}) -// -// // Call the tool with provided arguments -// val result = mcp.callTool( -// name = toolName, -// arguments = toolArgs ?: emptyMap() -// ) -// -// finalText.add("[Calling tool $toolName with args $toolArgs]") -// -// // Add the tool_result to messages -// val toolResultContent = """ -// { -// "type": "tool_result", -// "tool_name": "$toolName", -// "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" -// } -// """.trimIndent() -// -// messages.add( -// MessageParam.builder() -// .role(MessageParam.Role.USER) -// .content(toolResultContent) -// .build() -// ) -// -// // Retrieve an updated response after tool execution -// val aiResponse = anthropic.messages().create( -// messageParamsBuilder -// .messages(messages) -// .build() -// ) -// -// val aiReply = aiResponse.content().firstOrNull()?.text()?.getOrNull()?.text() -// if (!aiReply.isNullOrBlank()) { -// finalText.add(aiReply) -// -// // Save assistant's new response after tool use -// messages.add( -// MessageParam.builder() -// .role(MessageParam.Role.ASSISTANT) -// .content(aiReply) -// .build() -// ) -// } -// } -// } -// } -// -// println(messages) -// -// return finalText.joinToString("\n", prefix = "", postfix = "") -// } -// -// -// -// // Main chat loop for interacting with the user -// suspend fun chatLoop() { -// println("\n==============================================") -// println("\nMCP Client Started!") -// println("Type your queries or 'quit' to exit.") -// println("\n==============================================") -// -// while (true) { -// print("\nQuery: ") -// val message = readLine() ?: break -// if (message.lowercase() == "quit") break -// val response = processQuery(message) -// println("\n$response") -// } -// } -// -// override fun close() { -// runBlocking { -// mcp.close() -// anthropic.close() -// } -// } -//} -// -//// -////package io.modelcontextprotocol.sample.client -//// -////import com.anthropic.client.okhttp.AnthropicOkHttpClient -////import com.anthropic.core.JsonValue -////import com.anthropic.models.messages.* -////import com.fasterxml.jackson.core.type.TypeReference -////import com.fasterxml.jackson.databind.ObjectMapper -////import io.modelcontextprotocol.kotlin.sdk.Implementation -////import io.modelcontextprotocol.kotlin.sdk.TextContent -////import io.modelcontextprotocol.kotlin.sdk.client.Client -////import io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransport -////import kotlinx.coroutines.runBlocking -////import kotlinx.io.asSink -////import kotlinx.io.asSource -////import kotlinx.io.buffered -////import kotlinx.serialization.json.JsonObject -////import kotlin.jvm.optionals.getOrNull -//// -////import io.modelcontextprotocol.kotlin.sdk.ReadResourceRequest -//////import io.modelcontextprotocol.kotlin.sdk.ReadResourceResult -////import io.modelcontextprotocol.kotlin.sdk.TextResourceContents -//// -////class MCPClient : AutoCloseable { -//// // Configures using the `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` environment variables -////// private val anthropic = AnthropicOkHttpClient.fromEnv() -//////// .apiKey(System.getenv("ANTHROPIC_API_KEY") ?: "your_api_key_here") -//////// .build() -//// -//// private val anthropic = AnthropicOkHttpClient.builder() -//// .apiKey(System.getenv("ANTHROPIC_API_KEY") ) -//// .build() -//// -//// // Initialize MCP client -//// private val mcp: Client = Client(clientInfo = Implementation(name = "mcp-client-cli", version = "1.0.0")) -//// -//// private val messageParamsBuilder: MessageCreateParams.Builder = MessageCreateParams.builder() -//// .model(Model.CLAUDE_3_5_SONNET_20241022) -//// .maxTokens(1024) -//// -//// // List of tools offered by the server -//// private lateinit var tools: List -//// private var resourceContent: String? = null // Store resource content -//// // private val resourceUri = "file:///C://Users//developer//Downloads//kotlin-sdk//samples//weather-stdio-server//src//main//kotlin//io//modelcontextprotocol//sample//server//resources//who_guidelines_nutritional_interventions_anc.txt " -////// private val resourceUri = "file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt" -//// private fun JsonObject.toJsonValue(): JsonValue { -//// val mapper = ObjectMapper() -//// val node = mapper.readTree(this.toString()) -//// return JsonValue.fromJsonNode(node) -//// } -//// -//// -//// private val resourceContents = mutableMapOf() -//// -//// -//// // Connect to the server using the path to the server -//// suspend fun connectToServer(serverScriptPath: String) { -//// try { -//// // Build the command based on the file extension of the server script -//// val command = buildList { -//// when (serverScriptPath.substringAfterLast(".")) { -//// "js" -> add("node") -//// "py" -> add(if (System.getProperty("os.name").lowercase().contains("win")) "python" else "python3") -//// "jar" -> addAll(listOf("java", "-jar")) -//// else -> throw IllegalArgumentException("Server script must be a .js, .py or .jar file") -//// } -//// add(serverScriptPath) -//// } -//// -//// // Start the server process -//// val process = ProcessBuilder(command).start() -//// -//// // Setup I/O transport using the process streams -//// val transport = StdioClientTransport( -//// input = process.inputStream.asSource().buffered(), -//// output = process.outputStream.asSink().buffered() -//// ) -//// -//// // Connect the MCP client to the server using the transport -//// mcp.connect(transport) -//// -//// // Request the list of available tools from the server -//// val toolsResult = mcp.listTools() -//// tools = toolsResult?.tools?.map { tool -> -//// ToolUnion.ofTool( -//// Tool.builder() -//// .name(tool.name) -//// .description(tool.description ?: "") -//// .inputSchema( -//// Tool.InputSchema.builder() -//// .type(JsonValue.from(tool.inputSchema.type)) -//// .properties(tool.inputSchema.properties.toJsonValue()) -//// .putAdditionalProperty("required", JsonValue.from(tool.inputSchema.required)) -//// .build() -//// ) -//// .build() -//// ) -//// } ?: emptyList() -//// println("Connected to server with tools: ${tools.joinToString(", ") { it.tool().get().name() }}") -//// -//// -//// val resourcesResult = mcp.listResources() -//// println(resourcesResult) -//// println("🔍 Found ${resourcesResult?.resources?.size ?: 0} total resources:") -//// resourcesResult?.resources?.forEach { resource -> -//// println("• ${resource.name} (URI: ${resource.uri}, MIME type: ${resource.mimeType})") -//// -//// -////// Add this to see which files are being filtered out by the text check -//// if(resource.mimeType?.contains("text") == true) { -//// println(" ⚠️ Skipping: Not detected as text content (MIME type: ${resource.mimeType})") -//// } -//// -//// -////// Only process text resources -//// -////// / if (resource.mimeType?.contains("text") == true) { -////// val readRequest = ReadResourceRequest(uri = resource.uri) -////// println("readRequest ${readRequest}") -////// -////// val readResult = mcp.readResource(readRequest) -//////// return readResult?.contents -////// println("readResult ${readResult}") -////// if (readResult == null) { -////// println("❌ readResource returned null for ${resource.uri}") -////// } else { -////// println("✅ readResource success: $readResult") -////// } -////// -////// val content = readResult?.contents -////// ?.filterIsInstance() -////// ?.joinToString("\n") { it.text } -////// -////// println(content) -////// -////// if (!content.isNullOrBlank()) { -////// resourceContents[resource.name] = content -////// println("✔ Loaded resource '${resource.name}' (${content.length} characters)") -////// } else { -////// println("⚠ Could not read content of resource '${resource.name}'") -////// } -//// -//// if (resource != null) { -//// println("Found resource: ${resource.name} (${resource.uri})") -//// // Construct ReadResourceRequest -//// val readRequest = ReadResourceRequest(uri = resource.uri) -//// println("readRequest: ${readRequest}") -//// println("Before calling readResource()") -//// val readResult = mcp.readResource(readRequest) -//// println("After calling readResource()") -//// println("readResult: ${readResult}") -//// this.resourceContent = readResult?.contents -//// ?.filterIsInstance() -//// ?.joinToString("\n") { it.text } -//// -//// // println("Resource Text Content:\n$resourceContent") -//// // resourceContent = readResult?.contents?.firstOrNull()?.text -//// if (resourceContent != null) { -//// println("Successfully loaded resource content (${resourceContent?.length} characters)") -//// } else { -//// println("Warning: Could not read resource content for ${resource.uri}") -//// } -//// } else { -//// println("Warning: Resource not found") -//// } -//// } -//// -//// -//// } catch (e: Exception) { -//// println("Failed to connect to MCP server: $e") -//// throw e -//// } -//// } -//// -//// -//// -//// -//// private val messages = mutableListOf() -//// -//// // Process a user query and return a string response -//// suspend fun processQuery(query: String): String { -//// // Create an initial message with a user's query -//// -//// -//// -//// val combinedContext = resourceContents.entries.joinToString("\n\n") { (name, text) -> -//// val snippet = if (text.length > 2000) text.take(2000) + "... [truncated]" else text -//// "From $name:$snippet" -//// } -//// -////// println("Context available:combinedContext != null}") -//// println("Context available: ${combinedContext.isNotBlank()}") -//// println("Context length: ${combinedContext?.length ?: 0} characters") -//// -//// -//// val fullQuery = if (combinedContext.isNotBlank()) { -//// """ -//// Context from WHO Guidelines Resources: -//// $combinedContext -//// -//// User Query: -//// $query -//// """.trimIndent() -//// } else { -//// query -//// } -//// -//// -//// -//// messages.add( -//// MessageParam.builder() -//// .role(MessageParam.Role.USER) -//// .content(fullQuery) -//// .build() -//// ) -//// -//// // Send the query to the Anthropic model and get the response -//// val response = anthropic.messages().create( -//// messageParamsBuilder -//// .messages(messages) -//// .tools(tools) -//// .build() -//// ) -//// -//// val finalText = mutableListOf() -//// -//// response.content().forEach { content -> -//// when { -//// // Append text outputs from the response -//// content.isText() -> { -//// val text = content.text().getOrNull()?.text() -//// if (!text.isNullOrBlank()) { -//// finalText.add(text) -//// -//// // Save assistant response to memory -//// messages.add( -//// MessageParam.builder() -//// .role(MessageParam.Role.ASSISTANT) -//// .content(text) -//// .build() -//// ) -//// } -//// } -//// -//// // If the response indicates a tool use, process it further -//// content.isToolUse() -> { -//// val toolName = content.toolUse().get().name() -//// val toolArgs = -//// content.toolUse().get()._input().convert(object : TypeReference>() {}) -//// -//// // Call the tool with provided arguments -//// val result = mcp.callTool( -//// name = toolName, -//// arguments = toolArgs ?: emptyMap() -//// ) -//// -//// finalText.add("[Calling tool $toolName with args $toolArgs]") -//// -//// // Add the tool_result to messages -//// val toolResultContent = """ -//// { -//// "type": "tool_result", -//// "tool_name": "$toolName", -//// "result": "${result?.content?.joinToString("\n") { (it as TextContent).text ?: "" }}" -//// } -//// """.trimIndent() -//// -//// messages.add( -//// MessageParam.builder() -//// .role(MessageParam.Role.USER) -//// .content(toolResultContent) -//// .build() -//// ) -//// -//// // Retrieve an updated response after tool execution -//// val aiResponse = anthropic.messages().create( -//// messageParamsBuilder -//// .messages(messages) -//// .build() -//// ) -//// -//// val aiReply = aiResponse.content().firstOrNull()?.text()?.getOrNull()?.text() -//// if (!aiReply.isNullOrBlank()) { -//// finalText.add(aiReply) -//// -//// // Save assistant's new response after tool use -//// messages.add( -//// MessageParam.builder() -//// .role(MessageParam.Role.ASSISTANT) -//// .content(aiReply) -//// .build() -//// ) -//// } -//// } -//// } -//// } -//// -//// println(messages) -//// -//// return finalText.joinToString("\n", prefix = "", postfix = "") -//// } -//// -//// -//// -//// // Main chat loop for interacting with the user -//// suspend fun chatLoop() { -//// println("\n==============================================") -//// println("\nMCP Client Started!") -//// println("Type your queries or 'quit' to exit.") -//// println("\n==============================================") -//// -//// while (true) { -//// print("\nQuery: ") -//// val message = readLine() ?: break -//// if (message.lowercase() == "quit") break -//// val response = processQuery(message) -//// println("\n$response") -//// } -//// } -//// -//// override fun close() { -//// runBlocking { -//// mcp.close() -//// anthropic.close() -//// } -//// } -////} \ No newline at end of file diff --git a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt index dbe2a2dd..c42655be 100644 --- a/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt +++ b/samples/kotlin-mcp-client/src/main/kotlin/io/modelcontextprotocol/sample/client/main.kt @@ -2,37 +2,37 @@ package io.modelcontextprotocol.sample.client import kotlinx.coroutines.runBlocking -//fun main(args: Array) = runBlocking { -// if (args.isEmpty()) throw IllegalArgumentException("Usage: java -jar /build/libs/kotlin-mcp-client-0.1.0-all.jar ") -// val serverPath = args.first() -// val client = MCPClient() -// client.use { -// client.connectToServer(serverPath) -// println("starting mcp client") -// client.chatLoop() -// } -//} - - fun main(args: Array) = runBlocking { - if (args.isEmpty()) { - println("Please provide the path to the MCP server script as a command-line argument.") - return@runBlocking - } - - val serverScriptPath = args[0] - MCPClient().use { client -> - try { - client.connectToServer(serverScriptPath) - client.chatLoop() - } catch (e: Exception) { - println("Error: ${e.message}") - e.printStackTrace() - } + if (args.isEmpty()) throw IllegalArgumentException("Usage: java -jar /build/libs/kotlin-mcp-client-0.1.0-all.jar ") + val serverPath = args.first() + val client = MCPClient() + client.use { + client.connectToServer(serverPath) + println("starting mcp client") + client.chatLoop() } } +//fun main(args: Array) = runBlocking { +// if (args.isEmpty()) { +// println("Please provide the path to the MCP server script as a command-line argument.") +// return@runBlocking +// } +// +// val serverScriptPath = args[0] +// MCPClient().use { client -> +// try { +// client.connectToServer(serverScriptPath) +// client.chatLoop() +// } catch (e: Exception) { +// println("Error: ${e.message}") +// e.printStackTrace() +// } +// } +//} + + //fun main() = runBlocking { // val client = MCPClient() // client.connectToServer(System.getenv("SERVER_PATH")!!) diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt index 0875b9f6..f8018a5a 100644 --- a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/McpWeatherServer.kt @@ -1,7 +1,3 @@ - - - - package io.modelcontextprotocol.sample.server import io.ktor.client.* @@ -20,7 +16,10 @@ import kotlinx.io.asSink import kotlinx.io.buffered import kotlinx.serialization.json.* -import java.io.File +import java.nio.file.Files +import java.nio.file.Paths + +//import java.io.File // Main function to run the MCP server fun `run mcp server`() { @@ -60,10 +59,6 @@ fun `run mcp server`() { ) ) - - - - // Register a tool to fetch weather alerts by state server.addTool( name = "get_alerts", @@ -123,75 +118,34 @@ fun `run mcp server`() { CallToolResult(content = forecast.map { TextContent(it) }) } + val files = listOf( +// Triple("file:///C:/Users/tanu0/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/context-files/Iron_folic_acid_supplements_who_guidelines.txt", "Iron folic acid supplement by who for pregnant women", "C:\\Users\\tanu0\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\context-files\\Iron_folic_acid_supplements_who_guidelines.txt"), +// Triple("file:///C:/Users/tanu0/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/context-files/nutritional_intervention_who_guidelines.txt", "nutritional intervention guidelines by WHO", "C:\\Users\\tanu0\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\context-files\\nutritional_intervention_who_guidelines.txt"), + Triple("file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Calcium_supplements.txt", "who ANC Guideline Calcium supplements", "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources\\who_ANC_Guideline_Calcium_supplements.txt"), + Triple("file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Zinc_supplements.txt", "who ANC Guideline Zinc supplements", "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources\\who_ANC_Guideline_Zinc_supplements.txt"), + Triple("file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Vitamin_A_Supplements.txt", "who ANC Guideline Vitamin A Supplements", "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources\\who_ANC_Guideline_Vitamin_A_Supplements.txt"), + Triple("file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt", "who guidelines nutritional interventions anc", "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources\\who_guidelines_nutritional_interventions_anc.txt") + ) - - - -// val textFilePath = "/C://Users//developer//Downloads//kotlin-sdk//samples//weather-stdio-server//src//main//kotlin//io//modelcontextprotocol//sample//server//resources//who_guidelines_nutritional_interventions_anc.txt" -// val resourceFolderPath = "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources" -// val resourceDir = File(resourceFolderPath) -// -// if(!resourceDir.exists() || !resourceDir.isDirectory){ -// throw RuntimeException("Resource directory not found: $resourceFolderPath") -// } -// -// resourceDir.listFiles{ file -> file.extension == "txt"}?.forEach{file -> -// val name = file.nameWithoutExtension.replace('_',' ').replaceFirstChar{it.uppercase()} -// val uri = "file://${file.absolutePath.replace("\\","/")}" -// val description = "Guideline section: $name" -// -// server.addResource( -// uri = uri, -// name = name, -// description = description, -// mimeType = "text/plain" -// ){ -// request -> -// val content = file.readText() -// println("content: ${content}") -// println("Serving resource: $name") -// ReadResourceResult( -// contents = listOf( -// TextResourceContents( -// text = content, -// uri = request.uri, -// mimeType = "text/plain" -// ) -// ) -// ) -// -// -// } -// } - -// -// val textFilePath = "C:\\Users\\developer\\Downloads\\kotlin-sdk\\samples\\weather-stdio-server\\src\\main\\kotlin\\io\\modelcontextprotocol\\sample\\server\\resources\\who_guidelines_nutritional_interventions_anc.txt" -// val textFile = File(textFilePath) -// val resourceUri = "file:///C:/Users/developer/Downloads/kotlin-sdk/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_guidelines_nutritional_interventions_anc.txt" -// // Handle resources/list request -// server.addResource( -// uri = resourceUri, -// name = "WHO Nutritional Interventions Guidelines", -// description = "WHO guidelines on nutritional interventions for antenatal care", -// mimeType = "text/plain" -// ) { request -> -// if (!textFile.exists()) { -// throw RuntimeException("Resource file not found: $textFilePath") -// } -// val content = textFile.readText() -// println("content: ${content}") -// ReadResourceResult( -// contents = listOf( -// TextResourceContents( -// text = content, -// uri = request.uri, -// mimeType = "text/plain" -// ) -// ) -// ) -// } - - + for ((uri, name, path) in files) { + server.addResource( + uri = uri, + name = name, + description = "Resource for $name", + mimeType = "text/plain" + ) { request -> + val content = Files.readString(Paths.get(path)) // 🔥 Read from file at runtime + ReadResourceResult( + contents = listOf( + TextResourceContents( + text = content, + uri = request.uri, + mimeType = "text/plain" + ) + ) + ) + } + } // Create a transport using standard IO for server communication val transport = StdioServerTransport( @@ -208,6 +162,3 @@ fun `run mcp server`() { done.join() } } - - - diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt deleted file mode 100644 index a69ad967..00000000 --- a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/one.txt +++ /dev/null @@ -1 +0,0 @@ -sjcweifjceefekfkekfpewlfpewfdlk \ No newline at end of file diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Calcium_supplements.txt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Calcium_supplements.txt new file mode 100644 index 00000000..05929bd8 --- /dev/null +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Calcium_supplements.txt @@ -0,0 +1,7 @@ +A.3: Calcium supplements + + +RECOMMENDATION A.3: In populations with low dietary calcium intake, daily calcium supplementation (1.5–2.0 g oral elemental calcium) is recommended for pregnant women to reduce the risk of pre-eclampsia. (Context-specific recommendation) + + +Remarks • This recommendation is consistent with the 2011 WHO recommendations for prevention and treatment of pre-eclampsia and eclampsia (57) (strong recommendation, moderate-quality evidence) and supersedes the WHO recommendation found in the 2013 Guideline: calcium supplementation in pregnant women (38). • Dietary counselling of pregnant women should promote adequate calcium intake through locally available, calcium-rich foods. • Dividing the dose of calcium may improve acceptability. The suggested scheme for calcium supplementation is 1.5–2 g daily, with the total dose divided into three doses, preferably taken at mealtimes. • Negative interactions between iron and calcium supplements may occur. Therefore, the two nutrients should preferably be administered several hours apart rather than concomitantly (38). • As there is no clear evidence on the timing of initiation of calcium supplementation, stakeholders may wish to commence supplementation at the first ANC visit, given the possibility of compliance issues. • To reach the most vulnerable populations and ensure a timely and continuous supply of supplements, stakeholders may wish to consider task shifting the provision of calcium supplementation in community settings with poor access to health-care professionals (see Recommendation E.6.1, in section E: Health systems interventions to improve the utilization and quality of ANC). • The implementation and impact of this recommendation should be monitored at the health service, regional and country levels, based on clearly defined criteria and indicators associated with locally agreed targets. Successes and failures should be evaluated to inform integration of this recommendation into the ANC package. • Further WHO guidance on prevention and treatment of pre-eclampsia and eclampsia is available in the 2011 WHO recommendations (57), available at: http://apps.who.int/iris/ bitstream/10665/44703/1/9789241548335_eng.pdf Summary of evidence and considerations Effects of calcium supplements compared with no calcium supplements (for outcomes other than hypertension/pre-eclampsia) (EB Table A.3) Evidence on the effects of calcium supplements on outcomes other than hypertension/pre-eclampsia was derived from a Cochrane systematic review (58). The review included data from 23 trials involving 18 587 pregnant women. The aim of the review was to determine the effect of calcium on maternal and perinatal outcomes other than hypertension. There is a separate Cochrane review on the latter (59), which has been referenced to support existing WHO recommendations on calcium supplementation to prevent pre-eclampsia in populations with low dietary calcium intake (38, 57). In 14 trials, daily calcium doses ranged from 1000 mg to 2000 mg, and in the remainder it was less than 1000 mg. Eleven trials started calcium supplementation at or after 20 weeks of gestation, five trials started before 20 weeks, and the rest did not specify when supplementation was initiated. The primary outcome of 16 of the trials was pregnancy induced hypertension. For outcomes other than hypertension, few trials contributed to each outcome; this is the evidence presented in this section. Maternal outcomes High-certainty evidence shows that calcium supplementation does not have important effects on maternal anaemia (1 trial, 1098 women; RR: 1.04, 95% CI: 0.90–1.22) or caesarean section rates (9 trials, 7440 women; RR: 0.99, 95% CI: 0.89–1.10). Moderate-certainty evidence indicates that calcium supplementation probably has little or no effect on maternal mortality (2 trials, 8974 women; RR: 0.29, 95% CI: 0.06–1.38) and probably makes little or no difference to the risk of urinary tract infections (3 trials, 1743 women; RR: 0.95, 95% CI: 0.69–1.30). Low-certainty evidence suggests that calcium supplementation may make little or no difference to maternal weight gain (3 trials; MD: –29.46 g per week, 95% CI: –119.80 to 60.89 g per week). Maternal satisfaction was not reported in any of the trials included in the Cochrane review. WHO recommendations on antenatal care for a positive pregnancy experience 28 Side-effects: Calcium supplementation makes little or no difference to the risk of “any side-effect”, a composite outcome including headache, vomiting, backache, swelling, vaginal and urinary complaints, dyspepsia and abdominal pain (1 trial, 8312 women; RR: 1.02, 95% CI: 0.93–1.12), and probably makes little or no difference to the risk of urinary stones (3 trials, 13 419 women; RR: 1.11, 95% CI: 0.48–2.54), renal colic (1 trial, 8312 women; RR: 1.67, 95% CI: 0.40–6.99) and impaired renal function (1 trial, 4589 women; RR: 0.91, 95% CI: 0.51–1.64), all assessed as moderate-certainty evidence. Low-certainty evidence suggests that it may have little or no effect on the risk of gallstones (1 trial, 518 women; RR: 1.35, 95% CI: 0.48–3.85). Fetal and neonatal outcomes Calcium supplementation probably has little or no ef fect on low-birth-weight babies (< 2500 g), as indicat ed by evidence that was of moderate certainty due to inconsistency (6 trials, 14 162 women; RR: 0.93, 95% CI: 0.81–1.07). Low-certainty evidence suggests that it may have little or no effect on preterm birth before 37 weeks of gestation (13 trials, 16 139 women; RR: 0.86, 95% CI: 0.70–1.05). However, when trials are stratified by dose (< 1000 mg vs ≥ 1000 mg), moderate-certain ty evidence shows that high-dose calcium supplemen tation probably reduces preterm birth (12 trials, 15 479 women; RR: 0.81, 95% CI: 0.66–0.99). Low-certainty evidence suggests that calcium supplementation may make little or no difference to perinatal mortality (8 trials, 15 785 women; RR: 0.87, 95% CI: 0.72–1.06), and moderate-certainty evidence shows that it probably has little or no effect on stillbirths or fetal deaths (6 trials, 15 269 women; RR: 0.91, 95% CI: 0.72–1.14). Additional considerations n n In the WHO recommendations for prevention and treatment of pre-eclampsia and eclampsia (2011), the recommendation on calcium states: “In areas where dietary calcium intake is low, calcium supplementa tion during pregnancy (at doses of 1.5–2.0 g elemen tal calcium/day) is recommended for the prevention of pre-eclampsia in all women, but especially in those at high risk of developing pre-eclampsia (strong recommendation)” (57). This recommenda tion is based on moderate-quality evidence showing a 64% risk reduction (CI: 35–80%) in pre-eclamp sia among women or populations with low baseline dietary calcium intake (57). n n In considering the evidence from the review of “non-hypertensive” effects, the GDG agreed that the effect of calcium on preterm birth is probably not distinct from the effect on preventing pre-eclampsia, as preterm birth is frequently a consequence of pre-eclampsia. Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources The GDG noted that the cost of calcium (3 × 1 tablet 600 mg per day for 6 months = US$ 11.50) (27) is relatively high compared with supplements such as iron and folic acid. The weight of the supplement may also have cost and logistical implications with respect to storage and transport. Equity In many LMICs, women who are poor, least educated and residing in rural areas have worse pregnancy outcomes than do more advantaged women (29). Preterm birth is the most common cause of neonatal mortality, with the majority of deaths occurring in LMICs. Therefore, effective nutritional interventions in disadvantaged populations aimed at reducing preterm birth could help to address health inequalities. Acceptability Qualitative evidence indicates that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). However, Chapter 3. Evidence and recommendations 29 calcium carbonate tablets might be unpalatable to many women, as they can be large and have a powdery texture (59). In addition, this intervention usually involves taking three tablets a day, which significantly increasing the number of tablets a woman is required to take on a daily basis (i.e. in addition to iron and folic acid). This could have implications for both acceptability and compliance, which needs to be assessed in a programmatic context. Feasibility In addition to the cost, providing calcium supplements may be associated with logistical issues (e.g. supplements are bulky and require adequate transport and storage to maintain stock in facilities) and other challenges (e.g. forecasting). Qualitative evidence on health-care providers’ views suggests that resource constraints may limit implementation (high confidence in the evidence) (45) \ No newline at end of file diff --git a/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Vitamin_A_Supplements.txt b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Vitamin_A_Supplements.txt new file mode 100644 index 00000000..4585fdad --- /dev/null +++ b/samples/weather-stdio-server/src/main/kotlin/io/modelcontextprotocol/sample/server/resources/who_ANC_Guideline_Vitamin_A_Supplements.txt @@ -0,0 +1,7 @@ +A.4: Vitamin A supplements + + +RECOMMENDATION A.4: Vitamin A supplementation is only recommended for pregnant women in areas where vitamin A deficiency is a severe public health problem, to prevent night blindness. (Context-specific recommendation) + + +Remarks • This recommendation supersedes the previous WHO recommendation found in the 2011 Guideline: vitamin A supplementation in pregnant women (60). • Vitamin A is not recommended to improve maternal and perinatal outcomes. • Vitamin A deficiency is a severe public health problem if 5% or more of women in a population have a history of night blindness in their most recent pregnancy in the previous 3–5 years that ended in a live birth, or if 20% or more of pregnant women have a serum retinol level below 0.70 µmol/L (61). Determination of vitamin A deficiency as a public health problem involves estimating the prevalence of deficiency in a population by using specific biochemical and clinical indicators of vitamin A status. • Pregnant women should be encouraged to receive adequate nutrition, which is best achieved through consumption of a healthy, balanced diet, and to refer to WHO guidance on healthy eating (41). • In areas where supplementation is indicated for vitamin A deficiency, it can be given daily or weekly. Existing WHO guidance suggests a dose of up to 10 000 IU vitamin A per day, or a weekly dose of up to 25 000 IU (60). • A single dose of a vitamin A supplement greater than 25 000 IU is not recommended as its safety is uncertain. Furthermore, a single dose of a vitamin A supplement greater than 25 000 IU might be teratogenic if consumed between day 15 and day 60 from conception (60). • There is no demonstrated benefit from taking vitamin A supplements in populations where habitual daily vitamin A intakes exceed 8000 IU or 2400 µg, and the potential risk of adverse events increases with higher intakes (above 10 000 IU) if supplements are routinely taken by people in these populations (62). Summary of evidence and considerations Effects of vitamin A supplements compared with no vitamin A supplements (EB Table A.4) The evidence was derived from a Cochrane systematic review of 19 trials of vitamin A (with or without other supplements) compared with no vitamin A (or placebo, or other supplements) involving over 310 000 women (63). All but one trial (conducted in the United Kingdom) were conducted in LMICs, including Bangladesh, China, Ghana, India, Indonesia, Malawi, Nepal, South Africa and the United Republic of Tanzania. Most trials were conducted in vitamin A deficient populations, with one study including only women living with HIV. Trials varied considerably in design, including in the dose and timing of the intervention. Ten trials contributed data to the comparison of vitamin A alone versus placebo or no treatment. Maternal outcomes Moderate-certainty evidence shows that vitamin A supplementation in vitamin A deficient populations during pregnancy probably reduces maternal anaemia (3 trials, 15 649 women; RR: 0.64, 95% CI: 0.43 0.94), but that it probably has little or no effect on maternal mortality (4 trials, 101 574 women; RR: 0.88, 95% CI: 0.65–1.20). Low-certainty evidence on a composite outcome for maternal infection (including fever for more than one week at one week postnatally, puerperal fever greater than 38°C, subclinical mastitis and/or bacterial vaginosis) suggests that vitamin A supplementation may reduce maternal infection (5 trials, 17 313 women; average RR: 0.45, 95% CI: 0.2–0.99). Side-effects and other maternal ANC guideline outcomes were not reported in the trials. Fetal and neonatal outcomes High-certainly evidence shows that vitamin A supplementation makes little or no difference to perinatal mortality (76 176 women; RR: 1.01, 95% CI: 0.95–1.07), neonatal mortality (3 trials, 89 556 neonates; RR: 0.97, 95% CI: 0.90–1.05) or stillbirths (2 trials, 122 850 neonates; RR: 1.04, 95% CI: 0.98–1.10). Moderate-certainty evidence indicates that vitamin A supplementation probably has little or no effect on low birth weight (< 2500 g) (4 trials, 14 599 neonates; RR: 0. 1.02, 95% CI: 0.89–1.16), and low-certainty evidence suggests that it may have little or no effect on preterm birth (5 trials, 40 137 women; RR: 0.98, 95% CI: 0.94–1.01). Neonatal infections and congenital anomalies were not reported in the trials. Additional considerations n WHO recommendations on antenatal care for a positive pregnancy experience 30 n Moderate-certainty evidence shows that vitamin A supplementation reduces night blindness in pregnant women living in areas with a high prevalence of this condition (2 trials, approximately 100 000 women; RR: 0.79, 95% CI: 0.64–0.98). n n Miscarriage and teratogenicity have been associated with high vitamin A intake within 60 days of conception; however, a WHO expert group consultation in 1998 concluded that daily doses of up to 3000 µg per day after day 60 are probably safe, especially in areas where vitamin A deficiency is common (62). Values Please see “Women’s values” in section 3.A: Background (p. 15). Resources Vitamin A supplements are relatively inexpensive at approximately US$ 0.30 per woman per month (10 000 IU per day or 25 000 IU per week) (27). Vitamin A can be given as a daily or weekly supplement. Equity Effective nutritional interventions in disadvantaged populations could help to address health inequalities by improving nutritional status and promoting good maternal health. Acceptability Qualitative evidence suggests that women in a variety of settings tend to view ANC as a source of knowledge and information and that they generally appreciate any advice (including dietary or nutritional) that may lead to a healthy baby and a positive pregnancy experience (high confidence in the evidence) (22). Feasibility Qualitative evidence shows that where there are additional costs associated with supplements (high confidence in the evidence) or where the recommended intervention is unavailable because of resource constraints (low confidence in the evidence), women may be less likely to engage with ANC (45) \ No newline at end of file