D: D2 list_peers and get_peer behind peers.enabled
The two status tools and the optional peer argument exist only when a registry is configured. rmcp's disable_route hides the tools; the eight shared schemas lose the optional peer property, and the two list tools also lose the derived $schema key, so the peers-off list and schemas match a build without the feature byte for byte. Both snapshot variants and the wire-level tool list are asserted.
This commit is contained in:
1 parent
d3285a994b
commit
ae09f0530c
3 files changed
+357
-12
No files matched your search
+165
-7
@@ -111,6 +111,12 @@ pub struct PeerOnlyParams {
|
||||
pub peer: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
pub struct GetPeerParams {
|
||||
/// Peer name, as listed by `list_peers`.
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Per-session MCP handler. Holds the shared state.
|
||||
#[derive(Clone)]
|
||||
pub struct TrackerService {
|
||||
@@ -207,10 +213,11 @@ fn capped<T: Serialize>(
|
||||
#[tool_router]
|
||||
impl TrackerService {
|
||||
pub fn new(state: AppState) -> Self {
|
||||
Self {
|
||||
state,
|
||||
tool_router: Self::tool_router(),
|
||||
let mut tool_router = Self::tool_router();
|
||||
if state.peers.is_none() {
|
||||
peers::configure(&mut tool_router);
|
||||
}
|
||||
Self { state, tool_router }
|
||||
}
|
||||
|
||||
#[tool(
|
||||
@@ -390,6 +397,35 @@ impl TrackerService {
|
||||
.map(|v| capped(v, true, None)),
|
||||
)
|
||||
}
|
||||
|
||||
#[tool(
|
||||
description = "Status of every configured peer of this consolidator: `server.up` (TCP connect), `api.up` (authenticated ping with `auth` = ok, rejected or unknown), latency and the time of the last change. Use it to tell a dead peer from a rejected token before calling another tool with `peer`."
|
||||
)]
|
||||
async fn list_peers(&self) -> Result<CallToolResult, ErrorData> {
|
||||
let Ok(reg) = peers::registry(&self.state) else {
|
||||
return Ok(tool_error(&AppError::NotFound(
|
||||
"no peers are configured".into(),
|
||||
)));
|
||||
};
|
||||
json_result(Ok(peers::statuses(reg)))
|
||||
}
|
||||
|
||||
#[tool(
|
||||
description = "Status of one configured peer by name, with the same fields as `list_peers`. An unknown name is an error; use `list_peers` for the available names."
|
||||
)]
|
||||
async fn get_peer(
|
||||
&self,
|
||||
Parameters(p): Parameters<GetPeerParams>,
|
||||
) -> Result<CallToolResult, ErrorData> {
|
||||
let reg = match peers::registry(&self.state) {
|
||||
Ok(reg) => reg,
|
||||
Err(e) => return Ok(tool_error(&e)),
|
||||
};
|
||||
match reg.status(&p.name) {
|
||||
Ok(status) => json_result(Ok(status)),
|
||||
Err(e) => Ok(tool_error(&e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tool_handler(router = self.tool_router)]
|
||||
@@ -526,7 +562,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::config::Config;
|
||||
use crate::peers::testing::{
|
||||
fake_peers_config, fake_state_with_peers, registry_with, FakeTransport,
|
||||
fake_peers_config, fake_state_with_peers, registry_with, static_registry, FakeTransport,
|
||||
};
|
||||
use crate::sources::fake::fake_state;
|
||||
use rmcp::model::GetPromptResult;
|
||||
@@ -807,8 +843,13 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn peer_svc(fake: &std::sync::Arc<FakeTransport>, names: &[&str]) -> TrackerService {
|
||||
let reg = registry_with(fake.clone(), fake_peers_config(names));
|
||||
TrackerService::new(fake_state_with_peers(Config::default(), reg))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_list_snapshot() {
|
||||
fn tool_list_without_peers_is_unchanged() {
|
||||
let svc = svc();
|
||||
let tools = tools(&svc);
|
||||
let names: Vec<&str> = tools.iter().map(|t| &*t.name).collect();
|
||||
@@ -825,16 +866,85 @@ mod tests {
|
||||
"tail_journal"
|
||||
]
|
||||
);
|
||||
assert!(svc.tool_router.get("list_peers").is_none());
|
||||
assert!(svc.tool_router.get("get_peer").is_none());
|
||||
|
||||
for (tool, properties, required) in LOCAL_PROPERTIES {
|
||||
let t = tools.iter().find(|t| t.name == tool).unwrap();
|
||||
assert_eq!(prop_names(t), properties, "{tool}");
|
||||
assert_eq!(required_names(t), required, "{tool}");
|
||||
assert_eq!(t.input_schema["type"], "object", "{tool}");
|
||||
assert!(
|
||||
t.input_schema.get("properties").is_some(),
|
||||
"{tool} must keep its properties object"
|
||||
);
|
||||
// The two list tools had no parameter schema before the peer
|
||||
// argument, so they must not gain `$schema` either.
|
||||
assert_eq!(
|
||||
t.input_schema.get("$schema").is_some(),
|
||||
!properties.is_empty(),
|
||||
"{tool}"
|
||||
);
|
||||
let d = t.description.as_deref().unwrap_or("");
|
||||
assert!(d.len() > 40, "{tool}");
|
||||
assert!(
|
||||
!d.to_ascii_lowercase().contains("peer"),
|
||||
"{tool} must not mention peers when they are off: {d}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_list_with_peers_adds_argument_and_tools() {
|
||||
let fake = FakeTransport::new();
|
||||
let svc = peer_svc(&fake, &["beta"]);
|
||||
let tools = tools(&svc);
|
||||
let names: Vec<&str> = tools.iter().map(|t| &*t.name).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"get_container",
|
||||
"get_container_logs",
|
||||
"get_journal_logs",
|
||||
"get_peer",
|
||||
"get_systemd_unit",
|
||||
"list_containers",
|
||||
"list_peers",
|
||||
"list_systemd_timers",
|
||||
"list_systemd_units",
|
||||
"tail_journal"
|
||||
]
|
||||
);
|
||||
|
||||
for (tool, properties, required) in LOCAL_PROPERTIES {
|
||||
let t = tools.iter().find(|t| t.name == tool).unwrap();
|
||||
let mut want: Vec<String> = properties.iter().map(|p| (*p).to_owned()).collect();
|
||||
want.push("peer".to_owned());
|
||||
want.sort();
|
||||
assert_eq!(prop_names(t), want, "{tool}");
|
||||
// `peer` is optional, so it never joins `required`.
|
||||
assert_eq!(required_names(t), required, "{tool}");
|
||||
assert_eq!(t.input_schema["type"], "object", "{tool}");
|
||||
let peer = &t.input_schema["properties"]["peer"];
|
||||
let ty = peer["type"].as_array().expect("peer type is a union");
|
||||
assert!(ty.iter().any(|t| t == "string"), "{tool}: {peer}");
|
||||
assert!(
|
||||
peer["description"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.contains("configured peer"),
|
||||
"{tool}"
|
||||
);
|
||||
assert!(t.description.as_deref().unwrap_or("").len() > 40, "{tool}");
|
||||
}
|
||||
|
||||
for tool in ["list_peers", "get_peer"] {
|
||||
let t = tools.iter().find(|t| t.name == tool).unwrap();
|
||||
assert!(t.description.as_deref().unwrap_or("").len() > 40, "{tool}");
|
||||
}
|
||||
let list_peers = tools.iter().find(|t| t.name == "list_peers").unwrap();
|
||||
assert!(required_names(list_peers).is_empty());
|
||||
let get_peer = tools.iter().find(|t| t.name == "get_peer").unwrap();
|
||||
assert_eq!(required_names(get_peer), ["name"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -994,7 +1104,21 @@ mod tests {
|
||||
|
||||
mod peer_tests {
|
||||
use super::*;
|
||||
use crate::peers::PeerError;
|
||||
use crate::peers::types::{ApiStatus, ServerStatus};
|
||||
use crate::peers::{PeerError, PeerName, PeerStatus};
|
||||
|
||||
fn status(name: &str, up: bool) -> PeerStatus {
|
||||
PeerStatus {
|
||||
name: PeerName::parse(name).unwrap(),
|
||||
enabled: true,
|
||||
url: format!("http://{name}:1984"),
|
||||
server: ServerStatus {
|
||||
up,
|
||||
..ServerStatus::default()
|
||||
},
|
||||
api: ApiStatus::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(r: &CallToolResult) -> String {
|
||||
match &r.content[0] {
|
||||
@@ -1357,5 +1481,39 @@ mod tests {
|
||||
assert_eq!(calls[1].1.path, "/api/v1/docker/containers/web-1/logs");
|
||||
assert_eq!(calls[1].1.query, vec![("tail".to_owned(), "1".to_owned())]);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn list_peers_and_get_peer_render_the_snapshot() {
|
||||
let reg = static_registry(vec![status("gamma", false), status("beta", true)]);
|
||||
let s = TrackerService::new(fake_state_with_peers(Config::default(), reg));
|
||||
let v = json(s.list_peers().await.unwrap());
|
||||
let names: Vec<&str> = v["peers"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| p["name"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, ["beta", "gamma"]);
|
||||
assert_eq!(v["peers"][0]["server"]["up"], true);
|
||||
assert_eq!(v["peers"][1]["server"]["up"], false);
|
||||
assert_eq!(v["peers"][0]["api"]["auth"], "unknown");
|
||||
|
||||
let v = json(
|
||||
s.get_peer(Parameters(GetPeerParams {
|
||||
name: "beta".into(),
|
||||
}))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(v["name"], "beta");
|
||||
|
||||
let r = s
|
||||
.get_peer(Parameters(GetPeerParams {
|
||||
name: "nope".into(),
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.is_error, Some(true));
|
||||
assert!(text_of(&r).contains("not_found"), "{}", text_of(&r));
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
-2
@@ -5,25 +5,93 @@
|
||||
//! REST uses, so allowlists, the hop marker and error mapping stay in one
|
||||
//! place. No URL or header is built here.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::StreamExt;
|
||||
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
|
||||
use rmcp::handler::server::router::tool::ToolRouter;
|
||||
use rmcp::model::{CallToolResult, ContentBlock};
|
||||
use rmcp::ErrorData;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{capped, json_result, tool_error, MAX_RESULT_BYTES, TAIL_BACKLOG};
|
||||
use super::{capped, json_result, tool_error, TrackerService, MAX_RESULT_BYTES, TAIL_BACKLOG};
|
||||
use crate::error::AppError;
|
||||
use crate::peers::error::{peer_error_to_app, PeerError};
|
||||
use crate::peers::transport::{PeerBody, PeerResponse};
|
||||
use crate::peers::{PeerName, ProxyOpts};
|
||||
use crate::peers::{PeerName, PeerRegistry, PeerStatus, ProxyOpts};
|
||||
use crate::sources::docker::normalize_name;
|
||||
use crate::sources::systemd::validate_unit_name;
|
||||
use crate::sources::{clamp_count, Priority};
|
||||
use crate::state::AppState;
|
||||
|
||||
/// Tools that gain the optional `peer` argument.
|
||||
const PEER_AWARE: [&str; 8] = [
|
||||
"get_container",
|
||||
"get_container_logs",
|
||||
"get_journal_logs",
|
||||
"get_systemd_unit",
|
||||
"list_containers",
|
||||
"list_systemd_timers",
|
||||
"list_systemd_units",
|
||||
"tail_journal",
|
||||
];
|
||||
|
||||
/// Tools that only exist while peers are configured.
|
||||
const PEER_TOOLS: [&str; 2] = ["get_peer", "list_peers"];
|
||||
|
||||
/// The two list tools took no parameters before the peer argument existed, so
|
||||
/// their schema carried no `$schema` key; `schemars` adds one to derived
|
||||
/// parameters. Dropping it keeps the peers-off schema byte-identical.
|
||||
const NO_PARAM_TOOLS: [&str; 2] = ["list_containers", "list_systemd_timers"];
|
||||
|
||||
/// Hide the peer tools and the `peer` argument when the feature is off.
|
||||
///
|
||||
/// `rmcp` builds one fixed table per process, so the peers-off variant is
|
||||
/// produced from it: the two peer tools are disabled and the optional `peer`
|
||||
/// property is removed from the eight shared schemas. That keeps the visible
|
||||
/// list and every schema identical to a build without the feature.
|
||||
pub(crate) fn configure(router: &mut ToolRouter<TrackerService>) {
|
||||
for name in PEER_TOOLS {
|
||||
router.disable_route(name);
|
||||
}
|
||||
for name in PEER_AWARE {
|
||||
if let Some(route) = router.map.get_mut(name) {
|
||||
let schema = Arc::make_mut(&mut route.attr.input_schema);
|
||||
if let Some(props) = schema.get_mut("properties").and_then(|p| p.as_object_mut()) {
|
||||
// The property is optional, so `required` needs no edit.
|
||||
props.remove("peer");
|
||||
}
|
||||
if NO_PARAM_TOOLS.contains(&name) {
|
||||
schema.remove("$schema");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry, or the "unknown peer" error used everywhere else when the
|
||||
/// feature is off. Gated tools cannot reach this; it guards the direct API.
|
||||
pub(crate) fn registry(state: &AppState) -> Result<&PeerRegistry, AppError> {
|
||||
state
|
||||
.peers
|
||||
.as_deref()
|
||||
.ok_or_else(|| AppError::NotFound("no peers are configured".into()))
|
||||
}
|
||||
|
||||
/// `{"peers":[...]}`, the shape of the `list_peers` tool.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(crate) struct PeerStatuses {
|
||||
pub peers: Vec<PeerStatus>,
|
||||
}
|
||||
|
||||
pub(crate) fn statuses(reg: &PeerRegistry) -> PeerStatuses {
|
||||
PeerStatuses {
|
||||
peers: reg.snapshot(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch(
|
||||
state: &AppState,
|
||||
peer: &str,
|
||||
|
||||
+122
-3
@@ -113,13 +113,24 @@ impl Harness {
|
||||
sid
|
||||
}
|
||||
|
||||
async fn rpc(&self, sid: &str, body: &str) -> serde_json::Value {
|
||||
let (status, head, text) = self.post(body, Some(sid)).await;
|
||||
assert_eq!(status, 200, "{head}\n{text}");
|
||||
rpc(&text)
|
||||
}
|
||||
|
||||
async fn call(&self, sid: &str, id: u32, tool: &str, arguments: &str) -> serde_json::Value {
|
||||
let body = format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"tools/call","params":{{"name":"{tool}","arguments":{arguments}}}}}"#
|
||||
);
|
||||
let (status, head, text) = self.post(&body, Some(sid)).await;
|
||||
assert_eq!(status, 200, "{head}\n{text}");
|
||||
rpc(&text)
|
||||
self.rpc(sid, &body).await
|
||||
}
|
||||
|
||||
async fn tools(&self, sid: &str) -> Vec<serde_json::Value> {
|
||||
let v = self
|
||||
.rpc(sid, r#"{"jsonrpc":"2.0","id":9,"method":"tools/list"}"#)
|
||||
.await;
|
||||
v["result"]["tools"].as_array().expect("tools").clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +160,114 @@ fn result_text(v: &serde_json::Value) -> String {
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
fn tool<'a>(tools: &'a [serde_json::Value], name: &str) -> &'a serde_json::Value {
|
||||
tools
|
||||
.iter()
|
||||
.find(|t| t["name"] == name)
|
||||
.unwrap_or_else(|| panic!("tool {name} missing from {tools:?}"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_list_is_ten_with_peers_and_eight_without() {
|
||||
let fake = FakeTransport::new();
|
||||
let h = start(peers_state(&fake)).await;
|
||||
let sid = h.open().await;
|
||||
let tools = h.tools(&sid).await;
|
||||
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
names.sort();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"get_container",
|
||||
"get_container_logs",
|
||||
"get_journal_logs",
|
||||
"get_peer",
|
||||
"get_systemd_unit",
|
||||
"list_containers",
|
||||
"list_peers",
|
||||
"list_systemd_timers",
|
||||
"list_systemd_units",
|
||||
"tail_journal"
|
||||
]
|
||||
);
|
||||
let units = tool(&tools, "list_systemd_units");
|
||||
assert!(
|
||||
units["inputSchema"]["properties"]["peer"].is_object(),
|
||||
"{units}"
|
||||
);
|
||||
assert!(
|
||||
units["inputSchema"]["required"]
|
||||
.as_array()
|
||||
.is_none_or(|r| r.is_empty()),
|
||||
"peer and state are optional: {units}"
|
||||
);
|
||||
|
||||
let h = start(local_state()).await;
|
||||
let sid = h.open().await;
|
||||
let tools = h.tools(&sid).await;
|
||||
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names.len(), 8, "{names:?}");
|
||||
assert!(!names.contains(&"list_peers"));
|
||||
assert!(!names.contains(&"get_peer"));
|
||||
for t in &tools {
|
||||
let props = &t["inputSchema"]["properties"];
|
||||
assert!(
|
||||
props.get("peer").is_none(),
|
||||
"{} must not advertise peer when peers are off: {t}",
|
||||
t["name"]
|
||||
);
|
||||
assert!(
|
||||
!t["description"].as_str().unwrap_or("").contains("peer"),
|
||||
"{}",
|
||||
t["name"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_peers_and_get_peer_tools() {
|
||||
let fake = FakeTransport::new();
|
||||
let h = start(peers_state(&fake)).await;
|
||||
let sid = h.open().await;
|
||||
|
||||
let v = h.call(&sid, 2, "list_peers", "{}").await;
|
||||
assert_eq!(v["result"]["isError"], false, "{v}");
|
||||
let body: serde_json::Value = serde_json::from_str(&result_text(&v)).unwrap();
|
||||
let mut names: Vec<&str> = body["peers"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| p["name"].as_str().unwrap())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["beta", "gamma"]);
|
||||
assert!(body["peers"][0].get("server").is_some());
|
||||
|
||||
let v = h.call(&sid, 3, "get_peer", r#"{"name":"beta"}"#).await;
|
||||
assert_eq!(v["result"]["isError"], false, "{v}");
|
||||
|
||||
let v = h.call(&sid, 4, "get_peer", r#"{"name":"nope"}"#).await;
|
||||
assert_eq!(v["result"]["isError"], true, "{v}");
|
||||
assert!(result_text(&v).contains("not_found"), "{v}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_tools_are_absent_without_configuration() {
|
||||
let h = start(local_state()).await;
|
||||
let sid = h.open().await;
|
||||
let v = h.call(&sid, 2, "list_peers", "{}").await;
|
||||
let error = &v["error"];
|
||||
assert!(error.is_object(), "{v}");
|
||||
assert!(
|
||||
error["message"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.contains("tool not found"),
|
||||
"{v}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_argument_reads_through_the_consolidator() {
|
||||
let fake = FakeTransport::new();
|
||||
|
||||
Reference in new issue
Block a user