···
1
-
(** MCP - Model Context Protocol implementation
3
-
The Model Context Protocol (MCP) is a standardized protocol for AI agents to exchange context
4
-
with servers. This module provides the core OCaml implementation of MCP including
5
-
all message types, content representations, and serialization functionality.
1
+
(** MCP - Model Context Protocol implementation
3
+
The Model Context Protocol (MCP) is a standardized protocol for AI agents to
4
+
exchange context with servers. This module provides the core OCaml
5
+
implementation of MCP including all message types, content representations,
6
+
and serialization functionality.
- Uses JSON-RPC 2.0 as its underlying message format with UTF-8 encoding
9
-
- Follows a client-server model where clients (often LLM-integrated applications) communicate with MCP servers
10
+
- Follows a client-server model where clients (often LLM-integrated
11
+
applications) communicate with MCP servers
- Supports multiple transport methods including stdio and streamable HTTP
11
-
- Implements a three-phase connection lifecycle: initialization, operation, and shutdown
12
-
- Provides capability negotiation during initialization to determine available features
13
-
- Offers four primary context exchange mechanisms:
14
-
1. Resources: Server-exposed data that provides context to language models
15
-
2. Tools: Server-exposed functionality that can be invoked by language models
16
-
3. Prompts: Server-defined templates for structuring interactions with models
13
+
- Implements a three-phase connection lifecycle: initialization, operation,
15
+
- Provides capability negotiation during initialization to determine
17
+
- Offers four primary context exchange mechanisms: 1. Resources:
18
+
Server-exposed data that provides context to language models 2. Tools:
19
+
Server-exposed functionality that can be invoked by language models 3.
20
+
Prompts: Server-defined templates for structuring interactions with models
4. Sampling: Client-exposed ability to generate completions from LLMs
18
-
- Supports multimodal content types: text, images, audio, and embedded resources
22
+
- Supports multimodal content types: text, images, audio, and embedded
- Includes standardized error handling with defined error codes
21
-
This implementation follows Protocol Revision 2025-03-26.
26
+
This implementation follows Protocol Revision 2025-03-26. *)
(** Utility functions for JSON parsing *)
32
+
val json_error : ('a, unit, string, 'b) format4 -> Json.t -> 'a
(** Helper to raise a Json.Of_json exception with formatted message
@param fmt Format string for the error message
@param json JSON value to include in the exception
@return Never returns, always raises an exception
32
-
@raise Json.Of_json with the formatted message and JSON value
34
-
val json_error : ('a, unit, string, 'b) format4 -> Json.t -> 'a
36
-
(** Extract a string field from JSON object or raise an error
37
+
@raise Json.Of_json with the formatted message and JSON value *)
39
+
val get_string_field : (string * Json.t) list -> string -> Json.t -> string
40
+
(** Extract a string field from JSON object or raise an error
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@param json Original JSON for error context
@return The string value of the field
41
-
@raise Json.Of_json if the field is missing or not a string
43
-
val get_string_field : (string * Json.t) list -> string -> Json.t -> string
45
+
@raise Json.Of_json if the field is missing or not a string *)
47
+
val get_optional_string_field :
48
+
(string * Json.t) list -> string -> string option
(** Extract an optional string field from JSON object
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@return Some string if present and a string, None if missing
49
-
@raise Json.Of_json if the field exists but is not a string
51
-
val get_optional_string_field : (string * Json.t) list -> string -> string option
53
+
@raise Json.Of_json if the field exists but is not a string *)
55
+
val get_int_field : (string * Json.t) list -> string -> Json.t -> int
(** Extract an int field from JSON object or raise an error
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@param json Original JSON for error context
@return The int value of the field
58
-
@raise Json.Of_json if the field is missing or not an int
60
-
val get_int_field : (string * Json.t) list -> string -> Json.t -> int
61
+
@raise Json.Of_json if the field is missing or not an int *)
63
+
val get_float_field : (string * Json.t) list -> string -> Json.t -> float
(** Extract a float field from JSON object or raise an error
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@param json Original JSON for error context
@return The float value of the field
67
-
@raise Json.Of_json if the field is missing or not a float
69
-
val get_float_field : (string * Json.t) list -> string -> Json.t -> float
69
+
@raise Json.Of_json if the field is missing or not a float *)
71
+
val get_bool_field : (string * Json.t) list -> string -> Json.t -> bool
(** Extract a boolean field from JSON object or raise an error
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@param json Original JSON for error context
@return The boolean value of the field
76
-
@raise Json.Of_json if the field is missing or not a boolean
78
-
val get_bool_field : (string * Json.t) list -> string -> Json.t -> bool
77
+
@raise Json.Of_json if the field is missing or not a boolean *)
79
+
val get_object_field :
80
+
(string * Json.t) list -> string -> Json.t -> (string * Json.t) list
(** Extract an object field from JSON object or raise an error
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@param json Original JSON for error context
@return The object as an assoc list
85
-
@raise Json.Of_json if the field is missing or not an object
87
-
val get_object_field : (string * Json.t) list -> string -> Json.t -> (string * Json.t) list
86
+
@raise Json.Of_json if the field is missing or not an object *)
88
+
val get_list_field : (string * Json.t) list -> string -> Json.t -> Json.t list
(** Extract a list field from JSON object or raise an error
@param fields Assoc list of fields from JSON object
@param name Field name to extract
@param json Original JSON for error context
94
-
@raise Json.Of_json if the field is missing or not a list
96
-
val get_list_field : (string * Json.t) list -> string -> Json.t -> Json.t list
94
+
@raise Json.Of_json if the field is missing or not a list *)
96
+
val verify_string_field :
97
+
(string * Json.t) list -> string -> string -> Json.t -> unit
(** Verify a specific string value in a field
@param fields Assoc list of fields from JSON object
@param name Field name to check
···
@param json Original JSON for error context
@raise Json.Of_json if the field is missing or not equal to expected_value
105
-
val verify_string_field : (string * Json.t) list -> string -> string -> Json.t -> unit
(** Error codes for JSON-RPC *)
(** Standard JSON-RPC error codes with MCP-specific additions *)
112
-
| ParseError (** -32700 - Invalid JSON *)
113
-
| InvalidRequest (** -32600 - Invalid JSON-RPC request *)
114
-
| MethodNotFound (** -32601 - Method not available *)
115
-
| InvalidParams (** -32602 - Invalid method parameters *)
116
-
| InternalError (** -32603 - Internal JSON-RPC error *)
117
-
| ResourceNotFound (** -32002 - Custom MCP error: requested resource not found *)
118
-
| AuthRequired (** -32001 - Custom MCP error: authentication required *)
119
-
| CustomError of int (** For any other error codes *)
111
+
| ParseError (** -32700 - Invalid JSON *)
112
+
| InvalidRequest (** -32600 - Invalid JSON-RPC request *)
113
+
| MethodNotFound (** -32601 - Method not available *)
114
+
| InvalidParams (** -32602 - Invalid method parameters *)
115
+
| InternalError (** -32603 - Internal JSON-RPC error *)
117
+
(** -32002 - Custom MCP error: requested resource not found *)
118
+
| AuthRequired (** -32001 - Custom MCP error: authentication required *)
119
+
| CustomError of int (** For any other error codes *)
121
+
val to_int : t -> int
(** Convert the error code to its integer representation
@param code The error code to convert
123
-
@return The integer error code as defined in the JSON-RPC spec
125
-
val to_int : t -> int
124
+
@return The integer error code as defined in the JSON-RPC spec *)
126
+
val to_message : t -> string
(** Get error message for standard error codes
@param code The error code to get message for
129
-
@return A standard message for the error code
131
-
val to_message : t -> string
129
+
@return A standard message for the error code *)
(** MCP Protocol Methods - Algebraic data type representing all MCP methods *)
···
(** Method type representing all MCP protocol methods *)
(* Initialization and lifecycle methods *)
139
-
| Initialize (** Start the MCP lifecycle *)
140
-
| Initialized (** Signal readiness after initialization *)
137
+
| Initialize (** Start the MCP lifecycle *)
138
+
| Initialized (** Signal readiness after initialization *)
143
-
| ResourcesList (** Discover available resources *)
144
-
| ResourcesRead (** Retrieve resource contents *)
140
+
| ResourcesList (** Discover available resources *)
141
+
| ResourcesRead (** Retrieve resource contents *)
| ResourceTemplatesList (** List available resource templates *)
146
-
| ResourcesSubscribe (** Subscribe to resource changes *)
147
-
| ResourcesListChanged (** Resource list has changed *)
148
-
| ResourcesUpdated (** Resource has been updated *)
143
+
| ResourcesSubscribe (** Subscribe to resource changes *)
144
+
| ResourcesListChanged (** Resource list has changed *)
145
+
| ResourcesUpdated (** Resource has been updated *)
151
-
| ToolsList (** Discover available tools *)
152
-
| ToolsCall (** Invoke a tool *)
153
-
| ToolsListChanged (** Tool list has changed *)
147
+
| ToolsList (** Discover available tools *)
148
+
| ToolsCall (** Invoke a tool *)
149
+
| ToolsListChanged (** Tool list has changed *)
156
-
| PromptsList (** Discover available prompts *)
157
-
| PromptsGet (** Retrieve a prompt template with arguments *)
158
-
| PromptsListChanged (** Prompt list has changed *)
151
+
| PromptsList (** Discover available prompts *)
152
+
| PromptsGet (** Retrieve a prompt template with arguments *)
153
+
| PromptsListChanged (** Prompt list has changed *)
(* Progress notifications *)
161
-
| Progress (** Progress update for long-running operations *)
155
+
| Progress (** Progress update for long-running operations *)
157
+
val to_string : t -> string
(** Convert method type to string representation
@param meth The method to convert
165
-
@return The string representation of the method (e.g., "initialize", "resources/list")
167
-
val to_string : t -> string
161
+
The string representation of the method (e.g., "initialize",
162
+
"resources/list") *)
164
+
val of_string : string -> t
(** Convert string to method type
@param s The string representation of the method
@return The corresponding method type
172
-
@raise Failure if the string is not a valid MCP method
174
-
val of_string : string -> t
168
+
@raise Failure if the string is not a valid MCP method *)
(** Roles for conversation participants *)
182
-
(** Role represents conversation participants in MCP messages.
183
-
Roles can be either 'user' or 'assistant', determining the
184
-
source of each message in a conversation. *)
type t = [ `User | `Assistant ]
176
+
(** Role represents conversation participants in MCP messages. Roles can be
177
+
either 'user' or 'assistant', determining the source of each message in a
include Json.Jsonable.S with type t := t
(** Progress tokens for long-running operations *)
module ProgressToken : sig
191
-
(** Progress tokens identify long-running operations and enable
192
-
servers to provide progress updates to clients. This is used
193
-
to track operations that may take significant time to complete. *)
type t = [ `String of string | `Int of int ]
186
+
(** Progress tokens identify long-running operations and enable servers to
187
+
provide progress updates to clients. This is used to track operations that
188
+
may take significant time to complete. *)
include Json.Jsonable.S with type t := t
200
-
(** Request IDs uniquely identify JSON-RPC requests, allowing responses
201
-
to be correlated with their originating requests. They can be either
202
-
string or integer values. *)
type t = [ `String of string | `Int of int ]
196
+
(** Request IDs uniquely identify JSON-RPC requests, allowing responses to be
197
+
correlated with their originating requests. They can be either string or
include Json.Jsonable.S with type t := t
(** Cursors for pagination *)
209
-
(** Cursors enable pagination in list operations for resources, tools, and prompts.
210
-
When a server has more items than can be returned in a single response,
211
-
it provides a cursor for the client to retrieve subsequent pages. *)
206
+
(** Cursors enable pagination in list operations for resources, tools, and
207
+
prompts. When a server has more items than can be returned in a single
208
+
response, it provides a cursor for the client to retrieve subsequent
include Json.Jsonable.S with type t := t
(** Annotations for objects *)
218
-
(** Annotations provide metadata for content objects, allowing
219
-
role-specific targeting and priority settings. *)
221
-
annotations: annotation option;
216
+
type t = { annotations : annotation option }
217
+
(** Annotations provide metadata for content objects, allowing role-specific
218
+
targeting and priority settings. *)
224
-
audience: Role.t list option;
225
-
(** Optional list of roles that should receive this content *)
226
-
priority: float option;
227
-
(** Optional priority value for this content *)
221
+
audience : Role.t list option;
222
+
(** Optional list of roles that should receive this content *)
223
+
priority : float option; (** Optional priority value for this content *)
include Json.Jsonable.S with type t := t
(** Text content - Core textual message representation in MCP *)
234
-
(** TextContent represents plain text messages in MCP conversations.
235
-
This is the most common content type used for natural language interactions
236
-
between users and assistants. Text content is used in prompts, tool results,
237
-
and model responses.
232
+
text : string; (** The actual text content as a UTF-8 encoded string *)
233
+
annotations : Annotated.annotation option;
234
+
(** Optional annotations for audience targeting and priority.
235
+
Annotations can restrict content visibility to specific roles
236
+
(user/assistant) and indicate relative importance of different
237
+
content elements. *)
239
+
(** TextContent represents plain text messages in MCP conversations. This is
240
+
the most common content type used for natural language interactions
241
+
between users and assistants. Text content is used in prompts, tool
242
+
results, and model responses.
In JSON-RPC, this is represented as:
···
"text": "The text content of the message"
For security, implementations must sanitize text content to prevent
injection attacks or unauthorized access to resources. *)
251
-
(** The actual text content as a UTF-8 encoded string *)
252
-
annotations: Annotated.annotation option;
253
-
(** Optional annotations for audience targeting and priority.
254
-
Annotations can restrict content visibility to specific roles (user/assistant)
255
-
and indicate relative importance of different content elements. *)
include Json.Jsonable.S with type t := t
(** Image content - Visual data representation in MCP *)
module ImageContent : sig
262
+
(** Base64-encoded image data. All binary image data must be encoded
263
+
using standard base64 encoding (RFC 4648) to safely transmit within
265
+
mime_type : string;
266
+
(** MIME type of the image (e.g., "image/png", "image/jpeg",
267
+
"image/gif", "image/svg+xml"). This field is required and must
268
+
accurately represent the image format to ensure proper handling by
270
+
annotations : Annotated.annotation option;
271
+
(** Optional annotations for audience targeting and priority.
272
+
Annotations can restrict content visibility to specific roles
273
+
(user/assistant) and indicate relative importance of different
274
+
content elements. *)
(** ImageContent enables including visual information in MCP messages,
supporting multimodal interactions where visual context is important.
Images can be used in several scenarios:
- As user inputs for visual understanding tasks
- As context for generating descriptions or analysis
- As outputs from tools that generate visualizations
- As part of prompt templates with visual components
In JSON-RPC, this is represented as:
···
The data MUST be base64-encoded to ensure safe transmission in JSON.
281
-
Common mime types include image/png, image/jpeg, image/gif, and image/svg+xml. *)
284
-
(** Base64-encoded image data. All binary image data must be encoded using
285
-
standard base64 encoding (RFC 4648) to safely transmit within JSON. *)
287
-
(** MIME type of the image (e.g., "image/png", "image/jpeg", "image/gif", "image/svg+xml").
288
-
This field is required and must accurately represent the image format to ensure
289
-
proper handling by clients. *)
290
-
annotations: Annotated.annotation option;
291
-
(** Optional annotations for audience targeting and priority.
292
-
Annotations can restrict content visibility to specific roles (user/assistant)
293
-
and indicate relative importance of different content elements. *)
295
+
Common mime types include image/png, image/jpeg, image/gif, and
include Json.Jsonable.S with type t := t
(** Audio content - Sound data representation in MCP *)
module AudioContent : sig
305
+
(** Base64-encoded audio data. All binary audio data must be encoded
306
+
using standard base64 encoding (RFC 4648) to safely transmit within
308
+
mime_type : string;
309
+
(** MIME type of the audio (e.g., "audio/wav", "audio/mp3", "audio/ogg",
310
+
"audio/mpeg"). This field is required and must accurately represent
311
+
the audio format to ensure proper handling by clients. *)
312
+
annotations : Annotated.annotation option;
313
+
(** Optional annotations for audience targeting and priority.
314
+
Annotations can restrict content visibility to specific roles
315
+
(user/assistant) and indicate relative importance of different
316
+
content elements. *)
(** AudioContent enables including audio information in MCP messages,
supporting multimodal interactions where audio context is important.
Audio can be used in several scenarios:
- As user inputs for speech recognition or audio analysis
- As context for transcription or sound classification tasks
- As outputs from tools that generate audio samples
- As part of prompt templates with audio components
In JSON-RPC, this is represented as:
···
The data MUST be base64-encoded to ensure safe transmission in JSON.
319
-
Common mime types include audio/wav, audio/mp3, audio/ogg, and audio/mpeg. *)
322
-
(** Base64-encoded audio data. All binary audio data must be encoded using
323
-
standard base64 encoding (RFC 4648) to safely transmit within JSON. *)
325
-
(** MIME type of the audio (e.g., "audio/wav", "audio/mp3", "audio/ogg", "audio/mpeg").
326
-
This field is required and must accurately represent the audio format to ensure
327
-
proper handling by clients. *)
328
-
annotations: Annotated.annotation option;
329
-
(** Optional annotations for audience targeting and priority.
330
-
Annotations can restrict content visibility to specific roles (user/assistant)
331
-
and indicate relative importance of different content elements. *)
337
+
Common mime types include audio/wav, audio/mp3, audio/ogg, and audio/mpeg.
include Json.Jsonable.S with type t := t
(** Base resource contents - Core resource metadata in MCP *)
module ResourceContents : sig
338
-
(** ResourceContents provides basic metadata for resources in MCP.
340
-
Resources are server-exposed data that provides context to language models,
341
-
such as files, database schemas, or application-specific information.
342
-
Each resource is uniquely identified by a URI.
344
-
The MCP resources architecture is designed to be application-driven, with
345
-
host applications determining how to incorporate context based on their needs.
347
-
In the protocol, resources are discovered via the 'resources/list' endpoint
348
-
and retrieved via the 'resources/read' endpoint. Servers that support resources
349
-
must declare the 'resources' capability during initialization. *)
352
-
(** URI that uniquely identifies the resource.
354
-
Resources use standard URI schemes including:
355
-
- file:// - For filesystem-like resources
356
-
- https:// - For web-accessible resources
357
-
- git:// - For version control integration
359
-
The URI serves as a stable identifier even if the underlying content changes. *)
360
-
mime_type: string option;
361
-
(** Optional MIME type of the resource content to aid in client rendering.
362
-
Common MIME types include text/plain, application/json, image/png, etc.
363
-
For directories, the XDG MIME type inode/directory may be used. *)
347
+
(** URI that uniquely identifies the resource.
349
+
Resources use standard URI schemes including:
350
+
- file:// - For filesystem-like resources
351
+
- https:// - For web-accessible resources
352
+
- git:// - For version control integration
354
+
The URI serves as a stable identifier even if the underlying content
356
+
mime_type : string option;
357
+
(** Optional MIME type of the resource content to aid in client
358
+
rendering. Common MIME types include text/plain, application/json,
359
+
image/png, etc. For directories, the XDG MIME type inode/directory
362
+
(** ResourceContents provides basic metadata for resources in MCP.
364
+
Resources are server-exposed data that provides context to language
365
+
models, such as files, database schemas, or application-specific
366
+
information. Each resource is uniquely identified by a URI.
368
+
The MCP resources architecture is designed to be application-driven, with
369
+
host applications determining how to incorporate context based on their
372
+
In the protocol, resources are discovered via the 'resources/list'
373
+
endpoint and retrieved via the 'resources/read' endpoint. Servers that
374
+
support resources must declare the 'resources' capability during
include Json.Jsonable.S with type t := t
(** Text resource contents - Textual resource data *)
module TextResourceContents : sig
384
+
(** URI that uniquely identifies the resource. This URI can be
385
+
referenced in subsequent requests to fetch updates. *)
387
+
(** The actual text content of the resource as a UTF-8 encoded string.
388
+
This may be sanitized by the server to remove sensitive information.
390
+
mime_type : string option;
391
+
(** Optional MIME type of the text content to aid in client rendering.
392
+
Common text MIME types include: text/plain, text/markdown,
393
+
text/x-python, application/json, text/html, text/csv, etc. *)
(** TextResourceContents represents a text-based resource in MCP.
Text resources are used for sharing code snippets, documentation, logs,
configuration files, and other textual information with language models.
The server handles access control and security, ensuring that only
authorized resources are shared with clients.
In JSON-RPC, this is represented as:
···
"mimeType": "text/plain",
"text": "Resource content"
389
-
(** URI that uniquely identifies the resource.
390
-
This URI can be referenced in subsequent requests to fetch updates. *)
392
-
(** The actual text content of the resource as a UTF-8 encoded string.
393
-
This may be sanitized by the server to remove sensitive information. *)
394
-
mime_type: string option;
395
-
(** Optional MIME type of the text content to aid in client rendering.
396
-
Common text MIME types include: text/plain, text/markdown, text/x-python,
397
-
application/json, text/html, text/csv, etc. *)
include Json.Jsonable.S with type t := t
(** Binary resource contents - Binary resource data *)
module BlobResourceContents : sig
419
+
(** URI that uniquely identifies the resource. This URI can be
420
+
referenced in subsequent requests to fetch updates. *)
422
+
(** Base64-encoded binary data using standard base64 encoding (RFC
423
+
4648). This encoding ensures that binary data can be safely
424
+
transmitted in JSON. *)
425
+
mime_type : string option;
426
+
(** Optional MIME type of the binary content to aid in client rendering.
427
+
Common binary MIME types include: image/png, image/jpeg,
428
+
application/pdf, audio/wav, video/mp4, application/octet-stream,
(** BlobResourceContents represents a binary resource in MCP.
Binary resources allow sharing non-textual data like images, audio files,
407
-
PDFs, and other binary formats with language models that support processing
434
+
PDFs, and other binary formats with language models that support
435
+
processing such content.
In JSON-RPC, this is represented as:
···
"blob": "base64-encoded-data"
419
-
Binary data MUST be properly base64-encoded to ensure safe transmission
420
-
in JSON payloads. *)
423
-
(** URI that uniquely identifies the resource.
424
-
This URI can be referenced in subsequent requests to fetch updates. *)
426
-
(** Base64-encoded binary data using standard base64 encoding (RFC 4648).
427
-
This encoding ensures that binary data can be safely transmitted in JSON. *)
428
-
mime_type: string option;
429
-
(** Optional MIME type of the binary content to aid in client rendering.
430
-
Common binary MIME types include: image/png, image/jpeg, application/pdf,
431
-
audio/wav, video/mp4, application/octet-stream, etc. *)
446
+
Binary data MUST be properly base64-encoded to ensure safe transmission in
include Json.Jsonable.S with type t := t
(** Embedded resource - Resource included directly in messages *)
module EmbeddedResource : sig
438
-
(** EmbeddedResource allows referencing server-side resources directly
439
-
in MCP messages, enabling seamless incorporation of managed content.
456
+
[ `Text of TextResourceContents.t | `Blob of BlobResourceContents.t ];
457
+
(** The resource content, either as text or binary blob. *)
458
+
annotations : Annotated.annotation option;
459
+
(** Optional annotations for audience targeting and priority.
460
+
Annotations can restrict resource visibility to specific roles
461
+
(user/assistant) and indicate relative importance of different
462
+
content elements. *)
464
+
(** EmbeddedResource allows referencing server-side resources directly in MCP
465
+
messages, enabling seamless incorporation of managed content.
Embedded resources can be included in:
- Tool results to provide rich context
- Prompt templates to include reference materials
- Messages to provide additional context to language models
In contrast to direct content (TextContent, ImageContent, AudioContent),
447
-
embedded resources have the advantage of being persistently stored on the server
448
-
with a stable URI, allowing later retrieval and updates through the resources API.
450
-
For example, a tool might return an embedded resource containing a chart or
451
-
a large dataset that the client can later reference or update. *)
453
-
resource: [ `Text of TextResourceContents.t | `Blob of BlobResourceContents.t ];
454
-
(** The resource content, either as text or binary blob. *)
455
-
annotations: Annotated.annotation option;
456
-
(** Optional annotations for audience targeting and priority.
457
-
Annotations can restrict resource visibility to specific roles (user/assistant)
458
-
and indicate relative importance of different content elements. *)
473
+
embedded resources have the advantage of being persistently stored on the
474
+
server with a stable URI, allowing later retrieval and updates through the
477
+
For example, a tool might return an embedded resource containing a chart
478
+
or a large dataset that the client can later reference or update. *)
include Json.Jsonable.S with type t := t
463
-
(** Content type used in messages - Unified multimodal content representation in MCP *)
465
-
| Text of TextContent.t (** Text content for natural language messages. This is the most common content type for user-assistant interactions. *)
466
-
| Image of ImageContent.t (** Image content for visual data. Used for sharing visual context in multimodal conversations. *)
467
-
| Audio of AudioContent.t (** Audio content for audio data. Used for sharing audio context in multimodal conversations. *)
468
-
| Resource of EmbeddedResource.t (** Resource content for referencing server-side resources. Used for incorporating managed server content with stable URIs. *)
483
+
(** Content type used in messages - Unified multimodal content representation in
486
+
| Text of TextContent.t
487
+
(** Text content for natural language messages. This is the most common
488
+
content type for user-assistant interactions. *)
489
+
| Image of ImageContent.t
490
+
(** Image content for visual data. Used for sharing visual context in
491
+
multimodal conversations. *)
492
+
| Audio of AudioContent.t
493
+
(** Audio content for audio data. Used for sharing audio context in
494
+
multimodal conversations. *)
495
+
| Resource of EmbeddedResource.t
496
+
(** Resource content for referencing server-side resources. Used for
497
+
incorporating managed server content with stable URIs. *)
470
-
(** Convert content to Yojson representation
471
-
@param content The content to convert
472
-
@return JSON representation of the content
val yojson_of_content : content -> Json.t
500
+
(** Convert content to Yojson representation
501
+
@param content The content to convert
502
+
@return JSON representation of the content *)
476
-
(** Convert Yojson representation to content
477
-
@param json JSON representation of content
478
-
@return Parsed content object
val content_of_yojson : Json.t -> content
505
+
(** Convert Yojson representation to content
506
+
@param json JSON representation of content
507
+
@return Parsed content object *)
(** Message for prompts - Template messages in the MCP prompts feature *)
module PromptMessage : sig
484
-
(** PromptMessage represents a message in an MCP prompt template,
485
-
containing a role and content which can be customized with arguments.
513
+
(** The role of the message sender (user or assistant). Prompt templates
514
+
typically alternate between user and assistant messages to create a
515
+
conversation structure. *)
517
+
(** The message content, which can be text, image, audio, or resource.
518
+
This unified content type supports rich multimodal prompts. *)
520
+
(** PromptMessage represents a message in an MCP prompt template, containing a
521
+
role and content which can be customized with arguments.
Prompt messages are part of prompt templates exposed by servers through
the prompts/get endpoint. They define structured conversation templates
that can be instantiated with user-provided arguments.
491
-
The prompt feature is designed to be user-controlled, with prompts typically
492
-
exposed through UI elements like slash commands that users can explicitly select.
527
+
The prompt feature is designed to be user-controlled, with prompts
528
+
typically exposed through UI elements like slash commands that users can
In JSON-RPC, prompt messages are represented as:
···
Where $code would be replaced with a user-provided argument. *)
508
-
(** The role of the message sender (user or assistant).
509
-
Prompt templates typically alternate between user and assistant messages
510
-
to create a conversation structure. *)
512
-
(** The message content, which can be text, image, audio, or resource.
513
-
This unified content type supports rich multimodal prompts. *)
include Json.Jsonable.S with type t := t
(** Message for sampling - Messages used in LLM completion requests *)
module SamplingMessage : sig
520
-
(** SamplingMessage represents a message in an MCP sampling request,
521
-
used for AI model generation based on a prompt.
551
+
(** The role of the message sender (user or assistant). Typically, a
552
+
sampling request will contain multiple messages representing a
553
+
conversation history, with alternating roles. *)
555
+
[ `Text of TextContent.t
556
+
| `Image of ImageContent.t
557
+
| `Audio of AudioContent.t ];
558
+
(** The message content, restricted to text, image, or audio (no
559
+
resources). Resources are not included since sampling messages
560
+
represent the actual context window for the LLM, not template
563
+
(** SamplingMessage represents a message in an MCP sampling request, used for
564
+
AI model generation based on a prompt.
The sampling feature allows clients to expose language model capabilities
to servers, enabling servers to request completions from the client's LLM.
This is effectively the reverse of the normal MCP flow, with the server
requesting generative capabilities from the client.
Sampling messages differ from prompt messages in that they don't support
529
-
embedded resources, as they represent the actual context window being
530
-
sent to the LLM rather than template definitions.
572
+
embedded resources, as they represent the actual context window being sent
573
+
to the LLM rather than template definitions.
Clients that support sampling must declare the 'sampling' capability
during initialization. *)
536
-
(** The role of the message sender (user or assistant).
537
-
Typically, a sampling request will contain multiple messages
538
-
representing a conversation history, with alternating roles. *)
539
-
content: [ `Text of TextContent.t | `Image of ImageContent.t | `Audio of AudioContent.t ];
540
-
(** The message content, restricted to text, image, or audio (no resources).
541
-
Resources are not included since sampling messages represent the
542
-
actual context window for the LLM, not template definitions. *)
include Json.Jsonable.S with type t := t
(** Implementation information *)
module Implementation : sig
584
+
name : string; (** Name of the implementation *)
585
+
version : string; (** Version of the implementation *)
(** Implementation provides metadata about client and server implementations,
used during the initialization phase to identify each party. *)
553
-
(** Name of the implementation *)
555
-
(** Version of the implementation *)
include Json.Jsonable.S with type t := t
(** JSONRPC message types - Core message protocol for MCP
562
-
MCP uses JSON-RPC 2.0 as its underlying messaging protocol.
563
-
All MCP messages are encoded as JSON-RPC 2.0 messages with UTF-8 encoding,
564
-
following the standard JSON-RPC message formats with some MCP-specific extensions.
566
-
MCP defines four message types:
567
-
1. Notifications: One-way messages that don't expect a response
568
-
2. Requests: Messages that expect a corresponding response
569
-
3. Responses: Replies to requests with successful results
570
-
4. Errors: Replies to requests with error information
595
+
MCP uses JSON-RPC 2.0 as its underlying messaging protocol. All MCP messages
596
+
are encoded as JSON-RPC 2.0 messages with UTF-8 encoding, following the
597
+
standard JSON-RPC message formats with some MCP-specific extensions.
599
+
MCP defines four message types: 1. Notifications: One-way messages that
600
+
don't expect a response 2. Requests: Messages that expect a corresponding
601
+
response 3. Responses: Replies to requests with successful results 4.
602
+
Errors: Replies to requests with error information
These can be transported over multiple transport mechanisms:
- stdio: Communication over standard input/output
- Streamable HTTP: HTTP POST/GET with SSE for server streaming
- Custom transports: Implementation-specific transports
577
-
Messages may be sent individually or as part of a JSON-RPC batch.
609
+
Messages may be sent individually or as part of a JSON-RPC batch. *)
module JSONRPCMessage : sig
580
-
(** Notification represents a JSON-RPC notification (one-way message without a response).
611
+
type notification = {
613
+
(** Method for the notification, using the Method.t type to ensure type
614
+
safety. Examples: Method.Initialized, Method.ResourcesUpdated *)
615
+
params : Json.t option;
616
+
(** Optional parameters for the notification as arbitrary JSON. The
617
+
structure depends on the specific notification method. *)
619
+
(** Notification represents a JSON-RPC notification (one-way message without a
Notifications are used for events that don't require a response, such as:
- The 'initialized' notification completing initialization
- Resource change notifications
- Progress updates for long-running operations
- List changed notifications for tools, resources, and prompts
In JSON-RPC, notifications are identified by the absence of an 'id' field:
···
"uri": "file:///project/src/main.rs"
599
-
type notification = {
601
-
(** Method for the notification, using the Method.t type to ensure type safety.
602
-
Examples: Method.Initialized, Method.ResourcesUpdated *)
603
-
params: Json.t option;
604
-
(** Optional parameters for the notification as arbitrary JSON.
605
-
The structure depends on the specific notification method. *)
641
+
(** Unique identifier for the request, which will be echoed in the
642
+
response. This can be a string or integer and should be unique
643
+
within the session. *)
645
+
(** Method for the request, using the Method.t type to ensure type
646
+
safety. Examples: Method.Initialize, Method.ResourcesRead,
647
+
Method.ToolsCall *)
648
+
params : Json.t option;
649
+
(** Optional parameters for the request as arbitrary JSON. The structure
650
+
depends on the specific request method. *)
651
+
progress_token : ProgressToken.t option;
652
+
(** Optional progress token for long-running operations. If provided,
653
+
the server can send progress notifications using this token to
654
+
inform the client about the operation's status. *)
(** Request represents a JSON-RPC request that expects a response.
Requests are used for operations that require a response, such as:
- Listing resources, tools, or prompts
617
-
In JSON-RPC, requests include an 'id' field that correlates with the response:
665
+
In JSON-RPC, requests include an 'id' field that correlates with the
···
"uri": "file:///project/src/main.rs"
631
-
(** Unique identifier for the request, which will be echoed in the response.
632
-
This can be a string or integer and should be unique within the session. *)
634
-
(** Method for the request, using the Method.t type to ensure type safety.
635
-
Examples: Method.Initialize, Method.ResourcesRead, Method.ToolsCall *)
636
-
params: Json.t option;
637
-
(** Optional parameters for the request as arbitrary JSON.
638
-
The structure depends on the specific request method. *)
639
-
progress_token: ProgressToken.t option;
640
-
(** Optional progress token for long-running operations.
641
-
If provided, the server can send progress notifications using this token
642
-
to inform the client about the operation's status. *)
680
+
(** ID matching the original request, allowing clients to correlate
681
+
responses with their originating requests, especially important when
682
+
multiple requests are in flight. *)
684
+
(** Result of the successful request as arbitrary JSON. The structure
685
+
depends on the specific request method that was called. *)
(** Response represents a successful JSON-RPC response to a request.
Responses are sent in reply to requests and contain the successful result.
Each response must include the same ID as its corresponding request.
In JSON-RPC, responses include the 'id' field matching the request:
···
669
-
(** ID matching the original request, allowing clients to correlate
670
-
responses with their originating requests, especially important
671
-
when multiple requests are in flight. *)
673
-
(** Result of the successful request as arbitrary JSON.
674
-
The structure depends on the specific request method that was called. *)
711
+
(** ID matching the original request, allowing clients to correlate
712
+
errors with their originating requests. *)
714
+
(** Error code indicating the type of error, following the JSON-RPC
715
+
standard. Common codes include:
716
+
- -32700: Parse error
717
+
- -32600: Invalid request
718
+
- -32601: Method not found
719
+
- -32602: Invalid params
720
+
- -32603: Internal error
721
+
- -32002: Resource not found (MCP-specific)
722
+
- -32001: Authentication required (MCP-specific) *)
724
+
(** Human-readable error message describing the issue. This should be
725
+
concise but informative enough for debugging. *)
726
+
data : Json.t option;
727
+
(** Optional additional error data as arbitrary JSON. This can provide
728
+
more context about the error, such as which resource wasn't found or
729
+
which parameter was invalid. *)
(** Error represents an error response to a JSON-RPC request.
679
-
Errors are sent in reply to requests when processing fails.
680
-
Each error must include the same ID as its corresponding request.
733
+
Errors are sent in reply to requests when processing fails. Each error
734
+
must include the same ID as its corresponding request.
MCP defines several standard error codes:
- Standard JSON-RPC errors (-32700 to -32603)
- MCP-specific errors (-32002 for resource not found, etc.)
In JSON-RPC, errors follow this structure:
···
703
-
(** ID matching the original request, allowing clients to correlate
704
-
errors with their originating requests. *)
706
-
(** Error code indicating the type of error, following the JSON-RPC standard.
707
-
Common codes include:
708
-
- -32700: Parse error
709
-
- -32600: Invalid request
710
-
- -32601: Method not found
711
-
- -32602: Invalid params
712
-
- -32603: Internal error
713
-
- -32002: Resource not found (MCP-specific)
714
-
- -32001: Authentication required (MCP-specific) *)
716
-
(** Human-readable error message describing the issue.
717
-
This should be concise but informative enough for debugging. *)
718
-
data: Json.t option;
719
-
(** Optional additional error data as arbitrary JSON.
720
-
This can provide more context about the error, such as which
721
-
resource wasn't found or which parameter was invalid. *)
724
-
(** Union type for all JSON-RPC message kinds, providing a single type
725
-
that can represent any MCP message. *)
755
+
(** Union type for all JSON-RPC message kinds, providing a single type that
756
+
can represent any MCP message. *)
| Notification of notification
732
-
(** Convert notification to Yojson representation
733
-
@param notification The notification to convert
734
-
@return JSON representation of the notification
val yojson_of_notification : notification -> Json.t
738
-
(** Convert request to Yojson representation
739
-
@param request The request to convert
740
-
@return JSON representation of the request
764
+
(** Convert notification to Yojson representation
765
+
@param notification The notification to convert
766
+
@return JSON representation of the notification *)
val yojson_of_request : request -> Json.t
744
-
(** Convert response to Yojson representation
745
-
@param response The response to convert
746
-
@return JSON representation of the response
769
+
(** Convert request to Yojson representation
770
+
@param request The request to convert
771
+
@return JSON representation of the request *)
val yojson_of_response : response -> Json.t
750
-
(** Convert error to Yojson representation
751
-
@param error The error to convert
752
-
@return JSON representation of the error
774
+
(** Convert response to Yojson representation
775
+
@param response The response to convert
776
+
@return JSON representation of the response *)
val yojson_of_error : error -> Json.t
756
-
(** Convert any message to Yojson representation
757
-
@param message The message to convert
758
-
@return JSON representation of the message
779
+
(** Convert error to Yojson representation
780
+
@param error The error to convert
781
+
@return JSON representation of the error *)
val yojson_of_t : t -> Json.t
784
+
(** Convert any message to Yojson representation
785
+
@param message The message to convert
786
+
@return JSON representation of the message *)
762
-
(** Convert Yojson representation to notification
788
+
val notification_of_yojson : Json.t -> notification
789
+
(** Convert Yojson representation to notification
@param json JSON representation of a notification
@return Parsed notification object
765
-
@raise Parse error if the JSON is not a valid notification
767
-
val notification_of_yojson : Json.t -> notification
769
-
(** Convert Yojson representation to request
792
+
@raise Parse error if the JSON is not a valid notification *)
794
+
val request_of_yojson : Json.t -> request
795
+
(** Convert Yojson representation to request
@param json JSON representation of a request
@return Parsed request object
772
-
@raise Parse error if the JSON is not a valid request
774
-
val request_of_yojson : Json.t -> request
776
-
(** Convert Yojson representation to response
798
+
@raise Parse error if the JSON is not a valid request *)
800
+
val response_of_yojson : Json.t -> response
801
+
(** Convert Yojson representation to response
@param json JSON representation of a response
@return Parsed response object
779
-
@raise Parse error if the JSON is not a valid response
781
-
val response_of_yojson : Json.t -> response
783
-
(** Convert Yojson representation to error
804
+
@raise Parse error if the JSON is not a valid response *)
806
+
val error_of_yojson : Json.t -> error
807
+
(** Convert Yojson representation to error
@param json JSON representation of an error
@return Parsed error object
786
-
@raise Parse error if the JSON is not a valid error
788
-
val error_of_yojson : Json.t -> error
790
-
(** Convert Yojson representation to any message
810
+
@raise Parse error if the JSON is not a valid error *)
812
+
val t_of_yojson : Json.t -> t
813
+
(** Convert Yojson representation to any message
@param json JSON representation of any message type
@return Parsed message object
793
-
@raise Parse error if the JSON is not a valid message
795
-
val t_of_yojson : Json.t -> t
816
+
@raise Parse error if the JSON is not a valid message *)
818
+
val create_notification : ?params:Json.t option -> meth:Method.t -> unit -> t
(** Create a new notification message
@param params Optional parameters for the notification
@param meth Method name for the notification
800
-
@return A new JSON-RPC notification message
802
-
val create_notification : ?params:Json.t option -> meth:Method.t -> unit -> t
822
+
@return A new JSON-RPC notification message *)
824
+
val create_request :
825
+
?params:Json.t option ->
826
+
?progress_token:ProgressToken.t option ->
(** Create a new request message
@param params Optional parameters for the request
@param progress_token Optional progress token for long-running operations
@param id Unique identifier for the request
@param meth Method name for the request
809
-
@return A new JSON-RPC request message
811
-
val create_request : ?params:Json.t option -> ?progress_token:ProgressToken.t option -> id:RequestId.t -> meth:Method.t -> unit -> t
836
+
@return A new JSON-RPC request message *)
838
+
val create_response : id:RequestId.t -> result:Json.t -> t
(** Create a new response message
@param id ID matching the original request
@param result Result of the successful request
816
-
@return A new JSON-RPC response message
818
-
val create_response : id:RequestId.t -> result:Json.t -> t
842
+
@return A new JSON-RPC response message *)
848
+
?data:Json.t option ->
(** Create a new error message
@param id ID matching the original request
@param code Error code indicating the type of error
@param message Human-readable error message
@param data Optional additional error data
825
-
@return A new JSON-RPC error message
827
-
val create_error : id:RequestId.t -> code:int -> message:string -> ?data:Json.t option -> unit -> t
856
+
@return A new JSON-RPC error message *)
830
-
(** Initialize request/response - The first phase of the MCP lifecycle
832
-
The initialization phase is the mandatory first interaction between client and server.
833
-
During this phase, the protocol version is negotiated and capabilities are exchanged
834
-
to determine which optional features will be available during the session.
836
-
This follows a strict sequence:
837
-
1. Client sends an InitializeRequest containing its capabilities and protocol version
838
-
2. Server responds with an InitializeResult containing its capabilities and protocol version
839
-
3. Client sends an InitializedNotification to signal it's ready for normal operations
841
-
The Initialize module handles steps 1 and 2 of this process.
859
+
(** Initialize request/response - The first phase of the MCP lifecycle
861
+
The initialization phase is the mandatory first interaction between client
862
+
and server. During this phase, the protocol version is negotiated and
863
+
capabilities are exchanged to determine which optional features will be
864
+
available during the session.
866
+
This follows a strict sequence: 1. Client sends an InitializeRequest
867
+
containing its capabilities and protocol version 2. Server responds with an
868
+
InitializeResult containing its capabilities and protocol version 3. Client
869
+
sends an InitializedNotification to signal it's ready for normal operations
871
+
The Initialize module handles steps 1 and 2 of this process. *)
(** Initialize request *)
846
-
(** InitializeRequest starts the MCP lifecycle, negotiating capabilities
847
-
and protocol versions between client and server. This is always the first
848
-
message sent by the client and MUST NOT be part of a JSON-RPC batch.
850
-
The client SHOULD send the latest protocol version it supports. If the server
851
-
does not support this version, it will respond with a version it does support,
852
-
and the client must either use that version or disconnect. *)
854
-
capabilities: Json.t; (** ClientCapabilities that define supported optional features.
855
-
This includes which optional protocol features the client supports,
856
-
such as 'roots' (filesystem access), 'sampling' (LLM generation),
857
-
and any experimental features. *)
858
-
client_info: Implementation.t;
859
-
(** Client implementation details (name and version) used for identification
860
-
and debugging. Helps servers understand which client they're working with. *)
861
-
protocol_version: string;
862
-
(** MCP protocol version supported by the client, formatted as YYYY-MM-DD
863
-
according to the MCP versioning scheme. Example: "2025-03-26" *)
876
+
capabilities : Json.t;
877
+
(** ClientCapabilities that define supported optional features. This
878
+
includes which optional protocol features the client supports,
879
+
such as 'roots' (filesystem access), 'sampling' (LLM generation),
880
+
and any experimental features. *)
881
+
client_info : Implementation.t;
882
+
(** Client implementation details (name and version) used for
883
+
identification and debugging. Helps servers understand which
884
+
client they're working with. *)
885
+
protocol_version : string;
886
+
(** MCP protocol version supported by the client, formatted as
887
+
YYYY-MM-DD according to the MCP versioning scheme. Example:
890
+
(** InitializeRequest starts the MCP lifecycle, negotiating capabilities and
891
+
protocol versions between client and server. This is always the first
892
+
message sent by the client and MUST NOT be part of a JSON-RPC batch.
894
+
The client SHOULD send the latest protocol version it supports. If the
895
+
server does not support this version, it will respond with a version it
896
+
does support, and the client must either use that version or disconnect.
include Json.Jsonable.S with type t := t
902
+
capabilities:Json.t ->
903
+
client_info:Implementation.t ->
904
+
protocol_version:string ->
(** Create a new initialization request
868
-
@param capabilities Client capabilities that define supported optional features
907
+
@param capabilities
908
+
Client capabilities that define supported optional features
@param client_info Client implementation details
@param protocol_version MCP protocol version supported by the client
871
-
@return A new initialization request
873
-
val create : capabilities:Json.t -> client_info:Implementation.t -> protocol_version:string -> t
911
+
@return A new initialization request *)
913
+
val to_jsonrpc : id:RequestId.t -> t -> JSONRPCMessage.t
(** Convert to JSON-RPC message
@param id Unique request identifier
@param t Initialization request
878
-
@return JSON-RPC message containing the initialization request
880
-
val to_jsonrpc : id:RequestId.t -> t -> JSONRPCMessage.t
917
+
@return JSON-RPC message containing the initialization request *)
885
-
(** InitializeResult is the server's response to an initialization request,
886
-
completing capability negotiation and establishing the protocol version.
888
-
After receiving this message, the client must send an InitializedNotification.
889
-
The server should not send any requests other than pings and logging before
890
-
receiving the initialized notification. *)
892
-
capabilities: Json.t; (** ServerCapabilities that define supported optional features.
893
-
This declares which server features are available, including:
894
-
- prompts: Server provides prompt templates
895
-
- resources: Server provides readable resources
896
-
- tools: Server exposes callable tools
897
-
- logging: Server emits structured log messages
899
-
Each capability may have sub-capabilities like:
900
-
- listChanged: Server will notify when available items change
901
-
- subscribe: Clients can subscribe to individual resources *)
902
-
server_info: Implementation.t;
903
-
(** Server implementation details (name and version) used for identification
904
-
and debugging. Helps clients understand which server they're working with. *)
905
-
protocol_version: string;
906
-
(** MCP protocol version supported by the server, formatted as YYYY-MM-DD.
907
-
If the server supports the client's requested version, it responds with
908
-
the same version. Otherwise, it responds with a version it does support. *)
909
-
instructions: string option;
910
-
(** Optional instructions for using the server. These can provide human-readable
911
-
guidance on how to interact with this specific server implementation. *)
912
-
meta: Json.t option;
913
-
(** Optional additional metadata as arbitrary JSON. Can contain server-specific
914
-
information not covered by the standard fields. *)
923
+
capabilities : Json.t;
924
+
(** ServerCapabilities that define supported optional features. This
925
+
declares which server features are available, including:
926
+
- prompts: Server provides prompt templates
927
+
- resources: Server provides readable resources
928
+
- tools: Server exposes callable tools
929
+
- logging: Server emits structured log messages
931
+
Each capability may have sub-capabilities like:
932
+
- listChanged: Server will notify when available items change
933
+
- subscribe: Clients can subscribe to individual resources *)
934
+
server_info : Implementation.t;
935
+
(** Server implementation details (name and version) used for
936
+
identification and debugging. Helps clients understand which
937
+
server they're working with. *)
938
+
protocol_version : string;
939
+
(** MCP protocol version supported by the server, formatted as
940
+
YYYY-MM-DD. If the server supports the client's requested version,
941
+
it responds with the same version. Otherwise, it responds with a
942
+
version it does support. *)
943
+
instructions : string option;
944
+
(** Optional instructions for using the server. These can provide
945
+
human-readable guidance on how to interact with this specific
946
+
server implementation. *)
947
+
meta : Json.t option;
948
+
(** Optional additional metadata as arbitrary JSON. Can contain
949
+
server-specific information not covered by the standard fields. *)
951
+
(** InitializeResult is the server's response to an initialization request,
952
+
completing capability negotiation and establishing the protocol version.
954
+
After receiving this message, the client must send an
955
+
InitializedNotification. The server should not send any requests other
956
+
than pings and logging before receiving the initialized notification. *)
include Json.Jsonable.S with type t := t
961
+
capabilities:Json.t ->
962
+
server_info:Implementation.t ->
963
+
protocol_version:string ->
964
+
?instructions:string ->
(** Create a new initialization result
919
-
@param capabilities Server capabilities that define supported optional features
969
+
@param capabilities
970
+
Server capabilities that define supported optional features
@param server_info Server implementation details
@param protocol_version MCP protocol version supported by the server
@param instructions Optional instructions for using the server
@param meta Optional additional metadata
924
-
@return A new initialization result
926
-
val create : capabilities:Json.t -> server_info:Implementation.t -> protocol_version:string -> ?instructions:string -> ?meta:Json.t -> unit -> t
975
+
@return A new initialization result *)
977
+
val to_jsonrpc : id:RequestId.t -> t -> JSONRPCMessage.t
(** Convert to JSON-RPC message
@param id ID matching the original request
@param t Initialization result
931
-
@return JSON-RPC message containing the initialization result
933
-
val to_jsonrpc : id:RequestId.t -> t -> JSONRPCMessage.t
981
+
@return JSON-RPC message containing the initialization result *)
937
-
(** Initialized notification - Completes the initialization phase of the MCP lifecycle *)
985
+
(** Initialized notification - Completes the initialization phase of the MCP
module Notification : sig
940
-
(** InitializedNotification is sent by the client after receiving the initialization
941
-
response, indicating it's ready to begin normal operations. This completes the
942
-
three-step initialization process, after which both client and server can
943
-
freely exchange messages according to the negotiated capabilities.
945
-
Only after this notification has been sent should the client begin normal operations
946
-
like listing resources, calling tools, or requesting prompts. *)
948
-
meta: Json.t option;
949
-
(** Optional additional metadata as arbitrary JSON. Can contain client-specific
950
-
information not covered by the standard fields. *)
990
+
meta : Json.t option;
991
+
(** Optional additional metadata as arbitrary JSON. Can contain
992
+
client-specific information not covered by the standard fields. *)
994
+
(** InitializedNotification is sent by the client after receiving the
995
+
initialization response, indicating it's ready to begin normal
996
+
operations. This completes the three-step initialization process, after
997
+
which both client and server can freely exchange messages according to
998
+
the negotiated capabilities.
1000
+
Only after this notification has been sent should the client begin
1001
+
normal operations like listing resources, calling tools, or requesting
include Json.Jsonable.S with type t := t
1006
+
val create : ?meta:Json.t -> unit -> t
(** Create a new initialized notification
@param meta Optional additional metadata
956
-
@return A new initialized notification
958
-
val create : ?meta:Json.t -> unit -> t
1009
+
@return A new initialized notification *)
1011
+
val to_jsonrpc : t -> JSONRPCMessage.t
(** Convert to JSON-RPC message
@param t Initialized notification
962
-
@return JSON-RPC message containing the initialized notification
964
-
val to_jsonrpc : t -> JSONRPCMessage.t
1014
+
@return JSON-RPC message containing the initialized notification *)
968
-
(** Parse a JSON message into an MCP message
970
-
This function takes a raw JSON value and parses it into a structured MCP message.
971
-
It's the primary entry point for processing incoming JSON-RPC messages in the MCP protocol.
973
-
The function determines the message type (notification, request, response, or error)
974
-
based on the presence and values of specific fields:
1018
+
val parse_message : Json.t -> JSONRPCMessage.t
1019
+
(** Parse a JSON message into an MCP message
1021
+
This function takes a raw JSON value and parses it into a structured MCP
1022
+
message. It's the primary entry point for processing incoming JSON-RPC
1023
+
messages in the MCP protocol.
1025
+
The function determines the message type (notification, request, response,
1026
+
or error) based on the presence and values of specific fields:
- A message with "method" but no "id" is a notification
- A message with "method" and "id" is a request
- A message with "id" and "result" is a response
- A message with "id" and "error" is an error
980
-
@param json The JSON message to parse, typically received from the transport layer
1033
+
The JSON message to parse, typically received from the transport layer
@return The parsed MCP message as a structured JSONRPCMessage.t value
982
-
@raise Parse error if the JSON cannot be parsed as a valid MCP message
984
-
val parse_message : Json.t -> JSONRPCMessage.t
1035
+
@raise Parse error if the JSON cannot be parsed as a valid MCP message *)
1037
+
val create_notification :
1038
+
?params:Json.t option -> meth:Method.t -> unit -> JSONRPCMessage.t
(** Create a new notification message
988
-
Notifications are one-way messages that don't expect a response.
989
-
This is a convenience wrapper around JSONRPCMessage.create_notification.
1041
+
Notifications are one-way messages that don't expect a response. This is a
1042
+
convenience wrapper around JSONRPCMessage.create_notification.
Common notifications in MCP include:
- "notifications/initialized" - Sent after initialization
- "notifications/progress" - Updates on long-running operations
- "notifications/resources/updated" - Resource content changed
- "notifications/prompts/list_changed" - Available prompts changed
- "notifications/tools/list_changed" - Available tools changed
@param params Optional parameters for the notification as a JSON value
@param meth Method type for the notification
1000
-
@return A new JSON-RPC notification message
1002
-
val create_notification : ?params:Json.t option -> meth:Method.t -> unit -> JSONRPCMessage.t
1053
+
@return A new JSON-RPC notification message *)
1055
+
val create_request :
1056
+
?params:Json.t option ->
1057
+
?progress_token:ProgressToken.t option ->
(** Create a new request message
1006
-
Requests are messages that expect a corresponding response.
1007
-
This is a convenience wrapper around JSONRPCMessage.create_request.
1064
+
Requests are messages that expect a corresponding response. This is a
1065
+
convenience wrapper around JSONRPCMessage.create_request.
Common requests in MCP include:
- "initialize" - Start the MCP lifecycle
- "resources/list" - Discover available resources
···
- "tools/call" - Invoke a tool
- "prompts/list" - Discover available prompts
- "prompts/get" - Retrieve a prompt template
@param params Optional parameters for the request as a JSON value
1019
-
@param progress_token Optional progress token for long-running operations
1020
-
that can report progress updates
1021
-
@param id Unique identifier for the request, used to correlate with the response
1077
+
@param progress_token
1078
+
Optional progress token for long-running operations that can report
1081
+
Unique identifier for the request, used to correlate with the response
@param meth Method type for the request
1023
-
@return A new JSON-RPC request message
1025
-
val create_request : ?params:Json.t option -> ?progress_token:ProgressToken.t option -> id:RequestId.t -> meth:Method.t -> unit -> JSONRPCMessage.t
1083
+
@return A new JSON-RPC request message *)
1085
+
val create_response : id:RequestId.t -> result:Json.t -> JSONRPCMessage.t
(** Create a new response message
1029
-
Responses are sent in reply to requests and contain successful results.
1030
-
This is a convenience wrapper around JSONRPCMessage.create_response.
1032
-
Each response must include the same ID as its corresponding request
1033
-
to allow the client to correlate them, especially when multiple
1034
-
requests are in flight simultaneously.
1088
+
Responses are sent in reply to requests and contain successful results. This
1089
+
is a convenience wrapper around JSONRPCMessage.create_response.
1091
+
Each response must include the same ID as its corresponding request to allow
1092
+
the client to correlate them, especially when multiple requests are in
1093
+
flight simultaneously.
@param id ID matching the original request
@param result Result of the successful request as a JSON value
1038
-
@return A new JSON-RPC response message
1040
-
val create_response : id:RequestId.t -> result:Json.t -> JSONRPCMessage.t
1097
+
@return A new JSON-RPC response message *)
1099
+
val create_error :
1103
+
?data:Json.t option ->
(** Create a new error message
1044
-
Errors are sent in reply to requests when processing fails.
1045
-
This is a convenience wrapper around JSONRPCMessage.create_error.
1047
-
MCP uses standard JSON-RPC error codes as well as some protocol-specific codes:
1108
+
Errors are sent in reply to requests when processing fails. This is a
1109
+
convenience wrapper around JSONRPCMessage.create_error.
1111
+
MCP uses standard JSON-RPC error codes as well as some protocol-specific
- -32700: Parse error (invalid JSON)
- -32600: Invalid request (malformed JSON-RPC)
- -32601: Method not found
···
- -32002: Resource not found (MCP-specific)
- -32001: Authentication required (MCP-specific)
@param id ID matching the original request
@param code Error code indicating the type of error
@param message Human-readable error message describing the issue
@param data Optional additional error data providing more context
1060
-
@return A new JSON-RPC error message
1062
-
val create_error : id:RequestId.t -> code:int -> message:string -> ?data:Json.t option -> unit -> JSONRPCMessage.t
1125
+
@return A new JSON-RPC error message *)
1127
+
val make_text_content : string -> content
(** Create a new text content object
@param text The text content
1066
-
@return A content value with the text
1068
-
val make_text_content : string -> content
1130
+
@return A content value with the text *)
1132
+
val make_image_content : string -> string -> content
(** Create a new image content object
@param data Base64-encoded image data
1072
-
@param mime_type MIME type of the image (e.g., "image/png", "image/jpeg")
1073
-
@return A content value with the image
1075
-
val make_image_content : string -> string -> content
1135
+
@param mime_type MIME type of the image (e.g., "image/png", "image/jpeg")
1136
+
@return A content value with the image *)
1138
+
val make_audio_content : string -> string -> content
(** Create a new audio content object
@param data Base64-encoded audio data
@param mime_type MIME type of the audio (e.g., "audio/wav", "audio/mp3")
1080
-
@return A content value with the audio
1082
-
val make_audio_content : string -> string -> content
1142
+
@return A content value with the audio *)
1144
+
val make_resource_text_content : string -> string -> string option -> content
(** Create a new text resource content object
@param uri URI that uniquely identifies the resource
@param text The text content of the resource
@param mime_type Optional MIME type of the text content
1088
-
@return A content value with the text resource
1090
-
val make_resource_text_content : string -> string -> string option -> content
1149
+
@return A content value with the text resource *)
1151
+
val make_resource_blob_content : string -> string -> string option -> content
(** Create a new binary resource content object
@param uri URI that uniquely identifies the resource
@param blob Base64-encoded binary data
@param mime_type Optional MIME type of the binary content
1096
-
@return A content value with the binary resource
1098
-
val make_resource_blob_content : string -> string -> string option -> content
1156
+
@return A content value with the binary resource *)