Model Context Protocol in OCaml
at main 2.8 kB view raw
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 | _ -> 11 raise 12 (Failure (Printf.sprintf "Missing or invalid parameter: %s" name))) 13 | _ -> raise (Failure "Expected JSON object") 14 15(* Create a server *) 16let server = 17 create_server ~name:"OCaml MCP Capitalizer" ~version:"0.1.0" 18 ~protocol_version:"2024-11-05" () 19 |> fun server -> 20 (* Set default capabilities *) 21 configure_server server ~with_tools:true ~with_resources:true 22 ~with_prompts:true () 23 24(* Define and register a capitalize tool *) 25let _ = 26 add_tool server ~name:"capitalize" 27 ~description:"Capitalizes the provided text" 28 ~schema_properties:[ ("text", "string", "The text to capitalize") ] 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 35 TextContent.{ text = capitalized_text; annotations = None } 36 with Failure msg -> 37 Logs.err (fun m -> m "Error in capitalize tool: %s" msg); 38 TextContent.yojson_of_t 39 TextContent. 40 { text = Printf.sprintf "Error: %s" msg; annotations = None }) 41 42(* Define and register a resource template example *) 43let _ = 44 add_resource_template server ~uri_template:"greeting://{name}" 45 ~name:"Greeting" ~description:"Get a greeting for a name" 46 ~mime_type:"text/plain" (fun params -> 47 match params with 48 | [ name ] -> 49 Printf.sprintf "Hello, %s! Welcome to the OCaml MCP server." name 50 | _ -> "Hello, world! Welcome to the OCaml MCP server.") 51 52(* Define and register a prompt example *) 53let _ = 54 add_prompt server ~name:"capitalize-prompt" 55 ~description:"A prompt to help with text capitalization" 56 ~arguments:[ ("text", Some "The text to be capitalized", true) ] 57 (fun args -> 58 let text = 59 try List.assoc "text" args with Not_found -> "No text provided" 60 in 61 [ 62 Prompt. 63 { 64 role = `User; 65 content = 66 Mcp.make_text_content 67 "Please help me capitalize the following text:"; 68 }; 69 Prompt.{ role = `User; content = Mcp.make_text_content text }; 70 Prompt. 71 { 72 role = `Assistant; 73 content = Mcp.make_text_content "Here's the capitalized version:"; 74 }; 75 Prompt. 76 { 77 role = `Assistant; 78 content = Mcp.make_text_content (String.uppercase_ascii text); 79 }; 80 ]) 81 82let () = 83 Logs.set_reporter (Logs.format_reporter ()); 84 Eio_main.run @@ fun env -> Mcp_server.run_stdio_server env server