返回 CodeWhale
mcp.rs
1 //! The pinned SDK owns MCP framing; Rust owns every process/network operation.
2 //! The selected Host backend immediately adopts proc/* and FetchProxy sessions.
3 use crate::mcp::McpServerConfigExt;
4 use std::collections::HashMap;
5 use std::sync::{Arc, Mutex};
6 use std::time::{Duration, Instant};
7
8 use anyhow::{Context, Result, bail};
9 use codewhale_config::OwnerRef;
10 use serde_json::{Value, json};
11 use tokio::io::BufReader;
12 use tokio::sync::{Mutex as AsyncMutex, mpsc};
13 use tokio_util::sync::CancellationToken;
14
15 use super::protocol::*;
16 use super::registry::OwnerState;
17 use super::supervisor::{HostProcess, HostRequestContext};
18 use super::ticket::{Grant, Presented, Ticket, TicketKind};
19 use super::tier::HostCohort;
20 use super::{ExtensionHostManager, ManagerShared};
21 use crate::core::engine::HumanDecision;
22 use crate::mcp::process_broker::BrokerSession;
23 use crate::mcp::{MAX_MCP_RESPONSE_BYTES, McpPool};
24 use codewhale_mcp::config::McpServerConfig;
25
26 const MAX_SESSIONS: usize = 64;
27 const MAX_PENDING: usize = 256;
28 const MAX_DEADLINE: Duration = Duration::from_secs(86_400);
29 const SUPPORTED_METHODS: &[&str] = &[
30 "server/discover",
31 "initialize",
32 "notifications/initialized",
33 "tools/list",
34 "resources/list",
35 "resources/templates/list",
36 "prompts/list",
37 "tools/call",
38 "resources/read",
39 "prompts/get",
40 "skills/list",
41 "skills/get",
42 ];
43
44 #[derive(Clone)]
45 struct Operation {
46 target: Value,
47 ticket: Ticket,
48 expires: Instant,
49 decision: Option<HumanDecision>,
50 }
51 struct BoundRequest {
52 operation_id: String,
53 method: String,
54 }
55
56 /// No launch command, environment mapping, credential or decision key is wire data.
57 struct Session {
58 session_id: String,
59 owner: OwnerRef,
60 host_generation: u64,
61 name: String,
62 config: McpServerConfig,
63 auth_context: Arc<dyn codewhale_runtime::credentials::AuthContext>,
64 cancel: CancellationToken,
65 broker: AsyncMutex<Option<BrokerSession>>,
66 frames: AsyncMutex<mpsc::Receiver<Value>>,
67 frame_sender: mpsc::Sender<Value>,
68 operations: Mutex<HashMap<String, Operation>>,
69 pending: Mutex<HashMap<String, BoundRequest>>,
70 replies: Mutex<HashMap<String, Value>>,
71 server_requests: Mutex<HashMap<String, String>>,
72 decision_key: Mutex<Option<[u8; 32]>>,
73 protocol_version: Mutex<Option<String>>,
74 legacy_allowed: std::sync::atomic::AtomicBool,
75 list_changed: std::sync::atomic::AtomicBool,
76 launched: Mutex<bool>,
77 launch_ticket: Mutex<Option<Ticket>>,
78 http: Option<http::HttpSession>,
79 }
80 fn modern_metadata() -> Value {
81 json!({
82 "io.modelcontextprotocol/protocolVersion": crate::mcp::MCP_MODERN_PROTOCOL_VERSION,
83 "io.modelcontextprotocol/clientInfo": {"name": "codewhale-tui", "version": env!("CARGO_PKG_VERSION")},
84 "io.modelcontextprotocol/clientCapabilities": {}
85 })
86 }
87 impl Session {
88 fn modern(&self) -> bool {
89 self.protocol_version
90 .lock()
91 .expect("MCP protocol lock")
92 .as_deref()
93 == Some(crate::mcp::MCP_MODERN_PROTOCOL_VERSION)
94 }
95 fn validate(&self, shared: &ManagerShared, generation: u64, owner: &OwnerRef) -> Result<()> {
96 if self.cancel.is_cancelled() || generation != self.host_generation || owner != &self.owner
97 {
98 bail!("MCP broker session is stale or closed");
99 }
100 if shared
101 .builtin
102 .host_generation
103 .load(std::sync::atomic::Ordering::SeqCst)
104 != generation
105 {
106 bail!("MCP broker host generation is stale");
107 }
108 shared
109 .live_owner_authority(HostCohort::Builtin, |registry| {
110 registry
111 .owner(&owner.plugin_id)
112 .filter(|entry| entry.owner == *owner && entry.state == OwnerState::Active)
113 .map(|entry| entry.owner.clone())
114 .ok_or_else(|| "MCP builtin owner is no longer live".to_string())
115 })
116 .map_err(anyhow::Error::msg)?;
117 if let Some(source) = self.config.reviewed_plugin_source() {
118 source.validate_before_use(&self.name, "broker operation")?;
119 }
120 Ok(())
121 }
122 fn target(
123 &self,
124 operation_id: &str,
125 method: &str,
126 params: &Value,
127 wire_id: Option<&str>,
128 ) -> Value {
129 json!({"session_id": self.id(), "operation_id": operation_id, "method": method, "params": params, "wire_id": wire_id})
130 }
131 fn observe(&self, frame: &Value) -> Result<()> {
132 if frame.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
133 bail!("invalid MCP server frame");
134 }
135 if frame.get("id").is_none()
136 && frame["method"]
137 .as_str()
138 .is_some_and(crate::mcp::is_mcp_list_changed_method)
139 {
140 self.list_changed
141 .store(true, std::sync::atomic::Ordering::SeqCst);
142 }
143 if let Some(id) = frame.get("id") {
144 let id = wire_id(id)?;
145 if frame.get("method").is_some() {
146 let mut requests = self
147 .server_requests
148 .lock()
149 .expect("MCP server request lock");
150 if requests.len() >= MAX_PENDING || requests.contains_key(&id) {
151 bail!("MCP server request bound exceeded");
152 }
153 requests.insert(
154 id,
155 frame["method"]
156 .as_str()
157 .context("invalid MCP method")?
158 .to_string(),
159 );
160 } else if let Some(binding) = self.pending.lock().expect("MCP pending lock").remove(&id)
161 {
162 if binding.method == "server/discover" {
163 let error = &frame["error"];
164 let legacy = if let Some(result) = frame.get("result") {
165 !result["supportedVersions"]
166 .as_array()
167 .is_some_and(|versions| {
168 versions.iter().any(|version| {
169 version == crate::mcp::MCP_MODERN_PROTOCOL_VERSION
170 })
171 })
172 } else {
173 error["code"] != -32022
174 || (error["code"] == -32022
175 && error["data"]["supported"]
176 .as_array()
177 .is_some_and(|versions| {
178 !versions.is_empty()
179 && versions.iter().all(|version| {
180 version.as_str().is_some_and(|version| {
181 version != crate::mcp::MCP_MODERN_PROTOCOL_VERSION
182 && crate::mcp::MCP_CLIENT_ACCEPTED_PROTOCOL_VERSIONS
183 .contains(&version)
184 })
185 })
186 }))
187 };
188 if legacy {
189 self.legacy_allowed
190 .store(true, std::sync::atomic::Ordering::SeqCst);
191 }
192 }
193 let mut replies = self.replies.lock().expect("MCP reply lock");
194 if replies.len() >= MAX_PENDING || replies.contains_key(&binding.operation_id) {
195 bail!("MCP reply bound exceeded");
196 }
197 replies.insert(binding.operation_id, frame.clone());
198 }
199 }
200 Ok(())
201 }
202 fn cancel(&self) {
203 self.cancel.cancel();
204 if let Some(http) = &self.http {
205 http.close();
206 }
207 }
208 fn id(&self) -> &str {
209 &self.session_id
210 }
211 }
212
213 #[derive(Default)]
214 pub(super) struct Broker {
215 sessions: Mutex<HashMap<String, Arc<Session>>>,
216 }
217 impl Drop for Broker {
218 fn drop(&mut self) {
219 for session in self.sessions.get_mut().expect("MCP broker lock").values() {
220 session.cancel();
221 }
222 }
223 }
224 impl Broker {
225 pub(super) fn revoke_owner(&self, owner: &str) -> u64 {
226 let mut sessions = self.sessions.lock().expect("MCP broker lock");
227 let before = sessions.len();
228 sessions.retain(|_, session| {
229 if session.owner.plugin_id == owner {
230 session.cancel();
231 false
232 } else {
233 true
234 }
235 });
236 (before - sessions.len()) as u64
237 }
238 pub(super) fn revoke_host(&self, cohort: &HostCohort, generation: u64) -> u64 {
239 if !cohort.is_builtin() {
240 return 0;
241 }
242 let mut sessions = self.sessions.lock().expect("MCP broker lock");
243 let before = sessions.len();
244 sessions.retain(|_, session| {
245 if session.host_generation == generation {
246 session.cancel();
247 false
248 } else {
249 true
250 }
251 });
252 (before - sessions.len()) as u64
253 }
254 fn session(&self, id: &str) -> Result<Arc<Session>> {
255 self.sessions
256 .lock()
257 .expect("MCP broker lock")
258 .get(id)
259 .cloned()
260 .context("MCP broker session is closed")
261 }
262 fn remove(&self, shared: &ManagerShared, id: &str) -> Option<Arc<Session>> {
263 let session = self.sessions.lock().expect("MCP broker lock").remove(id)?;
264 session.cancel();
265 for operation in session
266 .operations
267 .lock()
268 .expect("MCP operation lock")
269 .drain()
270 .map(|(_, v)| v)
271 {
272 shared.core_calls.tickets.revoke(&operation.ticket);
273 }
274 if let Some(ticket) = session
275 .launch_ticket
276 .lock()
277 .expect("MCP launch ticket lock")
278 .take()
279 {
280 shared.core_calls.tickets.revoke(&ticket);
281 }
282 shared
283 .mcp_users
284 .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
285 Some(session)
286 }
287 pub(super) async fn serve(
288 &self,
289 shared: &ManagerShared,
290 generation: u64,
291 request: HostRequest,
292 cx: HostRequestContext,
293 ) -> Result<Value, RpcErrorWire> {
294 let launch = matches!(request, HostRequest::ProcLaunch(_));
295 let run = async {
296 match request {
297 request @ (HostRequest::NetStart(_)
298 | HostRequest::NetFetch(_)
299 | HostRequest::NetRead(_)
300 | HostRequest::NetRelease(_)
301 | HostRequest::NetClose(_)) => {
302 http::serve(self, shared, generation, request, &cx).await
303 }
304 HostRequest::ProcLaunch(params) => {
305 self.launch(shared, generation, params, &cx).await
306 }
307 HostRequest::ProcRead(params) => {
308 let session = self.session(&params.session_id)?;
309 session.validate(shared, generation, &params.owner)?;
310 let mut receiver = session.frames.lock().await;
311 let frame = tokio::select! { biased;
312 _ = cx.cancel.cancelled() => bail!("MCP broker read cancelled"),
313 _ = session.cancel.cancelled() => bail!("MCP broker session closed"),
314 frame = receiver.recv() => frame,
315 };
316 session.validate(shared, generation, &params.owner)?;
317 Ok(frame
318 .map_or_else(|| json!({"closed": true}), |frame| json!({"frame": frame})))
319 }
320 HostRequest::ProcWrite(params) => self.write(shared, generation, params, &cx).await,
321 HostRequest::ProcClose(params) => {
322 let session = self.session(&params.session_id)?;
323 // Closing needs exact ownership even after cancellation, but
324 // never grants a stale owner access to a replacement session.
325 if session.owner != params.owner || session.host_generation != generation {
326 bail!("MCP broker close has the wrong owner");
327 }
328 if let Some(session) = self.remove(shared, &params.session_id)
329 && let Some(mut broker) = session.broker.lock().await.take()
330 {
331 broker.shutdown().await;
332 }
333 Ok(json!({}))
334 }
335 _ => bail!("not an MCP broker request"),
336 }
337 };
338 run.await.map_err(|error| RpcErrorWire {
339 code: error_code::REFUSED,
340 message: if launch {
341 format!("MCP server launch failed: {error:#}")
342 } else {
343 "MCP broker request refused or closed".to_string()
344 },
345 data: None,
346 })
347 }
348 async fn launch(
349 &self,
350 shared: &ManagerShared,
351 generation: u64,
352 params: ProcLaunchParams,
353 cx: &HostRequestContext,
354 ) -> Result<Value> {
355 let session = self.session(&params.session_id)?;
356 session.validate(shared, generation, &params.owner)?;
357 let mut launch_guard = CancelGuard {
358 cancel: session.cancel.clone(),
359 armed: true,
360 };
361 if session.http.is_some() {
362 bail!("HTTP session cannot launch a process");
363 }
364 let target = json!({"session_id": params.session_id});
365 shared
366 .core_calls
367 .tickets
368 .redeem(&Presented {
369 ticket: &params.ticket,
370 kind: TicketKind::McpLaunch,
371 cohort: HostCohort::Builtin,
372 host_generation: generation,
373 owner: &params.owner,
374 method: "proc/launch",
375 target: Some(&target),
376 })
377 .map_err(|refused| {
378 if refused.violation {
379 cx.violation("too many invalid MCP broker tickets".to_string());
380 }
381 anyhow::anyhow!("MCP launch ticket refused")
382 })?;
383 session
384 .launch_ticket
385 .lock()
386 .expect("MCP launch ticket lock")
387 .take();
388 {
389 let mut launched = session.launched.lock().expect("MCP launch lock");
390 if *launched {
391 bail!("MCP session already launched");
392 }
393 *launched = true;
394 }
395 if cx.cancel.is_cancelled() {
396 session.cancel();
397 bail!("MCP launch cancelled");
398 }
399 let command = session
400 .config
401 .command
402 .as_deref()
403 .context("MCP host stdio requires a command")?;
404 let (mut broker, stdout) = BrokerSession::spawn_with_auth_context(
405 &session.name,
406 command,
407 &session.config,
408 session.cancel.clone(),
409 Arc::clone(&session.auth_context),
410 )?;
411 session.validate(shared, generation, &params.owner)?;
412 if session
413 .config
414 .reviewed_plugin_source()
415 .is_some_and(|source| source.plugin_name() == crate::mcp::COMPUTER_USE_PLUGIN_NAME)
416 {
417 let key = crate::mcp::random_key()?;
418 let keys = json!({"jsonrpc": "2.0", "method": crate::mcp::COMPUTER_USE_HOST_KEYS_METHOD, "params": {"decision_key": crate::mcp::hex_encode(&key), "ledger_key": crate::mcp::computer_use_ledger_key().await}});
419 let mut bytes = serde_json::to_vec(&keys)?;
420 bytes.push(b'\n');
421 tokio::select! { biased;
422 _ = cx.cancel.cancelled() => { session.cancel(); bail!("MCP launch cancelled"); },
423 _ = session.cancel.cancelled() => bail!("MCP launch revoked"),
424 result = broker.write(&bytes) => result?,
425 }
426 *session.decision_key.lock().expect("MCP decision key lock") = Some(key);
427 }
428 *session.broker.lock().await = Some(broker);
429 let reading = Arc::clone(&session);
430 tokio::spawn(async move {
431 let mut reader = BufReader::new(stdout);
432 let run = async {
433 loop {
434 let mut bytes = Vec::new();
435 let count = tokio::select! { biased;
436 _ = reading.cancel.cancelled() => break,
437 result = crate::mcp::read_line_capped(&mut reader, &mut bytes, MAX_MCP_RESPONSE_BYTES) => result?,
438 };
439 if count == 0 {
440 break;
441 }
442 if bytes.iter().all(u8::is_ascii_whitespace) {
443 continue;
444 }
445 let frame: Value = serde_json::from_slice(&bytes)?;
446 reading.observe(&frame)?;
447 tokio::select! { biased;
448 _ = reading.cancel.cancelled() => break,
449 result = reading.frame_sender.send(frame) => result.map_err(|_| anyhow::anyhow!("MCP frame consumer closed"))?,
450 }
451 }
452 Ok::<_, anyhow::Error>(())
453 };
454 if let Err(error) = run.await {
455 tracing::error!(target: "mcp", server = %reading.name, %error, "MCP stdio reader stopped");
456 }
457 reading.cancel();
458 if let Some(mut broker) = reading.broker.lock().await.take() {
459 broker.shutdown().await;
460 }
461 });
462 session.validate(shared, generation, &params.owner)?;
463 if cx.cancel.is_cancelled() {
464 bail!("MCP launch cancelled");
465 }
466 launch_guard.armed = false;
467 Ok(json!({}))
468 }
469 async fn write(
470 &self,
471 shared: &ManagerShared,
472 generation: u64,
473 params: ProcWriteParams,
474 cx: &HostRequestContext,
475 ) -> Result<Value> {
476 let session = self.session(&params.session_id)?;
477 session.validate(shared, generation, &params.owner)?;
478 let mut write_guard = CancelGuard {
479 cancel: session.cancel.clone(),
480 armed: true,
481 };
482 if session.http.is_some() {
483 bail!("HTTP session cannot write a pipe");
484 }
485 let owner = params.owner.clone();
486 let (frame, operation_deadline) =
487 self.authorize_frame(shared, generation, &session, params, cx, "proc/write")?;
488 let mut bytes = serde_json::to_vec(&frame)?;
489 bytes.push(b'\n');
490 session.validate(shared, generation, &owner)?;
491 let result = async {
492 let mut slot = session.broker.lock().await;
493 let broker = slot.as_mut().context("MCP process not launched")?;
494 tokio::select! { biased;
495 _ = cx.cancel.cancelled() => bail!("MCP write cancelled"),
496 _ = session.cancel.cancelled() => bail!("MCP write revoked"),
497 result = tokio::time::timeout_at(tokio::time::Instant::from_std(operation_deadline), broker.write(&bytes)) => result.context("MCP pipe write expired")??,
498 }
499 Ok::<_, anyhow::Error>(())
500 }.await;
501 if result.is_err() {
502 session.cancel();
503 }
504 result?;
505 session.validate(shared, generation, &owner)?;
506 write_guard.armed = false;
507 Ok(json!({}))
508 }
509 fn authorize_frame(
510 &self,
511 shared: &ManagerShared,
512 generation: u64,
513 session: &Arc<Session>,
514 params: ProcWriteParams,
515 cx: &HostRequestContext,
516 ticket_method: &'static str,
517 ) -> Result<(Value, Instant)> {
518 let mut frame = params.frame;
519 let object = frame.as_object().context("MCP frame must be an object")?;
520 if object.keys().any(|key| {
521 !["jsonrpc", "id", "method", "params", "error", "result"].contains(&key.as_str())
522 }) || frame["jsonrpc"] != "2.0"
523 {
524 bail!("invalid MCP outbound frame");
525 }
526 let method = frame
527 .get("method")
528 .and_then(Value::as_str)
529 .map(str::to_owned);
530 if method.is_some() && (frame.get("error").is_some() || frame.get("result").is_some()) {
531 bail!("MCP request cannot contain an error");
532 }
533 let mut operation_deadline = Instant::now() + Duration::from_secs(2);
534 match method.as_deref() {
535 Some("notifications/cancelled") => {
536 if params.ticket.is_some() || frame.get("id").is_some() {
537 bail!("invalid MCP cancellation");
538 }
539 let id = wire_id(&frame["params"]["requestId"])?;
540 let pending = session.pending.lock().expect("MCP pending lock");
541 let binding = pending
542 .get(&id)
543 .context("MCP cancellation has no active request")?;
544 if params.operation_id.as_deref() != Some(binding.operation_id.as_str()) {
545 bail!("MCP cancellation target mismatch");
546 }
547 let fields = frame["params"]
548 .as_object()
549 .context("invalid MCP cancellation params")?;
550 if fields
551 .keys()
552 .any(|key| !["requestId", "reason", "_meta"].contains(&key.as_str()))
553 {
554 bail!("invalid MCP cancellation params");
555 }
556 if fields.get("_meta")
557 != expected_metadata(session, "notifications/cancelled").as_ref()
558 {
559 bail!("MCP cancellation metadata refused");
560 }
561 }
562 Some(method) => {
563 if !SUPPORTED_METHODS.contains(&method) {
564 bail!("MCP method has no Rust grant");
565 }
566 let operation_id = params
567 .operation_id
568 .as_deref()
569 .context("MCP operation id absent")?;
570 let body = frame.get("params").cloned().unwrap_or_else(|| json!({}));
571 if !body.is_object() {
572 bail!("MCP named params required");
573 }
574 let admitted_id = frame
575 .get("id")
576 .map(|id| {
577 id.as_str()
578 .context("MCP wire request ID must be a Rust string")
579 })
580 .transpose()?;
581 let target = session.target(operation_id, method, &body, admitted_id);
582 let ticket = params
583 .ticket
584 .as_deref()
585 .context("MCP operation ticket absent")?;
586 shared
587 .core_calls
588 .tickets
589 .redeem(&Presented {
590 ticket,
591 kind: TicketKind::McpOperation,
592 cohort: HostCohort::Builtin,
593 host_generation: generation,
594 owner: &params.owner,
595 method: ticket_method,
596 target: Some(&target),
597 })
598 .map_err(|refused| {
599 if refused.violation {
600 cx.violation("too many invalid MCP broker tickets".to_string());
601 }
602 anyhow::anyhow!("MCP operation ticket refused")
603 })?;
604 let operation = session
605 .operations
606 .lock()
607 .expect("MCP operation lock")
608 .remove(operation_id)
609 .context("MCP operation absent")?;
610 if operation.target != target || ticket != operation.ticket.expose() {
611 bail!("MCP operation does not match");
612 }
613 if body.get("_meta") != expected_metadata(session, method).as_ref() {
614 bail!("host-supplied MCP metadata refused");
615 }
616 if matches!(method, "initialize" | "notifications/initialized")
617 && (!session
618 .legacy_allowed
619 .load(std::sync::atomic::Ordering::SeqCst)
620 || session.modern())
621 {
622 bail!("legacy MCP handshake has no typed refusal");
623 }
624 if operation.expires <= Instant::now() {
625 bail!("MCP operation expired");
626 }
627 operation_deadline = operation.expires;
628 if method == "tools/call" {
629 let tool = body["name"].as_str().context("MCP tool name absent")?;
630 if !session.config.is_tool_enabled(tool) {
631 bail!("MCP tool disabled");
632 }
633 if let Some(decision) = operation.decision.as_ref() {
634 if !decision.authorizes(
635 &McpPool::mcp_model_tool_name(&session.name, tool),
636 &body["arguments"],
637 ) {
638 bail!("MCP decision does not match");
639 }
640 if let Some(key) = session
641 .decision_key
642 .lock()
643 .expect("MCP decision key lock")
644 .as_ref()
645 {
646 frame["params"]
647 .as_object_mut()
648 .context("MCP params absent")?
649 .entry("_meta")
650 .or_insert_with(|| json!({}));
651 frame["params"]["_meta"][crate::mcp::COMPUTER_USE_DECISION_META] =
652 crate::mcp::attest_decision(key, tool, &body["arguments"])?;
653 }
654 }
655 }
656 if method == "notifications/initialized" {
657 if frame.get("id").is_some() {
658 bail!("initialized must be a notification");
659 }
660 } else {
661 let id = wire_id(frame.get("id").context("MCP request id absent")?)?;
662 let mut pending = session.pending.lock().expect("MCP pending lock");
663 if pending.len() >= MAX_PENDING || pending.contains_key(&id) {
664 bail!("MCP request id unavailable");
665 }
666 pending.insert(
667 id,
668 BoundRequest {
669 operation_id: operation_id.to_string(),
670 method: method.to_string(),
671 },
672 );
673 }
674 }
675 None => {
676 if params.ticket.is_some()
677 || params.operation_id.is_some()
678 || frame.get("params").is_some()
679 {
680 bail!("invalid MCP server request answer");
681 }
682 let id = wire_id(frame.get("id").context("MCP response id absent")?)?;
683 let mut requests = session
684 .server_requests
685 .lock()
686 .expect("MCP server request lock");
687 let method = requests
688 .get(&id)
689 .context("MCP response has no observed server request")?;
690 let refusal = frame.get("result").is_none()
691 && frame["error"]["code"] == -32601
692 && frame["error"]["message"].is_string();
693 let ping = method == "ping"
694 && frame.get("error").is_none()
695 && frame
696 .get("result")
697 .and_then(Value::as_object)
698 .is_some_and(|result| result.is_empty());
699 if !refusal && !ping {
700 bail!("MCP server request success requires Rust authority");
701 }
702 requests.remove(&id);
703 }
704 }
705 if serde_json::to_vec(&frame)?.len() > MAX_MCP_RESPONSE_BYTES {
706 bail!("MCP outbound frame exceeds bound");
707 }
708 Ok((frame, operation_deadline))
709 }
710 }
711 fn expected_metadata(session: &Session, method: &str) -> Option<Value> {
712 (method == "server/discover" || session.modern()).then(modern_metadata)
713 }
714 struct CancelGuard {
715 cancel: CancellationToken,
716 armed: bool,
717 }
718 impl Drop for CancelGuard {
719 fn drop(&mut self) {
720 if self.armed {
721 self.cancel.cancel();
722 }
723 }
724 }
725 fn wire_id(id: &Value) -> Result<String> {
726 if !(id.is_string() || id.as_i64().is_some() || id.as_u64().is_some()) {
727 bail!("invalid MCP request id");
728 }
729 Ok(serde_json::to_string(id)?)
730 }
731
732 /// Semantic adapter: the existing Rust MCP connection still consumes raw
733 /// server replies for policy/catalog admission; it never writes MCP bytes.
734 pub struct SdkTransport {
735 manager: Arc<ExtensionHostManager>,
736 host: Arc<HostProcess>,
737 session: Arc<Session>,
738 session_id: String,
739 replies: std::collections::VecDeque<Vec<u8>>,
740 discovery_timeout: Duration,
741 }
742 impl SdkTransport {
743 #[cfg(any(test, feature = "test-support"))]
744 pub async fn connect(
745 name: &str,
746 config: &McpServerConfig,
747 cancel: CancellationToken,
748 timeout: Duration,
749 ) -> Result<Self> {
750 Self::connect_with_http(name, config, cancel, timeout, None).await
751 }
752 pub async fn connect_with_http(
753 name: &str,
754 config: &McpServerConfig,
755 cancel: CancellationToken,
756 timeout: Duration,
757 client: Option<crate::mcp::http_client::McpHttpClient>,
758 ) -> Result<Self> {
759 Self::connect_with_http_and_auth_context(
760 name,
761 config,
762 cancel,
763 timeout,
764 client,
765 crate::mcp::process_mcp_auth_context(),
766 )
767 .await
768 }
769
770 pub async fn connect_with_http_and_auth_context(
771 name: &str,
772 config: &McpServerConfig,
773 cancel: CancellationToken,
774 timeout: Duration,
775 client: Option<crate::mcp::http_client::McpHttpClient>,
776 auth_context: Arc<dyn codewhale_runtime::credentials::AuthContext>,
777 ) -> Result<Self> {
778 if (config.url.is_some() != client.is_some())
779 || (config.url.is_none() && config.command.is_none())
780 {
781 bail!(
782 "Host MCP backend requires a Rust-prepared HTTP client or a stdio command; no Rust fallback is allowed"
783 );
784 }
785 struct McpUsersGuard {
786 shared: Arc<ManagerShared>,
787 armed: bool,
788 }
789 impl Drop for McpUsersGuard {
790 fn drop(&mut self) {
791 if self.armed {
792 self.shared
793 .mcp_users
794 .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
795 }
796 }
797 }
798 let manager = super::manager();
799 manager
800 .shared
801 .mcp_users
802 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
803 let mut mcp_users_guard = McpUsersGuard {
804 shared: Arc::clone(&manager.shared),
805 armed: true,
806 };
807 let (host, owner, host_generation) = manager
808 .ensure_mcp_builtin()
809 .await
810 .map_err(anyhow::Error::msg)?;
811 let session_id = uuid::Uuid::new_v4().to_string();
812 let (frame_sender, frames) = mpsc::channel(1);
813 let session = Arc::new(Session {
814 session_id: session_id.clone(),
815 owner,
816 host_generation,
817 name: name.to_string(),
818 config: config.clone(),
819 auth_context,
820 // The facade owns caller cancellation. Retiring this transport
821 // must release its resources without cancelling that facade and
822 // masking the concrete reply or failure it is about to receive.
823 cancel: cancel.child_token(),
824 broker: AsyncMutex::new(None),
825 frames: AsyncMutex::new(frames),
826 frame_sender,
827 operations: Mutex::new(HashMap::new()),
828 pending: Mutex::new(HashMap::new()),
829 replies: Mutex::new(HashMap::new()),
830 server_requests: Mutex::new(HashMap::new()),
831 decision_key: Mutex::new(None),
832 protocol_version: Mutex::new(None),
833 legacy_allowed: std::sync::atomic::AtomicBool::new(
834 crate::mcp::is_legacy_sse_transport(config),
835 ),
836 list_changed: std::sync::atomic::AtomicBool::new(false),
837 launched: Mutex::new(false),
838 launch_ticket: Mutex::new(None),
839 http: client.map(|client| {
840 http::HttpSession::new(
841 client,
842 config.url.as_deref().expect("HTTP config URL"),
843 crate::mcp::is_legacy_sse_transport(config),
844 )
845 }),
846 });
847 if session.http.is_some() {
848 // Handler cancellation can drop a body future outside an exchange.
849 // The weak watch releases retained network bodies on every token
850 // cancellation without extending the broker session's lifetime.
851 let weak = Arc::downgrade(&session);
852 let cancel = session.cancel.clone();
853 tokio::spawn(async move {
854 cancel.cancelled().await;
855 if let Some(session) = weak.upgrade()
856 && let Some(http) = &session.http
857 {
858 http.close();
859 }
860 });
861 }
862 {
863 let mut sessions = manager
864 .shared
865 .mcp_broker
866 .sessions
867 .lock()
868 .expect("MCP broker lock");
869 if sessions.len() >= MAX_SESSIONS {
870 bail!("MCP host session limit exceeded");
871 }
872 sessions.insert(session_id.clone(), Arc::clone(&session));
873 mcp_users_guard.armed = false;
874 }
875 let transport = Self {
876 manager,
877 host,
878 session,
879 session_id,
880 replies: Default::default(),
881 discovery_timeout: timeout,
882 };
883 Ok(transport)
884 }
885 fn grant(
886 &self,
887 method: &str,
888 mut params: Value,
889 timeout: Duration,
890 decision: Option<&HumanDecision>,
891 wire_id: Option<&str>,
892 ) -> Result<McpOperationGrant> {
893 if timeout.is_zero()
894 || timeout > MAX_DEADLINE
895 || !params.is_object()
896 || serde_json::to_vec(&params)?.len() > MAX_MCP_RESPONSE_BYTES
897 {
898 bail!("MCP grant exceeds bound");
899 }
900 self.session.validate(
901 &self.manager.shared,
902 self.session.host_generation,
903 &self.session.owner,
904 )?;
905 if params.get("_meta").is_some() {
906 bail!("MCP semantic metadata is Rust-owned");
907 }
908 if let Some(metadata) = expected_metadata(&self.session, method) {
909 params["_meta"] = metadata;
910 }
911 let operation_id = uuid::Uuid::new_v4().to_string();
912 let target = self.session.target(&operation_id, method, &params, wire_id);
913 let mut operations = self.session.operations.lock().expect("MCP operation lock");
914 if operations.len() >= MAX_PENDING {
915 bail!("MCP grant bound exceeded");
916 }
917 let ticket = self.manager.shared.core_calls.tickets.mint(Grant {
918 kind: TicketKind::McpOperation,
919 cohort: HostCohort::Builtin,
920 host_generation: self.session.host_generation,
921 owner: self.session.owner.clone(),
922 method: if self.session.http.is_some() {
923 "net/fetch"
924 } else {
925 "proc/write"
926 },
927 target: target.clone(),
928 ttl: timeout,
929 uses: 1,
930 });
931 let wire_ticket = ticket.expose().to_string();
932 operations.insert(
933 operation_id.clone(),
934 Operation {
935 target,
936 ticket,
937 expires: Instant::now() + timeout,
938 decision: decision.cloned(),
939 },
940 );
941 Ok(McpOperationGrant {
942 ticket: wire_ticket,
943 operation_id,
944 method: method.to_string(),
945 wire_id: wire_id.map(str::to_owned),
946 params,
947 })
948 }
949 async fn exchange(
950 &mut self,
951 bytes: Vec<u8>,
952 decision: Option<&HumanDecision>,
953 timeout: Duration,
954 ) -> Result<()> {
955 let value: Value = serde_json::from_slice(&bytes)?;
956 let method = value["method"]
957 .as_str()
958 .context("MCP semantic method absent")?;
959 // The SDK owns the legacy handshake; modern connections use discovery.
960 // Completing the facade handshake never writes another notification.
961 if method == "notifications/initialized" {
962 return Ok(());
963 }
964 if !SUPPORTED_METHODS.contains(&method) {
965 bail!("MCP semantic operation unavailable");
966 }
967 let params = value.get("params").cloned().unwrap_or_else(|| json!({}));
968 let wire_id = value
969 .get("id")
970 .map(|id| {
971 id.as_str()
972 .context("Rust MCP facade request ID must be a string")
973 })
974 .transpose()?;
975 let grant = self.grant(method, params, timeout, decision, wire_id)?;
976 let operation_id = grant.operation_id.clone();
977 let mut guard = ExchangeGuard {
978 transport: self,
979 armed: true,
980 };
981 let mut discovery_operation = None;
982 let mut opening_operations = Vec::new();
983 let request = if method == "initialize" {
984 let discover = if crate::mcp::is_legacy_sse_transport(&guard.transport.session.config) {
985 None
986 } else {
987 Some(guard.transport.grant(
988 "server/discover",
989 json!({}),
990 timeout,
991 None,
992 Some(&uuid::Uuid::new_v4().to_string()),
993 )?)
994 };
995 discovery_operation = discover.as_ref().map(|grant| grant.operation_id.clone());
996 let initialized = guard.transport.grant(
997 "notifications/initialized",
998 json!({}),
999 timeout,
1000 None,
1001 None,
1002 )?;
1003 opening_operations
1004 .extend([grant.operation_id.clone(), initialized.operation_id.clone()]);
1005 opening_operations.extend(discovery_operation.iter().cloned());
1006 let target = json!({"session_id": guard.transport.session_id});
1007 let launch = guard
1008 .transport
1009 .manager
1010 .shared
1011 .core_calls
1012 .tickets
1013 .mint(Grant {
1014 kind: TicketKind::McpLaunch,
1015 cohort: HostCohort::Builtin,
1016 host_generation: guard.transport.session.host_generation,
1017 owner: guard.transport.session.owner.clone(),
1018 method: if guard.transport.session.http.is_some() {
1019 "net/start"
1020 } else {
1021 "proc/launch"
1022 },
1023 target,
1024 ttl: timeout,
1025 uses: 1,
1026 });
1027 *guard
1028 .transport
1029 .session
1030 .launch_ticket
1031 .lock()
1032 .expect("MCP launch ticket lock") = Some(launch.clone());
1033 CoreRequest::McpOpen(Box::new(McpOpenParams {
1034 owner: guard.transport.session.owner.clone(),
1035 session_id: guard.transport.session_id.clone(),
1036 launch_ticket: launch.expose().to_string(),
1037 transport: if guard.transport.session.http.is_none() {
1038 "stdio"
1039 } else if crate::mcp::is_legacy_sse_transport(&guard.transport.session.config) {
1040 "sse"
1041 } else {
1042 "http"
1043 }
1044 .to_string(),
1045 discover_grant: discover,
1046 initialize_grant: grant,
1047 initialized_grant: initialized,
1048 client_version: env!("CARGO_PKG_VERSION").to_string(),
1049 deadline_ms: timeout.as_millis() as u64,
1050 }))
1051 } else {
1052 CoreRequest::McpRequest(McpRequestParams {
1053 owner: guard.transport.session.owner.clone(),
1054 session_id: guard.transport.session_id.clone(),
1055 grant,
1056 deadline_ms: timeout.as_millis() as u64,
1057 })
1058 };
1059 let outcome = guard
1060 .transport
1061 .host
1062 .call(request, Some("host:mcp".to_string()))
1063 .await;
1064 for operation_id in opening_operations {
1065 guard
1066 .transport
1067 .session
1068 .pending
1069 .lock()
1070 .expect("MCP pending lock")
1071 .retain(|_, binding| binding.operation_id != operation_id);
1072 if let Some(operation) = guard
1073 .transport
1074 .session
1075 .operations
1076 .lock()
1077 .expect("MCP operation lock")
1078 .remove(&operation_id)
1079 {
1080 guard
1081 .transport
1082 .manager
1083 .shared
1084 .core_calls
1085 .tickets
1086 .revoke(&operation.ticket);
1087 }
1088 }
1089 let discovery = discovery_operation.and_then(|id| {
1090 guard
1091 .transport
1092 .session
1093 .replies
1094 .lock()
1095 .expect("MCP reply lock")
1096 .remove(&id)
1097 });
1098 if method == "initialize"
1099 && let Ok(opened) = &outcome
1100 {
1101 let version = opened["protocolVersion"]
1102 .as_str()
1103 .context("MCP SDK omitted negotiated version")?;
1104 if version == crate::mcp::MCP_MODERN_PROTOCOL_VERSION {
1105 let mut result = discovery
1106 .as_ref()
1107 .and_then(|reply| reply.get("result"))
1108 .cloned()
1109 .context("modern MCP discovery reply absent")?;
1110 anyhow::ensure!(
1111 result["resultType"] == "complete"
1112 && result["capabilities"].is_object()
1113 && result["supportedVersions"]
1114 .as_array()
1115 .is_some_and(|versions| versions.iter().any(|v| v == version)),
1116 "modern MCP discovery result refused"
1117 );
1118 result["protocolVersion"] = json!(version);
1119 if let Some(info) = result["_meta"]
1120 .get("io.modelcontextprotocol/serverInfo")
1121 .cloned()
1122 {
1123 result["serverInfo"] = info;
1124 }
1125 *guard
1126 .transport
1127 .session
1128 .protocol_version
1129 .lock()
1130 .expect("MCP protocol lock") = Some(version.to_string());
1131 guard.transport.replies.push_back(serde_json::to_vec(
1132 &json!({"jsonrpc":"2.0", "id":value["id"], "result":result}),
1133 )?);
1134 guard.armed = false;
1135 return Ok(());
1136 }
1137 anyhow::ensure!(
1138 crate::mcp::MCP_CLIENT_ACCEPTED_PROTOCOL_VERSIONS.contains(&version),
1139 "MCP SDK negotiated unsupported revision"
1140 );
1141 *guard
1142 .transport
1143 .session
1144 .protocol_version
1145 .lock()
1146 .expect("MCP protocol lock") = Some(version.to_string());
1147 }
1148 let raw = guard
1149 .transport
1150 .session
1151 .replies
1152 .lock()
1153 .expect("MCP reply lock")
1154 .remove(&operation_id);
1155 let legacy_allowed = guard
1156 .transport
1157 .session
1158 .legacy_allowed
1159 .load(std::sync::atomic::Ordering::SeqCst);
1160 let raw = raw
1161 .or_else(|| discovery.filter(|reply| reply.get("error").is_some() && !legacy_allowed));
1162 if let Some(mut raw) = raw {
1163 if guard.transport.session.modern()
1164 && let Some(result) = raw.get("result")
1165 {
1166 anyhow::ensure!(
1167 matches!(
1168 result["resultType"].as_str(),
1169 Some("complete" | "input_required")
1170 ),
1171 "MCP modern result type is missing or unsupported; request was not replayed"
1172 );
1173 }
1174 // Preserve the server's exact result/error (including extra MCP
1175 // fields), changing only correlation back to the Rust facade id.
1176 raw["id"] = value["id"].clone();
1177 // Rust's existing initialize validation owns the diagnostic and
1178 // accepted-revision contract, including when the SDK refused it.
1179 guard.transport.replies.push_back(serde_json::to_vec(&raw)?);
1180 guard.armed = false;
1181 return Ok(());
1182 }
1183 if let Some(error) = guard
1184 .transport
1185 .session
1186 .http
1187 .as_ref()
1188 .and_then(http::HttpSession::failure)
1189 {
1190 return Err(error);
1191 }
1192 outcome
1193 .map_err(anyhow::Error::msg)
1194 .context("MCP SDK request failed before an admitted reply")?;
1195 bail!("MCP SDK connection closed before an admitted reply")
1196 }
1197 }
1198 struct ExchangeGuard<'a> {
1199 transport: &'a mut SdkTransport,
1200 armed: bool,
1201 }
1202 impl Drop for ExchangeGuard<'_> {
1203 fn drop(&mut self) {
1204 if self.armed {
1205 self.transport.session.cancel();
1206 }
1207 }
1208 }
1209 impl Drop for SdkTransport {
1210 fn drop(&mut self) {
1211 self.manager
1212 .shared
1213 .mcp_broker
1214 .remove(&self.manager.shared, &self.session_id);
1215 }
1216 }
1217 #[async_trait::async_trait]
1218 impl crate::mcp::McpTransport for SdkTransport {
1219 async fn send(&mut self, bytes: Vec<u8>) -> Result<()> {
1220 self.exchange(bytes, None, self.discovery_timeout).await
1221 }
1222 async fn send_decided(
1223 &mut self,
1224 bytes: Vec<u8>,
1225 decision: Option<&HumanDecision>,
1226 timeout: Duration,
1227 ) -> Result<()> {
1228 self.exchange(bytes, decision, timeout).await
1229 }
1230 async fn recv(&mut self) -> Result<Vec<u8>> {
1231 self.replies
1232 .pop_front()
1233 .context("MCP SDK connection closed without a reply")
1234 }
1235 fn is_modern(&self) -> bool {
1236 self.session.modern()
1237 }
1238 async fn last_stderr_line(&self) -> Option<String> {
1239 let slot = self.session.broker.lock().await;
1240 slot.as_ref()?.last_stderr_line().await
1241 }
1242 fn probe_dead(&self) -> bool {
1243 self.session.cancel.is_cancelled() || self.host.has_exited() || self.host.is_retiring()
1244 }
1245 fn take_list_changed(&self) -> bool {
1246 self.session
1247 .list_changed
1248 .swap(false, std::sync::atomic::Ordering::SeqCst)
1249 }
1250 async fn shutdown(&mut self) {
1251 if let Some(session) = self
1252 .manager
1253 .shared
1254 .mcp_broker
1255 .remove(&self.manager.shared, &self.session_id)
1256 && let Some(mut broker) = session.broker.lock().await.take()
1257 {
1258 broker.shutdown().await;
1259 }
1260 let _ = self
1261 .host
1262 .call(
1263 CoreRequest::McpClose(McpCloseParams {
1264 owner: self.session.owner.clone(),
1265 session_id: self.session_id.clone(),
1266 deadline_ms: 2500,
1267 }),
1268 Some("host:mcp".to_string()),
1269 )
1270 .await;
1271 }
1272 }
1273
1274 #[cfg(test)]
1275 #[path = "mcp_tests.rs"]
1276 mod tests;
1277
1278 #[path = "mcp_http.rs"]
1279 mod http;
1280
1280 lines RUST