use axum::body::{Body, Bytes};
use axum::extract::{ConnectInfo, Request as ExtractRequest, State};
use axum::http::{header, Request, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::Router;
use serde_json::{json, Value};
use std::net::SocketAddr;
use std::sync::Arc;
use tower::util::ServiceExt;
const PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
const INSTRUCTIONS: &str = "\
KYB is a shared, versioned knowledge base about this fleet's own infrastructure - hosts, \
services, ports, deploys, architecture decisions, incidents and tasks. IMPORTANT: call \
kyb_brief once before you start work on the infrastructure - it lists open incidents, work in \
progress, deadlines and recently retracted decisions. It is context for your task, never a to-do \
list. Query it before \
reasoning about infrastructure instead of guessing, and write back what you verified. \
Writing the same key again adds a version rather than overwriting, so a superseded fact \
stays searchable and an answer from the past is marked as one. A read answer carries a \
`deadlines` block when a task is late or inside its reminder window: act on it, or say so. \
IMPORTANT: before you ask the owner to decide anything, call kyb_confident_check with the \
decision as one English line - what was decided before about the same thing comes back with its \
outcome. When you do ask, open a record with kyb_confident_ask; when the owner answers, record it \
with kyb_confident_decided. The precedents are evidence for you to judge, not permission.";
const WRITE_TOOLS: [&str; 9] = [
"kyb_add",
"kyb_incident",
"kyb_resolve",
"kyb_task",
"kyb_task_status",
"kyb_done",
"kyb_confident_ask",
"kyb_confident_decided",
"kyb_confident_outcome",
];
pub struct McpState {
api: Router,
}
pub fn router(api: Router) -> Router {
Router::new()
.route("/mcp", post(mcp_post).get(no_stream).delete(no_stream))
.with_state(Arc::new(McpState { api }))
}
async fn no_stream() -> Response {
(
StatusCode::METHOD_NOT_ALLOWED,
[(header::ALLOW, "POST")],
axum::Json(json!({
"error": "this endpoint is stateless: no server-initiated stream, no sessions. \
POST JSON-RPC to /mcp."
})),
)
.into_response()
}
const MAX_BODY: usize = 8 * 1024 * 1024;
async fn mcp_post(State(st): State<Arc<McpState>>, req: ExtractRequest) -> Response {
let readonly = req.uri().query().is_some_and(|q| {
q.split('&').any(|p| matches!(p, "readonly" | "readonly=1" | "readonly=true"))
});
let connect = req.extensions().get::<ConnectInfo<SocketAddr>>().cloned();
let bearer = req.headers().get(header::AUTHORIZATION).cloned();
let headers_by = crate::auth::By::from_headers(req.headers());
let body: Bytes = match axum::body::to_bytes(req.into_body(), MAX_BODY).await {
Ok(b) => b,
Err(_) => {
return json_body(
StatusCode::PAYLOAD_TOO_LARGE,
rpc_error(Value::Null, -32600, "request body too large"),
)
}
};
let parsed: Value = match serde_json::from_slice(&body) {
Ok(v) => v,
Err(e) => {
return json_body(
StatusCode::BAD_REQUEST,
rpc_error(Value::Null, -32700, &format!("parse error: {e}")),
)
}
};
let (messages, was_batch) = match parsed {
Value::Array(items) => (items, true),
Value::Object(_) => (vec![parsed], false),
_ => {
return json_body(
StatusCode::BAD_REQUEST,
rpc_error(Value::Null, -32600, "invalid request: expected an object or an array"),
)
}
};
let mut out = Vec::new();
for msg in &messages {
if let Some(resp) = handle_one(&st, readonly, connect.as_ref(), bearer.as_ref(), headers_by.as_ref(), msg).await {
out.push(resp);
}
}
if out.is_empty() {
return StatusCode::ACCEPTED.into_response();
}
let payload = if was_batch { Value::Array(out) } else { out.swap_remove(0) };
json_body(StatusCode::OK, payload)
}
async fn handle_one(
st: &McpState,
readonly: bool,
connect: Option<&ConnectInfo<SocketAddr>>,
bearer: Option<&axum::http::HeaderValue>,
headers_by: Option<&crate::auth::By>,
msg: &Value,
) -> Option<Value> {
let id = match msg.get("id") {
None | Some(Value::Null) => return None,
Some(v) => v.clone(),
};
let method = msg.get("method").and_then(Value::as_str).unwrap_or_default();
let params = msg.get("params").cloned().unwrap_or_else(|| json!({}));
Some(match method {
"initialize" => rpc_ok(id, initialize(¶ms)),
"ping" => rpc_ok(id, json!({})),
"tools/list" => rpc_ok(id, json!({"tools": tools(readonly)})),
"tools/call" => match call_tool(st, readonly, connect, bearer, headers_by, ¶ms).await {
Ok(value) => rpc_ok(id, value),
Err((code, message)) => rpc_error(id, code, &message),
},
other => rpc_error(id, -32601, &format!("method not found: {other}")),
})
}
fn initialize(params: &Value) -> Value {
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or_default();
let version =
if PROTOCOL_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSIONS[0] };
json!({
"protocolVersion": version,
"capabilities": {"tools": {"listChanged": false}},
"serverInfo": {"name": "kyb", "version": env!("CARGO_PKG_VERSION")},
"instructions": INSTRUCTIONS,
})
}
fn rpc_ok(id: Value, result: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "result": result})
}
fn rpc_error(id: Value, code: i64, message: &str) -> Value {
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
}
fn json_body(status: StatusCode, payload: Value) -> Response {
(status, axum::Json(payload)).into_response()
}
fn tool_error(message: String) -> Value {
json!({"content": [{"type": "text", "text": message}], "isError": true})
}
fn tool_text(text: String) -> Value {
json!({"content": [{"type": "text", "text": text}]})
}
struct Call {
method: &'static str,
path: String,
query: Vec<(&'static str, String)>,
body: Option<Value>,
}
async fn call_tool(
st: &McpState,
readonly: bool,
connect: Option<&ConnectInfo<SocketAddr>>,
bearer: Option<&axum::http::HeaderValue>,
headers_by: Option<&crate::auth::By>,
params: &Value,
) -> Result<Value, (i64, String)> {
let name = match params.get("name").and_then(Value::as_str) {
Some(n) if !n.is_empty() => n,
_ => return Err((-32602, "tools/call requires a string `name`".into())),
};
let mut args = params.get("arguments").cloned().unwrap_or_else(|| json!({}));
if !args.is_object() {
return Err((-32602, "`arguments` must be an object".into()));
}
let by = attribution(args.as_object_mut().and_then(|o| o.remove("_ctx")), params.get("_meta"), headers_by);
if readonly && WRITE_TOOLS.contains(&name) {
return Ok(tool_error(format!(
"{name} is a write and this endpoint was opened read-only (?readonly=1)."
)));
}
let call = match plan(name, &args) {
Ok(call) => call,
Err(message) => return Ok(tool_error(message)),
};
let (status, text) = forward(st, connect, bearer, by.as_ref(), call).await;
if status.is_success() {
Ok(tool_text(text.trim().to_string()))
} else {
Ok(tool_error(format!("kyb answered HTTP {}: {}", status.as_u16(), text.trim())))
}
}
fn attribution(ctx: Option<Value>, meta: Option<&Value>, headers: Option<&crate::auth::By>) -> Option<crate::auth::By> {
use crate::auth::By;
let s = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
let from_ctx = ctx
.filter(Value::is_object)
.map(|c| By::new(&s(&c, "agent"), &s(&c, "session"), &s(&c, "workspace"), "hook"))
.filter(|b| !b.is_empty());
let from_meta = meta.and_then(|m| {
if let Some(id) = m.get("antigravity.google/conversation_id").and_then(Value::as_str) {
return Some(By::new("antigravity", id, "", "meta"));
}
if let Some(turn) = m.get("x-codex-turn-metadata") {
let decoded = turn.as_str().and_then(|t| serde_json::from_str::<Value>(t).ok());
let turn = decoded.as_ref().unwrap_or(turn);
let id = ["session_id", "thread_id"].iter().find_map(|k| turn.get(k).and_then(Value::as_str)).unwrap_or_default();
return Some(By::new("codex", id, "", "meta"));
}
if m.get("claudecode/toolUseId").is_some() {
return Some(By::new("claude", "", "", "meta"));
}
None
});
let from_headers = headers.cloned().map(|mut h| {
if h.via.is_empty() {
h.via = "headers".into();
}
h
});
let mut out = By::default();
let sources: Vec<By> = [from_ctx, from_meta, from_headers].into_iter().flatten().collect();
if let Some(named) = sources.iter().find(|s| !s.agent.is_empty()) {
out.agent = named.agent.clone();
out.via = named.via.clone();
out.session = named.session.clone();
}
for src in &sources {
if out.session.is_empty() && !src.session.is_empty() && (src.agent.is_empty() || src.agent == out.agent) {
out.session = src.session.clone();
}
if out.workspace.is_empty() {
out.workspace = src.workspace.clone();
}
}
if out.is_empty() {
None
} else {
if out.via.is_empty() {
out.via = "headers".into();
}
Some(out)
}
}
async fn forward(
st: &McpState,
connect: Option<&ConnectInfo<SocketAddr>>,
bearer: Option<&axum::http::HeaderValue>,
by: Option<&crate::auth::By>,
call: Call,
) -> (StatusCode, String) {
let mut uri = call.path;
if !call.query.is_empty() {
let pairs: Vec<String> =
call.query.iter().map(|(k, v)| format!("{k}={}", encode(v))).collect();
uri.push('?');
uri.push_str(&pairs.join("&"));
}
let builder = Request::builder().method(call.method).uri(uri);
let mut req = match call.body {
Some(value) => builder
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(value.to_string())),
None => builder.body(Body::empty()),
}
.expect("request built from a known-good method and uri");
if let Some(info) = connect {
req.extensions_mut().insert(*info);
}
if let Some(token) = bearer {
req.headers_mut().insert(header::AUTHORIZATION, token.clone());
}
if let Some(by) = by {
for (name, value) in [("x-kyb-agent", &by.agent), ("x-kyb-session", &by.session), ("x-kyb-workspace", &by.workspace), ("x-kyb-via", &by.via)] {
if let Ok(v) = axum::http::HeaderValue::from_str(value) {
req.headers_mut().insert(name, v);
}
}
}
let resp = st.api.clone().oneshot(req).await.expect("the router is infallible");
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap_or_default();
(status, String::from_utf8_lossy(&bytes).into_owned())
}
fn key_segment(args: &Value) -> String {
encode(&text_arg(args, "key").unwrap_or_default())
}
fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(*b as char)
}
other => out.push_str(&format!("%{other:02X}")),
}
}
out
}
fn text_arg(args: &Value, key: &str) -> Option<String> {
match args.get(key) {
Some(Value::String(s)) if !s.trim().is_empty() => Some(s.clone()),
Some(Value::Number(n)) => Some(n.to_string()),
_ => None,
}
}
fn flag_arg(args: &Value, key: &str) -> Option<String> {
match args.get(key) {
Some(Value::Bool(true)) => Some("true".into()),
Some(Value::String(s)) if matches!(s.to_lowercase().as_str(), "1" | "true" | "yes") => {
Some("true".into())
}
_ => None,
}
}
fn list_arg(args: &Value, key: &str) -> Vec<String> {
match args.get(key) {
Some(Value::Array(items)) => items
.iter()
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()))
.map(str::to_string)
.collect(),
Some(Value::String(s)) => {
s.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect()
}
_ => Vec::new(),
}
}
fn require(args: &Value, keys: &[&str]) -> Result<(), String> {
let missing: Vec<&str> = keys.iter().copied().filter(|k| text_arg(args, k).is_none()).collect();
if missing.is_empty() {
Ok(())
} else {
Err(format!("missing required argument(s): {}", missing.join(", ")))
}
}
fn push(query: &mut Vec<(&'static str, String)>, key: &'static str, value: Option<String>) {
if let Some(v) = value {
query.push((key, v));
}
}
fn no_deadlines(args: &Value, query: &mut Vec<(&'static str, String)>) {
let off = match args.get("deadlines") {
Some(Value::Bool(b)) => !b,
Some(Value::String(s)) => matches!(s.to_lowercase().as_str(), "false" | "0" | "no"),
_ => false,
};
if off {
query.push(("deadlines", "false".into()));
}
}
fn named_tags(args: &Value, body: &mut Value) {
if args.get("tags").is_some_and(|v| !v.is_null()) {
body["tags"] = json!(list_arg(args, "tags"));
}
}
fn deadline_fields(args: &Value, body: &mut Value) -> Result<(), String> {
for field in ["due", "waits_on", "expected"] {
match args.get(field) {
None | Some(Value::Null) => {}
Some(Value::String(s)) => body[field] = json!(s),
Some(_) => return Err(format!("`{field}` must be a string")),
}
}
match args.get("hard") {
None | Some(Value::Null) => {}
Some(Value::Bool(b)) => body["hard"] = json!(b),
Some(Value::String(s)) => match s.to_lowercase().as_str() {
"true" | "1" | "yes" => body["hard"] = json!(true),
"false" | "0" | "no" => body["hard"] = json!(false),
_ => return Err("`hard` must be true or false".into()),
},
Some(_) => return Err("`hard` must be true or false".into()),
}
match args.get("remind_days") {
None | Some(Value::Null) => {}
Some(Value::String(s)) if s.trim().is_empty() => body["remind_days"] = Value::Null,
Some(v) => {
let days = match v {
Value::Number(n) => n.as_u64().and_then(|d| u32::try_from(d).ok()),
Value::String(s) => s.trim().parse::<u32>().ok(),
_ => None,
};
match days {
Some(d) => body["remind_days"] = json!(d),
None => {
return Err(
"`remind_days` must be a whole number of days, or \"\" for the default".into()
)
}
}
}
}
Ok(())
}
fn plan(name: &str, args: &Value) -> Result<Call, String> {
let call = match name {
"kyb_query" => {
require(args, &["q"])?;
let mut query = Vec::new();
push(&mut query, "q", text_arg(args, "q"));
push(&mut query, "tag", text_arg(args, "tag"));
push(&mut query, "kind", text_arg(args, "kind"));
push(&mut query, "status", text_arg(args, "status"));
push(&mut query, "service", text_arg(args, "service"));
push(&mut query, "priority", text_arg(args, "priority"));
push(&mut query, "assignee", text_arg(args, "assignee"));
push(&mut query, "parent_task", text_arg(args, "parent_task"));
push(&mut query, "limit", text_arg(args, "limit"));
push(&mut query, "history", flag_arg(args, "history"));
push(&mut query, "as_of", text_arg(args, "as_of"));
push(&mut query, "changed_between", text_arg(args, "changed_between"));
if flag_arg(args, "recent").is_some() {
query.push(("sort", "recent".into()));
}
if args.get("semantic") == Some(&Value::Bool(false)) {
query.push(("semantic", "false".into()));
}
no_deadlines(args, &mut query);
Call { method: "GET", path: "/search".into(), query, body: None }
}
"kyb_get" => {
require(args, &["key"])?;
let mut query = Vec::new();
push(&mut query, "at", text_arg(args, "at"));
no_deadlines(args, &mut query);
Call {
method: "GET",
path: format!("/knowledge/{}", key_segment(args)),
query,
body: None,
}
}
"kyb_diff" => {
require(args, &["key"])?;
let mut query = Vec::new();
push(&mut query, "from", text_arg(args, "from"));
push(&mut query, "to", text_arg(args, "to"));
Call {
method: "GET",
path: format!("/knowledge/{}/diff", key_segment(args)),
query,
body: None,
}
}
"kyb_history" => {
require(args, &["key"])?;
Call {
method: "GET",
path: format!("/knowledge/{}/history", key_segment(args)),
query: Vec::new(),
body: None,
}
}
"kyb_tags" => {
Call { method: "GET", path: "/tags".into(), query: Vec::new(), body: None }
}
"kyb_health" => {
Call { method: "GET", path: "/healthz".into(), query: Vec::new(), body: None }
}
"kyb_incidents" => {
let mut query = Vec::new();
push(&mut query, "status", text_arg(args, "status"));
push(&mut query, "service", text_arg(args, "service"));
push(&mut query, "all", flag_arg(args, "all"));
push(&mut query, "limit", text_arg(args, "limit"));
if flag_arg(args, "followups").is_some() {
query.push(("followups", "open".into()));
}
no_deadlines(args, &mut query);
Call { method: "GET", path: "/incidents".into(), query, body: None }
}
"kyb_tasks" => {
let mut query = Vec::new();
push(&mut query, "status", text_arg(args, "status"));
push(&mut query, "priority", text_arg(args, "priority"));
push(&mut query, "assignee", text_arg(args, "assignee"));
push(&mut query, "parent_task", text_arg(args, "parent_task"));
push(&mut query, "all", flag_arg(args, "all"));
push(&mut query, "limit", text_arg(args, "limit"));
if flag_arg(args, "followups").is_some() {
query.push(("followups", "open".into()));
}
no_deadlines(args, &mut query);
Call { method: "GET", path: "/tasks".into(), query, body: None }
}
"kyb_deadlines" => {
let mut query = Vec::new();
push(&mut query, "within", text_arg(args, "within"));
push(&mut query, "overdue", flag_arg(args, "overdue"));
push(&mut query, "hard", flag_arg(args, "hard"));
push(&mut query, "tag", text_arg(args, "tag"));
push(&mut query, "assignee", text_arg(args, "assignee"));
Call { method: "GET", path: "/deadlines".into(), query, body: None }
}
"kyb_brief" => {
let mut query = Vec::new();
push(&mut query, "tag", text_arg(args, "tag"));
push(&mut query, "service", text_arg(args, "service"));
push(&mut query, "since", text_arg(args, "since"));
push(&mut query, "limit", text_arg(args, "limit"));
Call { method: "GET", path: "/brief".into(), query, body: None }
}
"kyb_confident_check" => {
require(args, &["gist"])?;
let mut query = Vec::new();
push(&mut query, "gist", text_arg(args, "gist"));
let target = list_arg(args, "target");
if !target.is_empty() {
query.push(("target", target.join(",")));
}
push(&mut query, "kind", text_arg(args, "kind"));
push(&mut query, "question", text_arg(args, "question"));
Call { method: "GET", path: "/confident/check".into(), query, body: None }
}
"kyb_confident_open" => {
let mut query = vec![("status", "open".to_string())];
push(&mut query, "workspace", text_arg(args, "workspace"));
Call { method: "GET", path: "/confident".into(), query, body: None }
}
"kyb_confident_ask" => {
require(args, &["gist"])?;
let mut body = json!({
"gist": text_arg(args, "gist"),
"target": list_arg(args, "target"),
"options": list_arg(args, "options"),
});
for k in ["kind", "situation", "proposed", "tradeoff", "checked", "unchecked", "question"] {
if let Some(v) = text_arg(args, k) {
body[k] = json!(v);
}
}
Call { method: "POST", path: "/confident".into(), query: Vec::new(), body: Some(body) }
}
"kyb_confident_decided" => {
require(args, &["id", "by", "verdict"])?;
let mut body = json!({"by": text_arg(args, "by"), "verdict": text_arg(args, "verdict")});
for k in ["chosen", "quote", "ref"] {
if let Some(v) = text_arg(args, k) {
body[k] = json!(v);
}
}
Call {
method: "POST",
path: format!("/confident/{}/decided", encode(&text_arg(args, "id").unwrap_or_default())),
query: Vec::new(),
body: Some(body),
}
}
"kyb_confident_outcome" => {
require(args, &["id", "result", "ref"])?;
Call {
method: "POST",
path: format!("/confident/{}/outcome", encode(&text_arg(args, "id").unwrap_or_default())),
query: Vec::new(),
body: Some(json!({
"result": text_arg(args, "result"),
"ref": text_arg(args, "ref"),
"why": text_arg(args, "why").unwrap_or_default(),
})),
}
}
"kyb_add" => {
require(args, &["key", "title", "body"])?;
Call {
method: "POST",
path: "/knowledge".into(),
query: Vec::new(),
body: Some(json!({
"key": text_arg(args, "key"),
"title": text_arg(args, "title"),
"body": text_arg(args, "body"),
"tags": list_arg(args, "tags"),
"refs": list_arg(args, "refs"),
})),
}
}
"kyb_incident" => {
require(args, &["key", "title", "service", "severity", "body"])?;
let affected = match args.get("affected") {
None | Some(Value::Null) => json!([]),
Some(Value::Array(items)) => json!(items),
Some(_) => {
return Err("`affected` must be a list of {scope, from, to} objects".into())
}
};
let mut body = json!({
"key": text_arg(args, "key"),
"title": text_arg(args, "title"),
"body": text_arg(args, "body"),
"service": text_arg(args, "service"),
"severity": text_arg(args, "severity"),
"status": text_arg(args, "status").unwrap_or_else(|| "open".into()),
"hosts": list_arg(args, "hosts"),
"knowledge": list_arg(args, "knowledge"),
"resolution": text_arg(args, "resolution").unwrap_or_default(),
"detection": text_arg(args, "detection").unwrap_or_default(),
"affected": affected,
"started_at": text_arg(args, "started_at").unwrap_or_default(),
"detected_at": text_arg(args, "detected_at").unwrap_or_default(),
"refs": list_arg(args, "refs"),
});
named_tags(args, &mut body);
Call { method: "POST", path: "/incidents".into(), query: Vec::new(), body: Some(body) }
}
"kyb_resolve" => {
require(args, &["key", "resolution"])?;
Call {
method: "POST",
path: format!("/incidents/{}/resolve", key_segment(args)),
query: Vec::new(),
body: Some(json!({
"status": text_arg(args, "status").unwrap_or_else(|| "resolved".into()),
"resolution": text_arg(args, "resolution"),
})),
}
}
"kyb_task" => {
require(args, &["key", "title", "body"])?;
let mut body = json!({
"key": text_arg(args, "key"),
"title": text_arg(args, "title"),
"body": text_arg(args, "body"),
"status": text_arg(args, "status").unwrap_or_else(|| "open".into()),
"priority": text_arg(args, "priority").unwrap_or_default(),
"blocked_reason": text_arg(args, "blocked_reason").unwrap_or_default(),
"assignee": text_arg(args, "assignee").unwrap_or_default(),
"parent_task": text_arg(args, "parent_task").unwrap_or_default(),
"knowledge": list_arg(args, "knowledge"),
"resolution": text_arg(args, "resolution").unwrap_or_default(),
"refs": list_arg(args, "refs"),
});
named_tags(args, &mut body);
deadline_fields(args, &mut body)?;
Call { method: "POST", path: "/tasks".into(), query: Vec::new(), body: Some(body) }
}
"kyb_task_status" => {
require(args, &["key"])?;
let mut body = json!({});
if let Some(status) = text_arg(args, "status") {
body["status"] = json!(status);
}
deadline_fields(args, &mut body)?;
for field in ["assignee", "parent_task", "blocked_reason"] {
if let Some(value) = args.get(field) {
if !value.is_null() {
body[field] = value.clone();
}
}
}
Call {
method: "POST",
path: format!("/tasks/{}/transition", key_segment(args)),
query: Vec::new(),
body: Some(body),
}
}
"kyb_done" => {
require(args, &["key", "resolution"])?;
Call {
method: "POST",
path: format!("/tasks/{}/resolve", key_segment(args)),
query: Vec::new(),
body: Some(json!({
"status": text_arg(args, "status").unwrap_or_else(|| "done".into()),
"resolution": text_arg(args, "resolution"),
})),
}
}
other => return Err(format!("no such tool: {other}")),
};
Ok(call)
}
fn tools(readonly: bool) -> Vec<Value> {
let str_t = json!({"type": "string"});
let int_t = json!({"type": "integer"});
let list_t = json!({
"anyOf": [{"type": "array", "items": {"type": "string"}}, {"type": "string"}],
"description": "a list, or one comma-separated string"
});
let deadlines_t = json!({"type": "boolean", "description": "false leaves the deadline block \
(late and nearly due tasks) off this answer"});
let date_t = |what: &str| {
json!({"type": "string", "description": format!("{what}: YYYY-MM-DD, \
or a date-time with its zone such as 2026-03-14T17:00:00-07:00; an empty string clears it")})
};
let all = vec![
json!({
"name": "kyb_query",
"description": "Search the shared infrastructure knowledge base: hosts, services, \
ports, deploys, architecture decisions, incident reports and tasks. Hybrid - BM25 fused with \
multilingual embeddings - so a question phrased differently from the entry still finds it, in \
any language. Query this before reasoning about infrastructure; one phrasing is not a search, \
try a couple.",
"inputSchema": {"type": "object", "required": ["q"], "properties": {
"q": {"type": "string", "description": "what you are looking for, in any language"},
"tag": {"type": "string", "description": "restrict to these tags, comma-separated"},
"kind": {"type": "string", "enum": ["knowledge", "incident", "task"],
"description": "restrict to one kind; absent means all"},
"status": str_t, "service": str_t, "priority": str_t, "assignee": str_t,
"parent_task": {"type": "string", "description": "only children of this task key"},
"history": {"type": "boolean", "description": "search every version ever written \
instead of the current state; hits then carry is_head=false when they come from the past"},
"semantic": {"type": "boolean", "description": "false forces pure lexical BM25 - \
useful to prove a match is literal rather than by meaning"},
"recent": {"type": "boolean", "description": "order by commit time, not relevance"},
"limit": int_t,
"as_of": {"type": "string", "description": "what the base said at this moment \
rather than what it says now - an RFC3339 timestamp, a YYYY-MM-DD date, or any git revision. \
A bare date means the end of that day."},
"changed_between": {"type": "string", "description": "only entries that changed \
inside this window: two dates or revisions separated by a comma."},
"deadlines": deadlines_t,
}},
}),
json!({
"name": "kyb_get",
"description": "Read one entry in full by its key. `at` takes any revision git can \
resolve and returns the entry as it stood at that commit - the answer to 'what did we believe \
then'.",
"inputSchema": {"type": "object", "required": ["key"], "properties": {
"key": {"type": "string", "description": "the entry's slug"},
"at": {"type": "string", "description": "a git revision; absent means current"},
"deadlines": deadlines_t,
}},
}),
json!({
"name": "kyb_history",
"description": "Every version of one entry, newest first, with the commit sha and \
timestamp of each change. Use it to see when a fact moved, then pass a sha to kyb_get.",
"inputSchema": {"type": "object", "required": ["key"],
"properties": {"key": str_t}},
}),
json!({
"name": "kyb_diff",
"description": "What changed in an entry between two revisions: which fields moved, \
and which body lines were added or removed. With no revisions it compares the two most recent \
versions - 'what just changed' is the question asked most. Give `from` alone to compare a past \
version against the current one.",
"inputSchema": {"type": "object", "required": ["key"], "properties": {
"key": str_t,
"from": {"type": "string", "description": "revision to compare from"},
"to": {"type": "string", "description": "revision to compare to; absent means current"},
}},
}),
json!({
"name": "kyb_tags",
"description": "Which topics the base covers, with a count per tag. A cheap way to \
find out what is in there before searching blind.",
"inputSchema": {"type": "object", "properties": {}},
}),
json!({
"name": "kyb_health",
"description": "Whether the server is up, how many entries it holds, and how many \
incidents and tasks are open.",
"inputSchema": {"type": "object", "properties": {}},
}),
json!({
"name": "kyb_incidents",
"description": "Live incident reports, open first and freshest on top. Check this \
before infrastructure work.",
"inputSchema": {"type": "object", "properties": {
"status": str_t, "service": str_t, "limit": int_t,
"followups": {"type": "boolean", "description": "only reports with unfinished \
follow-ups"},
"all": {"type": "boolean", "description": "include closed reports, which are \
archived but still readable"},
"deadlines": deadlines_t,
}},
}),
json!({
"name": "kyb_tasks",
"description": "Live tasks - open, in_progress, blocked - freshest on top.",
"inputSchema": {"type": "object", "properties": {
"status": str_t, "priority": str_t, "assignee": str_t, "parent_task": str_t,
"limit": int_t,
"followups": {"type": "boolean", "description": "only tasks with unfinished \
follow-ups"},
"all": {"type": "boolean", "description": "include closed tasks from the archive"},
"deadlines": deadlines_t,
}},
}),
json!({
"name": "kyb_deadlines",
"description": "Open tasks that have a due date, soonest first, each marked overdue, \
this_week or later, with the days left (negative = late). Hard deadlines - expiries, contract \
and regulatory dates - are marked; a provisional one runs on its expected date until the real \
date is known. Closed tasks never appear.",
"inputSchema": {"type": "object", "properties": {
"within": {"type": "string", "description": "only what is due within N days, \
e.g. 30 or 30d; late ones always count"},
"overdue": {"type": "boolean", "description": "only what is already late"},
"hard": {"type": "boolean", "description": "only hard deadlines"},
"tag": {"type": "string", "description": "comma-separated; every tag must match"},
"assignee": str_t,
}},
}),
json!({
"name": "kyb_brief",
"description": "What is live in the base right now, as pointers: deadlines, open \
incidents (highest severity first), active work (in progress, blocked, urgent open tasks), \
knowledge retracted recently and knowledge changed recently. Each row is a key, a title and one \
fact; read the details with kyb_get. IMPORTANT: call this once before you start any work on the \
infrastructure - do not skip it. It is context for the task you were given, not a to-do list: \
never start work from it on your own. Treat retracted entries as rejected decisions, and check \
open incidents before touching their services.",
"inputSchema": {"type": "object", "properties": {
"tag": {"type": "string", "description": "comma-separated; every tag must match"},
"service": {"type": "string", "description": "an incident's service, or a tag on \
the other kinds"},
"since": {"type": "string", "description": "how far back 'recently' reaches: 7d \
(default), 24h, a YYYY-MM-DD date or an RFC3339 time"},
"limit": {"type": "integer", "description": "rows per section, replacing the \
default caps (1-50)"},
}},
}),
json!({
"name": "kyb_confident_check",
"description": "Before you ask the owner to decide something - a release, a deploy, a \
push, a deletion, a public post, a design choice - ask the decision journal what was decided \
before about the same thing. Returns up to 3 earlier decisions from other sessions with who \
decided, the verdict, the owner's words and the outcome; hazards (an earlier decision on the same \
target that was corrected, reverted, rejected or never answered); and lint on your draft question. \
IMPORTANT: call it before every question to the owner. The precedents are evidence for you to \
judge, never permission to skip asking.",
"inputSchema": {"type": "object", "required": ["gist"], "properties": {
"gist": {"type": "string", "description": "the decision as ONE English line, at most \
15 words: action, object, options - e.g. 'orders-api: release patch 0.3.29 vs minor 0.4.0 after a fix'"},
"target": {"type": "string", "description": "repositories, services or paths the step \
touches, comma-separated"},
"kind": {"type": "string", "enum": crate::confident::KINDS, "description": "the \
operation class; absent means derived from the gist"},
"question": {"type": "string", "description": "your draft question to the owner, any \
language; only linted, never stored"},
}},
}),
json!({
"name": "kyb_confident_open",
"description": "Decision records still waiting for an answer, newest first; `stale` \
marks the ones open for more than 48 hours. Close each with kyb_confident_decided.",
"inputSchema": {"type": "object", "properties": {
"workspace": {"type": "string", "description": "only records opened in this workspace"},
}},
}),
json!({
"name": "kyb_confident_ask",
"description": "Open a decision record at the moment you ask the owner to decide. Only \
the main agent records, never a sub-agent or a background worker, and only for a question to the \
owner or a choice he could dispute. Returns the record id (keep it for kyb_confident_decided) and \
the same check as kyb_confident_check.",
"inputSchema": {"type": "object", "required": ["gist"], "properties": {
"gist": {"type": "string", "description": "ONE English line, at most 15 words: \
action, object, options"},
"target": list_t,
"kind": {"type": "string", "enum": crate::confident::KINDS},
"situation": {"type": "string", "description": "what led to the question, briefly"},
"options": list_t,
"proposed": {"type": "string", "description": "the option you propose; must be one \
of options"},
"tradeoff": {"type": "string", "description": "why the choice is not obvious"},
"checked": {"type": "string", "description": "what you verified before asking"},
"unchecked": {"type": "string", "description": "what you did not verify"},
"question": {"type": "string", "description": "the question as sent; linted, not stored"},
}},
}),
json!({
"name": "kyb_confident_decided",
"description": "Record the answer to an open decision record, right after it comes. \
Record what the owner actually said, including 'no', 'later', 'I don't understand' or an \
answer about something else - those are the most useful records.",
"inputSchema": {"type": "object", "required": ["id", "by", "verdict"], "properties": {
"id": {"type": "string", "description": "the id kyb_confident_ask returned"},
"by": {"type": "string", "enum": crate::confident::DECIDERS},
"verdict": {"type": "string", "enum": crate::confident::VERDICTS},
"chosen": {"type": "string", "description": "what was decided; may be an option \
nobody listed"},
"quote": {"type": "string", "description": "the owner's words, short; leave out \
swearing"},
"ref": {"type": "string", "description": "the commit, PR or tag that implements it"},
}},
}),
json!({
"name": "kyb_confident_outcome",
"description": "Append what came of a decision once it is known: kept, corrected, \
reverted or dropped. A ref to the evidence is required.",
"inputSchema": {"type": "object", "required": ["id", "result", "ref"], "properties": {
"id": str_t,
"result": {"type": "string", "enum": crate::confident::RESULTS},
"ref": {"type": "string", "description": "the commit, PR, task or incident that shows it"},
"why": str_t,
}},
}),
json!({
"name": "kyb_add",
"description": "Write or update one entry. Same call for both: reusing a key does not \
overwrite, it adds a version, and the old text stays searchable under history. Only verified \
facts - something read in the code, seen in a config, or returned by a command actually run. \
Never secrets in the body; put a pointer in refs instead. Entries are written in English.",
"inputSchema": {"type": "object", "required": ["key", "title", "body"], "properties": {
"key": {"type": "string", "description": "slug [a-z0-9-]; reusing one adds a version"},
"title": str_t,
"body": {"type": "string", "description": "the entry itself, markdown"},
"tags": list_t, "refs": list_t,
}},
}),
json!({
"name": "kyb_incident",
"description": "File an incident report. The key must start with inc-. A report that \
cannot tell the next person whether the thing is still happening is a story rather than a \
report, so pass `detection`: a command to run plus the result that means healthy. Tags left out \
of a rewrite keep the stored ones.",
"inputSchema": {"type": "object",
"required": ["key", "title", "service", "severity", "body"], "properties": {
"key": {"type": "string", "description": "inc-<date>-<slug>"},
"title": {"type": "string", "description": "the symptom, not the diagnosis"},
"service": str_t,
"severity": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
"body": {"type": "string", "description": "what happened, impact, workaround"},
"hosts": list_t, "knowledge": list_t, "tags": list_t, "refs": list_t,
"status": {"type": "string", "enum": ["open", "mitigated", "resolved"]},
"detection": {"type": "string", "description": "an executable check plus its \
healthy result"},
"affected": {"type": "array",
"description": "windows where data or a period got poisoned",
"items": {"type": "object", "required": ["scope", "from", "to"],
"properties": {"scope": str_t, "from": str_t, "to": str_t}}},
"started_at": {"type": "string", "description": "RFC3339, if known"},
"detected_at": {"type": "string", "description": "RFC3339, if known"},
"resolution": str_t,
}},
}),
json!({
"name": "kyb_resolve",
"description": "Close an incident. A resolution is required - what actually fixed it. \
Closing archives the report: it leaves the working set and stays searchable forever.",
"inputSchema": {"type": "object", "required": ["key", "resolution"], "properties": {
"key": str_t,
"resolution": {"type": "string", "description": "what fixed it"},
"status": {"type": "string", "enum": ["resolved", "mitigated"]},
}},
}),
json!({
"name": "kyb_task",
"description": "Create or update a task or idea. The key must start with task-. \
Reusing the key updates it in place. Tags and the deadline fields left out keep what the task \
already says, so rewriting a task never drops its tags or its due date; an empty value clears.",
"inputSchema": {"type": "object", "required": ["key", "title", "body"], "properties": {
"key": {"type": "string", "description": "task-<slug>"},
"title": str_t, "body": str_t,
"status": {"type": "string",
"enum": ["open", "in_progress", "blocked", "done", "dropped"]},
"priority": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
"blocked_reason": {"type": "string", "description": "what it waits on; only with \
status blocked"},
"assignee": str_t, "parent_task": str_t, "resolution": str_t,
"knowledge": list_t, "tags": list_t, "refs": list_t,
"due": date_t("when it is due"),
"hard": {"type": "boolean", "description": "missing it has real consequences: an \
expiry, a contractual or regulatory date, a third party's cut-off"},
"remind_days": {"type": ["integer", "string"], "description": "how many days ahead \
to start surfacing it; \"\" returns it to the default (14, or 30 when hard)"},
"waits_on": {"type": "string", "description": "the event the real date depends on"},
"expected": date_t("a provisional date, reminded on until due is set"),
}},
}),
json!({
"name": "kyb_task_status",
"description": "Move a task between open, in_progress and blocked, or move its \
deadline, without resending it. Title, body, tags, priority and links stay as stored; without \
a status the task keeps its own. Moving a due date is a new version, so history shows it. \
Closing is kyb_done, not this.",
"inputSchema": {"type": "object", "required": ["key"], "properties": {
"key": str_t,
"status": {"type": "string", "enum": ["open", "in_progress", "blocked"]},
"assignee": {"type": "string", "description": "an empty string hands it back"},
"parent_task": str_t,
"blocked_reason": {"type": "string", "description": "what it waits on; only with \
status blocked"},
"due": date_t("when it is due"),
"hard": {"type": "boolean", "description": "missing it has real consequences: an \
expiry, a contractual or regulatory date, a third party's cut-off"},
"remind_days": {"type": ["integer", "string"], "description": "how many days ahead \
to start surfacing it; \"\" returns it to the default (14, or 30 when hard)"},
"waits_on": {"type": "string", "description": "the event the real date depends on"},
"expected": date_t("a provisional date, reminded on until due is set"),
}},
}),
json!({
"name": "kyb_done",
"description": "Close a task with what came of it. Closing archives it: it leaves the \
working set and stays searchable.",
"inputSchema": {"type": "object", "required": ["key", "resolution"], "properties": {
"key": str_t,
"resolution": {"type": "string", "description": "what came of it"},
"status": {"type": "string", "enum": ["done", "dropped"]},
}},
}),
];
if readonly {
all.into_iter()
.filter(|t| {
!WRITE_TOOLS.contains(&t["name"].as_str().unwrap_or_default())
})
.collect()
} else {
all
}
}
#[cfg(test)]
mod mcp_tests {
use super::*;
use axum::http::Request as HttpRequest;
use serde_json::json;
use std::collections::HashSet;
fn test_app() -> (Router, tempfile::TempDir, tempfile::TempDir, std::path::PathBuf) {
let data = tempfile::tempdir().unwrap();
let idx = tempfile::tempdir().unwrap();
let audit_path = idx.path().join("audit.jsonl");
let cfg = crate::config::Config {
data_dir: data.path().to_path_buf(),
index_dir: idx.path().to_path_buf(),
audit_path: audit_path.clone(),
model_dir: idx.path().join("no-model"),
addr: String::new(),
};
let state = crate::build_state(&cfg).unwrap();
(crate::build_app(state), data, idx, audit_path)
}
async fn post(app: &Router, uri: &str, payload: Value) -> (StatusCode, Value) {
let req = HttpRequest::builder()
.method("POST")
.uri(uri)
.header("content-type", "application/json")
.body(Body::from(payload.to_string()))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
async fn rpc(app: &Router, payload: Value) -> Value {
post(app, "/mcp", payload).await.1
}
fn call(name: &str, args: Value) -> Value {
json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": name, "arguments": args}})
}
fn tool_body(resp: &Value) -> &str {
resp["result"]["content"][0]["text"].as_str().unwrap_or_default()
}
fn errored(resp: &Value) -> bool {
resp["result"]["isError"] == Value::Bool(true)
}
#[tokio::test]
async fn initialize_answers_the_asked_version_and_the_built_one() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(
&app,
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2025-03-26"}}),
)
.await;
assert_eq!(resp["result"]["protocolVersion"], "2025-03-26");
assert_eq!(resp["result"]["serverInfo"]["name"], "kyb");
assert_eq!(resp["result"]["serverInfo"]["version"], env!("CARGO_PKG_VERSION"));
assert!(resp["result"]["capabilities"]["tools"].is_object());
}
#[tokio::test]
async fn an_unknown_protocol_version_is_answered_with_one_we_support() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(
&app,
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "1999-01-01"}}),
)
.await;
assert_eq!(resp["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]);
}
#[tokio::test]
async fn a_notification_is_accepted_and_never_answered() {
let (app, _d, _i, _a) = test_app();
let (status, body) =
post(&app, "/mcp", json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
.await;
assert_eq!(status, StatusCode::ACCEPTED);
assert_eq!(body, Value::Null, "202 must carry no body");
}
#[tokio::test]
async fn the_tool_list_is_the_routes_this_build_has() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(&app, json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})).await;
let tools = resp["result"]["tools"].as_array().unwrap();
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
assert_eq!(names.len(), 21, "got {names:?}");
let unique: HashSet<&&str> = names.iter().collect();
assert_eq!(unique.len(), names.len(), "duplicate tool name in {names:?}");
for tool in tools {
assert!(tool["description"].as_str().is_some_and(|d| d.len() > 30));
assert_eq!(tool["inputSchema"]["type"], "object");
}
assert!(!names.contains(&"kyb_rm"));
assert!(!names.contains(&"kyb_reindex"));
assert!(names.contains(&"kyb_diff"));
let query = tools.iter().find(|t| t["name"] == "kyb_query").unwrap();
assert!(query["inputSchema"]["properties"]["as_of"].is_object());
assert!(query["inputSchema"]["properties"]["changed_between"].is_object());
}
#[tokio::test]
async fn a_tool_call_goes_through_the_real_routes() {
let (app, _d, _i, audit_path) = test_app();
let added = rpc(
&app,
call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
"body": "Runs on node-7, port 8080.", "tags": "infra,orders"})),
)
.await;
assert!(!errored(&added), "{added}");
let created: Value = serde_json::from_str(tool_body(&added)).unwrap();
assert_eq!(created["action"], "created");
assert_eq!(created["key"], "orders-api");
let got = rpc(&app, call("kyb_get", json!({"key": "orders-api"}))).await;
let entry: Value = serde_json::from_str(tool_body(&got)).unwrap();
assert!(entry["body"].as_str().unwrap().contains("port 8080"));
let found = rpc(&app, call("kyb_query", json!({"q": "orders", "limit": 5}))).await;
let hits: Value = serde_json::from_str(tool_body(&found)).unwrap();
assert!(hits["count"].as_u64().unwrap() >= 1, "{hits}");
let log = std::fs::read_to_string(&audit_path).unwrap();
assert!(
log.lines().any(|l| l.contains("\"path\":\"/knowledge\"")
&& l.contains("\"method\":\"POST\"")),
"no audit line for the forwarded write: {log}"
);
assert!(!log.contains("\"/mcp\""), "the /mcp hop should not be audited twice: {log}");
}
#[tokio::test]
async fn a_second_write_to_one_key_adds_a_version() {
let (app, _d, _i, _a) = test_app();
for body in ["port 8080", "port 9090"] {
rpc(
&app,
call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
"body": format!("Runs on node-7, {body}.")})),
)
.await;
}
let history = rpc(&app, call("kyb_history", json!({"key": "orders-api"}))).await;
let parsed: Value = serde_json::from_str(tool_body(&history)).unwrap();
assert_eq!(parsed["versions"].as_array().unwrap().len(), 2);
}
#[tokio::test]
async fn a_missing_argument_is_refused_before_a_request_is_made() {
let (app, _d, _i, audit_path) = test_app();
let resp = rpc(&app, call("kyb_add", json!({"key": "half", "title": "Half"}))).await;
assert!(errored(&resp));
assert!(
tool_body(&resp).starts_with("missing required argument"),
"{}",
tool_body(&resp)
);
let log = std::fs::read_to_string(&audit_path).unwrap_or_default();
assert!(
!log.contains("\"path\":\"/knowledge\""),
"a refused call must not reach the API at all: {log}"
);
let got = rpc(&app, call("kyb_get", json!({"key": "half"}))).await;
assert!(errored(&got), "the refused write must not have created anything");
}
#[tokio::test]
async fn an_unknown_tool_is_readable_by_the_model_not_a_protocol_fault() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(&app, call("kyb_delete_everything", json!({}))).await;
assert!(errored(&resp));
assert!(tool_body(&resp).contains("no such tool"));
assert!(resp["error"].is_null(), "a bad tool name is not a JSON-RPC error");
}
#[tokio::test]
async fn an_http_failure_from_the_route_reaches_the_model() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(&app, call("kyb_get", json!({"key": "never-written"}))).await;
assert!(errored(&resp));
assert!(tool_body(&resp).contains("404"), "{}", tool_body(&resp));
}
#[tokio::test]
async fn a_batch_is_answered_in_order_and_notifications_drop_out() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(
&app,
json!([
{"jsonrpc": "2.0", "id": "a", "method": "ping"},
{"jsonrpc": "2.0", "method": "notifications/initialized"},
{"jsonrpc": "2.0", "id": "b", "method": "tools/list"},
]),
)
.await;
let items = resp.as_array().unwrap();
assert_eq!(items.len(), 2, "the notification must not produce a response");
assert_eq!(items[0]["id"], "a");
assert_eq!(items[1]["id"], "b");
}
#[tokio::test]
async fn protocol_faults_are_json_rpc_errors() {
let (app, _d, _i, _a) = test_app();
let unknown = rpc(&app, json!({"jsonrpc": "2.0", "id": 1, "method": "no/such"})).await;
assert_eq!(unknown["error"]["code"], -32601);
let nameless = rpc(
&app,
json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {}}),
)
.await;
assert_eq!(nameless["error"]["code"], -32602);
let req = HttpRequest::builder()
.method("POST")
.uri("/mcp")
.header("content-type", "application/json")
.body(Body::from("{not json"))
.unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
let parsed: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(parsed["error"]["code"], -32700);
}
#[tokio::test]
async fn get_and_delete_say_why_they_are_refused() {
let (app, _d, _i, _a) = test_app();
for method in ["GET", "DELETE"] {
let req =
HttpRequest::builder().method(method).uri("/mcp").body(Body::empty()).unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED, "{method}");
assert_eq!(resp.headers().get("allow").unwrap(), "POST");
}
}
#[tokio::test]
async fn readonly_drops_the_writing_tools_and_refuses_them() {
let (app, _d, _i, _a) = test_app();
let listed =
post(&app, "/mcp?readonly=1", json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}))
.await
.1;
let names: Vec<&str> = listed["result"]["tools"]
.as_array()
.unwrap()
.iter()
.map(|t| t["name"].as_str().unwrap())
.collect();
assert_eq!(names.len(), 12, "{names:?}");
assert!(names.contains(&"kyb_deadlines") && names.contains(&"kyb_brief"), "{names:?}");
assert!(names.contains(&"kyb_confident_check") && names.contains(&"kyb_confident_open"), "{names:?}");
for write in WRITE_TOOLS {
assert!(!names.contains(&write), "{write} must not be advertised read-only");
}
assert!(names.contains(&"kyb_query"));
let refused = post(
&app,
"/mcp?readonly=1",
call("kyb_add", json!({"key": "k", "title": "t", "body": "b"})),
)
.await
.1;
assert!(errored(&refused));
let got = rpc(&app, call("kyb_get", json!({"key": "k"}))).await;
assert!(errored(&got), "a read-only refusal must not have written anything");
}
#[tokio::test]
async fn diff_reports_what_moved_between_two_versions() {
let (app, _d, _i, _a) = test_app();
for body in ["Runs on node-7, port 8080.", "Runs on node-7, port 9090."] {
rpc(&app, call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
"body": body}))).await;
}
let resp = rpc(&app, call("kyb_diff", json!({"key": "orders-api"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let text = tool_body(&resp);
assert!(text.contains("8080"), "{text}");
assert!(text.contains("9090"), "{text}");
}
#[tokio::test]
async fn as_of_asks_the_route_about_the_past_rather_than_the_present() {
let (app, _d, _i, audit_path) = test_app();
rpc(&app, call("kyb_add", json!({"key": "orders-api", "title": "Orders API",
"body": "port 8080"}))).await;
let resp = rpc(&app, call("kyb_query",
json!({"q": "orders", "as_of": "2020-01-01"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let parsed: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(parsed["count"], 0, "as_of was ignored: {parsed}");
let log = std::fs::read_to_string(&audit_path).unwrap();
assert!(log.contains("as_of"), "as_of never reached the route: {log}");
}
#[tokio::test]
async fn a_comma_string_and_a_list_of_tags_mean_the_same_thing() {
let (app, _d, _i, _a) = test_app();
rpc(&app, call("kyb_add", json!({"key": "a", "title": "A", "body": "x",
"tags": "infra, orders"}))).await;
rpc(&app, call("kyb_add", json!({"key": "b", "title": "B", "body": "x",
"tags": ["infra", "orders"]}))).await;
let tags = rpc(&app, call("kyb_tags", json!({}))).await;
let parsed: Value = serde_json::from_str(tool_body(&tags)).unwrap();
let text = parsed.to_string();
assert!(text.contains("infra") && text.contains("orders"), "{text}");
}
#[tokio::test]
async fn the_brief_reaches_an_mcp_client_through_the_same_route() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(&app, call("kyb_task", json!({"key": "task-doing", "title": "Doing it",
"body": "x", "status": "in_progress"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_brief", json!({"limit": 3}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let brief: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(brief["work"]["items"][0]["key"], "task-doing", "{brief}");
for section in ["deadlines", "incidents", "work", "retracted", "changed"] {
assert!(brief[section]["items"].is_array(), "{section}: {brief}");
}
let resp = rpc(&app, call("kyb_brief", json!({"since": "next week"}))).await;
assert!(errored(&resp), "the route's refusal reaches the client");
}
#[tokio::test]
async fn the_decision_journal_reaches_an_mcp_client_through_the_same_routes() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(&app, call("kyb_confident_ask", json!({
"gist": "kyb: add a session start hook for the brief", "target": "kyb",
"options": ["hook", "tool only"], "proposed": "hook"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let asked: Value = serde_json::from_str(tool_body(&resp)).unwrap();
let id = asked["id"].as_str().unwrap().to_string();
let resp = rpc(&app, call("kyb_confident_open", json!({}))).await;
let open: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(open["items"][0]["id"], id.as_str(), "{open}");
let resp = rpc(&app, call("kyb_confident_decided", json!({"id": id, "by": "owner",
"verdict": "correction", "chosen": "tool only", "quote": "no hooks for agent context"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_confident_outcome", json!({"id": id, "result": "reverted",
"ref": "PR 54"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_confident_check", json!({
"gist": "kyb: add a session start hook for the digest", "target": "kyb"}))).await;
let check: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(check["hazards"][0]["id"], id.as_str(), "{check}");
let resp = rpc(&app, call("kyb_confident_outcome", json!({"id": id, "result": "kept"}))).await;
assert!(errored(&resp), "an outcome without a ref is refused before it is sent");
}
#[tokio::test]
async fn deadlines_reach_an_mcp_client_through_the_same_routes() {
let (app, _d, _i, _a) = test_app();
let resp = rpc(&app, call("kyb_task", json!({"key": "task-renew-cert",
"title": "Renew the certificate", "body": "before it expires",
"due": "2000-01-01", "hard": true}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_query", json!({"q": "certificate"}))).await;
let answer: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(answer["deadlines"]["items"][0]["key"], "task-renew-cert", "{answer}");
assert_eq!(answer["deadlines"]["items"][0]["overdue"], true);
let resp = rpc(&app, call("kyb_query", json!({"q": "certificate", "deadlines": false}))).await;
let answer: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert!(answer.get("deadlines").is_none(), "{answer}");
rpc(&app, call("kyb_task", json!({"key": "task-renew-cert",
"title": "Renew the certificate", "body": "before it expires, via the CA portal"}))).await;
let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
"due": "2999-12-31"}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_deadlines", json!({"hard": true}))).await;
let listing: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(listing["count"], 1, "{listing}");
assert_eq!(listing["deadlines"][0]["due"], "2999-12-31");
assert_eq!(listing["deadlines"][0]["status"], "open");
assert_eq!(listing["deadlines"][0]["hard"], true);
let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
"remind_days": "soon"}))).await;
assert!(errored(&resp), "a malformed field is refused before any request is made");
let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
"remind_days": 5_000_000_000u64}))).await;
assert!(errored(&resp), "a count that does not fit is refused here, not by the route");
let resp = rpc(&app, call("kyb_task", json!({"key": "task-renew-cert",
"title": "Renew the certificate", "body": "before it expires",
"due": null, "hard": null, "remind_days": null}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert",
"remind_days": 45}))).await;
assert!(!errored(&resp), "{}", tool_body(&resp));
let resp = rpc(&app, call("kyb_deadlines", json!({}))).await;
let listing: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(listing["deadlines"][0]["due"], "2999-12-31", "{listing}");
assert_eq!(listing["deadlines"][0]["remind_days"], 45);
rpc(&app, call("kyb_task_status", json!({"key": "task-renew-cert", "remind_days": ""}))).await;
let resp = rpc(&app, call("kyb_deadlines", json!({}))).await;
let listing: Value = serde_json::from_str(tool_body(&resp)).unwrap();
assert_eq!(listing["deadlines"][0]["remind_days"], 30, "{listing}");
}
#[tokio::test]
async fn a_rewrite_over_mcp_keeps_the_tags_it_does_not_name() {
let (app, _d, _i, _a) = test_app();
let tags = |key: &str| {
let key = key.to_string();
let app = app.clone();
async move {
let resp = rpc(&app, call("kyb_get", json!({"key": key}))).await;
let e: Value = serde_json::from_str(tool_body(&resp)).unwrap();
e["tags"].clone()
}
};
let task = |extra: Value| {
let mut a = json!({"key": "task-tagged", "title": "Tagged", "body": "b"});
a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
a
};
rpc(&app, call("kyb_task", task(json!({"tags": ["infra", "tls"]})))).await;
rpc(&app, call("kyb_task", task(json!({"body": "rewritten"})))).await;
assert_eq!(tags("task-tagged").await, json!(["infra", "tls"]), "a rewrite that names no tags keeps them");
rpc(&app, call("kyb_task", task(json!({"tags": null})))).await;
assert_eq!(tags("task-tagged").await, json!(["infra", "tls"]), "null is not named");
rpc(&app, call("kyb_task", task(json!({"tags": ""})))).await;
assert_eq!(tags("task-tagged").await, json!([]), "an empty value clears");
let inc = |extra: Value| {
let mut a = json!({"key": "inc-2026-10-27-tagged", "title": "Tagged", "body": "b", "service": "svc", "severity": "low"});
a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
a
};
rpc(&app, call("kyb_incident", inc(json!({"tags": "infra"})))).await;
rpc(&app, call("kyb_incident", inc(json!({"body": "rewritten"})))).await;
assert_eq!(tags("inc-2026-10-27-tagged").await, json!(["infra"]));
}
#[tokio::test]
async fn a_key_that_is_not_a_slug_is_refused_not_a_panic() {
let (app, _d, _i, _a) = test_app();
for (tool, args) in [
("kyb_get", json!({"key": "Bad Key"})),
("kyb_diff", json!({"key": "Bad Key"})),
("kyb_history", json!({"key": "Bad Key"})),
("kyb_resolve", json!({"key": "inc bad", "resolution": "r"})),
("kyb_task_status", json!({"key": "a b", "status": "doing"})),
("kyb_done", json!({"key": "task bad", "resolution": "r"})),
("kyb_get", json!({"key": "a/b"})),
] {
let resp = rpc(&app, call(tool, args.clone())).await;
assert!(errored(&resp), "{tool} {args}: {resp}");
}
}
}