Model Context Protocol in OCaml
1open Mcp
2open Jsonrpc
3open Mcp_sdk
4
5(* Process initialize request *)
6let handle_initialize server req =
7 Log.debug "Processing initialize request";
8 let result = match req.JSONRPCMessage.params with
9 | Some params ->
10 let req_data = Initialize.Request.t_of_yojson params in
11 Log.debug (Printf.sprintf "Client info: %s v%s"
12 req_data.client_info.name req_data.client_info.version);
13 Log.debug (Printf.sprintf "Client protocol version: %s" req_data.protocol_version);
14
15 (* Create initialize response *)
16 let result = Initialize.Result.create
17 ~capabilities:(capabilities server)
18 ~server_info:Implementation.{
19 name = name server;
20 version = version server
21 }
22 ~protocol_version:(protocol_version server)
23 ~instructions:(Printf.sprintf "This server provides tools for %s." (name server))
24 ()
25 in
26 Initialize.Result.yojson_of_t result
27 | None ->
28 Log.error "Missing params for initialize request";
29 `Assoc [("error", `String "Missing params for initialize request")]
30 in
31 Some (create_response ~id:req.id ~result)
32
33(* Process tools/list request *)
34let handle_tools_list server (req:JSONRPCMessage.request) =
35 Log.debug "Processing tools/list request";
36 let tool_list = List.map Tool.to_json (tools server) in
37 let result = `Assoc [("tools", `List tool_list)] in
38 Some (create_response ~id:req.id ~result)
39
40(* Process prompts/list request *)
41let handle_prompts_list server (req:JSONRPCMessage.request) =
42 Log.debug "Processing prompts/list request";
43 let prompt_list = List.map Prompt.to_json (prompts server) in
44 let result = `Assoc [("prompts", `List prompt_list)] in
45 Some (create_response ~id:req.id ~result)
46
47(* Process resources/list request *)
48let handle_resources_list server (req:JSONRPCMessage.request) =
49 Log.debug "Processing resources/list request";
50 let resource_list = List.map Resource.to_json (resources server) in
51 let result = `Assoc [("resources", `List resource_list)] in
52 Some (create_response ~id:req.id ~result)
53
54(* Extract the tool name from params *)
55let extract_tool_name params =
56 match List.assoc_opt "name" params with
57 | Some (`String name) ->
58 Log.debug (Printf.sprintf "Tool name: %s" name);
59 Some name
60 | _ ->
61 Log.error "Missing or invalid 'name' parameter in tool call";
62 None
63
64(* Extract the tool arguments from params *)
65let extract_tool_arguments params =
66 match List.assoc_opt "arguments" params with
67 | Some (args) ->
68 Log.debug (Printf.sprintf "Tool arguments: %s" (Yojson.Safe.to_string args));
69 args
70 | _ ->
71 Log.debug "No arguments provided for tool call, using empty object";
72 `Assoc [] (* Empty arguments is valid *)
73
74(* Create a proper JSONRPC error with code and data *)
75let create_jsonrpc_error id code message ?data () =
76 let error_code = ErrorCode.to_int code in
77 let error_data = match data with
78 | Some d -> d
79 | None -> `Null
80 in
81 create_error ~id ~code:error_code ~message ~data:(Some error_data) ()
82
83(* Create a tool error result with structured content *)
84let create_tool_error_result error =
85 create_tool_result [make_text_content error] ~is_error:true
86
87(* Handle tool execution errors *)
88let handle_tool_execution_error err =
89 Log.error (Printf.sprintf "Tool execution failed: %s" err);
90 create_tool_error_result (Printf.sprintf "Error executing tool: %s" err)
91
92(* Handle unknown tool error *)
93let handle_unknown_tool_error name =
94 Log.error (Printf.sprintf "Unknown tool: %s" name);
95 create_tool_error_result (Printf.sprintf "Unknown tool: %s" name)
96
97(* Handle general tool execution exception *)
98let handle_tool_execution_exception exn =
99 Log.error (Printf.sprintf "Exception executing tool: %s" (Printexc.to_string exn));
100 create_tool_error_result (Printf.sprintf "Internal error: %s" (Printexc.to_string exn))
101
102(* Execute a tool *)
103let execute_tool server ctx name args =
104 try
105 let tool = List.find (fun t -> t.Tool.name = name) (tools server) in
106 Log.debug (Printf.sprintf "Found tool: %s" name);
107
108 (* Call the tool handler *)
109 match tool.handler ctx args with
110 | Ok result ->
111 Log.debug "Tool execution succeeded";
112 result
113 | Error err -> handle_tool_execution_error err
114 with
115 | Not_found -> handle_unknown_tool_error name
116 | exn -> handle_tool_execution_exception exn
117
118(* Process tools/call request *)
119let handle_tools_call server req =
120 Log.debug "Processing tools/call request";
121 match req.JSONRPCMessage.params with
122 | Some (`Assoc params) ->
123 (match extract_tool_name params with
124 | Some name ->
125 let args = extract_tool_arguments params in
126
127 (* Create context for this request *)
128 let ctx = Context.create
129 ?request_id:(Some req.id)
130 ?progress_token:req.progress_token
131 ~lifespan_context:[("tools/call", `Assoc params)]
132 ()
133 in
134
135 (* Execute the tool *)
136 let result = execute_tool server ctx name args in
137
138 Some (create_response ~id:req.id ~result)
139 | None ->
140 Some (create_jsonrpc_error req.id InvalidParams "Missing tool name parameter" ()))
141 | _ ->
142 Log.error "Invalid params format for tools/call";
143 Some (create_jsonrpc_error req.id InvalidParams "Invalid params format for tools/call" ())
144
145(* Process ping request *)
146let handle_ping (req:JSONRPCMessage.request) =
147 Log.debug "Processing ping request";
148 Some (create_response ~id:req.JSONRPCMessage.id ~result:(`Assoc []))
149
150(* Handle notifications/initialized *)
151let handle_initialized (notif:JSONRPCMessage.notification) =
152 Log.debug "Client initialization complete - Server is now ready to receive requests";
153 Log.debug (Printf.sprintf "Notification params: %s"
154 (match notif.JSONRPCMessage.params with
155 | Some p -> Yojson.Safe.to_string p
156 | None -> "null"));
157 None
158
159(* Process a single message using the MCP SDK *)
160let process_message server message =
161 try
162 Log.debug (Printf.sprintf "Processing message: %s" (Yojson.Safe.to_string message));
163 match JSONRPCMessage.t_of_yojson message with
164 | JSONRPCMessage.Request req ->
165 Log.debug (Printf.sprintf "Received request with method: %s" req.method_);
166 (match req.method_ with
167 | "initialize" -> handle_initialize server req
168 | "tools/list" -> handle_tools_list server req
169 | "tools/call" -> handle_tools_call server req
170 | "prompts/list" -> handle_prompts_list server req
171 | "resources/list" -> handle_resources_list server req
172 | "ping" -> handle_ping req
173 | _ ->
174 Log.error (Printf.sprintf "Unknown method received: %s" req.method_);
175 Some (create_jsonrpc_error req.id MethodNotFound ("Method not found: " ^ req.method_) ()))
176 | JSONRPCMessage.Notification notif ->
177 Log.debug (Printf.sprintf "Received notification with method: %s" notif.method_);
178 (match notif.method_ with
179 | "notifications/initialized" -> handle_initialized notif
180 | _ ->
181 Log.debug (Printf.sprintf "Ignoring notification: %s" notif.method_);
182 None)
183 | JSONRPCMessage.Response _ ->
184 Log.error "Unexpected response message received";
185 None
186 | JSONRPCMessage.Error _ ->
187 Log.error "Unexpected error message received";
188 None
189 with
190 | Json.Of_json (msg, _) ->
191 Log.error (Printf.sprintf "JSON error: %s" msg);
192 (* Can't respond with error because we don't have a request ID *)
193 None
194 | Yojson.Json_error msg ->
195 Log.error (Printf.sprintf "JSON parse error: %s" msg);
196 (* Can't respond with error because we don't have a request ID *)
197 None
198 | exc ->
199 Log.error (Printf.sprintf "Exception during message processing: %s" (Printexc.to_string exc));
200 Log.error (Printf.sprintf "Backtrace: %s" (Printexc.get_backtrace()));
201 Log.error (Printf.sprintf "Message was: %s" (Yojson.Safe.to_string message));
202 None
203
204(* Extract a request ID from a potentially malformed message *)
205let extract_request_id json =
206 try
207 match json with
208 | `Assoc fields ->
209 (match List.assoc_opt "id" fields with
210 | Some (`Int id) -> Some (`Int id)
211 | Some (`String id) -> Some (`String id)
212 | _ -> None)
213 | _ -> None
214 with _ -> None
215
216(* Handle processing for an input line *)
217let process_input_line server line =
218 if line = "" then (
219 Log.debug "Empty line received, ignoring";
220 None
221 ) else (
222 Log.debug (Printf.sprintf "Raw input: %s" line);
223 try
224 let json = Yojson.Safe.from_string line in
225 Log.debug "Successfully parsed JSON";
226
227 (* Process the message *)
228 process_message server json
229 with
230 | Yojson.Json_error msg -> begin
231 Log.error (Printf.sprintf "Error parsing JSON: %s" msg);
232 Log.error (Printf.sprintf "Input was: %s" line);
233 None
234 end
235 )
236
237(* Send a response to the client *)
238let send_response stdout response =
239 let response_json = JSONRPCMessage.yojson_of_t response in
240 let response_str = Yojson.Safe.to_string response_json in
241 Log.debug (Printf.sprintf "Sending response: %s" response_str);
242
243 (* Write the response followed by a newline *)
244 Eio.Flow.copy_string response_str stdout;
245 Eio.Flow.copy_string "\n" stdout
246
247(* Run the MCP server with the given server configuration *)
248let run_server env server =
249 let stdin = Eio.Stdenv.stdin env in
250 let stdout = Eio.Stdenv.stdout env in
251
252 Log.debug (Printf.sprintf "Starting MCP server: %s v%s" (name server) (version server));
253 Log.debug (Printf.sprintf "Protocol version: %s" (protocol_version server));
254
255 (* Enable exception backtraces *)
256 Printexc.record_backtrace true;
257
258 let buf = Eio.Buf_read.of_flow stdin ~initial_size:100 ~max_size:1_000_000 in
259
260 (* Main processing loop *)
261 try
262 while true do
263 Log.debug "Waiting for message...";
264 let line = Eio.Buf_read.line buf in
265
266 (* Process the input and send response if needed *)
267 match process_input_line server line with
268 | Some response -> send_response stdout response
269 | None -> Log.debug "No response needed for this message"
270 done
271 with
272 | End_of_file ->
273 Log.debug "End of file received on stdin";
274 ()
275 | Eio.Exn.Io _ as exn ->
276 Log.error (Printf.sprintf "I/O error while reading: %s" (Printexc.to_string exn));
277 ()
278 | exn ->
279 Log.error (Printf.sprintf "Exception while reading: %s" (Printexc.to_string exn));
280 ()