1use std::collections::BTreeMap;
4use std::sync::{Arc, OnceLock};
5
6use serde_json::json;
7
8use super::input::InputReader;
9use super::{js_number_text, seconds};
10use crate::cancel::CancelSignal;
11use crate::tools::{FunctionTool, ToolError};
12use crate::types::{JsonSchema, JsonValue};
13
14const DEFAULT_TIMEOUT: f64 = 30.0;
15const METHODS: [&str; 7] = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
16
17pub(crate) const HTTP_REQUEST_DESCRIPTION: &str = "Makes HTTP requests to external APIs. Supports GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS methods. Returns response with status, headers, and body.";
19
20fn input_schema() -> JsonSchema {
21 json!({
22 "type": "object",
23 "properties": {
24 "method": {"type": "string", "enum": METHODS, "description": "HTTP method to use for the request"},
25 "url": {"type": "string", "format": "uri", "description": "URL to send the request to"},
26 "headers": {
27 "description": "Optional HTTP headers as key-value pairs",
28 "type": "object",
29 "propertyNames": {"type": "string"},
30 "additionalProperties": {"type": "string"}
31 },
32 "body": {"description": "Optional request body as a string", "type": "string"},
33 "timeout": {
34 "description": "Optional timeout in seconds (default: 30)",
35 "type": "number",
36 "exclusiveMinimum": 0
37 }
38 },
39 "required": ["method", "url"],
40 "additionalProperties": false
41 })
42}
43
44const MAX_REDIRECTS: usize = 20;
46
47const GET_HEAD_BODY_MESSAGE: &str = "Request with GET/HEAD method cannot have body.";
49
50pub(crate) fn client_builder() -> reqwest::ClientBuilder {
54 reqwest::Client::builder().redirect(reqwest::redirect::Policy::limited(MAX_REDIRECTS))
55}
56
57#[derive(Default)]
59pub(crate) struct LazyClient {
60 client: OnceLock<reqwest::Client>,
61}
62
63impl LazyClient {
64 #[cfg(test)]
65 pub(crate) fn with(client: reqwest::Client) -> Self {
66 Self {
67 client: OnceLock::from(client),
68 }
69 }
70
71 pub(crate) fn get(&self) -> Result<&reqwest::Client, ToolError> {
72 if let Some(client) = self.client.get() {
73 return Ok(client);
74 }
75 let client = client_builder()
76 .build()
77 .map_err(|error| ToolError::msg(format!("failed to create the HTTP client: {error}")))?;
78 Ok(self.client.get_or_init(|| client))
79 }
80}
81
82#[must_use]
98pub fn http_request() -> FunctionTool {
99 with_client(LazyClient::default())
100}
101
102pub(crate) fn with_client(client: LazyClient) -> FunctionTool {
103 let client = Arc::new(client);
104 FunctionTool::builder("http_request", HTTP_REQUEST_DESCRIPTION)
105 .input_schema(input_schema())
106 .callback(move |input, context| {
107 let client = client.clone();
108 let signal = context.cancel_signal().clone();
109 async move { run(&client, &input, &signal).await }
110 })
111}
112
113struct Request<'a> {
114 method: &'a str,
115 url: &'a str,
116 headers: Vec<(&'a str, &'a str)>,
117 body: Option<&'a str>,
118 timeout: f64,
119}
120
121fn parse(input: &JsonValue) -> Result<Request<'_>, ToolError> {
122 let mut reader = InputReader::new(input);
123 let method = reader.one_of("method", &METHODS);
124 let url = reader.string("url");
125 if url.is_some_and(|url| reqwest::Url::parse(url).is_err()) {
126 reader.issue("url", "Invalid URL");
127 }
128 let headers = match reader.get("headers") {
129 None => Vec::new(),
130 Some(JsonValue::Object(headers)) => {
131 let pairs: Option<Vec<(&str, &str)>> = headers
132 .iter()
133 .map(|(name, value)| value.as_str().map(|value| (name.as_str(), value)))
134 .collect();
135 pairs.unwrap_or_else(|| {
136 reader.issue("headers", "Invalid input: expected record of strings");
137 Vec::new()
138 })
139 }
140 Some(_) => {
141 reader.issue("headers", "Invalid input: expected record of strings");
142 Vec::new()
143 }
144 };
145 let body = reader.optional_string("body");
146 let timeout = reader.optional_positive("timeout", |_| "Too small: expected number to be >0".to_owned());
147 reader.finish()?;
148 if body.is_some() && matches!(method, Some("GET" | "HEAD")) {
149 return Err(ToolError::msg(GET_HEAD_BODY_MESSAGE));
150 }
151 Ok(Request {
152 method: method.unwrap_or_default(),
153 url: url.unwrap_or_default(),
154 headers,
155 body,
156 timeout: timeout.unwrap_or(DEFAULT_TIMEOUT),
157 })
158}
159
160enum Failure {
161 Timeout,
162 Cancelled,
163 Error(ToolError),
164}
165
166async fn run(client: &LazyClient, input: &JsonValue, signal: &CancelSignal) -> Result<JsonValue, ToolError> {
167 let request = parse(input)?;
168 let client = client.get()?;
169 let send = send(client, &request);
170 let limit = seconds(request.timeout);
171 let outcome = tokio::select! {
172 result = async {
173 match limit {
174 Some(limit) => tokio::time::timeout(limit, send).await.unwrap_or(Err(Failure::Timeout)),
175 None => send.await,
176 }
177 } => result,
178 () = signal.cancelled() => Err(Failure::Cancelled),
179 };
180 let (method, url) = (request.method, request.url);
181 match outcome {
182 Ok(value) => Ok(value),
183 Err(Failure::Timeout) => Err(ToolError::msg(format!(
184 "Request timed out after {} seconds: {method} {url}",
185 js_number_text(request.timeout)
186 ))),
187 Err(Failure::Cancelled) => Err(ToolError::msg(format!("Request cancelled: {method} {url}"))),
188 Err(Failure::Error(error)) => Err(error),
189 }
190}
191
192async fn send(client: &reqwest::Client, request: &Request<'_>) -> Result<JsonValue, Failure> {
193 let method = reqwest::Method::from_bytes(request.method.as_bytes())
194 .map_err(|error| Failure::Error(ToolError::new(error)))?;
195 let mut builder = client.request(method, request.url);
196 for (name, value) in &request.headers {
197 builder = builder.header(*name, *value);
198 }
199 if let Some(body) = request.body {
200 builder = builder.body(body.to_owned());
201 }
202 let response = builder
203 .send()
204 .await
205 .map_err(|error| Failure::Error(ToolError::new(error)))?;
206 let status = response.status();
207 let status_text = status.canonical_reason().unwrap_or_default();
208 let mut headers: BTreeMap<String, String> = BTreeMap::new();
209 for (name, value) in response.headers() {
210 let value = String::from_utf8_lossy(value.as_bytes()).into_owned();
211 headers
212 .entry(name.as_str().to_owned())
213 .and_modify(|joined| {
214 joined.push_str(", ");
215 joined.push_str(&value);
216 })
217 .or_insert(value);
218 }
219 let bytes = response
220 .bytes()
221 .await
222 .map_err(|error| Failure::Error(ToolError::new(error)))?;
223 if !status.is_success() {
224 return Err(Failure::Error(ToolError::msg(format!(
225 "HTTP {} {status_text}: {} {}",
226 status.as_u16(),
227 request.method,
228 request.url
229 ))));
230 }
231 let body = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes);
232 Ok(json!({
233 "status": status.as_u16(),
234 "statusText": status_text,
235 "headers": headers,
236 "body": String::from_utf8_lossy(body),
237 }))
238}
239
240#[cfg(test)]
241mod tests;