1use std::collections::HashMap;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::Arc;
9
10use futures::stream;
11use futures::{FutureExt, Stream};
12use rmcp::model::{
13 CallToolRequestParams, CallToolResult, ErrorCode, ErrorData, GetPromptResult,
14 ListResourcesResult, ListToolsResult, Prompt, ReadResourceResult, Resource, ServerNotification,
15 Tool,
16};
17use rmcp::service::ServiceError;
18use serde_json::Value;
19use tokio::sync::{mpsc, OnceCell};
20use tokio_stream::wrappers::ReceiverStream;
21use tokio_util::sync::CancellationToken;
22use tracing::warn;
23
24use super::{
25 get_tool_meta_value, get_tool_owner, get_tool_resource_uri, insert_trusted_tool_update_meta,
26 recover_mangled_tool_name, remove_untrusted_mcp_app_meta, ActionRequiredStream, Extension,
27 ExtensionHost, ExtensionLoadResult, ExtensionSlot, ExtensionSpec, GooseMcpAppToolAttachment,
28 ToolCallNotificationEmitter, ToolCallResult, TOOL_CALL_NOTIFICATION_CHANNEL_CAPACITY,
29};
30use crate::action_required_manager::ActionRequiredManager;
31use crate::extension::{name_to_key, ExtensionError, ExtensionInfo};
32use crate::mcp::client::McpCallContext;
33use crate::mcp::client::McpClientTrait;
34use crate::mcp::container::Container;
35use crate::tool_visibility::is_tool_visible_to_app;
36use oi_kit_provider_types::conversation::message::Message;
37
38#[derive(Debug)]
39pub struct ExtensionSet<C> {
40 scope_id: String,
41 working_dir: Option<PathBuf>,
42 container: Option<Container>,
43 extensions: Vec<C>,
44}
45
46impl<C: ExtensionSpec> ExtensionSet<C> {
47 pub fn new(
48 scope_id: impl Into<String>,
49 working_dir: Option<PathBuf>,
50 extensions: Vec<C>,
51 ) -> Result<Self, ExtensionError> {
52 let mut keys = std::collections::HashSet::new();
53 for config in &extensions {
54 if !keys.insert(config.key()) {
55 return Err(ExtensionError::ConfigError(format!(
56 "extension '{}' appears twice in the selection",
57 config.name()
58 )));
59 }
60 }
61 Ok(Self {
62 scope_id: scope_id.into(),
63 working_dir,
64 container: None,
65 extensions,
66 })
67 }
68
69 pub fn with_container(mut self, container: Option<Container>) -> Self {
70 self.container = container;
71 self
72 }
73
74 pub fn scope_id(&self) -> &str {
75 &self.scope_id
76 }
77
78 pub fn working_dir(&self) -> Option<&Path> {
79 self.working_dir.as_deref()
80 }
81
82 pub fn container(&self) -> Option<&Container> {
83 self.container.as_ref()
84 }
85
86 pub fn extensions(&self) -> &[C] {
87 &self.extensions
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
92pub struct LeaseId(u64);
93
94impl LeaseId {
95 fn next() -> Self {
96 static NEXT: AtomicU64 = AtomicU64::new(1);
97 Self(NEXT.fetch_add(1, Ordering::Relaxed))
98 }
99}
100
101struct CatalogEntry<C> {
102 tool: Tool,
103 extension: Arc<Extension<C>>,
104 server_name: String,
105}
106
107struct ToolCatalog<C> {
108 entries: Vec<CatalogEntry<C>>,
109 by_name: HashMap<String, usize>,
110}
111
112impl<C: ExtensionSpec> ToolCatalog<C> {
113 async fn build(scope_id: &str, extensions: &[Arc<Extension<C>>]) -> Self {
114 let lists = futures::future::join_all(
115 extensions
116 .iter()
117 .map(|extension| extension.public_tools(scope_id)),
118 )
119 .await;
120
121 let mut entries = Vec::new();
122 let mut by_name = HashMap::new();
123 for (extension, tools) in extensions.iter().zip(lists) {
124 for tool in tools.iter() {
125 let name = provider_safe_tool_name(&tool.name);
126 if by_name.contains_key(&name) {
127 warn!(
128 tool = %name,
129 extension = %extension.key,
130 "duplicate tool name, keeping the earlier extension's"
131 );
132 continue;
133 }
134 let server_name = tool
135 .name
136 .strip_prefix(&format!("{}__", extension.key))
137 .unwrap_or(&tool.name)
138 .to_string();
139 let mut tool = tool.clone();
140 tool.name = name.clone().into();
141 by_name.insert(name, entries.len());
142 entries.push(CatalogEntry {
143 tool,
144 extension: Arc::clone(extension),
145 server_name,
146 });
147 }
148 }
149 Self { entries, by_name }
150 }
151
152 fn get(&self, name: &str) -> Option<&CatalogEntry<C>> {
153 self.by_name.get(name).map(|&i| &self.entries[i])
154 }
155}
156
157fn provider_safe_tool_name(name: &str) -> String {
162 let is_safe = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
163 if name.len() <= 64 && name.chars().all(is_safe) {
164 return name.to_string();
165 }
166 let sanitized: String = name
167 .chars()
168 .map(|c| if is_safe(c) { c } else { '_' })
169 .take(55)
170 .collect();
171 let hash = blake3::hash(name.as_bytes()).to_hex();
172 format!("{sanitized}_{:.8}", hash.as_str())
173}
174
175pub struct ExtensionLease<C: ExtensionSpec> {
176 id: LeaseId,
177 scope_id: String,
178 working_dir: Option<PathBuf>,
179 slots: Vec<Arc<ExtensionSlot<C>>>,
180 tool_catalog: Arc<OnceCell<ToolCatalog<C>>>,
181 host: Arc<dyn ExtensionHost<C>>,
182 action_required: Arc<ActionRequiredManager>,
183 hydrate_mcp_apps: bool,
184}
185
186impl<C: ExtensionSpec> Clone for ExtensionLease<C> {
187 fn clone(&self) -> Self {
188 Self {
189 id: self.id,
190 scope_id: self.scope_id.clone(),
191 working_dir: self.working_dir.clone(),
192 slots: self.slots.clone(),
193 tool_catalog: Arc::clone(&self.tool_catalog),
194 host: Arc::clone(&self.host),
195 action_required: Arc::clone(&self.action_required),
196 hydrate_mcp_apps: self.hydrate_mcp_apps,
197 }
198 }
199}
200
201struct ResolvedTool<'a, C> {
202 extension: &'a Arc<Extension<C>>,
203 server_name: &'a str,
204 tool: &'a Tool,
205}
206
207impl<C: ExtensionSpec> ExtensionLease<C> {
208 pub(super) fn new(
209 scope_id: impl Into<String>,
210 working_dir: Option<PathBuf>,
211 slots: Vec<Arc<ExtensionSlot<C>>>,
212 host: Arc<dyn ExtensionHost<C>>,
213 action_required: Arc<ActionRequiredManager>,
214 hydrate_mcp_apps: bool,
215 ) -> Self {
216 Self {
217 id: LeaseId::next(),
218 scope_id: scope_id.into(),
219 working_dir,
220 slots,
221 tool_catalog: Arc::new(OnceCell::new()),
222 host,
223 action_required,
224 hydrate_mcp_apps,
225 }
226 }
227
228 async fn tool_catalog(&self) -> &ToolCatalog<C> {
229 self.tool_catalog
230 .get_or_init(|| async {
231 ToolCatalog::build(&self.scope_id, &self.start_extensions().await).await
232 })
233 .await
234 }
235
236 async fn start_extensions(&self) -> Vec<Arc<Extension<C>>> {
237 futures::future::join_all(self.slots.iter().map(|slot| slot.start()))
238 .await
239 .into_iter()
240 .flatten()
241 .cloned()
242 .collect()
243 }
244
245 async fn start_extension(&self, extension_name: &str) -> Option<Arc<Extension<C>>> {
246 let key = name_to_key(extension_name);
247 let slot = self.slots.iter().find(|slot| slot.key == key)?;
248 slot.start().await.cloned()
249 }
250
251 pub async fn start(&self) -> Vec<ExtensionLoadResult> {
252 futures::future::join_all(self.slots.iter().map(|slot| slot.load_result())).await
253 }
254
255 pub fn id(&self) -> LeaseId {
256 self.id
257 }
258
259 pub fn scope_id(&self) -> &str {
260 &self.scope_id
261 }
262
263 pub fn working_dir(&self) -> Option<&Path> {
264 self.working_dir.as_deref()
265 }
266
267 pub async fn tools(&self) -> Vec<Tool> {
268 self.tool_catalog()
269 .await
270 .entries
271 .iter()
272 .map(|entry| entry.tool.clone())
273 .collect()
274 }
275
276 pub fn is_enabled(&self, extension: &str) -> bool {
277 let key = name_to_key(extension);
278 self.slots.iter().any(|slot| slot.key == key)
279 }
280
281 pub fn configs(&self) -> Vec<C> {
282 self.slots.iter().map(|slot| slot.config.clone()).collect()
283 }
284
285 pub async fn read_resource(
286 &self,
287 uri: &str,
288 extension_name: &str,
289 cancellation_token: CancellationToken,
290 ) -> Result<ReadResourceResult, ErrorData> {
291 let client = self
292 .start_extension(extension_name)
293 .await
294 .map(|extension| Arc::clone(&extension.client))
295 .ok_or_else(|| {
296 let available = self
297 .slots
298 .iter()
299 .map(|slot| slot.key.as_str())
300 .collect::<Vec<_>>()
301 .join(", ");
302 ErrorData::new(
303 ErrorCode::INVALID_PARAMS,
304 format!(
305 "Extension '{extension_name}' not found. Here are the available extensions: {available}"
306 ),
307 None,
308 )
309 })?;
310
311 client
312 .read_resource(&self.scope_id, uri, cancellation_token)
313 .await
314 .map_err(|_| {
315 ErrorData::new(
316 ErrorCode::INTERNAL_ERROR,
317 format!("Could not read resource with uri: {uri}"),
318 None,
319 )
320 })
321 }
322
323 async fn client(&self, extension_name: &str) -> Result<Arc<dyn McpClientTrait>, ErrorData> {
324 self.start_extension(extension_name)
325 .await
326 .map(|extension| Arc::clone(&extension.client))
327 .ok_or_else(|| {
328 ErrorData::new(
329 ErrorCode::INVALID_PARAMS,
330 format!("Extension {extension_name} is not valid"),
331 None,
332 )
333 })
334 }
335
336 pub async fn list_tools_from_extension(
337 &self,
338 extension_name: &str,
339 cancellation_token: CancellationToken,
340 ) -> Result<ListToolsResult, ErrorData> {
341 self.client(extension_name)
342 .await?
343 .list_tools(&self.scope_id, None, cancellation_token)
344 .await
345 .map_err(|error| {
346 ErrorData::new(
347 ErrorCode::INTERNAL_ERROR,
348 format!("Unable to list tools for {extension_name}, {error:?}"),
349 None,
350 )
351 })
352 }
353
354 pub async fn list_prompts_from_extension(
355 &self,
356 extension_name: &str,
357 cancellation_token: CancellationToken,
358 ) -> Result<Vec<Prompt>, ErrorData> {
359 self.client(extension_name)
360 .await?
361 .list_prompts(&self.scope_id, None, cancellation_token)
362 .await
363 .map(|result| result.prompts)
364 .map_err(|error| {
365 ErrorData::new(
366 ErrorCode::INTERNAL_ERROR,
367 format!("Unable to list prompts for {extension_name}, {error:?}"),
368 None,
369 )
370 })
371 }
372
373 pub async fn list_prompts(
374 &self,
375 cancellation_token: CancellationToken,
376 ) -> HashMap<String, Vec<Prompt>> {
377 let running = self.start_extensions().await;
378 let results = futures::future::join_all(running.iter().map(|extension| {
379 let token = cancellation_token.clone();
380 async move {
381 (
382 extension.key.clone(),
383 self.list_prompts_from_extension(&extension.key, token)
384 .await,
385 )
386 }
387 }))
388 .await;
389 let mut prompts = HashMap::new();
390 for (key, result) in results {
391 match result {
392 Ok(listed) => {
393 prompts.insert(key, listed);
394 }
395 Err(error) => tracing::debug!(?error, "failed to list prompts"),
396 }
397 }
398 prompts
399 }
400
401 pub async fn get_prompt(
402 &self,
403 extension_name: &str,
404 name: &str,
405 arguments: Value,
406 cancellation_token: CancellationToken,
407 ) -> anyhow::Result<GetPromptResult> {
408 self.client(extension_name)
409 .await?
410 .get_prompt(&self.scope_id, name, arguments, cancellation_token)
411 .await
412 .map_err(|e| anyhow::anyhow!("Failed to get prompt: {}", e))
413 }
414
415 pub async fn ui_resources(&self) -> Vec<(String, Resource)> {
416 let mut ui_resources = Vec::new();
417 for extension in self.start_extensions().await {
418 match extension
419 .client
420 .list_resources(&self.scope_id, None, CancellationToken::default())
421 .await
422 {
423 Ok(listed) => ui_resources.extend(
424 listed
425 .resources
426 .into_iter()
427 .filter(|resource| resource.uri.starts_with("ui://"))
428 .map(|resource| (extension.key.clone(), resource)),
429 ),
430 Err(error) => warn!(extension = %extension.key, ?error, "failed to list resources"),
431 }
432 }
433 ui_resources
434 }
435
436 pub async fn list_resources_result_from_extension(
437 &self,
438 extension_name: &str,
439 cancellation_token: CancellationToken,
440 ) -> Result<ListResourcesResult, ErrorData> {
441 self.client(extension_name)
442 .await?
443 .list_resources(&self.scope_id, None, cancellation_token)
444 .await
445 .map_err(|error| {
446 ErrorData::new(
447 ErrorCode::INTERNAL_ERROR,
448 format!("Unable to list resources for {extension_name}, {error:?}"),
449 None,
450 )
451 })
452 }
453
454 pub async fn instructions(&self) -> Vec<ExtensionInfo> {
455 let working_dir = self
456 .working_dir
457 .clone()
458 .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
459 let placeholder = working_dir.to_string_lossy();
460 let mut infos = Vec::new();
461 for extension in self.start_extensions().await {
462 let instructions = extension
463 .server_info
464 .as_ref()
465 .and_then(|info| info.instructions.clone())
466 .unwrap_or_default();
467 infos.push(ExtensionInfo::new(
468 &extension.key,
469 &instructions.replace("{{WORKING_DIR}}", &placeholder),
470 extension.supports_resources(),
471 ));
472 }
473 infos
474 }
475
476 async fn resolve_tool(
477 &self,
478 tool_name: &str,
479 calling_app: Option<&str>,
480 ) -> Result<ResolvedTool<'_, C>, ErrorData> {
481 let catalog = self.tool_catalog().await;
482 let extension_key = calling_app.map(name_to_key);
483 let belongs_to_extension = |entry: &&CatalogEntry<C>| {
484 extension_key
485 .as_ref()
486 .is_none_or(|key| entry.extension.key == *key)
487 };
488 let entry = catalog
489 .get(tool_name)
490 .filter(belongs_to_extension)
491 .or_else(|| {
492 let tool_owners = catalog
493 .entries
494 .iter()
495 .filter(belongs_to_extension)
496 .map(|entry| (entry.tool.name.as_ref(), get_tool_owner(&entry.tool)))
497 .collect::<Vec<_>>();
498 recover_mangled_tool_name(
499 tool_name,
500 tool_owners
501 .iter()
502 .map(|(name, owner)| (*name, owner.as_deref())),
503 )
504 .and_then(|recovered| catalog.get(&recovered))
505 });
506
507 let Some(entry) = entry else {
508 let available = catalog
509 .entries
510 .iter()
511 .filter(belongs_to_extension)
512 .map(|entry| entry.tool.name.as_ref())
513 .collect::<Vec<&str>>()
514 .join(", ");
515 return Err(ErrorData::new(
516 ErrorCode::RESOURCE_NOT_FOUND,
517 format!(
518 "Tool '{}' not found. Available tools: [{}]",
519 tool_name, available
520 ),
521 None,
522 ));
523 };
524
525 if calling_app.is_some() && !is_tool_visible_to_app(&entry.tool) {
526 return Err(ErrorData::new(
527 ErrorCode::INVALID_PARAMS,
528 "Tool is not visible to app clients",
529 None,
530 ));
531 }
532
533 Ok(ResolvedTool {
534 extension: &entry.extension,
535 server_name: &entry.server_name,
536 tool: &entry.tool,
537 })
538 }
539
540 pub async fn call(
541 &self,
542 tool_call: CallToolRequestParams,
543 request: CallRequest,
544 cancellation_token: CancellationToken,
545 ) -> Result<ToolCallResult, ErrorData> {
546 let resolved = self.resolve_tool(&tool_call.name, None).await?;
547 Ok(self
548 .call_resolved(resolved, tool_call.arguments, request, cancellation_token)
549 .await)
550 }
551
552 pub async fn call_for_app(
553 &self,
554 tool_call: CallToolRequestParams,
555 app_extension: &str,
556 request: CallRequest,
557 cancellation_token: CancellationToken,
558 ) -> Result<ToolCallResult, ErrorData> {
559 let resolved = self
560 .resolve_tool(&tool_call.name, Some(app_extension))
561 .await?;
562 Ok(self
563 .call_resolved(resolved, tool_call.arguments, request, cancellation_token)
564 .await)
565 }
566
567 async fn call_resolved(
568 &self,
569 resolved: ResolvedTool<'_, C>,
570 arguments: Option<rmcp::model::JsonObject>,
571 request: CallRequest,
572 cancellation_token: CancellationToken,
573 ) -> ToolCallResult {
574 let CallRequest {
575 tool_call_id,
576 notification_emitter,
577 container: _,
578 } = request;
579 let client = resolved.extension.client.clone();
580 let action_required_stream = self.action_required_stream(tool_call_id.as_deref()).await;
581 let (emitter, notification_stream) = Self::notifications_for_call(
582 client.subscribe().await,
583 notification_emitter,
584 tool_call_id.as_deref(),
585 );
586 let call_context = McpCallContext::new(
587 self.scope_id.clone(),
588 self.working_dir.clone(),
589 tool_call_id,
590 );
591 let call_context = match emitter {
592 Some(emitter) => call_context.with_notification_emitter(emitter),
593 None => call_context,
594 };
595
596 let mcp_app_call = McpAppCall::from_resolved(&resolved, self.hydrate_mcp_apps);
597 let server_name = resolved.server_name.to_string();
598 let session_id = self.scope_id.clone();
599 let host = Arc::clone(&self.host);
600 let result = async move {
601 let mut result = client
602 .call_tool(
603 &call_context,
604 &server_name,
605 arguments,
606 cancellation_token.clone(),
607 )
608 .await
609 .map_err(|e| match e {
610 ServiceError::McpError(error_data) => error_data,
611 _ => ErrorData::new(ErrorCode::INTERNAL_ERROR, e.to_string(), None),
612 })?;
613 remove_untrusted_mcp_app_meta(&mut result);
614 host.sanitize_result(&mut result);
615 if let Some(mcp_app_call) = mcp_app_call {
616 mcp_app_call
617 .attach_resource(&*client, &session_id, &mut result, cancellation_token)
618 .await;
619 }
620 Ok(result)
621 };
622
623 ToolCallResult {
624 result: Box::new(result.boxed()),
625 notification_stream: Some(notification_stream),
626 action_required_stream,
627 }
628 }
629
630 async fn action_required_stream(
631 &self,
632 tool_call_id: Option<&str>,
633 ) -> Option<Box<dyn Stream<Item = Message> + Send + Unpin>> {
634 let tool_call_id = tool_call_id?;
635 if self
636 .action_required
637 .has_action_required_stream(&self.scope_id, tool_call_id)
638 .await
639 {
640 return None;
641 }
642 let receiver = self
643 .action_required
644 .register_action_required_stream(self.scope_id.clone(), tool_call_id.to_string())
645 .await;
646 Some(Box::new(ActionRequiredStream::new(
647 receiver,
648 self.action_required.clone(),
649 self.scope_id.clone(),
650 tool_call_id.to_string(),
651 )))
652 }
653
654 fn notifications_for_call(
655 client_notifications: mpsc::Receiver<ServerNotification>,
656 emitter: Option<ToolCallNotificationEmitter>,
657 tool_call_id: Option<&str>,
658 ) -> (
659 Option<ToolCallNotificationEmitter>,
660 Box<dyn Stream<Item = ServerNotification> + Send + Unpin>,
661 ) {
662 if emitter.is_some() || tool_call_id.is_none() {
663 return (emitter, Box::new(ReceiverStream::new(client_notifications)));
664 }
665 let (sender, receiver) = mpsc::channel(TOOL_CALL_NOTIFICATION_CHANNEL_CAPACITY);
666 (
667 Some(ToolCallNotificationEmitter::new(sender)),
668 Box::new(stream::select(
669 ReceiverStream::new(client_notifications),
670 ReceiverStream::new(receiver),
671 )),
672 )
673 }
674}
675
676#[derive(Default)]
677pub struct CallRequest {
678 pub tool_call_id: Option<String>,
679 pub notification_emitter: Option<ToolCallNotificationEmitter>,
680 pub container: Option<Container>,
681}
682
683impl CallRequest {
684 pub fn new(tool_call_id: impl Into<String>) -> Self {
685 Self {
686 tool_call_id: Some(tool_call_id.into()),
687 ..Default::default()
688 }
689 }
690
691 pub fn with_container(mut self, container: Option<Container>) -> Self {
692 self.container = container;
693 self
694 }
695}
696
697struct McpAppCall {
698 server_tool_name: String,
699 extension_key: String,
700 resource_uri: String,
701 tool_meta: Option<serde_json::Value>,
702}
703
704impl McpAppCall {
705 fn from_resolved<C>(resolved: &ResolvedTool<'_, C>, host_supports_apps: bool) -> Option<Self> {
706 if !host_supports_apps {
707 return None;
708 }
709 Some(Self {
710 server_tool_name: resolved.server_name.to_string(),
711 extension_key: resolved.extension.key.clone(),
712 resource_uri: get_tool_resource_uri(resolved.tool)?,
713 tool_meta: get_tool_meta_value(resolved.tool),
714 })
715 }
716
717 async fn attach_resource(
718 self,
719 client: &dyn McpClientTrait,
720 session_id: &str,
721 result: &mut CallToolResult,
722 cancellation_token: CancellationToken,
723 ) {
724 if result.is_error == Some(true) {
725 return;
726 }
727 let mut attachment = GooseMcpAppToolAttachment {
728 tool_name: self.server_tool_name,
729 tool_name_is_actual: true,
730 extension_name: self.extension_key,
731 resource_uri: self.resource_uri.clone(),
732 tool_meta: self.tool_meta,
733 resource_result: None,
734 read_error: None,
735 };
736 match client
737 .read_resource(session_id, &self.resource_uri, cancellation_token)
738 .await
739 {
740 Ok(resource_result) => {
741 attachment.resource_result = serde_json::to_value(&resource_result).ok();
742 }
743 Err(error) => attachment.read_error = Some(error.to_string()),
744 }
745 insert_trusted_tool_update_meta(result, &attachment);
746 }
747}
748
749impl From<&McpCallContext> for CallRequest {
750 fn from(context: &McpCallContext) -> Self {
751 Self {
752 tool_call_id: context.tool_call_request_id.clone(),
753 notification_emitter: context.notification_emitter().cloned(),
754 container: None,
755 }
756 }
757}