1use std::sync::Arc;
2
3use anyhow::{anyhow, bail, Result};
4use assistant_tool::{ActionLog, 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 _action_log: Entity<ActionLog>,
65 cx: &mut App,
66 ) -> Task<Result<String>> {
67 if let Some(server) = self.server_manager.read(cx).get_server(&self.server_id) {
68 cx.foreground_executor().spawn({
69 let tool_name = self.tool.name.clone();
70 async move {
71 let Some(protocol) = server.client() else {
72 bail!("Context server not initialized");
73 };
74
75 let arguments = if let serde_json::Value::Object(map) = input {
76 Some(map.into_iter().collect())
77 } else {
78 None
79 };
80
81 log::trace!(
82 "Running tool: {} with arguments: {:?}",
83 tool_name,
84 arguments
85 );
86 let response = protocol.run_tool(tool_name, arguments).await?;
87
88 let mut result = String::new();
89 for content in response.content {
90 match content {
91 types::ToolResponseContent::Text { text } => {
92 result.push_str(&text);
93 }
94 types::ToolResponseContent::Image { .. } => {
95 log::warn!("Ignoring image content from tool response");
96 }
97 types::ToolResponseContent::Resource { .. } => {
98 log::warn!("Ignoring resource content from tool response");
99 }
100 }
101 }
102 Ok(result)
103 }
104 })
105 } else {
106 Task::ready(Err(anyhow!("Context server not found")))
107 }
108 }
109}