Skip to main content

agentmux_mcp/tools/
srv_calls.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One way for a tool to ask this agent's srv: the address, the instance key, the request and
5//! the words of a failure, written once.
6//!
7//! An agent reads a failure's words and acts on them, so they are the ones each call has always
8//! used: `request failed: ..` when srv was not reached, `<name> failed: HTTP <status> — <what srv
9//! said>` when srv refused, with srv's body whole, and `response parse failed: ..` when the answer
10//! is not JSON. `srv_calls_tests.rs` pins them call by call.
11//!
12//! The calls that word a failure the longer way (`srv_http::describe_http_error`) still go
13//! through `srv_get_json` and `srv_post_json`; the tools that write their request by hand move
14//! here family by family.
15
16use serde::de::DeserializeOwned;
17use serde::Serialize;
18
19use super::*;
20
21/// The name a call's failure carries, and the mark between the status and what srv said: a dash,
22/// except in the messages that have always had a hyphen.
23#[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    /// GET `path` with `query`: srv's answer, as JSON.
47    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    /// POST `body` to `path`: srv's answer, as JSON.
53    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    /// POST `body` to `path`: srv's answer, read as `T`.
58    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    /// [`Self::post_as`] for a call srv may hold while it asks the person: `limit` is how long this
64    /// request waits, in place of the client's own limit.
65    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    /// POST `body` to `path` where only srv's yes matters: the answer is not read.
77    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
83/// The response when srv was reached and said yes; otherwise the failure in the call's words.
84async 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}