Model Context Protocol in OCaml
1open Mcp 2open Mcp_sdk 3 4(* Helper for extracting string value from JSON *) 5let get_string_param json name = 6 match json with 7 | `Assoc fields -> 8 (match List.assoc_opt name fields with 9 | Some (`String value) -> value 10 | _ -> raise (Failure (Printf.sprintf "Missing or invalid parameter: %s" name))) 11 | _ -> raise (Failure "Expected JSON object") 12 13(* Create a server *) 14let server = create_server 15 ~name:"OCaml MCP Capitalizer" 16 ~version:"0.1.0" 17 ~protocol_version:"2024-11-05" () |> 18 fun server -> 19 (* Set default capabilities *) 20 configure_server server ~with_tools:true ~with_resources:true ~with_prompts:true () 21 22(* Define and register a capitalize tool *) 23let _ = add_tool server 24 ~name:"capitalize" 25 ~description:"Capitalizes the provided text" 26 ~schema_properties:[ 27 ("text", "string", "The text to capitalize") 28 ] 29 ~schema_required:["text"] 30 (fun args -> 31 try 32 let text = get_string_param args "text" in 33 let capitalized_text = String.uppercase_ascii text in 34 TextContent.yojson_of_t TextContent.{ 35 text = capitalized_text; 36 annotations = None 37 } 38 with 39 | Failure msg -> 40 Log.errorf "Error in capitalize tool: %s" msg; 41 TextContent.yojson_of_t TextContent.{ 42 text = Printf.sprintf "Error: %s" msg; 43 annotations = None 44 } 45 ) 46 47(* Define and register a resource example *) 48let _ = add_resource server 49 ~uri_template:"greeting://{name}" 50 ~description:"Get a greeting for a name" 51 ~mime_type:"text/plain" 52 (fun params -> 53 match params with 54 | [name] -> Printf.sprintf "Hello, %s! Welcome to the OCaml MCP server." name 55 | _ -> "Hello, world! Welcome to the OCaml MCP server." 56 ) 57 58(* Define and register a prompt example *) 59let _ = add_prompt server 60 ~name:"capitalize-prompt" 61 ~description:"A prompt to help with text capitalization" 62 ~arguments:[ 63 ("text", Some "The text to be capitalized", true) 64 ] 65 (fun args -> 66 let text = 67 try 68 List.assoc "text" args 69 with 70 | Not_found -> "No text provided" 71 in 72 [ 73 Prompt.{ 74 role = `User; 75 content = Mcp.make_text_content "Please help me capitalize the following text:" 76 }; 77 Prompt.{ 78 role = `User; 79 content = Mcp.make_text_content text 80 }; 81 Prompt.{ 82 role = `Assistant; 83 content = Mcp.make_text_content "Here's the capitalized version:" 84 }; 85 Prompt.{ 86 role = `Assistant; 87 content = Mcp.make_text_content (String.uppercase_ascii text) 88 } 89 ] 90 ) 91 92let () = 93 (* Run the server with the default scheduler *) 94 Eio_main.run @@ fun env-> 95 Mcp_server.run_server env server