llm-tool-mcp 0.9.4

Model Context Protocol (MCP) server integration for llm-tool registries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! JSON-RPC 2.0 protocol types for MCP communication.
//!
//! These types model the wire format used by MCP's JSON-RPC transport.
//! Each request/response is a single JSON line on the stream.

use serde::{Deserialize, Serialize};

// ── JSON-RPC 2.0 constants ──────────────────────────────────────────

/// The only valid JSON-RPC protocol version.
pub const JSONRPC_VERSION: &str = "2.0";

// ── Standard JSON-RPC 2.0 error codes ───────────────────────────────

/// Malformed JSON.
pub const PARSE_ERROR: i64 = -32700;

/// Valid JSON but not a valid JSON-RPC request.
pub const INVALID_REQUEST: i64 = -32600;

/// The requested method does not exist.
pub const METHOD_NOT_FOUND: i64 = -32601;

/// Invalid method parameters.
pub const INVALID_PARAMS: i64 = -32602;

/// Internal server error.
pub const INTERNAL_ERROR: i64 = -32603;

// ── MCP JSON-RPC method names ───────────────────────────────────────
//
// Every JSON-RPC `method` string the server dispatches on has a named
// constant here, so the wire protocol is defined in exactly one place and
// the server match arms never repeat a magic string literal.

/// `initialize` — capability negotiation handshake.
pub const METHOD_INITIALIZE: &str = "initialize";

/// `ping` — liveness check; server replies with an empty result.
pub const METHOD_PING: &str = "ping";

/// `logging/setLevel` — client sets the server log level.
pub const METHOD_LOGGING_SET_LEVEL: &str = "logging/setLevel";

/// `notifications/initialized` — client signals it finished initializing.
pub const METHOD_NOTIFICATIONS_INITIALIZED: &str = "notifications/initialized";

/// `initialized` — bare alias some clients send instead of the namespaced form.
pub const METHOD_INITIALIZED: &str = "initialized";

/// `notifications/cancelled` — client cancels an in-flight request.
pub const METHOD_NOTIFICATIONS_CANCELLED: &str = "notifications/cancelled";

/// `tools/list` — enumerate available tools and their schemas.
pub const METHOD_TOOLS_LIST: &str = "tools/list";

/// `tools/call` — invoke a named tool with arguments.
pub const METHOD_TOOLS_CALL: &str = "tools/call";

/// `resources/list` — enumerate concrete resources.
pub const METHOD_RESOURCES_LIST: &str = "resources/list";

/// `resources/templates/list` — enumerate resource URI templates.
pub const METHOD_RESOURCES_TEMPLATES_LIST: &str = "resources/templates/list";

/// `resources/read` — read a resource by URI.
pub const METHOD_RESOURCES_READ: &str = "resources/read";

/// `prompts/list` — enumerate registered prompts.
pub const METHOD_PROMPTS_LIST: &str = "prompts/list";

/// `prompts/get` — render a prompt with arguments.
pub const METHOD_PROMPTS_GET: &str = "prompts/get";

/// `completion/complete` — argument-completion request.
pub const METHOD_COMPLETION_COMPLETE: &str = "completion/complete";

/// `notifications/progress` — progress update notification.
pub const METHOD_NOTIFICATIONS_PROGRESS: &str = "notifications/progress";

/// `notifications/message` — log-message notification.
pub const METHOD_NOTIFICATIONS_MESSAGE: &str = "notifications/message";

// ── Request ─────────────────────────────────────────────────────────

/// A JSON-RPC 2.0 request.
#[derive(Debug, Deserialize)]
pub struct JsonRpcRequest {
    /// Protocol version — must be `"2.0"`.
    #[serde(rename = "jsonrpc")]
    pub version: String,

    /// Request identifier (number or string). `None` for notifications.
    pub id: Option<serde_json::Value>,

    /// Method name (e.g. `"initialize"`, `"tools/list"`, `"tools/call"`).
    pub method: String,

    /// Optional parameters.
    #[serde(default)]
    pub params: Option<serde_json::Value>,
}

// ── Response ────────────────────────────────────────────────────────

/// A JSON-RPC 2.0 response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JsonRpcResponse {
    /// Protocol version — always `"2.0"`.
    pub jsonrpc: &'static str,

    /// Echoed request identifier.
    pub id: Option<serde_json::Value>,

    /// Present on success.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,

    /// Present on error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

/// A JSON-RPC 2.0 error object.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct JsonRpcError {
    /// Numeric error code.
    pub code: i64,
    /// Human-readable description.
    pub message: String,
    /// Optional additional data about the error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

impl JsonRpcResponse {
    /// Build a success response from any serializable result type.
    ///
    /// # Panics
    ///
    /// Panics if `result` cannot be serialized to JSON. This should never
    /// happen for the well-formed MCP structs in this module.
    #[must_use]
    pub fn success(id: Option<serde_json::Value>, result: impl Serialize) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: Some(
                serde_json::to_value(result).expect("MCP result type must be JSON-serializable"),
            ),
            error: None,
        }
    }

    /// Build an error response.
    #[must_use]
    pub fn error(id: Option<serde_json::Value>, code: i64, message: impl Into<String>) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.into(),
                data: None,
            }),
        }
    }

    /// Build an error response with additional structured data.
    #[must_use]
    pub fn error_with_data(
        id: Option<serde_json::Value>,
        code: i64,
        message: impl Into<String>,
        data: serde_json::Value,
    ) -> Self {
        Self {
            jsonrpc: "2.0",
            id,
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.into(),
                data: Some(data),
            }),
        }
    }
}

// ── MCP-specific types ──────────────────────────────────────────────

/// Result body for `initialize`.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResult {
    /// MCP protocol version (e.g. `"2024-11-05"`).
    pub protocol_version: &'static str,
    /// Server name and version.
    pub server_info: ServerInfo,
    /// Optional instructions describing how to use the server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
    /// Advertised capabilities.
    pub capabilities: Capabilities,
}

/// Server identification returned in `initialize`.
#[derive(Debug, Serialize)]
pub struct ServerInfo {
    /// Human-readable server name.
    pub name: String,
    /// Server version string.
    pub version: String,
}

/// Server capabilities advertised during `initialize`.
#[derive(Debug, Default, Serialize)]
pub struct Capabilities {
    /// Tool support — presence signals that `tools/list` and `tools/call`
    /// are available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolCapabilities>,
    /// Resource support — presence signals that `resources/list` is available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResourceCapabilities>,
    /// Prompt support — presence signals that `prompts/list` is available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompts: Option<PromptCapabilities>,
}

/// Tool-specific capabilities (currently empty per MCP spec).
#[derive(Debug, Default, Serialize)]
pub struct ToolCapabilities {}

/// Resource-specific capabilities (currently empty per MCP spec).
#[derive(Debug, Default, Serialize)]
pub struct ResourceCapabilities {}

/// Prompt-specific capabilities (currently empty per MCP spec).
#[derive(Debug, Default, Serialize)]
pub struct PromptCapabilities {}

/// Result body for `tools/list`.
#[derive(Clone, Debug, Serialize)]
pub struct ToolsListResult {
    /// Available tools.
    pub tools: Vec<McpToolSchema>,
}

/// A single tool's schema in the `tools/list` response.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct McpToolSchema {
    /// Tool name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// JSON Schema for the tool's input parameters.
    pub input_schema: serde_json::Value,
}

/// Deserialized `tools/call` request parameters.
#[derive(Debug, Deserialize)]
pub struct ToolCallParams {
    /// Name of the tool to invoke.
    pub name: String,
    /// Tool arguments (defaults to `{}` if absent).
    #[serde(default = "empty_object")]
    pub arguments: serde_json::Value,
}

/// Returns an empty JSON object — used as the serde default for
/// `ToolCallParams::arguments`.
fn empty_object() -> serde_json::Value {
    serde_json::Value::Object(serde_json::Map::new())
}

/// Result body for a successful `tools/call`.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolCallResult {
    /// Response content blocks.
    pub content: Vec<ContentItem>,
    /// `true` when the tool returned an error (MCP-level, not JSON-RPC).
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub is_error: bool,
}

impl ToolCallResult {
    /// The text of the first content block, if any.
    ///
    /// Convenience for callers of [`McpServer::dispatch_tool`] who want the
    /// tool's textual output without indexing into [`content`](Self::content).
    ///
    /// [`McpServer::dispatch_tool`]: crate::McpServer::dispatch_tool
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        self.content.first().map(|item| item.text.as_str())
    }
}

/// The `type` value of a text [`ContentItem`] — currently the only content type
/// this server emits.
pub const CONTENT_TYPE_TEXT: &str = "text";

/// A single content block in a `tools/call` response.
#[derive(Debug, Serialize)]
pub struct ContentItem {
    /// Content type — currently always [`CONTENT_TYPE_TEXT`].
    #[serde(rename = "type")]
    pub content_type: &'static str,
    /// The text content.
    pub text: String,
}

impl ContentItem {
    /// Build a text content block, tagging it with [`CONTENT_TYPE_TEXT`].
    ///
    /// Prefer this over constructing [`ContentItem`] literally so the content
    /// type is set consistently in one place.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            content_type: CONTENT_TYPE_TEXT,
            text: text.into(),
        }
    }
}

// ── Prompts ─────────────────────────────────────────────────────────

/// Result body for `prompts/list`.
#[derive(Clone, Debug, Serialize)]
pub struct PromptsListResult {
    /// Available prompts.
    pub prompts: Vec<PromptDefinition>,
}

pub use llm_tool::{PromptArgumentDefinition, PromptDefinition};

/// Parameters for `prompts/get`.
#[derive(Debug, Deserialize)]
pub struct GetPromptParams {
    /// Name of the prompt to retrieve.
    pub name: String,
    /// Arguments to substitute into the template.
    #[serde(default = "empty_object")]
    pub arguments: serde_json::Value,
}

/// Result body for `prompts/get`.
#[derive(Debug, Serialize)]
pub struct GetPromptResult {
    /// Optional description of the rendered prompt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Rendered messages.
    pub messages: Vec<PromptMessage>,
}

/// A rendered message inside `GetPromptResult`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct PromptMessage {
    /// Role (`"user"` or `"assistant"`).
    pub role: String,
    /// Content block.
    pub content: PromptMessageContent,
}

/// Content inside a `PromptMessage`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type")]
pub enum PromptMessageContent {
    /// Text content.
    #[serde(rename = "text")]
    Text {
        /// Text string.
        text: String,
    },
    /// Embedded resource content.
    #[serde(rename = "resource")]
    Resource {
        /// Resource payload.
        resource: ResourceContent,
    },
}

// ── Resources ───────────────────────────────────────────────────────

/// Wire format for a concrete resource in `resources/list`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct McpResource {
    /// Resource URI.
    pub uri: String,
    /// Human-readable name.
    pub name: String,
    /// Optional description.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Optional MIME type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
}

pub use McpResource as Resource;

/// Result body for `resources/list`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ResourcesListResult {
    /// Available resources.
    pub resources: Vec<McpResource>,
}

pub use llm_tool::ResourceDefinition;

/// Parameters for `resources/read`.
#[derive(Debug, Deserialize)]
pub struct ReadResourceParams {
    /// URI of the resource to read.
    pub uri: String,
}

/// Result body for `resources/read`.
#[derive(Debug, Serialize, Deserialize)]
pub struct ReadResourceResult {
    /// Resource content blocks.
    pub contents: Vec<ResourceContent>,
}

pub use llm_tool::ResourceOutputContent as ResourceContent;

/// An empty JSON object used for responses like ping or logging/setLevel.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct EmptyResult {}

/// Result body for `resources/templates/list`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceTemplatesListResult {
    /// Available resource templates.
    pub resource_templates: Vec<ResourceDefinition>,
}

/// Result body for `completion/complete`.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct CompletionCompleteResult {
    /// Completion values and pagination.
    pub completion: CompletionResultData,
}

/// Data inside `CompletionCompleteResult`.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CompletionResultData {
    /// Recommended completion values.
    pub values: Vec<String>,
    /// Total number of available completions.
    pub total: usize,
    /// Whether more completions are available.
    pub has_more: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deserialize_request_with_params() {
        let json = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add"}}"#;
        let req: JsonRpcRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.version, "2.0");
        assert_eq!(req.id, Some(serde_json::json!(1)));
        assert_eq!(req.method, "tools/call");
        assert!(req.params.is_some());
    }

    #[test]
    fn deserialize_request_without_params() {
        let json = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#;
        let req: JsonRpcRequest = serde_json::from_str(json).unwrap();
        assert!(req.params.is_none());
    }

    #[test]
    fn deserialize_notification_without_id() {
        let json = r#"{"jsonrpc":"2.0","method":"initialized"}"#;
        let req: JsonRpcRequest = serde_json::from_str(json).unwrap();
        assert!(req.id.is_none());
    }

    #[test]
    fn serialize_success_response() {
        let resp =
            JsonRpcResponse::success(Some(serde_json::json!(1)), serde_json::json!({"ok": true}));
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""jsonrpc":"2.0""#));
        assert!(json.contains(r#""result":{""#));
        assert!(!json.contains("error"));
    }

    #[test]
    fn serialize_error_response() {
        let resp = JsonRpcResponse::error(Some(serde_json::json!(1)), PARSE_ERROR, "bad json");
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""code":-32700"#));
        assert!(json.contains(r#""message":"bad json""#));
        assert!(!json.contains("result"));
    }

    #[test]
    fn serialize_error_omits_null_id() {
        let resp = JsonRpcResponse::error(None, METHOD_NOT_FOUND, "no such method");
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""id":null"#));
    }

    #[test]
    fn response_jsonrpc_field_is_static() {
        let resp = JsonRpcResponse::success(None, serde_json::json!(null));
        // &'static str avoids allocation for every response.
        assert_eq!(resp.jsonrpc, "2.0");
    }

    #[test]
    fn error_without_data_omits_data_field() {
        let resp = JsonRpcResponse::error(Some(serde_json::json!(1)), PARSE_ERROR, "bad");
        let json = serde_json::to_string(&resp).unwrap();
        assert!(!json.contains("data"));
    }

    #[test]
    fn error_with_data_includes_data_field() {
        let resp = JsonRpcResponse::error_with_data(
            Some(serde_json::json!(1)),
            INTERNAL_ERROR,
            "boom",
            serde_json::json!({"detail": "stack trace"}),
        );
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains(r#""data":{"detail":"stack trace"}"#));
    }

    #[test]
    fn jsonrpc_version_constant() {
        assert_eq!(JSONRPC_VERSION, "2.0");
    }

    #[test]
    fn method_consts_match_wire_strings() {
        assert_eq!(METHOD_INITIALIZE, "initialize");
        assert_eq!(METHOD_PING, "ping");
        assert_eq!(METHOD_LOGGING_SET_LEVEL, "logging/setLevel");
        assert_eq!(
            METHOD_NOTIFICATIONS_INITIALIZED,
            "notifications/initialized"
        );
        assert_eq!(METHOD_INITIALIZED, "initialized");
        assert_eq!(METHOD_NOTIFICATIONS_CANCELLED, "notifications/cancelled");
        assert_eq!(METHOD_TOOLS_LIST, "tools/list");
        assert_eq!(METHOD_TOOLS_CALL, "tools/call");
        assert_eq!(METHOD_RESOURCES_LIST, "resources/list");
        assert_eq!(METHOD_RESOURCES_TEMPLATES_LIST, "resources/templates/list");
        assert_eq!(METHOD_RESOURCES_READ, "resources/read");
        assert_eq!(METHOD_PROMPTS_LIST, "prompts/list");
        assert_eq!(METHOD_PROMPTS_GET, "prompts/get");
        assert_eq!(METHOD_COMPLETION_COMPLETE, "completion/complete");
        assert_eq!(METHOD_NOTIFICATIONS_PROGRESS, "notifications/progress");
        assert_eq!(METHOD_NOTIFICATIONS_MESSAGE, "notifications/message");
    }

    #[test]
    fn content_item_text_constructor_sets_type() {
        let item = ContentItem::text("hello");
        assert_eq!(item.content_type, CONTENT_TYPE_TEXT);
        assert_eq!(item.content_type, "text");
        assert_eq!(item.text, "hello");
    }

    #[test]
    fn tool_call_result_text_returns_first_block() {
        let result = ToolCallResult {
            content: vec![ContentItem::text("first"), ContentItem::text("second")],
            is_error: false,
        };
        assert_eq!(result.text(), Some("first"));

        let empty = ToolCallResult {
            content: vec![],
            is_error: true,
        };
        assert_eq!(empty.text(), None);
    }
}