github-copilot-sdk 1.0.0-beta.4

Rust SDK for programmatic control of the GitHub Copilot CLI via JSON-RPC. Technical preview, pre-1.0.
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use std::sync::Arc;

use github_copilot_sdk::handler::{ApproveAllHandler, PermissionResult, SessionHandler};
use github_copilot_sdk::tool::{ToolHandler, ToolHandlerRouter};
use github_copilot_sdk::{
    Error, PermissionRequestData, RequestId, SessionConfig, SessionId, Tool, ToolInvocation,
    ToolResult,
};
use serde_json::json;
use tokio::sync::mpsc;

use super::support::{assistant_message_content, recv_with_timeout, with_e2e_context};

#[tokio::test]
async fn invokes_built_in_tools() {
    with_e2e_context("tools", "invokes_built_in_tools", |ctx| {
        Box::pin(async move {
            ctx.set_default_copilot_user();
            std::fs::write(
                ctx.work_dir().join("README.md"),
                "# ELIZA, the only chatbot you'll ever need",
            )
            .expect("write README");
            let client = ctx.start_client().await;
            let session = client
                .create_session(ctx.approve_all_session_config())
                .await
                .expect("create session");

            let answer = session
                .send_and_wait("What's the first line of README.md in this directory?")
                .await
                .expect("send")
                .expect("assistant message");
            assert!(assistant_message_content(&answer).contains("ELIZA"));

            session.disconnect().await.expect("disconnect session");
            client.stop().await.expect("stop client");
        })
    })
    .await;
}

#[tokio::test]
async fn invokes_custom_tool() {
    with_e2e_context("tools", "invokes_custom_tool", |ctx| {
        Box::pin(async move {
            ctx.set_default_copilot_user();
            let client = ctx.start_client().await;
            let router = ToolHandlerRouter::new(
                vec![Box::new(EncryptStringTool)],
                Arc::new(ApproveAllHandler),
            );
            let tools = router.tools();
            let session = client
                .create_session(
                    SessionConfig::default()
                        .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                        .with_handler(Arc::new(router))
                        .with_tools(tools),
                )
                .await
                .expect("create session");

            let answer = session
                .send_and_wait("Use encrypt_string to encrypt this string: Hello")
                .await
                .expect("send")
                .expect("assistant message");
            assert!(assistant_message_content(&answer).contains("HELLO"));

            session.disconnect().await.expect("disconnect session");
            client.stop().await.expect("stop client");
        })
    })
    .await;
}

#[tokio::test]
async fn handles_tool_calling_errors() {
    with_e2e_context("tools", "handles_tool_calling_errors", |ctx| {
        Box::pin(async move {
            ctx.set_default_copilot_user();
            let client = ctx.start_client().await;
            let router =
                ToolHandlerRouter::new(vec![Box::new(ErrorTool)], Arc::new(ApproveAllHandler));
            let tools = router.tools();
            let session = client
                .create_session(
                    SessionConfig::default()
                        .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                        .with_handler(Arc::new(router))
                        .with_tools(tools),
                )
                .await
                .expect("create session");

            let answer = session
                .send_and_wait("What is my location? If you can't find out, just say 'unknown'.")
                .await
                .expect("send")
                .expect("assistant message");
            let content = assistant_message_content(&answer);
            assert!(!content.contains("Melbourne"));
            assert!(content.to_lowercase().contains("unknown"));

            let exchanges = ctx.exchanges();
            let tool_results: Vec<_> = exchanges
                .last()
                .and_then(|exchange| exchange.get("request"))
                .and_then(|request| request.get("messages"))
                .and_then(serde_json::Value::as_array)
                .expect("messages")
                .iter()
                .filter(|message| {
                    message.get("role").and_then(serde_json::Value::as_str) == Some("tool")
                })
                .collect();
            assert_eq!(tool_results.len(), 1);
            assert!(!tool_results[0].to_string().contains("Melbourne"));

            session.disconnect().await.expect("disconnect session");
            client.stop().await.expect("stop client");
        })
    })
    .await;
}

#[tokio::test]
async fn can_receive_and_return_complex_types() {
    with_e2e_context("tools", "can_receive_and_return_complex_types", |ctx| {
        Box::pin(async move {
            ctx.set_default_copilot_user();
            let client = ctx.start_client().await;
            let router = ToolHandlerRouter::new(
                vec![Box::new(DbQueryTool)],
                Arc::new(ApproveAllHandler),
            );
            let tools = router.tools();
            let session = client
                .create_session(
                    SessionConfig::default()
                        .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                        .with_handler(Arc::new(router))
                        .with_tools(tools),
                )
                .await
                .expect("create session");

            let answer = session
                .send_and_wait(
                    "Perform a DB query for the 'cities' table using IDs 12 and 19, sorting ascending. \
                     Reply only with lines of the form: [cityname] [population]",
                )
                .await
                .expect("send")
                .expect("assistant message");
            let content = assistant_message_content(&answer);
            assert!(content.contains("Passos"));
            assert!(content.contains("San Lorenzo"));
            assert!(content.replace(',', "").contains("135460"));
            assert!(content.replace(',', "").contains("204356"));

            session.disconnect().await.expect("disconnect session");
            client.stop().await.expect("stop client");
        })
    })
    .await;
}

#[tokio::test]
async fn overrides_built_in_tool_with_custom_tool() {
    with_e2e_context("tools", "overrides_built_in_tool_with_custom_tool", |ctx| {
        Box::pin(async move {
            ctx.set_default_copilot_user();
            let client = ctx.start_client().await;
            let router =
                ToolHandlerRouter::new(vec![Box::new(CustomGrepTool)], Arc::new(ApproveAllHandler));
            let tools = router.tools();
            let session = client
                .create_session(
                    SessionConfig::default()
                        .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                        .with_handler(Arc::new(router))
                        .with_tools(tools),
                )
                .await
                .expect("create session");

            let answer = session
                .send_and_wait("Use grep to search for the word 'hello'")
                .await
                .expect("send")
                .expect("assistant message");
            assert!(assistant_message_content(&answer).contains("CUSTOM_GREP_RESULT"));

            session.disconnect().await.expect("disconnect session");
            client.stop().await.expect("stop client");
        })
    })
    .await;
}

#[tokio::test]
async fn skippermission_sent_in_tool_definition() {
    with_e2e_context("tools", "skippermission_sent_in_tool_definition", |ctx| {
        Box::pin(async move {
            ctx.set_default_copilot_user();
            let client = ctx.start_client().await;
            let (permission_tx, mut permission_rx) = mpsc::unbounded_channel();
            let handler = Arc::new(RecordingPermissionHandler {
                permission_tx,
                decision: PermissionResult::Denied,
            });
            let router = ToolHandlerRouter::new(vec![Box::new(SafeLookupTool)], handler);
            let tools = router.tools();
            let session = client
                .create_session(
                    SessionConfig::default()
                        .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                        .with_handler(Arc::new(router))
                        .with_tools(tools),
                )
                .await
                .expect("create session");

            let answer = session
                .send_and_wait("Use safe_lookup to look up 'test123'")
                .await
                .expect("send")
                .expect("assistant message");
            assert!(assistant_message_content(&answer).contains("RESULT"));
            assert!(
                tokio::time::timeout(std::time::Duration::from_millis(100), permission_rx.recv())
                    .await
                    .is_err(),
                "skip_permission tool should not request permission"
            );

            session.disconnect().await.expect("disconnect session");
            client.stop().await.expect("stop client");
        })
    })
    .await;
}

#[ignore = "Behaves as if no content was in the result. Binary tool results are not fully implemented yet."]
#[tokio::test]
async fn can_return_binary_result() {}

#[tokio::test]
async fn invokes_custom_tool_with_permission_handler() {
    with_e2e_context(
        "tools",
        "invokes_custom_tool_with_permission_handler",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let (permission_tx, mut permission_rx) = mpsc::unbounded_channel();
                let handler = Arc::new(RecordingPermissionHandler {
                    permission_tx,
                    decision: PermissionResult::Approved,
                });
                let router = ToolHandlerRouter::new(vec![Box::new(EncryptStringTool)], handler);
                let tools = router.tools();
                let session = client
                    .create_session(
                        SessionConfig::default()
                            .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                            .with_handler(Arc::new(router))
                            .with_tools(tools),
                    )
                    .await
                    .expect("create session");

                let answer = session
                    .send_and_wait("Use encrypt_string to encrypt this string: Hello")
                    .await
                    .expect("send")
                    .expect("assistant message");
                assert!(assistant_message_content(&answer).contains("HELLO"));
                let request = recv_with_timeout(&mut permission_rx, "custom tool permission").await;
                assert!(request.extra.is_object() || request.kind.is_some());

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn denies_custom_tool_when_permission_denied() {
    with_e2e_context(
        "tools",
        "denies_custom_tool_when_permission_denied",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let (call_tx, mut call_rx) = mpsc::unbounded_channel();
                let (permission_tx, _permission_rx) = mpsc::unbounded_channel();
                let handler = Arc::new(RecordingPermissionHandler {
                    permission_tx,
                    decision: PermissionResult::Denied,
                });
                let router = ToolHandlerRouter::new(
                    vec![Box::new(TrackedEncryptStringTool { call_tx })],
                    handler,
                );
                let tools = router.tools();
                let session = client
                    .create_session(
                        SessionConfig::default()
                            .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                            .with_handler(Arc::new(router))
                            .with_tools(tools),
                    )
                    .await
                    .expect("create session");

                session
                    .send_and_wait("Use encrypt_string to encrypt this string: Hello")
                    .await
                    .expect("send");
                assert!(
                    tokio::time::timeout(std::time::Duration::from_millis(100), call_rx.recv())
                        .await
                        .is_err(),
                    "denied custom tool should not be invoked"
                );

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn should_execute_multiple_custom_tools_in_parallel_single_turn() {
    with_e2e_context(
        "tools",
        "should_execute_multiple_custom_tools_in_parallel_single_turn",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let (city_tx, mut city_rx) = mpsc::unbounded_channel();
                let (country_tx, mut country_rx) = mpsc::unbounded_channel();
                let router = ToolHandlerRouter::new(
                    vec![
                        Box::new(LookupCityTool { call_tx: city_tx }),
                        Box::new(LookupCountryTool {
                            call_tx: country_tx,
                        }),
                    ],
                    Arc::new(ApproveAllHandler),
                );
                let tools = router.tools();
                let session = client
                    .create_session(
                        SessionConfig::default()
                            .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                            .with_handler(Arc::new(router))
                            .with_tools(tools),
                    )
                    .await
                    .expect("create session");

                let answer = session
                    .send_and_wait("Use lookup_city with 'Paris' and lookup_country with 'France' at the same time, then combine both results in your reply.")
                    .await
                    .expect("send")
                    .expect("assistant message");
                assert_eq!(recv_with_timeout(&mut city_rx, "city tool").await, "Paris");
                assert_eq!(
                    recv_with_timeout(&mut country_rx, "country tool").await,
                    "France"
                );
                let content = assistant_message_content(&answer);
                assert!(content.contains("CITY_PARIS"));
                assert!(content.contains("COUNTRY_FRANCE"));

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

#[tokio::test]
async fn should_respect_availabletools_and_excludedtools_combined() {
    with_e2e_context(
        "tools",
        "should_respect_availabletools_and_excludedtools_combined",
        |ctx| {
            Box::pin(async move {
                ctx.set_default_copilot_user();
                let client = ctx.start_client().await;
                let (excluded_tx, mut excluded_rx) = mpsc::unbounded_channel();
                let router = ToolHandlerRouter::new(
                    vec![
                        Box::new(AllowedTool),
                        Box::new(ExcludedTool {
                            call_tx: excluded_tx,
                        }),
                    ],
                    Arc::new(ApproveAllHandler),
                );
                let tools = router.tools();
                let session = client
                    .create_session(
                        SessionConfig::default()
                            .with_github_token(super::support::DEFAULT_TEST_TOKEN)
                            .with_handler(Arc::new(router))
                            .with_tools(tools)
                            .with_available_tools(["allowed_tool", "excluded_tool"])
                            .with_excluded_tools(["excluded_tool"]),
                    )
                    .await
                    .expect("create session");

                let answer = session
                    .send_and_wait(
                        "Use the allowed_tool with input 'test'. Do NOT use excluded_tool.",
                    )
                    .await
                    .expect("send")
                    .expect("assistant message");
                assert!(assistant_message_content(&answer).contains("ALLOWED_TEST"));
                assert!(
                    tokio::time::timeout(std::time::Duration::from_millis(100), excluded_rx.recv())
                        .await
                        .is_err(),
                    "excluded tool should not be invoked"
                );

                session.disconnect().await.expect("disconnect session");
                client.stop().await.expect("stop client");
            })
        },
    )
    .await;
}

struct EncryptStringTool;

#[async_trait::async_trait]
impl ToolHandler for EncryptStringTool {
    fn tool(&self) -> Tool {
        Tool::new("encrypt_string")
            .with_description("Encrypts a string")
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "input": {
                        "type": "string",
                        "description": "String to encrypt"
                    }
                },
                "required": ["input"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let input = invocation
            .arguments
            .get("input")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        Ok(ToolResult::Text(input.to_uppercase()))
    }
}

struct TrackedEncryptStringTool {
    call_tx: mpsc::UnboundedSender<()>,
}

#[async_trait::async_trait]
impl ToolHandler for TrackedEncryptStringTool {
    fn tool(&self) -> Tool {
        EncryptStringTool.tool()
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let _ = self.call_tx.send(());
        EncryptStringTool.call(invocation).await
    }
}

struct ErrorTool;

#[async_trait::async_trait]
impl ToolHandler for ErrorTool {
    fn tool(&self) -> Tool {
        Tool::new("get_user_location").with_description("Gets the user's location")
    }

    async fn call(&self, _invocation: ToolInvocation) -> Result<ToolResult, Error> {
        Ok(ToolResult::Text(
            "Failed to execute `get_user_location` tool with arguments: {} due to error: Error: Tool execution failed"
                .to_string(),
        ))
    }
}

struct CustomGrepTool;

#[async_trait::async_trait]
impl ToolHandler for CustomGrepTool {
    fn tool(&self) -> Tool {
        Tool::new("grep")
            .with_description("A custom grep implementation that overrides the built-in")
            .with_overrides_built_in_tool(true)
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string", "description": "Search query" }
                },
                "required": ["query"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let query = invocation
            .arguments
            .get("query")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        Ok(ToolResult::Text(format!("CUSTOM_GREP_RESULT: {query}")))
    }
}

struct SafeLookupTool;

#[async_trait::async_trait]
impl ToolHandler for SafeLookupTool {
    fn tool(&self) -> Tool {
        Tool::new("safe_lookup")
            .with_description("A tool that skips permission")
            .with_skip_permission(true)
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "id": { "type": "string", "description": "Lookup ID" }
                },
                "required": ["id"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let id = invocation
            .arguments
            .get("id")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        Ok(ToolResult::Text(format!("RESULT: {id}")))
    }
}

struct LookupCityTool {
    call_tx: mpsc::UnboundedSender<String>,
}

#[async_trait::async_trait]
impl ToolHandler for LookupCityTool {
    fn tool(&self) -> Tool {
        Tool::new("lookup_city")
            .with_description("Looks up city information")
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "city": { "type": "string", "description": "City name" }
                },
                "required": ["city"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let city = invocation
            .arguments
            .get("city")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        let _ = self.call_tx.send(city.clone());
        Ok(ToolResult::Text(format!("CITY_{}", city.to_uppercase())))
    }
}

struct LookupCountryTool {
    call_tx: mpsc::UnboundedSender<String>,
}

#[async_trait::async_trait]
impl ToolHandler for LookupCountryTool {
    fn tool(&self) -> Tool {
        Tool::new("lookup_country")
            .with_description("Looks up country information")
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "country": { "type": "string", "description": "Country name" }
                },
                "required": ["country"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let country = invocation
            .arguments
            .get("country")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        let _ = self.call_tx.send(country.clone());
        Ok(ToolResult::Text(format!(
            "COUNTRY_{}",
            country.to_uppercase()
        )))
    }
}

struct AllowedTool;

#[async_trait::async_trait]
impl ToolHandler for AllowedTool {
    fn tool(&self) -> Tool {
        Tool::new("allowed_tool")
            .with_description("An allowed tool")
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "input": { "type": "string", "description": "Input value" }
                },
                "required": ["input"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let input = invocation
            .arguments
            .get("input")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        Ok(ToolResult::Text(format!(
            "ALLOWED_{}",
            input.to_uppercase()
        )))
    }
}

struct ExcludedTool {
    call_tx: mpsc::UnboundedSender<()>,
}

#[async_trait::async_trait]
impl ToolHandler for ExcludedTool {
    fn tool(&self) -> Tool {
        Tool::new("excluded_tool")
            .with_description("A tool that should be excluded")
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "input": { "type": "string", "description": "Input value" }
                },
                "required": ["input"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let _ = self.call_tx.send(());
        let input = invocation
            .arguments
            .get("input")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        Ok(ToolResult::Text(format!(
            "EXCLUDED_{}",
            input.to_uppercase()
        )))
    }
}

struct RecordingPermissionHandler {
    permission_tx: mpsc::UnboundedSender<PermissionRequestData>,
    decision: PermissionResult,
}

#[async_trait::async_trait]
impl SessionHandler for RecordingPermissionHandler {
    async fn on_permission_request(
        &self,
        _session_id: SessionId,
        _request_id: RequestId,
        data: PermissionRequestData,
    ) -> PermissionResult {
        let _ = self.permission_tx.send(data);
        self.decision.clone()
    }
}

struct DbQueryTool;

#[async_trait::async_trait]
impl ToolHandler for DbQueryTool {
    fn tool(&self) -> Tool {
        Tool::new("db_query")
            .with_description("Performs a database query")
            .with_parameters(json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "object",
                        "properties": {
                            "table": { "type": "string" },
                            "ids": {
                                "type": "array",
                                "items": { "type": "integer" }
                            },
                            "sortAscending": { "type": "boolean" }
                        },
                        "required": ["table", "ids", "sortAscending"]
                    }
                },
                "required": ["query"]
            }))
    }

    async fn call(&self, invocation: ToolInvocation) -> Result<ToolResult, Error> {
        let query = invocation.arguments.get("query").expect("query argument");
        assert_eq!(
            query.get("table").and_then(serde_json::Value::as_str),
            Some("cities")
        );
        assert_eq!(
            query.get("ids").and_then(serde_json::Value::as_array),
            Some(&vec![json!(12), json!(19)])
        );
        assert_eq!(
            query
                .get("sortAscending")
                .and_then(serde_json::Value::as_bool),
            Some(true)
        );
        Ok(ToolResult::Text(
            r#"[{"cityName":"Passos","countryId":19,"population":135460},{"cityName":"San Lorenzo","countryId":12,"population":204356}]"#
                .to_string(),
        ))
    }
}