Skip to main content

kz_server/
mcp.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use rmcp::handler::server::wrapper::Parameters;
5use rmcp::model::{
6    CallToolResult, Content, Implementation, ServerCapabilities, ServerInfo, ToolsCapability,
7};
8use rmcp::handler::server::tool::ToolRouter;
9use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
10use schemars::JsonSchema;
11use serde::Deserialize;
12
13use crate::pipeline::{Pipeline, ResolveRequest};
14use crate::security::{
15    effective_location, format_credential_value, is_blocked_host, parse_credential_location,
16};
17
18// ---------------------------------------------------------------------------
19// Tool parameter types
20// ---------------------------------------------------------------------------
21
22#[derive(Debug, Deserialize, JsonSchema)]
23pub struct ResolveParams {
24    /// JWT token for authentication
25    pub jwt: String,
26    /// Resource ref path to resolve
27    pub resource: String,
28    /// Optional additional context
29    #[serde(default)]
30    pub context: HashMap<String, serde_json::Value>,
31}
32
33#[derive(Debug, Deserialize, JsonSchema)]
34pub struct FetchParams {
35    /// JWT token for authentication
36    pub jwt: String,
37    /// Resource ref path to resolve
38    pub resource: String,
39    /// Target URL to fetch
40    pub url: String,
41    /// HTTP method (defaults to GET)
42    #[serde(default = "default_method")]
43    pub method: String,
44    /// Extra headers to send
45    #[serde(default)]
46    pub headers: HashMap<String, String>,
47    /// Optional request body
48    pub body: Option<String>,
49    /// Optional additional context
50    #[serde(default)]
51    pub context: HashMap<String, serde_json::Value>,
52}
53
54fn default_method() -> String {
55    "GET".to_string()
56}
57
58// ---------------------------------------------------------------------------
59// MCP handler
60// ---------------------------------------------------------------------------
61
62#[derive(Clone)]
63pub struct McpHandler {
64    pipeline: Arc<Pipeline>,
65    http_client: reqwest::Client,
66    tool_router: ToolRouter<Self>,
67}
68
69#[tool_router]
70impl McpHandler {
71    pub fn new(pipeline: Arc<Pipeline>) -> Self {
72        let http_client = reqwest::Client::new();
73        Self {
74            pipeline,
75            http_client,
76            tool_router: Self::tool_router(),
77        }
78    }
79
80    /// Resolve a secret reference through the keyzero policy pipeline.
81    /// Returns the resolution result as JSON including the credential value
82    /// (if allowed), mode, and policy information.
83    #[tool(name = "resolve", description = "Resolve a secret reference through the keyzero policy pipeline")]
84    async fn resolve(
85        &self,
86        Parameters(params): Parameters<ResolveParams>,
87    ) -> std::result::Result<CallToolResult, McpError> {
88        let request = ResolveRequest {
89            ref_path: Some(params.resource),
90            refs: None,
91            context: if params.context.is_empty() {
92                None
93            } else {
94                Some(params.context)
95            },
96        };
97
98        match self.pipeline.resolve(&params.jwt, &request).await {
99            Ok(response) => {
100                let json = serde_json::to_string_pretty(&response)
101                    .unwrap_or_else(|e| format!("{{\"error\": \"serialization failed: {e}\"}}"));
102                Ok(CallToolResult::success(vec![Content::text(json)]))
103            }
104            Err(e) => Ok(CallToolResult::error(vec![Content::text(e.to_string())])),
105        }
106    }
107
108    /// Fetch a URL with credentials injected from the keyzero vault.
109    /// Resolves the secret for the given resource, performs SSRF validation,
110    /// injects the credential into the outgoing request, and returns the
111    /// upstream response status and body.
112    #[tool(name = "fetch", description = "Fetch a URL with credentials injected from the keyzero vault")]
113    async fn fetch(
114        &self,
115        Parameters(params): Parameters<FetchParams>,
116    ) -> std::result::Result<CallToolResult, McpError> {
117        // 1. SSRF check
118        let parsed_url = match reqwest::Url::parse(&params.url) {
119            Ok(u) => u,
120            Err(e) => {
121                return Err(McpError::invalid_params(
122                    format!("invalid URL: {e}"),
123                    None,
124                ));
125            }
126        };
127        let host = parsed_url.host_str().unwrap_or("");
128        if is_blocked_host(host) {
129            return Ok(CallToolResult::error(vec![Content::text(format!(
130                "blocked host: {host}"
131            ))]));
132        }
133
134        // 2. Resolve credential
135        let (secret_value, resource) = match self
136            .pipeline
137            .resolve_single(&params.jwt, &params.resource, &params.context)
138            .await
139        {
140            Ok(v) => v,
141            Err(e) => {
142                return Ok(CallToolResult::error(vec![Content::text(e.to_string())]));
143            }
144        };
145
146        // 3. Build outgoing request
147        let method = match reqwest::Method::from_bytes(params.method.as_bytes()) {
148            Ok(m) => m,
149            Err(e) => {
150                return Err(McpError::invalid_params(
151                    format!("invalid HTTP method: {e}"),
152                    None,
153                ));
154            }
155        };
156
157        let mut req_builder = self.http_client.request(method, parsed_url);
158
159        // Copy user-supplied headers
160        for (k, v) in &params.headers {
161            req_builder = req_builder.header(k.as_str(), v.as_str());
162        }
163
164        // Inject credential
165        let loc_str = effective_location(resource.credential_location.as_deref());
166        let cred_loc = match parse_credential_location(loc_str) {
167            Ok(loc) => loc,
168            Err(e) => {
169                return Err(McpError::invalid_params(
170                    format!("invalid credential_location: {e}"),
171                    None,
172                ));
173            }
174        };
175        let cred_value = format_credential_value(&cred_loc, &secret_value);
176        req_builder = req_builder.header(cred_loc.header_name, &cred_value);
177
178        // Attach body
179        if let Some(body) = params.body {
180            req_builder = req_builder.body(body);
181        }
182
183        // 4. Send
184        let resp = match req_builder.send().await {
185            Ok(r) => r,
186            Err(e) => {
187                return Err(McpError::internal_error(
188                    format!("HTTP request failed: {e}"),
189                    None,
190                ));
191            }
192        };
193
194        let status = resp.status().as_u16();
195        let body = resp.text().await.unwrap_or_default();
196
197        let result_json = serde_json::json!({
198            "status": status,
199            "body": body,
200        });
201
202        Ok(CallToolResult::success(vec![Content::text(
203            result_json.to_string(),
204        )]))
205    }
206}
207
208#[tool_handler]
209impl ServerHandler for McpHandler {
210    fn get_info(&self) -> ServerInfo {
211        ServerInfo {
212            protocol_version: Default::default(),
213            capabilities: ServerCapabilities {
214                tools: Some(ToolsCapability { list_changed: None }),
215                ..Default::default()
216            },
217            server_info: Implementation {
218                name: "keyzero".to_string(),
219                title: Some("KeyZero MCP Server".to_string()),
220                version: env!("CARGO_PKG_VERSION").to_string(),
221                icons: None,
222                website_url: None,
223            },
224            instructions: Some(
225                "KeyZero vault gateway — resolve secrets and fetch URLs with credential injection."
226                    .to_string(),
227            ),
228        }
229    }
230}
231
232// ---------------------------------------------------------------------------
233// Public entry point
234// ---------------------------------------------------------------------------
235
236/// Start the MCP server over stdio transport.
237pub async fn serve_mcp(pipeline: Arc<Pipeline>) -> crate::error::Result<()> {
238    let handler = McpHandler::new(pipeline);
239    let transport = rmcp::transport::stdio();
240    let service = handler.serve(transport).await.map_err(|e| {
241        crate::error::ServerError::Config(format!("MCP server failed to start: {e}"))
242    })?;
243
244    service.waiting().await.map_err(|e| {
245        crate::error::ServerError::Config(format!("MCP server error: {e}"))
246    })?;
247
248    Ok(())
249}