kuri 0.2.0

An SDK for building MCP servers, focused on elegant developer experience, where tools and prompts are just plain old Rust functions.
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
mod common;

use std::sync::atomic::{AtomicI32, Ordering};

use common::*;
use kuri::{context::Inject, tool, MCPService, MCPServiceBuilder, ToolError};
use kuri_mcp_protocol::{
    jsonrpc::{ErrorCode, RequestId, ResponseItem},
    messages::{CallToolResult, ListToolsResult},
    Content, TextContent,
};
use serde::Deserialize;
use tracing_subscriber::EnvFilter;

// Tool tests
// Spec: https://spec.modelcontextprotocol.io/specification/2025-03-26/server/tools/

#[tokio::test]
async fn test_tools_list() {
    let mut server = init_tool_server_simple();

    // Basic list
    let response = call_server(&mut server, "tools/list", serde_json::json!({}))
        .await
        .unwrap();
    validate_tools_list(response);

    // List with unnecessary params
    let response = call_server(
        &mut server,
        "tools/list",
        serde_json::json!({
            "cursor": "optional-cursor-value",
            "random_param": "some-value",
        }),
    )
    .await
    .unwrap();
    validate_tools_list(response);
}

fn validate_tools_list(response: ResponseItem) {
    match response {
        ResponseItem::Success { id, result, .. } => {
            assert_eq!(id, RequestId::Num(1));

            let actual: ListToolsResult = serde_json::from_value(result).unwrap();
            let expected = ListToolsResult {
                tools: vec![kuri_mcp_protocol::tool::Tool {
                    name: "calculator".to_string(),
                    description: "Perform basic arithmetic operations".to_string(),
                    input_schema: serde_json::json!({
                        "$schema": "http://json-schema.org/draft-07/schema#",
                        "properties": {
                            "operation": {
                                "description": "The operation to perform (add, subtract, multiply, divide)",
                                "type": "string"
                            },
                            "x": {
                                "description": "First number in the calculation",
                                "format": "int32",
                                "type": "integer"
                            },
                            "y": {
                                "description": "Second number in the calculation",
                                "format": "int32",
                                "type": "integer"
                            }
                        },
                        "required": ["operation", "x", "y"],
                        "title": "CalculatorParameters",
                        "type": "object"
                    }),
                }],
            };
            assert_eq!(actual, expected);
        }
        ResponseItem::Error { .. } => {
            panic!("Expected success response");
        }
    }
}

#[tokio::test]
async fn test_tools_call_simple_text() {
    let mut server = init_tool_server_simple();
    verify_calculator(&mut server, "calculator").await;
}

#[tokio::test]
async fn test_tools_call_no_tool_descriptions() {
    let mut server = init_tool_server_no_desc();
    verify_calculator(&mut server, "calculator_no_desc").await;
}

async fn verify_calculator(server: &mut MCPService, tool_name: &str) {
    let response = call_server(
        server,
        "tools/call",
        serde_json::json!({
            "name": tool_name,
            "arguments": {
                "x": 1,
                "y": 2,
                "operation": "add"
            }
        }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Success { id, result, .. } => {
            assert_eq!(id, RequestId::Num(1));

            let actual: CallToolResult = serde_json::from_value(result).unwrap();
            let expected = CallToolResult {
                content: vec![Content::Text(TextContent {
                    text: "3".to_string(),
                    annotations: None,
                })],
                is_error: false,
            };
            assert_eq!(actual.content[0], expected.content[0]);
            assert_eq!(actual.is_error, expected.is_error);
        }
        ResponseItem::Error { .. } => {
            panic!("Expected success response");
        }
    }
}

#[tokio::test]
async fn test_tools_call_with_invalid_parameters() {
    // TODO: more descriptive error msg, e.g. "Invalid tool args: missing `operation`"

    let mut server = init_tool_server_simple();

    // Parameters required by tool, but not given in request
    let response = call_server(
        &mut server,
        "tools/call",
        serde_json::json!({
            "name": "calculator",
        }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Error { id, error, .. } => {
            assert_eq!(id, RequestId::Num(1));
            assert_eq!(error.code, ErrorCode::InvalidParams);
            assert_eq!(
                error.message,
                "Invalid parameters: Missing or incorrect tool arguments"
            );
        }
        _ => {
            panic!("Expected error response");
        }
    }

    // Not all required params were given
    let response = call_server(
        &mut server,
        "tools/call",
        serde_json::json!({
            "name": "calculator",
            "arguments": {
                "x": 1,
                "y": 2,
            }
        }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Success { .. } => {
            panic!("Expected error response");
        }
        ResponseItem::Error { id, error, .. } => {
            assert_eq!(id, RequestId::Num(1));
            assert_eq!(error.code, ErrorCode::InvalidParams);
            assert_eq!(
                error.message,
                "Invalid parameters: Missing or incorrect tool arguments"
            );
        }
    }
}

#[tokio::test]
async fn test_tools_call_invalid_tool() {
    let mut server = init_tool_server_simple();

    let response = call_server(
        &mut server,
        "tools/call",
        serde_json::json!({
            "name": "some_invalid_tool",
            "arguments": {}
        }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Success { .. } => {
            panic!("Expected error response");
        }
        ResponseItem::Error { id, error, .. } => {
            assert_eq!(id, RequestId::Num(1));
            assert_eq!(error.code, ErrorCode::InvalidParams);
            assert_eq!(error.message, "Tool not found: some_invalid_tool");
        }
    }
}

#[tokio::test]
async fn test_tools_call_with_context() {
    let mut server = init_tool_server_with_ctx();

    // First call the increment tool
    let response = call_server(
        &mut server,
        "tools/call",
        serde_json::json!({
            "name": "increment",
            "arguments": {
                "quantity": 1
            }
        }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Success { id, result, .. } => {
            assert_eq!(id, RequestId::Num(1));
            let actual: CallToolResult = serde_json::from_value(result).unwrap();
            let expected = CallToolResult {
                content: vec![],
                is_error: false,
            };
            assert_eq!(actual.content, expected.content);
            assert_eq!(actual.is_error, expected.is_error);
        }
        ResponseItem::Error { .. } => {
            panic!("Expected success response");
        }
    }

    // Then get the value
    let response = call_server(
        &mut server,
        "tools/call",
        serde_json::json!({
            "name": "get_value",
            "arguments": {}
        }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Success { id, result, .. } => {
            assert_eq!(id, RequestId::Num(1));
            let actual: CallToolResult = serde_json::from_value(result).unwrap();
            let expected = CallToolResult {
                content: vec![Content::Text(TextContent {
                    text: "1".to_string(),
                    annotations: None,
                })],
                is_error: false,
            };
            assert_eq!(actual.content, expected.content);
            assert_eq!(actual.is_error, expected.is_error);
        }
        ResponseItem::Error { .. } => {
            panic!("Expected success response");
        }
    }

    // Request may provide no arguments, if no arguments are needed by the tool
    let response = call_server(
        &mut server,
        "tools/call",
        serde_json::json!({ "name": "get_value" }),
    )
    .await
    .unwrap();

    match response {
        ResponseItem::Success { id, result, .. } => {
            assert_eq!(id, RequestId::Num(1));
            let actual: CallToolResult = serde_json::from_value(result).unwrap();
            let expected = CallToolResult {
                content: vec![Content::Text(TextContent {
                    text: "1".to_string(),
                    annotations: None,
                })],
                is_error: false,
            };
            assert_eq!(actual.content, expected.content);
            assert_eq!(actual.is_error, expected.is_error);
        }
        ResponseItem::Error { .. } => {
            panic!("Expected success response when no arguments are provided, if none needed by the tool");
        }
    }
}

#[tool(
    description = "Perform basic arithmetic operations",
    params(
        x = "First number in the calculation",
        y = "Second number in the calculation",
        operation = "The operation to perform (add, subtract, multiply, divide)"
    )
)]
pub async fn calculator(x: i32, y: i32, operation: String) -> Result<i32, ToolError> {
    match operation.as_str() {
        "add" => Ok(x + y),
        "subtract" => Ok(x - y),
        "multiply" => Ok(x * y),
        "divide" => {
            if y == 0 {
                Err(ToolError::ExecutionError("Division by zero".into()))
            } else {
                Ok(x / y)
            }
        }
        _ => Err(ToolError::InvalidParameters(format!(
            "Unknown operation: {}",
            operation
        ))),
    }
}

#[tool]
pub async fn calculator_no_desc(x: i32, y: i32, operation: String) -> Result<i32, ToolError> {
    calculator(x, y, operation).await
}

#[derive(Default, Deserialize)]
struct Counter {
    inner: AtomicI32,
}

#[tool(
    description = "Increment the counter by a specified quantity",
    params(quantity = "How much to increment the counter by")
)]
async fn increment(counter: Inject<Counter>, quantity: u32) {
    counter.inner.fetch_add(quantity as i32, Ordering::SeqCst);
}

#[tool(
    description = "Decrement the counter by a specified quantity",
    params(quantity = "How much to decrement the counter by")
)]
async fn decrement(counter: Inject<Counter>, quantity: u32) {
    counter.inner.fetch_sub(quantity as i32, Ordering::SeqCst);
}

#[tool(description = "Get current value of counter")]
async fn get_value(counter: Inject<Counter>) -> i32 {
    counter.inner.load(Ordering::SeqCst)
}

pub fn init_tool_server_simple() -> MCPService {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .with_test_writer()
        .try_init();

    MCPServiceBuilder::new("Calculator".to_string())
        .with_tool(Calculator)
        .build()
}

pub fn init_tool_server_no_desc() -> MCPService {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .with_test_writer()
        .try_init();

    MCPServiceBuilder::new("Calculator".to_string())
        .with_tool(CalculatorNoDesc)
        .build()
}

pub fn init_tool_server_with_ctx() -> MCPService {
    let _ = tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .with_test_writer()
        .try_init();

    MCPServiceBuilder::new("Counter".to_string())
        .with_tool(Increment)
        .with_tool(Decrement)
        .with_tool(GetValue)
        .with_state(Inject::new(Counter::default()))
        .build()
}