context_server_tool.rs

  1use std::sync::Arc;
  2
  3use anyhow::{anyhow, bail, Result};
  4use assistant_tool::{Tool, ToolSource};
  5use gpui::{App, Entity, Task};
  6use language_model::LanguageModelRequestMessage;
  7use project::Project;
  8
  9use crate::manager::ContextServerManager;
 10use crate::types;
 11
 12pub struct ContextServerTool {
 13    server_manager: Entity<ContextServerManager>,
 14    server_id: Arc<str>,
 15    tool: types::Tool,
 16}
 17
 18impl ContextServerTool {
 19    pub fn new(
 20        server_manager: Entity<ContextServerManager>,
 21        server_id: impl Into<Arc<str>>,
 22        tool: types::Tool,
 23    ) -> Self {
 24        Self {
 25            server_manager,
 26            server_id: server_id.into(),
 27            tool,
 28        }
 29    }
 30}
 31
 32impl Tool for ContextServerTool {
 33    fn name(&self) -> String {
 34        self.tool.name.clone()
 35    }
 36
 37    fn description(&self) -> String {
 38        self.tool.description.clone().unwrap_or_default()
 39    }
 40
 41    fn source(&self) -> ToolSource {
 42        ToolSource::ContextServer {
 43            id: self.server_id.clone().into(),
 44        }
 45    }
 46
 47    fn input_schema(&self) -> serde_json::Value {
 48        match &self.tool.input_schema {
 49            serde_json::Value::Null => {
 50                serde_json::json!({ "type": "object", "properties": [] })
 51            }
 52            serde_json::Value::Object(map) if map.is_empty() => {
 53                serde_json::json!({ "type": "object", "properties": [] })
 54            }
 55            _ => self.tool.input_schema.clone(),
 56        }
 57    }
 58
 59    fn run(
 60        self: Arc<Self>,
 61        input: serde_json::Value,
 62        _messages: &[LanguageModelRequestMessage],
 63        _project: Entity<Project>,
 64        cx: &mut App,
 65    ) -> Task<Result<String>> {
 66        if let Some(server) = self.server_manager.read(cx).get_server(&self.server_id) {
 67            cx.foreground_executor().spawn({
 68                let tool_name = self.tool.name.clone();
 69                async move {
 70                    let Some(protocol) = server.client() else {
 71                        bail!("Context server not initialized");
 72                    };
 73
 74                    let arguments = if let serde_json::Value::Object(map) = input {
 75                        Some(map.into_iter().collect())
 76                    } else {
 77                        None
 78                    };
 79
 80                    log::trace!(
 81                        "Running tool: {} with arguments: {:?}",
 82                        tool_name,
 83                        arguments
 84                    );
 85                    let response = protocol.run_tool(tool_name, arguments).await?;
 86
 87                    let mut result = String::new();
 88                    for content in response.content {
 89                        match content {
 90                            types::ToolResponseContent::Text { text } => {
 91                                result.push_str(&text);
 92                            }
 93                            types::ToolResponseContent::Image { .. } => {
 94                                log::warn!("Ignoring image content from tool response");
 95                            }
 96                            types::ToolResponseContent::Resource { .. } => {
 97                                log::warn!("Ignoring resource content from tool response");
 98                            }
 99                        }
100                    }
101                    Ok(result)
102                }
103            })
104        } else {
105            Task::ready(Err(anyhow!("Context server not found")))
106        }
107    }
108}