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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
//! Server runtime context utilities
use super::{
handler::RequestHandler,
options::{McpOptions, RuntimeMcpOptions},
};
use crate::error::{Error, ErrorCode};
use crate::transport::Sender;
use crate::{
middleware::{MwContext, Next},
shared::{IntoArgs, RequestQueue},
transport::TransportProtoSender,
types::{
CallToolRequestParams, CallToolResponse, GetPromptRequestParams, GetPromptResult, Message,
Prompt, ReadResourceRequestParams, ReadResourceResult, Request, RequestId, Resource,
Response, Tool, ToolResult, ToolUse, Uri,
elicitation::{ElicitRequestParams, ElicitResult, ElicitationCompleteParams},
notification::Notification,
resource::SubscribeRequestParams,
root::{ListRootsRequestParams, ListRootsResult},
sampling::{CreateMessageRequestParams, CreateMessageResult},
},
};
use std::{
collections::HashMap,
fmt::{Debug, Formatter},
sync::Arc,
time::Duration,
};
use tokio::time::timeout;
#[cfg(feature = "tasks")]
use crate::{
shared::Either,
types::{
CancelTaskRequestParams, CreateTaskResult, Cursor, GetTaskPayloadRequestParams,
GetTaskRequestParams, ListTasksRequestParams, ListTasksResult, Task, TaskPayload,
tool::TaskSupport,
},
};
#[cfg(feature = "tasks")]
use serde::de::DeserializeOwned;
#[cfg(feature = "di")]
use volga_di::Container;
#[cfg(feature = "http-server")]
use {
crate::auth::DefaultClaims,
crate::transport::http::server::{validate_permissions, validate_roles},
volga::headers::HeaderMap,
};
#[cfg(feature = "tasks")]
pub(crate) type ToolOrTaskResponse = Either<CreateTaskResult, CallToolResponse>;
type RequestHandlers = HashMap<String, RequestHandler<Response>>;
/// Represents a Server runtime
#[derive(Clone)]
pub(crate) struct ServerRuntime {
/// Represents MCP server options
options: RuntimeMcpOptions,
/// Represents registered request handlers
handlers: Arc<RequestHandlers>,
/// Represents a queue of pending requests
pending: RequestQueue,
/// Represents a sender that depends on selected transport protocol
sender: TransportProtoSender,
/// Global middlewares entrypoint
mw_start: Option<Next>,
/// Represents a DI container
#[cfg(feature = "di")]
pub(crate) container: Container,
}
/// Represents MCP Request Context
#[derive(Clone)]
pub struct Context {
/// Represents current session id
pub session_id: Option<uuid::Uuid>,
/// Represents HTTP headers of the current request
#[cfg(feature = "http-server")]
pub headers: HeaderMap,
/// Represents JWT claims of the current request
#[cfg(feature = "http-server")]
pub(crate) claims: Option<DefaultClaims>,
/// Represents MCP server options
pub(crate) options: RuntimeMcpOptions,
/// Represents a queue of pending requests
pending: RequestQueue,
/// Represents a sender that depends on selected transport protocol
sender: TransportProtoSender,
/// Represents a timeout for the current request
timeout: Duration,
/// Represents a DI scope
#[cfg(feature = "di")]
pub(crate) scope: Option<Container>,
}
impl Debug for Context {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Context")
.field("session_id", &self.session_id)
.field("timeout", &self.timeout)
.finish()
}
}
impl ServerRuntime {
/// Creates a new server runtime
pub(crate) fn new(
sender: TransportProtoSender,
mut options: McpOptions,
handlers: RequestHandlers,
#[cfg(feature = "di")] container: Container,
) -> Self {
let middlewares = options.middlewares.take();
let request_timeout = options.request_timeout;
Self {
pending: RequestQueue::new(request_timeout),
handlers: Arc::new(handlers),
options: options.into_runtime(),
mw_start: middlewares.and_then(|mw| mw.compose()),
sender,
#[cfg(feature = "di")]
container,
}
}
/// Provides a [`RuntimeMcpOptions`]
pub(crate) fn options(&self) -> RuntimeMcpOptions {
self.options.clone()
}
/// Provides the current connections sender
pub(crate) fn sender(&self) -> TransportProtoSender {
self.sender.clone()
}
/// Returns a clone of this runtime with its sender replaced by `sender`.
///
/// Used by `execute_batch` to give each batch request an intercepted sender
/// so responses are captured into a channel instead of sent to the transport.
pub(crate) fn with_sender(mut self, sender: TransportProtoSender) -> Self {
self.sender = sender;
self
}
/// Provides a hash map of registered request handlers
pub(crate) fn request_handlers(&self) -> Arc<RequestHandlers> {
self.handlers.clone()
}
/// Creates a new MCP request [`Context`]
#[cfg(not(feature = "http-server"))]
pub(crate) fn context(&self, session_id: Option<uuid::Uuid>) -> Context {
Context {
session_id,
pending: self.pending.clone(),
sender: self.sender.clone(),
options: self.options.clone(),
timeout: self.options.request_timeout,
#[cfg(feature = "di")]
scope: None,
}
}
/// Creates a new MCP request [`Context`]
#[cfg(feature = "http-server")]
pub(crate) fn context(
&self,
session_id: Option<uuid::Uuid>,
headers: HeaderMap,
claims: Option<DefaultClaims>,
) -> Context {
Context {
session_id,
headers,
claims,
pending: self.pending.clone(),
sender: self.sender.clone(),
options: self.options.clone(),
timeout: self.options.request_timeout,
#[cfg(feature = "di")]
scope: None,
}
}
/// Provides a "queue" of pending requests
pub(crate) fn pending_requests(&self) -> &RequestQueue {
&self.pending
}
/// Starts the middleware pipeline
#[inline]
pub(crate) async fn execute(self, msg: Message) {
if let Some(mw_start) = self.mw_start.clone() {
mw_start(MwContext::msg(msg, self)).await;
}
}
}
impl Context {
/// Returns a list of all available tools
pub async fn tools(&self) -> Vec<Tool> {
self.options.tools.values().await
}
/// Finds a tool by `name`
pub async fn find_tool(&self, name: &str) -> Option<Tool> {
self.options.tools.get(name).await
}
/// Returns a list of tools by name.
/// If some tools requested in `names` are missing, they won't be in the result list.
pub async fn find_tools(&self, names: impl IntoIterator<Item = &str>) -> Vec<Tool> {
futures_util::future::join_all(names.into_iter().map(|name| self.options.tools.get(name)))
.await
.into_iter()
.flatten()
.collect()
}
/// Initiates a tool call once a [`ToolUse`] request received from assistant
/// withing a sampling window.
///
/// For multiple [`ToolUse`] requests, use the [`Context::use_tools`] method.
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::prelude::*;
///
/// #[tool]
/// async fn analyze_weather(ctx: Context, city: String) -> Result<(), Error> {
/// let args = ("city", city);
/// let weather = ctx.use_tool(ToolUse::new("get_weather", args)).await;
///
/// // do something with the weather result
///
/// # Ok(())
/// }
///
/// #[tool]
/// async fn get_weather(city: String) -> String {
/// // ...
///
/// format!("Sunny in {city}")
/// }
/// # }
/// ```
pub async fn use_tool(&self, tool: ToolUse) -> ToolResult {
let id = tool.id.clone();
let res = self.clone().call_tool(tool.into()).await;
match res {
Ok(res) => ToolResult::new(id, res),
Err(err) => ToolResult::error(id, err),
}
}
/// Initiates a parallel tool calls for multiple [`ToolUse`] requests.
///
/// For a single [`ToolUse`] use the [`Context::use_tool`] method.
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::prelude::*;
///
/// #[tool]
/// async fn analyze_weather(ctx: Context) -> Result<(), Error> {
/// let weather = ctx.use_tools([
/// ToolUse::new("get_weather", ("city", "London")),
/// ToolUse::new("get_weather", ("city", "Paris"))
/// ]).await;
///
/// // do something with the weather result
///
/// # Ok(())
/// }
/// # }
/// ```
pub async fn use_tools<I>(&self, tools: I) -> Vec<ToolResult>
where
I: IntoIterator<Item = ToolUse>,
{
futures_util::future::join_all(tools.into_iter().map(|t| self.use_tool(t))).await
}
/// Gets the prompt by name
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::prelude::*;
///
/// #[tool]
/// async fn analyze_weather(ctx: Context, city: String) -> Result<(), Error> {
/// let prompt = ctx.prompt("get_weather", ("city", city)).await?;
///
/// // do something with the prompt
///
/// # Ok(())
/// }
///
/// #[prompt]
/// async fn get_weather(city: String) -> PromptMessage {
/// PromptMessage::user()
/// .with(format!("What's the weather in {city}"))
/// }
/// # }
/// ```
pub async fn prompt<N, Args>(&self, name: N, args: Args) -> Result<GetPromptResult, Error>
where
N: Into<String>,
Args: IntoArgs,
{
let params = GetPromptRequestParams {
name: name.into(),
args: args.into_args(),
meta: None,
};
self.clone().get_prompt(params).await
}
/// Reads a resource content
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::prelude::*;
///
/// #[tool]
/// async fn summarize_document(ctx: Context, doc_uri: Uri) -> Result<(), Error> {
/// let doc = ctx.resource(doc_uri).await?;
///
/// // do something with the doc
///
/// # Ok(())
/// }
///
/// #[resource(uri = "file://{name}")]
/// async fn get_doc(name: String) -> TextResourceContents {
/// // read the doc
///
/// # TextResourceContents::new("", "")
/// }
/// # }
/// ```
pub async fn resource(&self, uri: impl Into<Uri>) -> Result<ReadResourceResult, Error> {
let uri = uri.into();
let params = ReadResourceRequestParams::from(uri);
self.clone().read_resource(params).await
}
/// Adds a new resource and notifies clients
pub async fn add_resource(&mut self, res: impl Into<Resource>) -> Result<(), Error> {
let res: Resource = res.into();
self.options.resources.insert(res.name.clone(), res).await?;
if self.options.is_resource_list_changed_supported() {
self.send_notification(crate::types::resource::commands::LIST_CHANGED, None)
.await
} else {
Ok(())
}
}
/// Removes a resource and notifies clients
pub async fn remove_resource(
&mut self,
uri: impl Into<Uri>,
) -> Result<Option<Resource>, Error> {
let removed = self.options.resources.remove(&uri.into()).await?;
if removed.is_some() && self.options.is_resource_list_changed_supported() {
self.send_notification(crate::types::resource::commands::LIST_CHANGED, None)
.await?;
}
Ok(removed)
}
/// Sends a [`Notification`] that the resource with the `uri` has been updated
pub async fn resource_updated(&mut self, uri: impl Into<Uri>) -> Result<(), Error> {
if !self.options.is_resource_subscription_supported() {
return Err(Error::new(
ErrorCode::MethodNotFound,
"Server does not support sending resource/updated notifications",
));
}
let uri = uri.into();
if self.is_subscribed(&uri) {
let params = serde_json::to_value(SubscribeRequestParams::from(uri)).ok();
self.send_notification(crate::types::resource::commands::UPDATED, params)
.await
} else {
Ok(())
}
}
/// Adds a subscription to the resource with the [`Uri`]
pub fn subscribe_to_resource(&mut self, uri: impl Into<Uri>) {
self.options.resource_subscriptions.insert(uri.into());
}
/// Removes a subscription to the resource with the [`Uri`]
pub fn unsubscribe_from_resource(&mut self, uri: &Uri) {
self.options.resource_subscriptions.remove(uri);
}
/// Returns `true` if there is a subscription to changes of the resource with the [`Uri`]
pub fn is_subscribed(&self, uri: &Uri) -> bool {
self.options.resource_subscriptions.contains(uri)
}
/// Adds a new prompt and notifies clients
pub async fn add_prompt(&mut self, prompt: Prompt) -> Result<(), Error> {
self.options
.prompts
.insert(prompt.name.clone(), prompt)
.await?;
if self.options.is_prompts_list_changed_supported() {
self.send_notification(crate::types::prompt::commands::LIST_CHANGED, None)
.await
} else {
Ok(())
}
}
/// Removes a prompt and notifies clients
pub async fn remove_prompt(
&mut self,
name: impl Into<String>,
) -> Result<Option<Prompt>, Error> {
let removed = self.options.prompts.remove(&name.into()).await?;
if removed.is_some() && self.options.is_prompts_list_changed_supported() {
self.send_notification(crate::types::prompt::commands::LIST_CHANGED, None)
.await?;
}
Ok(removed)
}
/// Adds a new prompt and notifies clients
pub async fn add_tool(&mut self, tool: Tool) -> Result<(), Error> {
self.options.tools.insert(tool.name.clone(), tool).await?;
if self.options.is_tools_list_changed_supported() {
self.send_notification(crate::types::tool::commands::LIST_CHANGED, None)
.await
} else {
Ok(())
}
}
/// Removes a tool and notifies clients
pub async fn remove_tool(&mut self, name: impl Into<String>) -> Result<Option<Tool>, Error> {
let removed = self.options.tools.remove(&name.into()).await?;
if removed.is_some() && self.options.is_tools_list_changed_supported() {
self.send_notification(crate::types::tool::commands::LIST_CHANGED, None)
.await?;
}
Ok(removed)
}
#[inline]
pub(crate) async fn read_resource(
self,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult, Error> {
let opt = self.options.clone();
match opt.read_resource(¶ms.uri) {
Some((handler, args)) => {
#[cfg(feature = "http-server")]
{
let template = opt.resources_templates.get(&handler.template).await;
self.validate_claims(
template.as_ref().and_then(|t| t.roles.as_deref()),
template.as_ref().and_then(|t| t.permissions.as_deref()),
)
}?;
handler
.call(params.with_args(args).with_context(self).into())
.await
}
_ => Err(Error::from(ErrorCode::ResourceNotFound)),
}
}
#[inline]
pub(crate) async fn get_prompt(
self,
params: GetPromptRequestParams,
) -> Result<GetPromptResult, Error> {
match self.options.get_prompt(¶ms.name).await {
None => Err(Error::new(ErrorCode::InvalidParams, "Prompt not found")),
Some(prompt) => {
#[cfg(feature = "http-server")]
self.validate_claims(prompt.roles.as_deref(), prompt.permissions.as_deref())?;
prompt.call(params.with_context(self).into()).await
}
}
}
#[inline]
pub(crate) async fn call_tool(
self,
params: CallToolRequestParams,
) -> Result<CallToolResponse, Error> {
match self.options.get_tool(¶ms.name).await {
None => Err(Error::new(ErrorCode::InvalidParams, "Tool not found")),
Some(tool) => {
#[cfg(feature = "http-server")]
self.validate_claims(tool.roles.as_deref(), tool.permissions.as_deref())?;
tool.call(params.with_context(self).into()).await
}
}
}
#[inline]
#[cfg(feature = "tasks")]
pub(crate) async fn call_tool_with_task(
self,
params: CallToolRequestParams,
) -> Result<ToolOrTaskResponse, Error> {
match self.options.get_tool(¶ms.name).await {
None => Err(Error::new(ErrorCode::InvalidParams, "Tool not found")),
Some(tool) => {
#[cfg(feature = "http-server")]
self.validate_claims(tool.roles.as_deref(), tool.permissions.as_deref())?;
let task_support = tool.task_support();
if let Some(task_meta) = params.task {
self.ensure_tool_augmentation_support(task_support)?;
let task = Task::from(task_meta);
let handle = self.options.track_task(task.clone());
let opt = self.options.clone();
let task_id = task.id.clone();
tokio::spawn(async move {
tokio::select! {
result = tool.call(params
.with_task(&task_id)
.with_context(self).into()) => {
let resp = match result {
Ok(result) => {
opt.tasks.complete(&task_id);
result
},
Err(err) => {
opt.tasks.fail(&task_id);
CallToolResponse::error(err)
}
};
handle.set_result(resp);
},
_ = handle.cancelled() => {}
}
});
Ok(Either::Left(CreateTaskResult::new(task)))
} else if task_support.is_some_and(|ts| ts == TaskSupport::Required) {
Err(Error::new(
ErrorCode::MethodNotFound,
"Tool required task augmented call",
))
} else {
tool.call(params.with_context(self).into())
.await
.map(Either::Right)
}
}
}
}
/// Requests a list of available roots from a client
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::{Context, error::Error, tool};
///
/// #[tool]
/// async fn handle_roots(mut ctx: Context) -> Result<(), Error> {
/// let roots = ctx.list_roots().await?;
///
/// // do something with roots
///
/// # Ok(())
/// }
/// # }
/// ```
pub async fn list_roots(&mut self) -> Result<ListRootsResult, Error> {
let method = crate::types::root::commands::LIST;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(ListRootsRequestParams::default()),
);
self.send_request(req).await?.into_result()
}
/// Sends the sampling request to the client
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::{
/// Context,
/// error::Error,
/// types::sampling::CreateMessageRequestParams,
/// tool
/// };
///
/// #[tool]
/// async fn generate_poem(mut ctx: Context, topic: String) -> Result<String, Error> {
/// let params = CreateMessageRequestParams::new()
/// .with_message(format!("Write a short poem about {topic}"))
/// .with_sys_prompt("You are a talented poet who writes concise, evocative verses.");
///
/// let result = ctx.sample(params).await?;
/// Ok(format!("{:?}", result.content))
/// }
/// # }
/// ```
#[cfg(not(feature = "tasks"))]
pub async fn sample(
&mut self,
params: CreateMessageRequestParams,
) -> Result<CreateMessageResult, Error> {
let method = crate::types::sampling::commands::CREATE;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_request(req).await?.into_result()
}
/// Sends the sampling request to the client
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "server-macros")] {
/// use neva::{
/// Context,
/// error::Error,
/// types::sampling::CreateMessageRequestParams,
/// tool
/// };
///
/// #[tool]
/// async fn generate_poem(mut ctx: Context, topic: String) -> Result<String, Error> {
/// let params = CreateMessageRequestParams::new()
/// .with_message(format!("Write a short poem about {topic}"))
/// .with_sys_prompt("You are a talented poet who writes concise, evocative verses.");
///
/// let result = ctx.sample(params).await?;
/// Ok(format!("{:?}", result.content))
/// }
/// # }
/// ```
#[cfg(feature = "tasks")]
pub async fn sample(
&mut self,
params: CreateMessageRequestParams,
) -> Result<CreateMessageResult, Error> {
let method = crate::types::sampling::commands::CREATE;
let is_task_aug = params.task.is_some();
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_maybe_task_augmented_request(req, is_task_aug)
.await
}
/// Sends the elicitation request to the client
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "serve-macros")] {
/// use neva::{
/// Context,
/// error::Error,
/// types::elicitation::ElicitRequestParams,
/// tool
/// };
///
/// #[tool]
/// async fn generate_poem(mut ctx: Context, _topic: String) -> Result<String, Error> {
/// let params = ElicitRequestParams::new("What is the poem mood you'd like?")
/// .with_required("mood", "string");
/// let result = ctx.elicit(params).await?;
/// Ok(format!("{:?}", result.content))
/// }
/// # }
/// ```
#[cfg(not(feature = "tasks"))]
pub async fn elicit(&mut self, params: ElicitRequestParams) -> Result<ElicitResult, Error> {
let method = crate::types::elicitation::commands::CREATE;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_request(req).await?.into_result()
}
/// Sends the elicitation request to the client
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "serve-macros")] {
/// use neva::{
/// Context,
/// error::Error,
/// types::elicitation::ElicitRequestParams,
/// tool
/// };
///
/// #[tool]
/// async fn generate_poem(mut ctx: Context, _topic: String) -> Result<String, Error> {
/// let params = ElicitRequestParams::new("What is the poem mood you'd like?")
/// .with_required("mood", "string");
/// let result = ctx.elicit(params).await?;
/// Ok(format!("{:?}", result.content))
/// }
/// # }
/// ```
#[cfg(feature = "tasks")]
pub async fn elicit(&mut self, params: ElicitRequestParams) -> Result<ElicitResult, Error> {
let related_task = params.related_task();
if let Some(related_task) = related_task {
let task_id = related_task.id;
let mut id = task_id
.as_str()
.parse::<RequestId>()
.expect("Invalid task id");
if let Some(session_id) = self.session_id {
id = id.concat(session_id.into());
}
let receiver = self.pending.push(&id);
self.options.tasks.set_result(&task_id, params);
self.options.tasks.require_input(&task_id);
let resp = match timeout(self.timeout, receiver).await {
Ok(Ok(crate::shared::PendingResponse::Response(resp))) => resp,
Ok(Ok(crate::shared::PendingResponse::Timeout)) => {
self.options.tasks.fail(&task_id);
return Err(Error::new(ErrorCode::Timeout, "Request timed out"));
}
Ok(Err(_)) => {
self.options.tasks.fail(&task_id);
return Err(Error::new(
ErrorCode::InternalError,
"Response channel closed",
));
}
Err(_) => {
_ = self.pending.pop(&id);
self.options.tasks.fail(&task_id);
return Err(Error::new(ErrorCode::Timeout, "Request timed out"));
}
};
self.options.tasks.reset(&task_id);
return resp.into_result();
}
let method = crate::types::elicitation::commands::CREATE;
let is_task_aug = params.is_task_augmented();
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_maybe_task_augmented_request(req, is_task_aug)
.await
}
/// Notifies the client that the elicitation with the `id` has been completed
pub async fn complete_elicitation(&mut self, id: impl Into<String>) -> Result<(), Error> {
let params = serde_json::to_value(ElicitationCompleteParams::new(id)).ok();
self.send_notification(crate::types::elicitation::commands::COMPLETE, params)
.await
}
/// Sends notification that a task with `id` was changed.
#[cfg(feature = "tasks")]
pub async fn task_changed(&mut self, id: &str) -> Result<(), Error> {
let task = self.options.tasks.get_status(id)?;
let params = serde_json::to_value(task).ok();
self.send_notification(crate::types::task::commands::STATUS, params)
.await
}
/// Applies earlier defined scopes to the current context.
#[inline]
#[cfg(feature = "di")]
pub fn with_scope(mut self, scope: Container) -> Self {
self.scope = Some(scope);
self
}
/// Resolves a service and returns a cloned instance.
/// `T` must implement `Clone` otherwise
/// use resolve_shared method that returns a shared pointer.
#[inline]
#[cfg(feature = "di")]
pub fn resolve<T: Send + Sync + Clone + 'static>(&self) -> Result<T, Error> {
self.scope
.as_ref()
.ok_or_else(|| Error::new(ErrorCode::InternalError, "DI scope is not set"))?
.resolve::<T>()
.map_err(Into::into)
}
/// Resolves a service and returns a shared pointer
#[inline]
#[cfg(feature = "di")]
pub fn resolve_shared<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, Error> {
self.scope
.as_ref()
.ok_or_else(|| Error::new(ErrorCode::InternalError, "DI scope is not set"))?
.resolve_shared::<T>()
.map_err(Into::into)
}
#[inline]
#[cfg(feature = "http-server")]
fn validate_claims(
&self,
roles: Option<&[String]>,
permissions: Option<&[String]>,
) -> Result<(), Error> {
let claims = self.claims.as_ref();
validate_roles(claims, roles)?;
validate_permissions(claims, permissions)?;
Ok(())
}
#[inline]
#[cfg(feature = "tasks")]
fn ensure_tool_augmentation_support(
&self,
task_support: Option<TaskSupport>,
) -> Result<(), Error> {
if !self.options.is_task_augmented_tool_call_supported() {
return Err(Error::new(
ErrorCode::MethodNotFound,
"Server does not support task augmented tool calls",
));
}
let Some(task_support) = task_support else {
return Err(Error::new(
ErrorCode::MethodNotFound,
"Tool does not support task augmented calls",
));
};
if task_support == TaskSupport::Forbidden {
return Err(Error::new(
ErrorCode::MethodNotFound,
"Tool forbid task augmented calls",
));
}
Ok(())
}
#[inline]
#[cfg(feature = "tasks")]
async fn send_maybe_task_augmented_request<T: DeserializeOwned>(
&mut self,
req: Request,
is_task_aug: bool,
) -> Result<T, Error> {
if is_task_aug {
let result = self.send_request(req).await?.into_result()?;
crate::shared::wait_to_completion(self, result).await
} else {
self.send_request(req).await?.into_result()
}
}
/// Sends a [`Request`] to a client
#[inline]
async fn send_request(&mut self, mut req: Request) -> Result<Response, Error> {
if let Some(session_id) = self.session_id {
req.session_id = Some(session_id);
}
let id = req.full_id();
let receiver = self.pending.push(&id);
if let Err(err) = self.sender.send(req.into()).await {
let _ = self.pending.pop(&id);
return Err(err);
}
self.pending.activate(&id);
match timeout(self.timeout, receiver).await {
Ok(Ok(crate::shared::PendingResponse::Response(resp))) => Ok(resp),
Ok(Ok(crate::shared::PendingResponse::Timeout)) => {
Err(Error::new(ErrorCode::Timeout, "Request timed out"))
}
Ok(Err(_)) => Err(Error::new(
ErrorCode::InternalError,
"Response channel closed",
)),
Err(_) => {
_ = self.pending.pop(&id);
Err(Error::new(ErrorCode::Timeout, "Request timed out"))
}
}
}
/// Sends a notification to a client
#[inline]
async fn send_notification(
&mut self,
method: &str,
params: Option<serde_json::Value>,
) -> Result<(), Error> {
let mut notification = Notification::new(method, params);
if let Some(session_id) = self.session_id {
notification.session_id = Some(session_id);
}
self.sender.send(notification.into()).await
}
}
#[cfg(feature = "tasks")]
impl crate::shared::TaskApi for Context {
/// Retrieve task result from the client. If the task is not completed yet, waits until it completes or cancels.
async fn get_task_result<T>(&mut self, id: impl Into<String>) -> Result<T, Error>
where
T: DeserializeOwned,
{
let params = GetTaskPayloadRequestParams { id: id.into() };
let method = crate::types::task::commands::RESULT;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_request(req).await?.into_result()
}
/// Retrieve task status from the client
async fn get_task(&mut self, id: impl Into<String>) -> Result<Task, Error> {
let params = GetTaskRequestParams { id: id.into() };
let method = crate::types::task::commands::GET;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_request(req).await?.into_result()
}
/// Cancels a task that is currently running on the client
async fn cancel_task(&mut self, id: impl Into<String>) -> Result<Task, Error> {
if !self.options.is_tasks_cancellation_supported() {
return Err(Error::new(
ErrorCode::InvalidRequest,
"Server does not support cancelling tasks.",
));
}
let params = CancelTaskRequestParams { id: id.into() };
let method = crate::types::task::commands::CANCEL;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_request(req).await?.into_result()
}
/// Retrieves a list of tasks from the client
async fn list_tasks(&mut self, cursor: Option<Cursor>) -> Result<ListTasksResult, Error> {
if !self.options.is_tasks_list_supported() {
return Err(Error::new(
ErrorCode::InvalidRequest,
"Server does not support retrieving a task list.",
));
}
let params = ListTasksRequestParams { cursor };
let method = crate::types::task::commands::LIST;
let req = Request::new(
Some(RequestId::Uuid(uuid::Uuid::new_v4())),
method,
Some(params),
);
self.send_request(req).await?.into_result()
}
async fn handle_input(&mut self, _id: &str, _params: TaskPayload) -> Result<(), Error> {
// Reserved, there are no cases so far, for the server
// to handle input requests from client.
Ok(())
}
}