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 template example *)
48let _ = add_resource_template server
49 ~uri_template:"greeting://{name}"
50 ~name:"Greeting"
51 ~description:"Get a greeting for a name"
52 ~mime_type:"text/plain"
53 (fun params ->
54 match params with
55 | [name] -> Printf.sprintf "Hello, %s! Welcome to the OCaml MCP server." name
56 | _ -> "Hello, world! Welcome to the OCaml MCP server."
57 )
58
59(* Define and register a prompt example *)
60let _ = add_prompt server
61 ~name:"capitalize-prompt"
62 ~description:"A prompt to help with text capitalization"
63 ~arguments:[
64 ("text", Some "The text to be capitalized", true)
65 ]
66 (fun args ->
67 let text =
68 try
69 List.assoc "text" args
70 with
71 | Not_found -> "No text provided"
72 in
73 [
74 Prompt.{
75 role = `User;
76 content = Mcp.make_text_content "Please help me capitalize the following text:"
77 };
78 Prompt.{
79 role = `User;
80 content = Mcp.make_text_content text
81 };
82 Prompt.{
83 role = `Assistant;
84 content = Mcp.make_text_content "Here's the capitalized version:"
85 };
86 Prompt.{
87 role = `Assistant;
88 content = Mcp.make_text_content (String.uppercase_ascii text)
89 }
90 ]
91 )
92
93let () =
94 (* Run the server with the default scheduler *)
95 Eio_main.run @@ fun env->
96 Mcp_server.run_server env server