返回 CodeWhale
mcp_server.rs
根目录 / crates / app-server / src / mcp_server.rs
1 //! MCP server implementation for exposing Codewhale tools over stdio.
2
3 use std::borrow::Cow;
4 use std::collections::HashSet;
5 use std::path::PathBuf;
6 use std::sync::Arc;
7 use std::sync::atomic::{AtomicBool, Ordering};
8
9 use anyhow::{Context, Result};
10 use rmcp::model::{
11 CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, ErrorCode,
12 Implementation, InitializeRequestParams, InitializeResult, ListResourceTemplatesResult,
13 ListResourcesResult, ListToolsResult, PaginatedRequestParams, ProtocolVersion,
14 ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult, Resource,
15 ResourceContents, ServerCapabilities, ServerConfig, Tool, ToolAnnotations,
16 };
17 use rmcp::service::RequestContext;
18 use rmcp::transport::async_rw::AsyncRwTransport;
19 use rmcp::{ErrorData, RoleServer, ServerHandler, ServiceExt};
20 use serde::{Deserialize, Serialize};
21 use serde_json::Value;
22 use tokio::io::{AsyncRead, AsyncWrite};
23 use tokio::sync::Mutex;
24 use tokio_util::sync::CancellationToken;
25
26 use codewhale_config::AppMode;
27 use codewhale_engine::core::authority::{
28 SandboxNetworkAccess, sandbox_policy_for_turn, shell_policy_for_mode,
29 };
30 use codewhale_engine::tools::shell::new_shared_shell_manager;
31 use codewhale_engine::tools::spec::{ToolError, ToolResult};
32 use codewhale_engine::tools::{ToolContext, ToolRegistryBuilder};
33 use codewhale_execpolicy::ApprovalMode;
34 use codewhale_sandbox::BwrapMountExtensions;
35 use codewhale_sandbox::backend::{SandboxBackend, create_backend};
36 use codewhale_sandbox::read_guard::{ReadDenylist, set_active as set_active_read_denylist};
37 use codewhale_skill_install::skill_parse::SkillInvocation;
38 use codewhale_skills::SkillSource;
39 use codewhale_tools::names::{
40 TERMINAL_CANCEL_NAME, TERMINAL_RESET_NAME, TERMINAL_RUN_NAME, TERMINAL_SEND_NAME,
41 TERMINAL_WAIT_NAME,
42 };
43
44 const SUPPORTED_PROTOCOL_VERSIONS: &[ProtocolVersion] = &[
45 ProtocolVersion::V_2024_11_05,
46 ProtocolVersion::V_2025_03_26,
47 ProtocolVersion::V_2025_06_18,
48 ProtocolVersion::V_2025_11_25,
49 ProtocolVersion::V_2026_07_28,
50 ];
51 const RESOURCE_PAGE_SIZE: usize = 100;
52 const MAX_RESOURCE_CURSOR_BYTES: usize = 4096;
53
54 #[derive(Debug, Default, Deserialize)]
55 struct McpServerConfigFile {
56 #[serde(default)]
57 server: McpServerSection,
58 }
59
60 #[derive(Debug, Default, Deserialize)]
61 struct McpServerSection {
62 expose_tools: Option<Vec<String>>,
63 /// Withhold tools that write files or run commands. This stdio server has
64 /// no channel for an out-of-band approval prompt, so "approval required"
65 /// means those tools are refused. Defaults to `true`; only the operator's
66 /// own config file can turn it off.
67 require_approval: Option<bool>,
68 }
69
70 #[derive(Debug, Clone)]
71 struct McpServerSettings {
72 expose_tools: Vec<String>,
73 require_approval: bool,
74 }
75
76 impl McpServerSettings {
77 fn load() -> Result<Self> {
78 let path = default_config_path();
79 Self::load_from_path(path.as_deref())
80 }
81
82 fn load_from_path(path: Option<&std::path::Path>) -> Result<Self> {
83 let contents = match path {
84 Some(path) => match std::fs::File::open(path) {
85 Ok(file) => {
86 let cap = codewhale_engine::mcp::MAX_MCP_CONFIG_BYTES as usize;
87 let (contents, len) =
88 codewhale_engine::prompts::read_prompt_text_bounded(file, cap)
89 .with_context(|| {
90 format!("Failed to read MCP server config: {}", path.display())
91 })?;
92 if len.max(contents.len()) > cap {
93 anyhow::bail!(
94 "MCP server config {} exceeds the {} MiB limit",
95 path.display(),
96 cap / (1024 * 1024)
97 );
98 }
99 Some(contents)
100 }
101 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
102 Err(error) => {
103 return Err(error).with_context(|| {
104 format!("Failed to read MCP server config: {}", path.display())
105 });
106 }
107 },
108 None => None,
109 };
110 if let (Some(path), Some(contents)) = (path, contents) {
111 Self::from_toml(&contents)
112 .with_context(|| format!("Failed to parse MCP server config: {}", path.display()))
113 } else {
114 Ok(Self {
115 expose_tools: default_expose_tools(),
116 require_approval: true,
117 })
118 }
119 }
120
121 fn refuse_shell_tools(&mut self) -> Vec<String> {
122 let (refused, kept): (Vec<String>, Vec<String>) = std::mem::take(&mut self.expose_tools)
123 .into_iter()
124 .partition(|name| {
125 build_exposed_tools(std::slice::from_ref(name))
126 .iter()
127 .any(|tool| is_shell_tool_name(&tool.internal))
128 });
129 self.expose_tools = kept;
130 refused
131 }
132
133 fn from_toml(contents: &str) -> Result<Self> {
134 let config: McpServerConfigFile = toml::from_str(contents)?;
135 Ok(Self {
136 expose_tools: config
137 .server
138 .expose_tools
139 .unwrap_or_else(default_expose_tools),
140 require_approval: config.server.require_approval.unwrap_or(true),
141 })
142 }
143 }
144
145 fn is_shell_tool_name(internal: &str) -> bool {
146 matches!(
147 internal,
148 "exec_shell"
149 | "bash"
150 | TERMINAL_RUN_NAME
151 | TERMINAL_SEND_NAME
152 | TERMINAL_WAIT_NAME
153 | TERMINAL_CANCEL_NAME
154 | TERMINAL_RESET_NAME
155 )
156 }
157
158 #[derive(Clone)]
159 struct McpServerSandboxConfig {
160 sandbox_mode: Option<String>,
161 sandbox_network_access: Option<bool>,
162 prefer_bwrap: bool,
163 tool_launcher: Option<Vec<String>>,
164 bwrap_extensions: BwrapMountExtensions,
165 read_denylist: ReadDenylist,
166 sandbox_backend: Option<Arc<dyn SandboxBackend>>,
167 }
168
169 impl Default for McpServerSandboxConfig {
170 fn default() -> Self {
171 let config = codewhale_runtime::config::Config::default();
172 Self {
173 sandbox_mode: config.sandbox_mode.clone(),
174 sandbox_network_access: config.sandbox_network_access,
175 prefer_bwrap: config.prefers_bwrap(),
176 tool_launcher: config.tool_launcher.clone(),
177 bwrap_extensions: BwrapMountExtensions {
178 read_only_roots: config.bwrap_ro_roots.clone(),
179 device_roots: config.bwrap_dev_roots.clone(),
180 },
181 read_denylist: ReadDenylist::from_config(&config),
182 sandbox_backend: None,
183 }
184 }
185 }
186
187 impl McpServerSandboxConfig {
188 fn from_config(config: &codewhale_runtime::config::Config) -> Result<Self> {
189 let sandbox_backend = create_backend(config)?.map(Arc::from);
190 Ok(Self {
191 sandbox_mode: config.sandbox_mode.clone(),
192 sandbox_network_access: config.sandbox_network_access,
193 prefer_bwrap: config.prefers_bwrap(),
194 tool_launcher: config.tool_launcher.clone(),
195 bwrap_extensions: BwrapMountExtensions {
196 read_only_roots: config.bwrap_ro_roots.clone(),
197 device_roots: config.bwrap_dev_roots.clone(),
198 },
199 read_denylist: ReadDenylist::from_config(config),
200 sandbox_backend,
201 })
202 }
203 }
204
205 #[derive(Debug, Clone)]
206 struct ExposedTool {
207 public: String,
208 internal: String,
209 }
210
211 pub async fn run_mcp_server(
212 workspace: PathBuf,
213 config: &codewhale_runtime::config::Config,
214 ) -> Result<()> {
215 // Settings load is a synchronous config read; keep it off the async
216 // worker per the blocking-call convention.
217 let mut settings = tokio::task::spawn_blocking(McpServerSettings::load)
218 .await
219 .context("MCP server settings task failed")??;
220 let sandbox = McpServerSandboxConfig::from_config(config)?;
221 set_active_read_denylist(sandbox.read_denylist.clone());
222 if sandbox.tool_launcher.is_some() {
223 for name in settings.refuse_shell_tools() {
224 eprintln!(
225 "codewhale mcp server: not exposing '{name}': the managed configuration sets \
226 tool_launcher, and this server does not run commands through it."
227 );
228 }
229 }
230 let skills_dir = config.skills_dir();
231 let skills_config = Arc::new(config.skills_config());
232 let server = McpServer::new(workspace, settings, skills_dir, skills_config, sandbox)?;
233 // stdout carries the protocol; the notice goes to stderr so an operator
234 // whose config lists write tools sees why they are missing.
235 for name in server.withheld_tools() {
236 eprintln!(
237 "codewhale mcp server: not exposing '{name}': it writes files or runs \
238 commands and require_approval is on. Set require_approval = false under \
239 [server] in the MCP server config to allow it."
240 );
241 }
242 let (input, output) = rmcp::transport::stdio_pipes();
243 server.run_io(input, output).await
244 }
245
246 struct McpServer {
247 workspace: PathBuf,
248 registry: codewhale_engine::tools::ToolRegistry,
249 exposed_tools: Vec<ExposedTool>,
250 tools: Vec<Tool>,
251 require_approval: bool,
252 initialized: AtomicBool,
253 tool_execution: Mutex<()>,
254 skills_dir: PathBuf,
255 skills_config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>,
256 }
257
258 struct SkillResource {
259 resource: Resource,
260 body: String,
261 }
262
263 impl McpServer {
264 fn new(
265 workspace: PathBuf,
266 settings: McpServerSettings,
267 skills_dir: PathBuf,
268 skills_config: std::sync::Arc<codewhale_runtime::config::SkillsConfig>,
269 sandbox: McpServerSandboxConfig,
270 ) -> Result<Self> {
271 let mut exposed_tools = build_exposed_tools(&settings.expose_tools);
272 if sandbox.tool_launcher.is_some() {
273 exposed_tools.retain(|tool| !is_shell_tool_name(&tool.internal));
274 }
275 let internal_names: HashSet<&str> = exposed_tools
276 .iter()
277 .map(|tool| tool.internal.as_str())
278 .collect();
279 let mut builder = ToolRegistryBuilder::new()
280 .with_file_tools()
281 .with_search_tools();
282 if internal_names.contains("apply_patch") {
283 builder = builder.with_patch_tools();
284 }
285 if sandbox.tool_launcher.is_none()
286 && internal_names.iter().any(|name| is_shell_tool_name(name))
287 {
288 builder = builder.with_foreground_shell_tools();
289 }
290 let shell_manager = new_shared_shell_manager(workspace.clone());
291 match shell_manager.lock() {
292 Ok(mut manager) => {
293 manager.set_prefer_bwrap(sandbox.prefer_bwrap);
294 manager.set_tool_launcher(sandbox.tool_launcher.clone());
295 manager.set_bwrap_extensions(sandbox.bwrap_extensions.clone());
296 manager.set_denied_read_subpaths(sandbox.read_denylist.subtree_paths());
297 }
298 Err(poisoned) => {
299 let mut manager = poisoned.into_inner();
300 manager.set_prefer_bwrap(sandbox.prefer_bwrap);
301 manager.set_tool_launcher(sandbox.tool_launcher.clone());
302 manager.set_bwrap_extensions(sandbox.bwrap_extensions.clone());
303 manager.set_denied_read_subpaths(sandbox.read_denylist.subtree_paths());
304 }
305 }
306 let sandbox_policy = sandbox_policy_for_turn(
307 AppMode::Agent,
308 ApprovalMode::Suggest,
309 sandbox.sandbox_mode.as_deref(),
310 &workspace,
311 SandboxNetworkAccess::from_config(sandbox.sandbox_network_access),
312 );
313 let shell_policy = shell_policy_for_mode(
314 AppMode::Agent,
315 sandbox.tool_launcher.is_none() && !settings.require_approval,
316 );
317 let mut context = ToolContext::new(workspace.clone())
318 .with_skills_config(skills_dir.clone(), skills_config.clone())
319 .with_shell_manager(shell_manager)
320 .with_shell_policy(shell_policy)
321 .with_elevated_sandbox_policy(sandbox_policy);
322 if let Some(backend) = sandbox.sandbox_backend {
323 context = context.with_sandbox_backend(backend);
324 }
325 let registry = builder.build(context);
326 let mut tools = Vec::new();
327 let mut seen = HashSet::new();
328 for entry in &exposed_tools {
329 if !seen.insert(entry.public.clone()) {
330 continue;
331 }
332 if let Some(tool) = registry.get(&entry.internal) {
333 if settings.require_approval && !tool.is_read_only() {
334 continue;
335 }
336 let schema = tool.input_schema();
337 let schema = schema
338 .as_object()
339 .cloned()
340 .context("Invalid native tool schema")?;
341 let mut annotations = ToolAnnotations::new();
342 annotations.read_only_hint = Some(tool.is_read_only());
343 tools.push(
344 Tool::new(entry.public.clone(), tool.description().to_string(), schema)
345 .with_annotations(annotations),
346 );
347 }
348 }
349 Ok(Self {
350 workspace,
351 registry,
352 exposed_tools,
353 tools,
354 require_approval: settings.require_approval,
355 initialized: AtomicBool::new(false),
356 tool_execution: Mutex::new(()),
357 skills_dir,
358 skills_config,
359 })
360 }
361
362 async fn run_io<R, W>(self, input: R, output: W) -> Result<()>
363 where
364 R: AsyncRead + Unpin + Send + 'static,
365 W: AsyncWrite + Unpin + Send + 'static,
366 {
367 let server = Arc::new(self);
368 let transport = AsyncRwTransport::new_server(input, output)
369 .with_max_line_length(codewhale_engine::mcp::MAX_MCP_RESPONSE_BYTES);
370 let service = server
371 .clone()
372 .serve(transport)
373 .await
374 .map_err(|_| anyhow::anyhow!("MCP server protocol setup failed"))?;
375 let outcome = service.waiting().await.context("MCP server task failed");
376 let _drained = server.tool_execution.lock().await;
377 outcome?;
378 Ok(())
379 }
380
381 /// Configured tools that `require_approval` keeps out of `tools/list`.
382 fn withheld_tools(&self) -> Vec<String> {
383 if !self.require_approval {
384 return Vec::new();
385 }
386 let mut seen = HashSet::new();
387 self.exposed_tools
388 .iter()
389 .filter(|entry| seen.insert(entry.public.clone()))
390 .filter(|entry| {
391 self.registry
392 .get(&entry.internal)
393 .is_some_and(|tool| !tool.is_read_only())
394 })
395 .map(|entry| entry.public.clone())
396 .collect()
397 }
398
399 async fn skill_resources(
400 &self,
401 cancel: &CancellationToken,
402 ) -> Result<Vec<SkillResource>, ErrorData> {
403 let workspace = self.workspace.clone();
404 let skills_dir = self.skills_dir.clone();
405 let skills_config = self.skills_config.clone();
406 #[cfg(any(test, feature = "test-support"))]
407 let env_ticket = codewhale_engine::test_support::env_scope_ticket();
408 let discovery = tokio::task::spawn_blocking(move || {
409 #[cfg(any(test, feature = "test-support"))]
410 let _membership = codewhale_engine::test_support::join_env_scope(env_ticket);
411 let registry = codewhale_skills::discover_for_workspace(
412 &workspace,
413 Some(&skills_dir),
414 &skills_config,
415 None,
416 );
417 let mut resources: Vec<_> = registry
418 .list()
419 .iter()
420 .filter(|skill| {
421 matches!(skill.source, SkillSource::Native)
422 && skill.invocation != SkillInvocation::Disabled
423 })
424 .map(|skill| {
425 let uri = format!("codewhale://skills/{}", urlencoding::encode(&skill.name));
426 let description: String = skill
427 .description
428 .chars()
429 .take(codewhale_skills::DEFAULT_SKILL_DESCRIPTION_CHARS)
430 .collect();
431 SkillResource {
432 resource: Resource::new(uri, skill.name.clone())
433 .with_title(format!("{} instructions", skill.name))
434 .with_description(description)
435 .with_mime_type("text/markdown")
436 .with_size(skill.body.len() as u64),
437 body: skill.body.clone(),
438 }
439 })
440 .collect();
441 resources.sort_by(|a, b| a.resource.uri.cmp(&b.resource.uri));
442 resources
443 });
444 tokio::select! {
445 biased;
446 _ = cancel.cancelled() => Err(cancelled_request()),
447 result = discovery => result.map_err(|_| ErrorData::internal_error("Skill discovery failed", None)),
448 }
449 }
450 }
451
452 impl ServerHandler for McpServer {
453 fn get_info(&self) -> ServerConfig {
454 ServerConfig::new(
455 ServerCapabilities::builder()
456 .enable_tools()
457 .enable_resources()
458 .build(),
459 )
460 .with_protocol_version(ProtocolVersion::V_2025_11_25)
461 .with_server_info(Implementation::new(
462 "codewhale-mcp-server",
463 env!("CARGO_PKG_VERSION"),
464 ))
465 }
466
467 fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
468 Cow::Borrowed(SUPPORTED_PROTOCOL_VERSIONS)
469 }
470
471 async fn initialize(
472 &self,
473 request: InitializeRequestParams,
474 context: RequestContext<RoleServer>,
475 ) -> Result<InitializeResult, ErrorData> {
476 if request.client_info.name.trim().is_empty()
477 || request.client_info.version.trim().is_empty()
478 || request.protocol_version.as_str().trim().is_empty()
479 {
480 return Err(ErrorData::invalid_params(
481 "Invalid MCP initialize parameters",
482 None,
483 ));
484 }
485 if self.initialized.swap(true, Ordering::AcqRel) {
486 return Err(ErrorData::invalid_request(
487 "Initialize may only be sent once",
488 None,
489 ));
490 }
491 let result = self.negotiate_initialize(&request)?;
492 context.peer.set_peer_info(request);
493 Ok(result)
494 }
495
496 async fn list_tools(
497 &self,
498 request: Option<PaginatedRequestParams>,
499 _context: RequestContext<RoleServer>,
500 ) -> Result<ListToolsResult, ErrorData> {
501 reject_cursor(request)?;
502 Ok(ListToolsResult::with_all_items(self.tools.clone())
503 .with_ttl_ms(0)
504 .with_cache_scope(CacheScope::Private))
505 }
506
507 fn get_tool(&self, name: &str) -> Option<Tool> {
508 self.tools
509 .iter()
510 .find(|tool| tool.name.as_ref() == name)
511 .cloned()
512 }
513
514 async fn call_tool(
515 &self,
516 request: CallToolRequestParams,
517 context: RequestContext<RoleServer>,
518 ) -> Result<CallToolResponse, ErrorData> {
519 let entry = self
520 .exposed_tools
521 .iter()
522 .find(|tool| tool.public == request.name.as_ref())
523 .ok_or_else(|| ErrorData::invalid_params("Tool not exposed", None))?;
524 let tool = self
525 .registry
526 .get(&entry.internal)
527 .ok_or_else(|| ErrorData::invalid_params("Tool not exposed", None))?;
528 let arguments = Value::Object(request.arguments.unwrap_or_default());
529 // Approval comes from the operator's config, never from the caller:
530 // a request cannot vouch for itself.
531 if self.require_approval && !(tool.is_read_only() && tool.is_read_only_for(&arguments)) {
532 return Err(ErrorData::new(
533 ErrorCode(-32001),
534 "Tool requires approval, which this server cannot request; the operator must explicitly permit it in the MCP server configuration",
535 None,
536 ));
537 }
538 let _execution = tokio::select! {
539 biased;
540 _ = context.ct.cancelled() => return Err(cancelled_request()),
541 guard = self.tool_execution.lock() => guard,
542 };
543 if context.ct.is_cancelled() {
544 return Err(cancelled_request());
545 }
546 let mut tool_context = self.registry.context().clone();
547 tool_context.cancel_token = Some(context.ct.clone());
548 let result = self
549 .registry
550 .execute_rich_full_with_context(&entry.internal, arguments, Some(&tool_context), || {
551 Ok(None)
552 })
553 .await
554 .map(|result| result.into_result());
555 Ok(tool_result_to_mcp(result).into())
556 }
557
558 async fn list_resources(
559 &self,
560 request: Option<PaginatedRequestParams>,
561 context: RequestContext<RoleServer>,
562 ) -> Result<ListResourcesResult, ErrorData> {
563 let resources = self.skill_resources(&context.ct).await?;
564 let start = match request.and_then(|request| request.cursor) {
565 None => 0,
566 Some(cursor) => {
567 let uri = cursor
568 .strip_prefix("v1:")
569 .filter(|_| cursor.len() <= MAX_RESOURCE_CURSOR_BYTES)
570 .ok_or_else(|| ErrorData::invalid_params("Invalid resource cursor", None))?;
571 resources
572 .binary_search_by(|item| item.resource.uri.as_str().cmp(uri))
573 .map(|index| index + 1)
574 .map_err(|_| {
575 ErrorData::invalid_params("Invalid or stale resource cursor", None)
576 })?
577 }
578 };
579 let end = start
580 .saturating_add(RESOURCE_PAGE_SIZE)
581 .min(resources.len());
582 let mut result = ListResourcesResult::with_all_items(
583 resources[start..end]
584 .iter()
585 .map(|item| item.resource.clone())
586 .collect(),
587 )
588 .with_ttl_ms(0)
589 .with_cache_scope(CacheScope::Private);
590 if end < resources.len() {
591 result.next_cursor = Some(format!("v1:{}", resources[end - 1].resource.uri));
592 }
593 bounded_resource_result(result)
594 }
595
596 async fn list_resource_templates(
597 &self,
598 request: Option<PaginatedRequestParams>,
599 _context: RequestContext<RoleServer>,
600 ) -> Result<ListResourceTemplatesResult, ErrorData> {
601 reject_cursor(request)?;
602 Ok(ListResourceTemplatesResult::default()
603 .with_ttl_ms(0)
604 .with_cache_scope(CacheScope::Private))
605 }
606
607 async fn read_resource(
608 &self,
609 request: ReadResourceRequestParams,
610 context: RequestContext<RoleServer>,
611 ) -> Result<ReadResourceResponse, ErrorData> {
612 if request.uri.len() > MAX_RESOURCE_CURSOR_BYTES
613 || !request.uri.starts_with("codewhale://skills/")
614 {
615 return Err(ErrorData::invalid_params("Resource not found", None));
616 }
617 let item = self
618 .skill_resources(&context.ct)
619 .await?
620 .into_iter()
621 .find(|item| item.resource.uri == request.uri)
622 .ok_or_else(|| ErrorData::invalid_params("Resource not found", None))?;
623 if item.body.len() > codewhale_engine::mcp::MAX_MCP_RESPONSE_BYTES {
624 return Err(ErrorData::internal_error(
625 "Skill resource exceeds the response limit",
626 None,
627 ));
628 }
629 let result = ReadResourceResult::new(vec![
630 ResourceContents::text(item.body, item.resource.uri).with_mime_type("text/markdown"),
631 ])
632 .with_ttl_ms(0)
633 .with_cache_scope(CacheScope::Private);
634 Ok(bounded_resource_result(result)?.into())
635 }
636 }
637
638 fn cancelled_request() -> ErrorData {
639 ErrorData::new(ErrorCode(-32800), "Request cancelled", None)
640 }
641
642 fn reject_cursor(request: Option<PaginatedRequestParams>) -> Result<(), ErrorData> {
643 if request.and_then(|request| request.cursor).is_some() {
644 Err(ErrorData::invalid_params("Invalid cursor", None))
645 } else {
646 Ok(())
647 }
648 }
649
650 fn bounded_resource_result<T: Serialize>(result: T) -> Result<T, ErrorData> {
651 let bytes = serde_json::to_vec(&result)
652 .map_err(|_| ErrorData::internal_error("Resource serialization failed", None))?;
653 if bytes.len() > codewhale_engine::mcp::MAX_MCP_RESPONSE_BYTES - 1024 {
654 return Err(ErrorData::internal_error(
655 "Skill resource exceeds the response limit",
656 None,
657 ));
658 }
659 Ok(result)
660 }
661
662 fn default_config_path() -> Option<PathBuf> {
663 codewhale_paths::user_home().map(|home| home.join(".deepseek").join("mcp_server.toml"))
664 }
665
666 /// Read-only by default: writing or executing tools must be named in the
667 /// operator's config and allowed with `require_approval = false`.
668 fn default_expose_tools() -> Vec<String> {
669 vec!["file_read".to_string(), "search".to_string()]
670 }
671
672 fn build_exposed_tools(names: &[String]) -> Vec<ExposedTool> {
673 let mut tools = Vec::new();
674 for name in names {
675 let trimmed = name.trim();
676 if trimmed.is_empty() {
677 continue;
678 }
679 let public = trimmed.to_string();
680 let internal = match trimmed {
681 "file_read" => "read_file",
682 "file_write" => "write_file",
683 "file_edit" => "edit_file",
684 "shell" => "bash",
685 "search" => "grep_files",
686 "file_search" => "file_search",
687 other => other,
688 }
689 .to_string();
690 tools.push(ExposedTool { public, internal });
691 }
692 tools
693 }
694
695 fn tool_result_to_mcp(result: Result<ToolResult, ToolError>) -> CallToolResult {
696 match result {
697 Ok(tool_result) => {
698 let mut response =
699 CallToolResult::success(vec![ContentBlock::text(tool_result.content)]);
700 response.is_error = Some(!tool_result.success);
701 response.structured_content = tool_result.metadata;
702 response
703 }
704 Err(error) => CallToolResult::error(vec![ContentBlock::text(error.to_string())]),
705 }
706 }
707
708 #[cfg(test)]
709 mod tests {
710 use super::*;
711 use serde_json::json;
712 use std::collections::HashMap;
713 use tokio::io::{
714 AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, DuplexStream, ReadHalf, WriteHalf,
715 };
716
717 fn initialize_request() -> Value {
718 json!({
719 "jsonrpc": "2.0", "id": 0, "method": "initialize",
720 "params": {
721 "protocolVersion": "2024-11-05",
722 "clientInfo": {"name": "native-server-test", "version": "1"},
723 "capabilities": {}
724 }
725 })
726 }
727
728 fn test_server(workspace: PathBuf, settings: McpServerSettings) -> McpServer {
729 test_server_with_sandbox(workspace, settings, McpServerSandboxConfig::default())
730 }
731
732 fn test_server_with_sandbox(
733 workspace: PathBuf,
734 settings: McpServerSettings,
735 sandbox: McpServerSandboxConfig,
736 ) -> McpServer {
737 let skills_dir = workspace.join(".fixture-skills");
738 McpServer::new(
739 workspace,
740 settings,
741 skills_dir,
742 std::sync::Arc::new(codewhale_runtime::config::SkillsConfig {
743 scan_codewhale_only: Some(true),
744 ..Default::default()
745 }),
746 sandbox,
747 )
748 .expect("build server")
749 }
750
751 struct Pipe {
752 reader: BufReader<ReadHalf<DuplexStream>>,
753 writer: WriteHalf<DuplexStream>,
754 task: tokio::task::JoinHandle<Result<()>>,
755 }
756
757 impl Pipe {
758 fn new(server: McpServer) -> Self {
759 let (client, server_io) = tokio::io::duplex(8192);
760 let (reader, writer) = tokio::io::split(client);
761 let (input, output) = tokio::io::split(server_io);
762 let task = tokio::spawn(server.run_io(input, output));
763 Self {
764 reader: BufReader::new(reader),
765 writer,
766 task,
767 }
768 }
769
770 async fn send(&mut self, request: Value) {
771 let mut bytes = serde_json::to_vec(&request).unwrap();
772 bytes.push(b'\n');
773 self.writer.write_all(&bytes).await.unwrap();
774 self.writer.flush().await.unwrap();
775 }
776
777 async fn response(&mut self) -> Value {
778 let mut line = String::new();
779 let count = tokio::time::timeout(
780 std::time::Duration::from_secs(5),
781 self.reader.read_line(&mut line),
782 )
783 .await
784 .expect("server response timeout")
785 .unwrap();
786 assert!(count > 0, "server closed before responding");
787 serde_json::from_str(&line).unwrap()
788 }
789
790 async fn request(&mut self, request: Value) -> Value {
791 self.send(request).await;
792 self.response().await
793 }
794
795 async fn finish(self) -> Result<()> {
796 drop(self.writer);
797 drop(self.reader);
798 tokio::time::timeout(std::time::Duration::from_secs(5), self.task)
799 .await
800 .expect("server shutdown timeout")
801 .unwrap()
802 }
803 }
804
805 async fn complete_handshake(pipe: &mut Pipe) {
806 let response = pipe.request(initialize_request()).await;
807 assert_eq!(response["result"]["protocolVersion"], "2024-11-05");
808 pipe.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
809 .await;
810 }
811
812 #[tokio::test]
813 async fn native_server_validates_identity_without_echoing_request_data() {
814 let mut pipe = Pipe::new(test_server(
815 PathBuf::from("."),
816 McpServerSettings {
817 expose_tools: default_expose_tools(),
818 require_approval: true,
819 },
820 ));
821 complete_handshake(&mut pipe).await;
822 for request in [
823 json!([]),
824 Value::Null,
825 json!({"method": "ping"}),
826 json!({"jsonrpc": "2", "id": 1, "method": "ping"}),
827 json!({"jsonrpc": "2.0", "id": true, "method": "ping"}),
828 json!({"jsonrpc": "2.0", "id": 1.5, "method": "ping"}),
829 json!({"jsonrpc": "2.0", "id": 1, "method": 7}),
830 json!({"jsonrpc": "2.0", "id": null, "method": "ping"}),
831 json!({"jsonrpc": "2.0", "id": 1, "method": "ping", "params": "PRIVATE_TOKEN=sentinel"}),
832 ] {
833 let response = pipe.request(request).await;
834 assert!(response["id"].is_null(), "{response}");
835 assert_eq!(response["error"]["code"], -32600, "{response}");
836 assert!(!response.to_string().contains("PRIVATE_TOKEN"));
837 assert!(!response.to_string().contains("sentinel"));
838 }
839 let response = pipe
840 .request(json!({"jsonrpc": "2.0", "id": 2, "method": "ping"}))
841 .await;
842 assert_eq!(response["result"], json!({}));
843 pipe.finish().await.unwrap();
844 }
845
846 #[tokio::test]
847 async fn native_server_requires_valid_lifecycle_before_any_tool_effect() {
848 let workspace = tempfile::tempdir().unwrap();
849 let mut pipe = Pipe::new(test_server(
850 workspace.path().to_path_buf(),
851 McpServerSettings {
852 expose_tools: vec!["file_write".into()],
853 require_approval: false,
854 },
855 ));
856 let write = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {
857 "name": "file_write", "arguments": {"path": "canary.txt", "content": "written"}
858 }});
859 let response = pipe.request(write.clone()).await;
860 assert!(response.get("error").is_some(), "{response}");
861 assert!(!workspace.path().join("canary.txt").exists());
862 let mut null_id = initialize_request();
863 null_id["id"] = Value::Null;
864 assert_eq!(pipe.request(null_id).await["error"]["code"], -32600);
865 assert!(pipe.request(write.clone()).await.get("error").is_some());
866 assert!(!workspace.path().join("canary.txt").exists());
867 let response = pipe.request(initialize_request()).await;
868 assert_eq!(response["result"]["protocolVersion"], "2024-11-05");
869 assert_eq!(
870 pipe.request(initialize_request()).await["error"]["code"],
871 -32600
872 );
873 let mut unacknowledged = write.clone();
874 unacknowledged.as_object_mut().unwrap().remove("id");
875 pipe.send(unacknowledged).await;
876 let response = pipe
877 .request(json!({"jsonrpc": "2.0", "id": 3, "method": "ping"}))
878 .await;
879 assert_eq!(response["id"], 3);
880 assert!(!workspace.path().join("canary.txt").exists());
881 let response = pipe.request(write).await;
882 assert!(response.get("error").is_none(), "{response}");
883 assert_eq!(
884 std::fs::read_to_string(workspace.path().join("canary.txt")).unwrap(),
885 "written"
886 );
887 pipe.send(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))
888 .await;
889 pipe.finish().await.unwrap();
890 }
891
892 async fn run_native_pipe(input: &[u8], expected_responses: usize) -> (Result<()>, Vec<u8>) {
893 let mut pipe = Pipe::new(test_server(
894 PathBuf::from("."),
895 McpServerSettings {
896 expose_tools: default_expose_tools(),
897 require_approval: true,
898 },
899 ));
900 complete_handshake(&mut pipe).await;
901 let mut output = Vec::new();
902 tokio::time::timeout(std::time::Duration::from_secs(5), async {
903 pipe.writer.write_all(input).await.unwrap();
904 pipe.writer.flush().await.unwrap();
905 for _ in 0..expected_responses {
906 let response = pipe.response().await;
907 output.extend(serde_json::to_vec(&response).unwrap());
908 output.push(b'\n');
909 }
910 pipe.writer.shutdown().await.unwrap();
911 pipe.reader.read_to_end(&mut output).await.unwrap();
912 })
913 .await
914 .expect("the bounded server pipe must settle");
915 (pipe.finish().await, output)
916 }
917
918 #[tokio::test]
919 async fn native_pipe_discards_invalid_json_and_preserves_the_following_frame() {
920 let (result, output) = run_native_pipe(b"{\"PRIVATE_TOKEN\":\"sentinel\",\n{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"ping\"}\n", 1).await;
921 result.unwrap();
922 let text = String::from_utf8(output).unwrap();
923 assert!(!text.contains("PRIVATE_TOKEN"));
924 assert!(!text.contains("sentinel"));
925 let responses: Vec<Value> = text
926 .lines()
927 .map(|line| serde_json::from_str(line).unwrap())
928 .collect();
929 assert_eq!(responses.len(), 1);
930 assert_eq!(responses[0]["id"], 7);
931 assert_eq!(responses[0]["result"], json!({}));
932 }
933
934 #[tokio::test]
935 async fn native_pipe_refuses_oversized_unterminated_input() {
936 let input = vec![b'x'; codewhale_engine::mcp::MAX_MCP_RESPONSE_BYTES + 8192];
937 let (result, output) = run_native_pipe(&input, 0).await;
938 result.unwrap();
939 assert!(output.is_empty());
940 }
941
942 #[test]
943 fn exposed_tools_map_aliases() {
944 let names = vec![
945 "file_read".to_string(),
946 "file_write".to_string(),
947 "search".to_string(),
948 "apply_patch".to_string(),
949 "shell".to_string(),
950 ];
951 let mut map = HashMap::new();
952 for tool in build_exposed_tools(&names) {
953 map.insert(tool.public, tool.internal);
954 }
955 assert_eq!(map.get("file_read").map(String::as_str), Some("read_file"));
956 assert_eq!(
957 map.get("file_write").map(String::as_str),
958 Some("write_file")
959 );
960 assert_eq!(map.get("search").map(String::as_str), Some("grep_files"));
961 assert_eq!(
962 map.get("apply_patch").map(String::as_str),
963 Some("apply_patch")
964 );
965 assert_eq!(map.get("shell").map(String::as_str), Some("bash"));
966 }
967
968 #[tokio::test]
969 async fn list_responses_omit_null_next_cursor() {
970 let _home = codewhale_engine::test_support::SealedHome::new();
971 let root = tempfile::tempdir().unwrap();
972 let workspace = root.path().join("workspace");
973 let skills_dir = root.path().join("skills");
974 std::fs::create_dir_all(&workspace).unwrap();
975 for index in 0..125 {
976 let name = format!("skill-{index:03}");
977 let path = skills_dir.join(&name);
978 std::fs::create_dir_all(&path).unwrap();
979 std::fs::write(
980 path.join("SKILL.md"),
981 format!(
982 "---\nname: {name}\ndescription: Fixture instructions\n---\nbody-{index}\n"
983 ),
984 )
985 .unwrap();
986 }
987 let server = McpServer::new(
988 workspace,
989 McpServerSettings {
990 expose_tools: vec!["file_read".into(), "apply_patch".into()],
991 require_approval: false,
992 },
993 skills_dir,
994 std::sync::Arc::new(codewhale_runtime::config::SkillsConfig {
995 scan_codewhale_only: Some(true),
996 ..Default::default()
997 }),
998 McpServerSandboxConfig::default(),
999 )
1000 .unwrap();
1001 let mut pipe = Pipe::new(server);
1002 complete_handshake(&mut pipe).await;
1003 let tools = pipe
1004 .request(json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
1005 .await;
1006 assert!(tools["result"]["tools"].is_array());
1007 assert!(tools["result"].get("nextCursor").is_none());
1008 let first = pipe
1009 .request(json!({"jsonrpc":"2.0","id":2,"method":"resources/list"}))
1010 .await;
1011 assert_eq!(
1012 first["result"]["resources"].as_array().unwrap().len(),
1013 RESOURCE_PAGE_SIZE
1014 );
1015 let cursor = first["result"]["nextCursor"].as_str().unwrap();
1016 let second = pipe.request(json!({"jsonrpc":"2.0","id":3,"method":"resources/list","params":{"cursor":cursor}})).await;
1017 assert_eq!(second["result"]["resources"].as_array().unwrap().len(), 25);
1018 assert!(second["result"].get("nextCursor").is_none());
1019 let uri = first["result"]["resources"][0]["uri"].as_str().unwrap();
1020 let body = pipe
1021 .request(json!({"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":uri}}))
1022 .await;
1023 assert_eq!(body["result"]["contents"][0]["uri"], uri);
1024 assert_eq!(body["result"]["contents"][0]["mimeType"], "text/markdown");
1025 assert_eq!(
1026 body["result"]["contents"][0]["text"]
1027 .as_str()
1028 .unwrap()
1029 .trim(),
1030 "body-0"
1031 );
1032 let invalid = pipe.request(json!({"jsonrpc":"2.0","id":5,"method":"resources/read","params":{"uri":"file:///etc/passwd"}})).await;
1033 assert_eq!(invalid["error"]["code"], -32602);
1034 let invalid = pipe.request(json!({"jsonrpc":"2.0","id":6,"method":"resources/list","params":{"cursor":"invalid"}})).await;
1035 assert_eq!(invalid["error"]["code"], -32602);
1036 pipe.finish().await.unwrap();
1037 }
1038
1039 #[tokio::test]
1040 async fn retired_deepseek_tools_are_not_exposed() {
1041 let server = test_server(
1042 PathBuf::from("."),
1043 McpServerSettings {
1044 expose_tools: vec!["deepseek".into(), "deepseek-reply".into()],
1045 require_approval: false,
1046 },
1047 );
1048 assert!(server.tools.is_empty());
1049 let mut pipe = Pipe::new(server);
1050 complete_handshake(&mut pipe).await;
1051 let response = pipe
1052 .request(
1053 json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
1054 "name":"deepseek","arguments":{"prompt":"hi"}
1055 }}),
1056 )
1057 .await;
1058 assert_eq!(response["error"]["code"], -32602, "{response}");
1059 pipe.finish().await.unwrap();
1060 }
1061
1062 #[test]
1063 fn default_settings_expose_only_read_only_tools() {
1064 assert_eq!(default_expose_tools(), vec!["file_read", "search"]);
1065 let server = test_server(
1066 PathBuf::from("."),
1067 McpServerSettings {
1068 expose_tools: default_expose_tools(),
1069 require_approval: true,
1070 },
1071 );
1072 let names: Vec<&str> = server.tools.iter().map(|tool| tool.name.as_ref()).collect();
1073 assert_eq!(names, vec!["file_read", "search"]);
1074 assert!(
1075 server
1076 .tools
1077 .iter()
1078 .all(|tool| tool.annotations.as_ref().unwrap().read_only_hint == Some(true))
1079 );
1080 }
1081
1082 #[test]
1083 fn a_tool_launcher_refuses_shell_tools_even_when_the_operator_allows_them() {
1084 let mut settings = McpServerSettings::from_toml(
1085 "[server]\nexpose_tools = [\"file_read\", \"shell\", \"exec_shell\", \"bash\", \"Bash\", \"terminal_run\"]\nrequire_approval = false\n",
1086 )
1087 .expect("parse config");
1088 assert_eq!(
1089 settings.refuse_shell_tools(),
1090 vec!["shell", "exec_shell", "bash", "terminal_run"]
1091 );
1092 let server = test_server(PathBuf::from("."), settings);
1093 let names: Vec<&str> = server.tools.iter().map(|tool| tool.name.as_ref()).collect();
1094 assert_eq!(names, vec!["file_read"]);
1095 for internal in ["exec_shell", "Bash", "bash", TERMINAL_RUN_NAME] {
1096 assert!(server.registry.get(internal).is_none(), "{internal}");
1097 }
1098 }
1099
1100 #[test]
1101 fn tool_launcher_blocks_shell_tools_even_in_direct_constructor() {
1102 let mut config = codewhale_runtime::config::Config::default();
1103 config.tool_launcher = Some(vec!["/usr/bin/sudo".into(), "-n".into()]);
1104 let sandbox = McpServerSandboxConfig::from_config(&config).expect("sandbox config");
1105 let server = test_server_with_sandbox(
1106 PathBuf::from("."),
1107 McpServerSettings {
1108 expose_tools: vec![
1109 "file_read".into(),
1110 "shell".into(),
1111 "bash".into(),
1112 "Bash".into(),
1113 "terminal_run".into(),
1114 ],
1115 require_approval: false,
1116 },
1117 sandbox,
1118 );
1119 let names: Vec<&str> = server.tools.iter().map(|tool| tool.name.as_ref()).collect();
1120 assert_eq!(names, vec!["file_read"]);
1121 assert_eq!(
1122 server.registry.context().shell_policy,
1123 codewhale_agent_contract::worker_profile::ShellPolicy::None
1124 );
1125 for internal in ["exec_shell", "Bash", "bash", TERMINAL_RUN_NAME] {
1126 assert!(server.registry.get(internal).is_none(), "{internal}");
1127 }
1128 }
1129
1130 #[tokio::test]
1131 async fn mcp_server_wires_sandbox_policy_and_external_backend_into_tool_context() {
1132 let workspace = tempfile::tempdir().unwrap();
1133 let mut config = codewhale_runtime::config::Config::default();
1134 config.sandbox_mode = Some("read-only".into());
1135 config.prefer_bwrap = Some(true);
1136 config.sandbox_backend = Some("unsupported-test-backend".into());
1137 let sandbox = McpServerSandboxConfig::from_config(&config).expect("sandbox config");
1138 let server = test_server_with_sandbox(
1139 workspace.path().to_path_buf(),
1140 McpServerSettings {
1141 expose_tools: vec!["file_read".into(), "bash".into()],
1142 require_approval: false,
1143 },
1144 sandbox,
1145 );
1146 let ctx = server.registry.context();
1147 assert_eq!(
1148 ctx.elevated_sandbox_policy,
1149 Some(codewhale_sandbox::SandboxPolicy::read_only())
1150 );
1151 let backend = ctx
1152 .sandbox_backend
1153 .as_ref()
1154 .expect("external sandbox backend must be attached");
1155 assert_eq!(
1156 backend.kind(),
1157 codewhale_sandbox::backend::SandboxKind::Unsupported
1158 );
1159 let mut pipe = Pipe::new(server);
1160 complete_handshake(&mut pipe).await;
1161 let response = pipe
1162 .request(json!({
1163 "jsonrpc": "2.0",
1164 "id": 1,
1165 "method": "tools/call",
1166 "params": {"name": "bash", "arguments": {"command": "echo bad > must-not-exist.txt"}}
1167 }))
1168 .await;
1169 assert_eq!(response["result"]["isError"], json!(true), "{response}");
1170 assert!(
1171 response.to_string().contains("external sandbox backend")
1172 || response.to_string().contains("Unsupported sandbox_backend"),
1173 "{response}"
1174 );
1175 assert!(!workspace.path().join("must-not-exist.txt").exists());
1176 pipe.finish().await.unwrap();
1177 }
1178
1179 #[test]
1180 fn configured_read_denylist_blocks_mcp_file_read_and_search() {
1181 let workspace = tempfile::tempdir().unwrap();
1182 let denied = workspace.path().join("secret.txt");
1183 let allowed = workspace.path().join("public.txt");
1184 std::fs::write(&denied, "TOP_SECRET_CANARY_VALUE").unwrap();
1185 std::fs::write(&allowed, "PUBLIC_ALLOWED_VALUE").unwrap();
1186 let mut config = codewhale_runtime::config::Config::default();
1187 config.sandbox_denied_read_paths = vec![denied.clone()];
1188 let sandbox = McpServerSandboxConfig::from_config(&config).expect("sandbox config");
1189 let denylist = sandbox.read_denylist.clone();
1190 codewhale_sandbox::read_guard::with_test_active_denylist(denylist, || {
1191 let rt = tokio::runtime::Builder::new_current_thread()
1192 .enable_all()
1193 .build()
1194 .unwrap();
1195 rt.block_on(async {
1196 let server = test_server_with_sandbox(
1197 workspace.path().to_path_buf(),
1198 McpServerSettings {
1199 expose_tools: default_expose_tools(),
1200 require_approval: true,
1201 },
1202 sandbox,
1203 );
1204 let mut pipe = Pipe::new(server);
1205 complete_handshake(&mut pipe).await;
1206 let denied_read = pipe
1207 .request(json!({
1208 "jsonrpc": "2.0",
1209 "id": 1,
1210 "method": "tools/call",
1211 "params": {"name": "file_read", "arguments": {"path": "secret.txt"}}
1212 }))
1213 .await;
1214 assert_eq!(
1215 denied_read["result"]["isError"],
1216 json!(true),
1217 "{denied_read}"
1218 );
1219 assert!(
1220 !denied_read.to_string().contains("TOP_SECRET_CANARY_VALUE"),
1221 "{denied_read}"
1222 );
1223 let search = pipe
1224 .request(json!({
1225 "jsonrpc": "2.0",
1226 "id": 2,
1227 "method": "tools/call",
1228 "params": {"name": "search", "arguments": {"pattern": "TOP_SECRET_CANARY_VALUE"}}
1229 }))
1230 .await;
1231 assert!(
1232 !search.to_string().contains("TOP_SECRET_CANARY_VALUE"),
1233 "{search}"
1234 );
1235 let allowed_read = pipe
1236 .request(json!({
1237 "jsonrpc": "2.0",
1238 "id": 3,
1239 "method": "tools/call",
1240 "params": {"name": "file_read", "arguments": {"path": "public.txt"}}
1241 }))
1242 .await;
1243 assert_eq!(
1244 allowed_read["result"]["isError"],
1245 json!(false),
1246 "{allowed_read}"
1247 );
1248 assert!(
1249 allowed_read.to_string().contains("PUBLIC_ALLOWED_VALUE"),
1250 "{allowed_read}"
1251 );
1252 pipe.finish().await.unwrap();
1253 });
1254 });
1255 }
1256
1257 #[test]
1258 fn existing_config_without_require_approval_withholds_and_names_write_tools() {
1259 let settings = McpServerSettings::from_toml(
1260 "[server]\nexpose_tools = [\"file_read\", \"file_write\", \"apply_patch\"]\n",
1261 )
1262 .expect("parse config");
1263 assert!(settings.require_approval);
1264 let server = test_server(PathBuf::from("."), settings);
1265 assert_eq!(server.withheld_tools(), vec!["file_write", "apply_patch"]);
1266 let allowed = McpServerSettings::from_toml(
1267 "[server]\nexpose_tools = [\"file_write\"]\nrequire_approval = false\n",
1268 )
1269 .expect("parse config");
1270 assert!(
1271 test_server(PathBuf::from("."), allowed)
1272 .withheld_tools()
1273 .is_empty()
1274 );
1275 }
1276
1277 #[tokio::test]
1278 async fn caller_cannot_self_approve_write_tools() {
1279 let workspace = tempfile::tempdir().unwrap();
1280 let canary = workspace.path().join("canary.txt");
1281 let server = test_server(
1282 workspace.path().to_path_buf(),
1283 McpServerSettings {
1284 expose_tools: vec![
1285 "file_read".into(),
1286 "file_write".into(),
1287 "apply_patch".into(),
1288 ],
1289 require_approval: true,
1290 },
1291 );
1292 let names: Vec<&str> = server.tools.iter().map(|tool| tool.name.as_ref()).collect();
1293 assert_eq!(names, vec!["file_read"]);
1294 let mut pipe = Pipe::new(server);
1295 complete_handshake(&mut pipe).await;
1296 for (name, arguments) in [
1297 ("file_write", json!({"path":"canary.txt","content":"x"})),
1298 (
1299 "apply_patch",
1300 json!({"patch":"--- /dev/null\n+++ b/canary.txt\n@@ -0,0 +1 @@\n+x\n"}),
1301 ),
1302 ] {
1303 let response = pipe
1304 .request(
1305 json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
1306 "name":name,"approved":true,"arguments":arguments
1307 }}),
1308 )
1309 .await;
1310 assert_eq!(response["error"]["code"], -32001, "{name}: {response}");
1311 assert!(!canary.exists());
1312 }
1313 pipe.finish().await.unwrap();
1314 }
1315
1316 #[tokio::test]
1317 async fn operator_config_can_allow_write_tools() {
1318 let workspace = tempfile::tempdir().unwrap();
1319 let mut pipe = Pipe::new(test_server(
1320 workspace.path().to_path_buf(),
1321 McpServerSettings {
1322 expose_tools: vec!["file_write".into()],
1323 require_approval: false,
1324 },
1325 ));
1326 complete_handshake(&mut pipe).await;
1327 let response = pipe
1328 .request(
1329 json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{
1330 "name":"file_write","arguments":{"path":"allowed.txt","content":"x"}
1331 }}),
1332 )
1333 .await;
1334 assert!(response.get("error").is_none(), "{response}");
1335 assert!(workspace.path().join("allowed.txt").exists(), "{response}");
1336 pipe.finish().await.unwrap();
1337 }
1338
1339 #[tokio::test]
1340 async fn initialize_uses_standard_mcp_shape_and_codewhale_identity() {
1341 let settings = McpServerSettings {
1342 expose_tools: default_expose_tools(),
1343 require_approval: true,
1344 };
1345 let mut pipe = Pipe::new(test_server(PathBuf::from("."), settings.clone()));
1346 let response = pipe.request(initialize_request()).await;
1347 assert_eq!(response["result"]["protocolVersion"], "2024-11-05");
1348 assert_eq!(
1349 response["result"]["serverInfo"]["name"],
1350 "codewhale-mcp-server"
1351 );
1352 assert_eq!(
1353 response["result"]["serverInfo"]["version"],
1354 env!("CARGO_PKG_VERSION")
1355 );
1356 assert_eq!(
1357 response["result"]["capabilities"],
1358 json!({"tools":{},"resources":{}})
1359 );
1360 pipe.finish().await.unwrap();
1361 let mut pipe = Pipe::new(test_server(PathBuf::from("."), settings));
1362 let mut malformed = initialize_request();
1363 malformed["params"]["clientInfo"]["name"] = json!("");
1364 let response = pipe.request(malformed).await;
1365 assert_eq!(response["error"]["code"], -32602);
1366 assert!(pipe.finish().await.is_err());
1367 }
1368
1369 #[tokio::test]
1370 async fn initialize_negotiates_supported_revisions() {
1371 let settings = McpServerSettings {
1372 expose_tools: default_expose_tools(),
1373 require_approval: true,
1374 };
1375 for requested in [
1376 "2024-11-05",
1377 "2025-03-26",
1378 "2025-06-18",
1379 "2025-11-25",
1380 "2026-07-28",
1381 "2099-01-01",
1382 ] {
1383 let mut pipe = Pipe::new(test_server(PathBuf::from("."), settings.clone()));
1384 let mut request = initialize_request();
1385 request["params"]["protocolVersion"] = json!(requested);
1386 let response = pipe.request(request).await;
1387 let expected = if requested < "2026-07-28" {
1388 requested
1389 } else {
1390 "2025-11-25"
1391 };
1392 assert_eq!(response["result"]["protocolVersion"], expected);
1393 pipe.finish().await.unwrap();
1394 }
1395 let meta = json!({
1396 "io.modelcontextprotocol/protocolVersion":"2026-07-28",
1397 "io.modelcontextprotocol/clientInfo":{"name":"modern-test","version":"1"},
1398 "io.modelcontextprotocol/clientCapabilities":{}
1399 });
1400 for discover_first in [false, true] {
1401 let mut pipe = Pipe::new(test_server(PathBuf::from("."), settings.clone()));
1402 if discover_first {
1403 let discovery = pipe.request(json!({"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":meta}})).await;
1404 assert_eq!(discovery["result"]["resultType"], "complete");
1405 assert_eq!(
1406 discovery["result"]["capabilities"],
1407 json!({"tools":{},"resources":{}})
1408 );
1409 assert!(
1410 discovery["result"]["supportedVersions"]
1411 .as_array()
1412 .unwrap()
1413 .contains(&json!("2026-07-28"))
1414 );
1415 }
1416 let tools = pipe
1417 .request(
1418 json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{"_meta":meta}}),
1419 )
1420 .await;
1421 assert_eq!(tools["result"]["resultType"], "complete");
1422 assert_eq!(tools["result"]["ttlMs"], 0);
1423 assert_eq!(tools["result"]["cacheScope"], "private");
1424 let missing = pipe
1425 .request(json!({"jsonrpc":"2.0","id":3,"method":"tools/list"}))
1426 .await;
1427 assert_eq!(missing["error"]["code"], -32602);
1428 pipe.finish().await.unwrap();
1429 }
1430 }
1431
1432 #[test]
1433 fn load_from_path_rejects_oversized_config_file() {
1434 let dir = tempfile::tempdir().unwrap();
1435 let missing = dir.path().join("missing.toml");
1436 let defaults = McpServerSettings::load_from_path(Some(&missing)).expect("missing defaults");
1437 assert!(defaults.require_approval);
1438
1439 let oversized = dir.path().join("mcp_server.toml");
1440 let cap = codewhale_engine::mcp::MAX_MCP_CONFIG_BYTES as usize;
1441 std::fs::write(&oversized, format!("# {}\n", "a".repeat(cap + 16))).unwrap();
1442 let err = McpServerSettings::load_from_path(Some(&oversized))
1443 .expect_err("oversized config must be rejected");
1444 assert!(err.to_string().contains("exceeds the 1 MiB limit"), "{err}");
1445 }
1446 }
1447
1447 lines RUST