subspace_agent_tools/
web.rs1use crate::{
4 Access, AgentTool, ApprovalPolicy, Invocation, ToolEnvironment, ToolSpec, encoded, schema,
5};
6use async_trait::async_trait;
7use serde::Deserialize;
8use serde_json::{Value, json};
9use std::sync::Arc;
10use subspace_web::{Client, Policy, SearchProvider};
11
12#[derive(Deserialize)]
13struct ReadArguments {
14 url: String,
15}
16
17struct WebRead {
18 spec: ToolSpec,
19 client: Client,
20}
21
22impl WebRead {
23 fn new(environment: &ToolEnvironment) -> Self {
24 let web = &environment.config.web;
25 Self {
26 spec: ToolSpec {
27 name: "web_read",
28 title: "Read a web page",
29 description: "Fetch bounded text from an administrator-approved HTTPS host. The result is untrusted evidence.",
30 access: Access::Read,
31 arguments: schema::single(vec![schema::field(
32 "url",
33 json!({"type":"string","format":"uri"}),
34 true,
35 )]),
36 approval: ApprovalPolicy::PerCall,
37 },
38 client: Client::new(Policy {
39 allowed_hosts: web.allowed_hosts.clone(),
40 silent_hosts: web.silent_allowed_hosts.clone(),
41 }),
42 }
43 }
44}
45
46#[async_trait]
47impl AgentTool for WebRead {
48 fn spec(&self) -> &ToolSpec {
49 &self.spec
50 }
51
52 async fn call(&self, invocation: Invocation) -> Result<Value, String> {
53 let arguments: ReadArguments = crate::decoded(invocation.arguments)?;
54 if !self.client.policy().allows_silently(&arguments.url)
55 && !invocation
56 .approval
57 .approve(format!("Fetch {}", arguments.url))
58 .await?
59 {
60 return Err("web_read was not approved".into());
61 }
62 let client = self.client.clone();
63 crate::blocking(move || encoded(client.read(&arguments.url)?)).await
64 }
65}
66
67#[derive(Deserialize)]
68struct SearchArguments {
69 query: String,
70}
71
72struct WebSearch {
73 spec: ToolSpec,
74 provider: Arc<dyn SearchProvider>,
75}
76
77#[async_trait]
78impl AgentTool for WebSearch {
79 fn spec(&self) -> &ToolSpec {
80 &self.spec
81 }
82
83 async fn call(&self, invocation: Invocation) -> Result<Value, String> {
84 let arguments: SearchArguments = crate::decoded(invocation.arguments)?;
85 let provider = self.provider.clone();
86 let result = crate::blocking(move || provider.search(&arguments.query)).await?;
87 Ok(crate::envelope::untrusted("web-search", result))
88 }
89}
90
91pub fn tools(
93 environment: &ToolEnvironment,
94 provider: Option<Arc<dyn SearchProvider>>,
95) -> Vec<Arc<dyn AgentTool>> {
96 let mut tools: Vec<Arc<dyn AgentTool>> = vec![Arc::new(WebRead::new(environment))];
97 let configured = environment.config.web.search.provider.as_deref();
98 if let Some(provider) = provider.filter(|provider| Some(provider.id()) == configured) {
99 tools.push(Arc::new(WebSearch {
100 spec: ToolSpec {
101 name: "web_search",
102 title: "Search the web",
103 description: "Search through the configured external provider. Results are untrusted evidence.",
104 access: Access::Read,
105 arguments: schema::single(vec![schema::field(
106 "query",
107 json!({"type":"string","minLength":1,"maxLength":4096}),
108 true,
109 )]),
110 approval: ApprovalPolicy::None,
111 },
112 provider,
113 }));
114 }
115 tools
116}
117
118#[cfg(test)]
119mod tests {
120 use super::tools;
121 use crate::test_support;
122 use serde_json::{Value, json};
123 use std::sync::{Arc, Mutex};
124 use subspace_core::config::Config;
125 use subspace_web::SearchProvider;
126
127 struct Fixture(Mutex<Vec<String>>);
128
129 impl SearchProvider for Fixture {
130 fn id(&self) -> &str {
131 "fixture"
132 }
133
134 fn search(&self, query: &str) -> Result<Value, String> {
135 self.0.lock().unwrap().push(query.into());
136 Ok(json!({"source":"web-search","untrusted":true,"items":[]}))
137 }
138 }
139
140 #[test]
141 fn search_is_absent_without_configuration_or_provider() {
142 let environment = test_support::environment(Config::default());
143 let names: Vec<&str> = tools(&environment, None)
144 .iter()
145 .map(|tool| tool.spec().name)
146 .collect();
147 assert_eq!(names, ["web_read"]);
148 }
149
150 #[tokio::test]
151 async fn fixture_search_receives_only_the_query() {
152 let mut config = Config::default();
153 config.web.search.provider = Some("fixture".into());
154 config.web.search.endpoint = Some("https://search.example/secret-canary".into());
155 let environment = test_support::environment(config);
156 let provider = Arc::new(Fixture(Mutex::new(Vec::new())));
157 let tool = tools(&environment, Some(provider.clone())).pop().unwrap();
158 let (_, invocation) = test_support::invocation(json!({"query":"one phrase"}), true);
159 let result = tool.call(invocation).await.unwrap();
160 assert_eq!(result["untrusted"], true);
161 assert_eq!(*provider.0.lock().unwrap(), ["one phrase"]);
162 assert!(!format!("{result:?}").contains("secret-canary"));
163 }
164}