llm-tool-mcp 0.5.0

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
//! 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;

// ── 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, 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, 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,
    /// 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, Serialize)]
pub struct Capabilities {
    /// Tool support — presence signals that `tools/list` and `tools/call`
    /// are available.
    pub tools: ToolCapabilities,
    /// Resource support — presence signals that `resources/list` is available.
    pub resources: ResourceCapabilities,
    /// Prompt support — presence signals that `prompts/list` is available.
    pub prompts: 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,
}

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

// ── 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");
    }
}