kz-server 0.1.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
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 {
    /// JWT bearer token for authentication
    pub jwt: String,
    /// Resource ID to resolve (e.g. "db/password")
    pub resource: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
pub struct FetchParams {
    /// JWT bearer token for authentication
    pub jwt: String,
    /// Resource ID to resolve credentials from
    pub resource: String,
    /// Which resolver on the resource to use for the credential
    pub resolver: String,
    /// Target URL to fetch
    pub url: String,
    /// HTTP method (default: GET)
    #[serde(default = "default_method")]
    pub method: String,
    /// Additional headers as key-value pairs
    #[serde(default)]
    pub headers: HashMap<String, String>,
    /// Request body
    #[serde(default)]
    pub body: Option<String>,
}

fn default_method() -> String {
    "GET".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(&params.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(&params.jwt, &params.resource, &params.resolver)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let credential_location = resolver_config
            .credential_location
            .as_deref()
            .unwrap_or("header:Authorization:Bearer");

        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, &params.url);

        for (name, value) in &params.headers {
            req = req.header(name.as_str(), value.as_str());
        }

        let parts: Vec<&str> = credential_location.splitn(3, ':').collect();
        match parts.as_slice() {
            ["header", header_name, prefix] => {
                let value = if prefix.is_empty() {
                    secret_value
                } else {
                    format!("{prefix} {secret_value}")
                };
                req = req.header(*header_name, value);
            }
            _ => {
                return Err(McpError::internal_error(
                    format!("unsupported credential_location: {credential_location}"),
                    None,
                ));
            }
        }

        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: "kzagent".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(),
            ),
        }
    }
}

/// Start the MCP server over stdio.
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(())
}