agentmux_mcp/tools/
srv_calls.rs1use serde::de::DeserializeOwned;
17use serde::Serialize;
18
19use super::*;
20
21#[derive(Clone, Copy)]
24pub(super) struct Named<'a> {
25 label: &'a str,
26 mark: &'a str,
27}
28
29impl<'a> Named<'a> {
30 pub(super) fn with_hyphen(label: &'a str) -> Self {
31 Named { label, mark: "-" }
32 }
33}
34
35impl<'a> From<&'a str> for Named<'a> {
36 fn from(label: &'a str) -> Self {
37 Named { label, mark: "—" }
38 }
39}
40
41impl ToolCtx<'_> {
42 fn srv_url(&self, path: &str) -> String {
43 format!("{}{path}", self.local_url.trim_end_matches('/'))
44 }
45
46 pub(super) async fn get_json<'n>(&self, path: &str, query: &[(&str, &str)], name: impl Into<Named<'n>>) -> Result<Value> {
48 let sent = self.client.get(self.srv_url(path)).header(AUTH_KEY_HEADER, self.auth_key).query(query).send().await;
49 read_json(accepted(sent, name.into()).await?).await
50 }
51
52 pub(super) async fn post_json<'n>(&self, path: &str, body: &Value, name: impl Into<Named<'n>>) -> Result<Value> {
54 self.post_as(path, body, name).await
55 }
56
57 pub(super) async fn post_as<'n, T: DeserializeOwned>(&self, path: &str, body: &(impl Serialize + ?Sized), name: impl Into<Named<'n>>) -> Result<T> {
59 let sent = self.client.post(self.srv_url(path)).header(AUTH_KEY_HEADER, self.auth_key).json(body).send().await;
60 read_json(accepted(sent, name.into()).await?).await
61 }
62
63 pub(super) async fn post_as_within<'n, T: DeserializeOwned>(
66 &self,
67 path: &str,
68 body: &(impl Serialize + ?Sized),
69 name: impl Into<Named<'n>>,
70 limit: std::time::Duration,
71 ) -> Result<T> {
72 let sent = self.client.post(self.srv_url(path)).header(AUTH_KEY_HEADER, self.auth_key).timeout(limit).json(body).send().await;
73 read_json(accepted(sent, name.into()).await?).await
74 }
75
76 pub(super) async fn post<'n>(&self, path: &str, body: &(impl Serialize + ?Sized), name: impl Into<Named<'n>>) -> Result<()> {
78 let sent = self.client.post(self.srv_url(path)).header(AUTH_KEY_HEADER, self.auth_key).json(body).send().await;
79 accepted(sent, name.into()).await.map(|_| ())
80 }
81}
82
83async fn accepted(sent: reqwest::Result<reqwest::Response>, name: Named<'_>) -> Result<reqwest::Response> {
85 let resp = sent.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
86 if !resp.status().is_success() {
87 let status = resp.status();
88 let text = resp.text().await.unwrap_or_default();
89 anyhow::bail!("{} failed: HTTP {status} {} {text}", name.label, name.mark);
90 }
91 Ok(resp)
92}
93
94async fn read_json<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T> {
95 resp.json().await.map_err(|e| anyhow::anyhow!("response parse failed: {e}"))
96}