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" (Method.to_string req.meth));
166 (match req.meth with
167 | Method.Initialize -> handle_initialize server req
168 | Method.ToolsList -> handle_tools_list server req
169 | Method.ToolsCall -> handle_tools_call server req
170 | Method.PromptsList -> handle_prompts_list server req
171 | Method.ResourcesList -> handle_resources_list server req
172 | _ ->
173 Log.error (Printf.sprintf "Unknown method received: %s" (Method.to_string req.meth));
174 Some (create_jsonrpc_error req.id MethodNotFound ("Method not found: " ^ (Method.to_string req.meth)) ()))
175 | JSONRPCMessage.Notification notif ->
176 Log.debug (Printf.sprintf "Received notification with method: %s" (Method.to_string notif.meth));
177 (match notif.meth with
178 | Method.Initialized -> handle_initialized notif
179 | _ ->
180 Log.debug (Printf.sprintf "Ignoring notification: %s" (Method.to_string notif.meth));
181 None)
182 | JSONRPCMessage.Response _ ->
183 Log.error "Unexpected response message received";
184 None
185 | JSONRPCMessage.Error _ ->
186 Log.error "Unexpected error message received";
187 None
188 with
189 | Json.Of_json (msg, _) ->
190 Log.error (Printf.sprintf "JSON error: %s" msg);
191 (* Can't respond with error because we don't have a request ID *)
192 None
193 | Yojson.Json_error msg ->
194 Log.error (Printf.sprintf "JSON parse error: %s" msg);
195 (* Can't respond with error because we don't have a request ID *)
196 None
197 | exc ->
198 Log.error (Printf.sprintf "Exception during message processing: %s" (Printexc.to_string exc));
199 Log.error (Printf.sprintf "Backtrace: %s" (Printexc.get_backtrace()));
200 Log.error (Printf.sprintf "Message was: %s" (Yojson.Safe.to_string message));
201 None
202
203(* Extract a request ID from a potentially malformed message *)
204let extract_request_id json =
205 try
206 match json with
207 | `Assoc fields ->
208 (match List.assoc_opt "id" fields with
209 | Some (`Int id) -> Some (`Int id)
210 | Some (`String id) -> Some (`String id)
211 | _ -> None)
212 | _ -> None
213 with _ -> None
214
215(* Handle processing for an input line *)
216let process_input_line server line =
217 if line = "" then (
218 Log.debug "Empty line received, ignoring";
219 None
220 ) else (
221 Log.debug (Printf.sprintf "Raw input: %s" line);
222 try
223 let json = Yojson.Safe.from_string line in
224 Log.debug "Successfully parsed JSON";
225
226 (* Process the message *)
227 process_message server json
228 with
229 | Yojson.Json_error msg -> begin
230 Log.error (Printf.sprintf "Error parsing JSON: %s" msg);
231 Log.error (Printf.sprintf "Input was: %s" line);
232 None
233 end
234 )
235
236(* Send a response to the client *)
237let send_response stdout response =
238 let response_json = JSONRPCMessage.yojson_of_t response in
239 let response_str = Yojson.Safe.to_string response_json in
240 Log.debug (Printf.sprintf "Sending response: %s" response_str);
241
242 (* Write the response followed by a newline *)
243 Eio.Flow.copy_string response_str stdout;
244 Eio.Flow.copy_string "\n" stdout
245
246(* Run the MCP server with the given server configuration *)
247let run_server env server =
248 let stdin = Eio.Stdenv.stdin env in
249 let stdout = Eio.Stdenv.stdout env in
250
251 Log.debug (Printf.sprintf "Starting MCP server: %s v%s" (name server) (version server));
252 Log.debug (Printf.sprintf "Protocol version: %s" (protocol_version server));
253
254 (* Enable exception backtraces *)
255 Printexc.record_backtrace true;
256
257 let buf = Eio.Buf_read.of_flow stdin ~initial_size:100 ~max_size:1_000_000 in
258
259 (* Main processing loop *)
260 try
261 while true do
262 Log.debug "Waiting for message...";
263 let line = Eio.Buf_read.line buf in
264
265 (* Process the input and send response if needed *)
266 match process_input_line server line with
267 | Some response -> send_response stdout response
268 | None -> Log.debug "No response needed for this message"
269 done
270 with
271 | End_of_file ->
272 Log.debug "End of file received on stdin";
273 ()
274 | Eio.Exn.Io _ as exn ->
275 Log.error (Printf.sprintf "I/O error while reading: %s" (Printexc.to_string exn));
276 ()
277 | exn ->
278 Log.error (Printf.sprintf "Exception while reading: %s" (Printexc.to_string exn));
279 ()