use std::collections::HashMap;
use std::sync::Arc;
use rmcp::{
handler::server::{tool::ToolRouter, wrapper::Parameters},
model::*,
tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler, ServiceExt,
};
use schemars::JsonSchema;
use serde::Deserialize;
use crate::pipeline::{Pipeline, ResolveRequest};
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResolveParams {
pub jwt: String,
pub resource: String,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct FetchParams {
pub jwt: String,
pub resource: String,
pub resolver: String,
pub url: String,
#[serde(default = "default_method")]
pub method: String,
#[serde(default)]
pub headers: HashMap<String, String>,
#[serde(default)]
pub body: Option<String>,
}
const DEFAULT_HTTP_METHOD: &str = "GET";
fn default_method() -> String {
DEFAULT_HTTP_METHOD.into()
}
#[derive(Clone)]
pub struct McpHandler {
pipeline: Arc<Pipeline>,
http_client: reqwest::Client,
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl McpHandler {
pub fn new(pipeline: Pipeline) -> Self {
Self {
pipeline: Arc::new(pipeline),
http_client: reqwest::Client::new(),
tool_router: Self::tool_router(),
}
}
#[tool(
description = "Resolve secrets for a resource through the keyzero policy pipeline. Verifies the JWT, maps claims to tags, evaluates CEL policies, and returns resolved secrets if allowed."
)]
pub async fn resolve(
&self,
Parameters(params): Parameters<ResolveParams>,
) -> Result<CallToolResult, McpError> {
let request = ResolveRequest {
resource: params.resource,
};
match self.pipeline.resolve(¶ms.jwt, &request).await {
Ok(response) => {
let json = serde_json::to_string_pretty(&response)
.unwrap_or_else(|e| format!("serialization error: {e}"));
Ok(CallToolResult::success(vec![Content::text(json)]))
}
Err(e) => Ok(CallToolResult::error(vec![Content::text(e.to_string())])),
}
}
#[tool(
description = "Make an authenticated HTTP request to an external service. Resolves the credential through the keyzero policy pipeline and injects it into the outgoing request. The raw secret is never returned — only the upstream HTTP response."
)]
pub async fn fetch(
&self,
Parameters(params): Parameters<FetchParams>,
) -> Result<CallToolResult, McpError> {
let (secret_value, resolver_config) = self
.pipeline
.resolve_single(¶ms.jwt, ¶ms.resource, ¶ms.resolver)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let credential_location = crate::security::effective_location(
resolver_config.credential_location.as_deref(),
);
let method = reqwest::Method::from_bytes(params.method.as_bytes())
.map_err(|e| McpError::invalid_params(format!("invalid method: {e}"), None))?;
let mut req = self.http_client.request(method, ¶ms.url);
if let Ok(url) = reqwest::Url::parse(¶ms.url) {
if let Some(host) = url.host_str() {
if crate::security::is_blocked_host(host) {
return Err(McpError::invalid_params(
format!("fetch to address '{host}' is not allowed (private or metadata endpoint)"),
None,
));
}
}
}
for (name, value) in ¶ms.headers {
req = req.header(name.as_str(), value.as_str());
}
let loc = crate::security::parse_credential_location(credential_location)
.map_err(|e| McpError::internal_error(e, None))?;
let header_value = crate::security::format_credential_value(&loc, &secret_value);
req = req.header(loc.header_name, header_value);
if let Some(body) = params.body {
req = req.body(body);
}
let response = req
.send()
.await
.map_err(|e| McpError::internal_error(format!("request failed: {e}"), None))?;
let status = response.status().as_u16();
let resp_headers: HashMap<String, String> = response
.headers()
.iter()
.filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
.collect();
let body = response
.text()
.await
.map_err(|e| McpError::internal_error(format!("failed to read body: {e}"), None))?;
let result = serde_json::json!({
"status": status,
"headers": resp_headers,
"body": body,
});
let text = serde_json::to_string_pretty(&result)
.unwrap_or_else(|e| format!("serialization error: {e}"));
Ok(CallToolResult::success(vec![Content::text(text)]))
}
}
#[tool_handler]
impl ServerHandler for McpHandler {
fn get_info(&self) -> ServerInfo {
ServerInfo {
protocol_version: ProtocolVersion::LATEST,
capabilities: ServerCapabilities::builder().enable_tools().build(),
server_info: Implementation {
name: "keyzero".into(),
title: None,
version: env!("CARGO_PKG_VERSION").into(),
icons: None,
website_url: None,
},
instructions: Some(
"Keyzero Agent — resolve secrets and make authenticated requests through policy-controlled pipelines."
.into(),
),
}
}
}
pub async fn serve_mcp(pipeline: Pipeline) -> anyhow::Result<()> {
let handler = McpHandler::new(pipeline);
let service = handler.serve(rmcp::transport::stdio()).await?;
service.waiting().await?;
Ok(())
}