1#![allow(clippy::too_many_lines)]
4
5use std::collections::{HashMap, HashSet};
6use std::io::{self, BufRead, Write};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use axum::{
11 Router,
12 routing::{get, post},
13};
14use reqwest::Client;
15use serde::Serialize;
16use serde_json::{Value, json};
17use tokio::sync::Mutex;
18
19use vela_edge::signals;
20use vela_edge::tool_registry;
21use vela_protocol::bundle::FindingBundle;
22use vela_protocol::project::{self, ConfidenceDistribution, Project, ProjectStats};
23use vela_protocol::repo;
24use vela_protocol::sources;
25
26use super::http::{
27 http_entries, http_entry, http_entry_events, http_entry_finding, http_entry_findings,
28 http_health, http_mcp, http_mcp_get,
29};
30use super::tools::{
31 tool_external, tool_finding, tool_graph, tool_nanopublication, tool_objects, tool_orient,
32 tool_search, tool_verify, tool_work,
33};
34pub enum ProjectSource {
35 Single(PathBuf),
36 Directory(PathBuf),
37}
38
39impl ProjectSource {
40 pub fn from_args(single: Option<&Path>, dir: Option<&Path>) -> Self {
41 if let Some(d) = dir {
42 Self::Directory(d.to_path_buf())
43 } else if let Some(s) = single {
44 Self::Single(s.to_path_buf())
45 } else {
46 eprintln!(
47 "{} provide either a frontier file or --frontiers <dir>",
48 vela_protocol::cli_style::err_prefix()
49 );
50 std::process::exit(1);
51 }
52 }
53}
54
55#[derive(Clone)]
56pub struct ProjectInfo {
57 pub name: String,
58 pub file: String,
59 pub findings_count: usize,
60 pub links_count: usize,
61 pub papers: usize,
62}
63
64pub fn load_projects(source: &ProjectSource) -> (Project, Vec<ProjectInfo>) {
65 match source {
66 ProjectSource::Single(path) => {
67 let mut frontier = repo::load_from_path(path).unwrap_or_else(|e| {
68 eprintln!(
69 "{} failed to load frontier: {e}",
70 vela_protocol::cli_style::err_prefix()
71 );
72 std::process::exit(1);
73 });
74 sources::materialize_project(&mut frontier);
75 let info = ProjectInfo {
76 name: frontier.project.name.clone(),
77 file: path.display().to_string(),
78 findings_count: frontier.findings.len(),
79 links_count: frontier.stats.links,
80 papers: frontier.project.papers_processed,
81 };
82 (frontier, vec![info])
83 }
84 ProjectSource::Directory(dir) => {
85 let mut entries: Vec<PathBuf> = std::fs::read_dir(dir)
86 .unwrap_or_else(|e| {
87 eprintln!(
88 "{} failed to read directory: {e}",
89 vela_protocol::cli_style::err_prefix()
90 );
91 std::process::exit(1);
92 })
93 .filter_map(Result::ok)
94 .map(|entry| entry.path())
95 .filter(|path| {
96 (path.is_dir() && path.join(".vela").exists())
97 || path.extension().is_some_and(|ext| ext == "json")
98 })
99 .collect();
100 entries.sort();
101 if entries.is_empty() {
102 eprintln!("no frontier files found in {}", dir.display());
103 std::process::exit(1);
104 }
105
106 let mut named = Vec::new();
107 for path in &entries {
108 let mut frontier = repo::load_from_path(path).unwrap_or_else(|e| {
109 eprintln!(
110 "{} failed to load {}: {e}",
111 vela_protocol::cli_style::err_prefix(),
112 path.display()
113 );
114 std::process::exit(1);
115 });
116 sources::materialize_project(&mut frontier);
117 let name = path
118 .file_stem()
119 .unwrap_or_default()
120 .to_string_lossy()
121 .to_string();
122 named.push((name, frontier));
123 }
124 let infos = named
125 .iter()
126 .map(|(name, frontier)| ProjectInfo {
127 name: frontier.project.name.clone(),
128 file: name.clone(),
129 findings_count: frontier.findings.len(),
130 links_count: frontier.stats.links,
131 papers: frontier.project.papers_processed,
132 })
133 .collect::<Vec<_>>();
134 (merge_projects(named), infos)
135 }
136 }
137}
138
139fn merge_projects(frontiers: Vec<(String, Project)>) -> Project {
140 let mut findings = Vec::<FindingBundle>::new();
141 let mut categories = HashMap::<String, usize>::new();
142 let mut link_types = HashMap::<String, usize>::new();
143 let mut names = Vec::new();
144 let mut papers_processed = 0usize;
145 let mut errors = 0usize;
146 let mut artifacts = Vec::new();
150
151 for (name, frontier) in frontiers {
152 names.push(name);
153 papers_processed += frontier.project.papers_processed;
154 errors += frontier.project.errors;
155 for (category, count) in frontier.stats.categories {
156 *categories.entry(category).or_default() += count;
157 }
158 for (link_type, count) in frontier.stats.link_types {
159 *link_types.entry(link_type).or_default() += count;
160 }
161 findings.extend(frontier.findings);
162 artifacts.extend(frontier.artifacts);
163 }
164
165 let mut deduped = Vec::<FindingBundle>::new();
166 let mut seen = HashMap::<String, usize>::new();
167 for finding in findings {
168 if let Some(existing) = seen.get(&finding.id).copied() {
169 if finding.confidence.score > deduped[existing].confidence.score {
170 deduped[existing] = finding;
171 }
172 } else {
173 seen.insert(finding.id.clone(), deduped.len());
174 deduped.push(finding);
175 }
176 }
177
178 let links = deduped.iter().map(|finding| finding.links.len()).sum();
179 let replicated = deduped
180 .iter()
181 .filter(|finding| finding.evidence.replicated)
182 .count();
183 let avg_confidence = if deduped.is_empty() {
184 0.0
185 } else {
186 (deduped
187 .iter()
188 .map(|finding| finding.confidence.score)
189 .sum::<f64>()
190 / deduped.len() as f64
191 * 1000.0)
192 .round()
193 / 1000.0
194 };
195 let stats = ProjectStats {
196 findings: deduped.len(),
197 links,
198 replicated,
199 unreplicated: deduped.len().saturating_sub(replicated),
200 avg_confidence,
201 gaps: deduped.iter().filter(|finding| finding.flags.gap).count(),
202 negative_space: deduped
203 .iter()
204 .filter(|finding| finding.flags.negative_space)
205 .count(),
206 contested: deduped
207 .iter()
208 .filter(|finding| finding.flags.contested)
209 .count(),
210 categories,
211 link_types,
212 human_reviewed: deduped
213 .iter()
214 .filter(|finding| {
215 finding.provenance.review.as_ref().is_some_and(|review| {
216 review.reviewed
217 && review
218 .reviewer
219 .as_deref()
220 .map(vela_protocol::events::actor_kind)
221 .unwrap_or("human")
222 == "human"
223 })
224 })
225 .count(),
226 agent_reviewed: deduped
227 .iter()
228 .filter(|finding| {
229 finding.provenance.review.as_ref().is_some_and(|review| {
230 review.reviewed
231 && review
232 .reviewer
233 .as_deref()
234 .map(vela_protocol::events::actor_kind)
235 .unwrap_or("human")
236 != "human"
237 })
238 })
239 .count(),
240 review_event_count: 0,
241 confidence_update_count: 0,
242 event_count: 0,
243 source_count: 0,
244 evidence_atom_count: 0,
245 condition_record_count: 0,
246 proposal_count: 0,
247 confidence_distribution: ConfidenceDistribution {
248 high_gt_80: deduped
249 .iter()
250 .filter(|finding| finding.confidence.score > 0.8)
251 .count(),
252 medium_60_80: deduped
253 .iter()
254 .filter(|finding| (0.6..=0.8).contains(&finding.confidence.score))
255 .count(),
256 low_lt_60: deduped
257 .iter()
258 .filter(|finding| finding.confidence.score < 0.6)
259 .count(),
260 },
261 };
262
263 let mut project = Project {
264 vela_version: project::VELA_SCHEMA_VERSION.to_string(),
265 schema: project::VELA_SCHEMA_URL.to_string(),
266 frontier_id: None,
267 project: project::ProjectMeta {
268 name: format!("merged: {}", names.join(", ")),
269 description: format!("Merged from {} frontiers", names.len()),
270 compiled_at: chrono::Utc::now().to_rfc3339(),
271 compiler: project::VELA_COMPILER_VERSION.to_string(),
272 papers_processed,
273 errors,
274 dependencies: Vec::new(),
275 },
276 stats,
277 findings: deduped,
278 sources: Vec::new(),
279 evidence_atoms: Vec::new(),
280 condition_records: Vec::new(),
281 review_events: Vec::new(),
282 confidence_updates: Vec::new(),
283 events: Vec::new(),
284 proposals: Vec::new(),
285 proof_state: Default::default(),
286 signatures: Vec::new(),
287 actors: Vec::new(),
288 artifacts,
289 released_diff_packs: Vec::new(),
290 verdict_conflicts: Vec::new(),
291 contradictions: Vec::new(),
292 verifier_attachments: Vec::new(),
293 attempts: Vec::new(),
294 attempt_resolutions: Vec::new(),
295 transfers: Vec::new(),
296 endorsements: Vec::new(),
297 statement_attestations: Vec::new(),
298 anchor_links: Vec::new(),
299 attempt_claims: Vec::new(),
300 statement_registrations: Vec::new(),
301 };
302 sources::materialize_project(&mut project);
303 project
304}
305
306pub async fn run(
307 source: ProjectSource,
308 _backend: Option<&str>,
309 profile: tool_registry::McpProfile,
310) {
311 let (frontier, project_infos) = load_projects(&source);
314 let source_path: Option<PathBuf> = match &source {
315 ProjectSource::Single(path) => Some(path.clone()),
316 ProjectSource::Directory(_) => None,
317 };
318 let state = AppState {
319 project: Arc::new(Mutex::new(frontier)),
320 project_infos,
321 client: Client::new(),
322 profile,
323 source_path,
324 };
325 let no_exclusions = HashSet::new();
326 let stdin = io::stdin();
327 let stdout = io::stdout();
328
329 for line in stdin.lock().lines() {
330 let Ok(line) = line else {
331 break;
332 };
333 if line.trim().is_empty() {
334 continue;
335 }
336 let Ok(request) = serde_json::from_str::<Value>(&line) else {
337 continue;
338 };
339 let Some(response) = rpc_dispatch(&request, &state, &no_exclusions).await else {
340 continue;
341 };
342 let mut out = stdout.lock();
343 let _ = serde_json::to_writer(&mut out, &response);
344 let _ = out.write_all(b"\n");
345 let _ = out.flush();
346 }
347}
348
349async fn rpc_dispatch(request: &Value, st: &AppState, excluded: &HashSet<String>) -> Option<Value> {
356 let id = request.get("id").cloned();
357 let method = request["method"].as_str().unwrap_or_default();
358 if method.starts_with("notifications/") {
359 return None;
360 }
361 Some(match method {
362 "initialize" => {
363 let requested = request["params"]["protocolVersion"]
366 .as_str()
367 .unwrap_or("2024-11-05");
368 json_rpc_result(
369 &id,
370 json!({
371 "protocolVersion": requested,
372 "capabilities": {"tools": {}},
373 "serverInfo": {"name": "vela", "version": project::VELA_SCHEMA_VERSION}
374 }),
375 )
376 }
377 "tools/list" => {
378 let mut tools = tool_registry::mcp_tools_json_for_profile(st.profile);
379 if !excluded.is_empty()
380 && let Some(arr) = tools.as_array_mut()
381 {
382 arr.retain(|t| t["name"].as_str().is_none_or(|n| !excluded.contains(n)));
383 }
384 json_rpc_result(&id, json!({"tools": tools}))
385 }
386 "tools/call" => {
387 let name = request["params"]["name"].as_str().unwrap_or_default();
388 let args = request["params"]["arguments"].clone();
389 if excluded.contains(name) {
390 let available: Vec<String> = tool_registry::tools_for_profile(st.profile)
391 .into_iter()
392 .map(|t| t.name)
393 .filter(|n| !excluded.contains(n))
394 .collect();
395 json_rpc_error(
396 &id,
397 -32602,
398 &format!(
399 "`{name}` is not served on this hosted endpoint (it operates on \
400 local filesystem paths); clone the frontier repo and run it \
401 there. Tools available here: {}",
402 available.join(", ")
403 ),
404 )
405 } else if let Some(err) = profile_gate(name, st.profile) {
406 ToolResult::failure(name, err, 0).to_rpc(&id)
407 } else {
408 handle_tool_call(
409 &id,
410 name,
411 &args,
412 &st.project,
413 &st.client,
414 &st.project_infos,
415 st.source_path.as_deref(),
416 )
417 .await
418 }
419 }
420 "ping" => json_rpc_result(&id, json!({})),
421 _ => json_rpc_error(&id, -32601, "Method not found"),
422 })
423}
424
425pub(crate) async fn mcp_http_exchange(
430 body: &str,
431 st: &AppState,
432 excluded: &HashSet<String>,
433) -> (u16, Option<Value>) {
434 let Ok(message) = serde_json::from_str::<Value>(body) else {
435 return (
436 400,
437 Some(json!({
438 "jsonrpc": "2.0", "id": null,
439 "error": {"code": -32700, "message": "Parse error"}
440 })),
441 );
442 };
443 if let Some(batch) = message.as_array() {
444 let mut responses = Vec::new();
445 for request in batch {
446 if let Some(response) = rpc_dispatch(request, st, excluded).await {
447 responses.push(response);
448 }
449 }
450 if responses.is_empty() {
451 (202, None)
452 } else {
453 (200, Some(Value::Array(responses)))
454 }
455 } else {
456 match rpc_dispatch(&message, st, excluded).await {
457 Some(response) => (200, Some(response)),
458 None => (202, None),
459 }
460 }
461}
462
463pub struct McpService {
467 state: AppState,
468 excluded: HashSet<String>,
469}
470
471impl McpService {
472 pub fn from_named_paths(
478 entries: &[(String, PathBuf)],
479 profile_str: &str,
480 exclude: &[String],
481 ) -> Result<(Self, Vec<String>), String> {
482 let mut loaded = Vec::new();
483 let mut warnings = Vec::new();
484 for (name, path) in entries {
485 match repo::load_from_path(path) {
486 Ok(frontier) => loaded.push((name.clone(), frontier)),
487 Err(e) => warnings.push(format!("{name}: {e}")),
488 }
489 }
490 if loaded.is_empty() {
491 return Err(format!(
492 "no loadable frontier among {} entries: {}",
493 entries.len(),
494 warnings.join(" | ")
495 ));
496 }
497 let (service, more) = Self::from_projects(loaded, profile_str, exclude)?;
498 warnings.extend(more);
499 Ok((service, warnings))
500 }
501
502 pub fn from_projects(
508 entries: Vec<(String, Project)>,
509 profile_str: &str,
510 exclude: &[String],
511 ) -> Result<(Self, Vec<String>), String> {
512 let profile = tool_registry::McpProfile::parse(profile_str)?;
513 if entries.is_empty() {
514 return Err("no frontier projects to serve".to_string());
515 }
516 let mut named = Vec::with_capacity(entries.len());
517 for (name, mut frontier) in entries {
518 sources::materialize_project(&mut frontier);
519 named.push((name, frontier));
520 }
521 let project_infos = named
522 .iter()
523 .map(|(name, frontier)| ProjectInfo {
524 name: frontier.project.name.clone(),
525 file: name.clone(),
526 findings_count: frontier.findings.len(),
527 links_count: frontier.stats.links,
528 papers: frontier.project.papers_processed,
529 })
530 .collect();
531 let project = merge_projects(named);
532 Ok((
533 Self {
534 state: AppState {
535 project: Arc::new(Mutex::new(project)),
536 project_infos,
537 client: Client::new(),
538 profile,
539 source_path: None,
540 },
541 excluded: exclude.iter().cloned().collect(),
542 },
543 Vec::new(),
544 ))
545 }
546
547 pub fn hosted_exclusions() -> Vec<String> {
554 ["verify", "work", "objects"]
555 .into_iter()
556 .map(str::to_string)
557 .collect()
558 }
559
560 pub async fn handle_http(&self, body: &str) -> (u16, Option<Value>) {
563 mcp_http_exchange(body, &self.state, &self.excluded).await
564 }
565
566 pub fn frontier_labels(&self) -> Vec<String> {
568 self.state
569 .project_infos
570 .iter()
571 .map(|i| format!("{} ({})", i.name, i.file))
572 .collect()
573 }
574}
575
576pub async fn run_http(
577 source: ProjectSource,
578 backend: Option<&str>,
579 port: u16,
580 profile: tool_registry::McpProfile,
581) {
582 let _ = backend;
583 let (frontier, project_infos) = load_projects(&source);
586 let source_path = match &source {
587 ProjectSource::Single(path) => Some(path.clone()),
588 ProjectSource::Directory(_) => None,
589 };
590 let state = AppState {
591 project: Arc::new(Mutex::new(frontier)),
592 project_infos,
593 client: Client::new(),
594 profile,
595 source_path,
596 };
597
598 let app = Router::new()
603 .route("/health", get(http_health))
604 .route("/healthz", get(http_health))
605 .route("/entries", get(http_entries))
606 .route("/entries/{vfr}", get(http_entry))
607 .route("/entries/{vfr}/findings", get(http_entry_findings))
608 .route("/entries/{vfr}/findings/{id}", get(http_entry_finding))
609 .route("/entries/{vfr}/events", get(http_entry_events))
610 .route("/mcp", post(http_mcp).get(http_mcp_get));
613
614 let app = app
622 .layer(axum::extract::DefaultBodyLimit::max(8 * 1024 * 1024))
623 .with_state(state);
624
625 let addr = format!("127.0.0.1:{port}");
630 eprintln!(
631 " {}",
632 format!("VELA · SERVE · HTTP :{port}").to_uppercase()
633 );
634 eprintln!(" {}", vela_protocol::cli_style::tick_row(60));
635 eprintln!(" listening on http://{addr}");
636 eprintln!(" endpoints:");
640 eprintln!(" health: GET /health /healthz");
641 eprintln!(" entries: GET /entries (single-element list)");
642 eprintln!(" GET /entries/self (frontier summary)");
643 eprintln!(" GET /entries/self/findings (?query= to search)");
644 eprintln!(" GET /entries/self/findings/{{id}}");
645 eprintln!(" GET /entries/self/events?cursor=&limit=");
646 eprintln!(" tools: POST /mcp (streamable-HTTP MCP; the tool surface)");
647 let listener = tokio::net::TcpListener::bind(&addr)
648 .await
649 .unwrap_or_else(|e| {
650 eprintln!(
651 "{} failed to bind to {addr}: {e}",
652 vela_protocol::cli_style::err_prefix()
653 );
654 std::process::exit(1);
655 });
656 axum::serve(listener, app).await.unwrap();
657}
658
659pub fn check_tools(source: ProjectSource, adoption: bool) -> Result<Value, String> {
660 let started = std::time::Instant::now();
661 let source_label = match &source {
662 ProjectSource::Single(path) => path.display().to_string(),
663 ProjectSource::Directory(path) => path.display().to_string(),
664 };
665 let source_path = match &source {
666 ProjectSource::Single(p) => Some(p.as_path()),
667 ProjectSource::Directory(p) => Some(p.as_path()),
668 };
669 let (frontier, _project_infos) = load_projects(&source);
670 let first_id = frontier.findings.first().map(|finding| finding.id.clone());
671 let mut checks = vec![
672 check_tool_result(
673 "orient",
674 tool_orient(&json!({}), &frontier, source_path),
675 started,
676 ),
677 check_tool_result(
678 "search",
679 tool_search(&json!({"query": "Sidon", "limit": 3}), &frontier),
680 started,
681 ),
682 check_tool_result("graph", tool_graph(&json!({}), &frontier), started),
683 check_tool_result(
684 "graph",
685 tool_graph(&json!({"mode": "contradictions"}), &frontier),
686 started,
687 ),
688 ];
689 if let Some(id) = first_id {
690 checks.push(check_tool_result(
691 "finding",
692 tool_finding(
693 &json!({"id": id, "include": ["history", "dependents", "neighborhood"]}),
694 &frontier,
695 ),
696 started,
697 ));
698 checks.push(check_tool_result(
699 "orient",
700 tool_orient(&json!({"problem": id}), &frontier, source_path),
701 started,
702 ));
703 checks.push(check_tool_result(
704 "graph",
705 tool_graph(
706 &json!({"root": id, "mode": "traverse", "max_hops": 3}),
707 &frontier,
708 ),
709 started,
710 ));
711 checks.push(check_tool_result(
712 "graph",
713 tool_graph(&json!({"root": id, "mode": "impact"}), &frontier),
714 started,
715 ));
716 checks.push(check_tool_result(
717 "external",
718 parse_payload(tool_nanopublication(&json!({"finding_id": id}), &frontier))
719 .map(|v| (v, Vec::new())),
720 started,
721 ));
722 }
723 let failures = checks
724 .iter()
725 .filter(|check| check.get("ok").and_then(Value::as_bool) != Some(true))
726 .filter_map(|check| {
727 check
728 .get("tool")
729 .and_then(Value::as_str)
730 .map(str::to_string)
731 })
732 .collect::<Vec<_>>();
733 let checked_tools = checks
734 .iter()
735 .filter_map(|check| check.get("tool").and_then(Value::as_str))
736 .map(str::to_string)
737 .collect::<Vec<_>>();
738 let registered_tools = tool_registry::all_tools()
739 .into_iter()
740 .map(|tool| tool.name)
741 .collect::<Vec<_>>();
742 let adoption_report = adoption.then(|| adoption_tool_report(&checks, &source_label));
743
744 Ok(json!({
745 "ok": failures.is_empty(),
746 "command": if adoption { "serve --check-tools --adoption" } else { "serve --check-tools" },
747 "schema": "vela.tool-check.v0",
748 "frontier": {
749 "name": frontier.project.name,
750 "findings": frontier.stats.findings,
751 "links": frontier.stats.links,
752 },
753 "summary": {
754 "checks": checks.len(),
755 "passed": checks.len().saturating_sub(failures.len()),
756 "failed": failures.len(),
757 },
758 "tool_count": checked_tools.len(),
759 "tools": checked_tools,
760 "registered_tool_count": registered_tools.len(),
761 "registered_tools": registered_tools,
762 "checks": checks,
763 "failures": failures,
764 "adoption": adoption_report,
765 }))
766}
767
768fn adoption_tool_report(checks: &[Value], source_label: &str) -> Value {
769 let required_tools = vec!["orient", "search", "finding", "graph"];
770 let missing_or_failed = required_tools
771 .iter()
772 .filter(|tool| {
773 !checks.iter().any(|check| {
774 check.get("tool").and_then(Value::as_str) == Some(**tool)
775 && check.get("ok").and_then(Value::as_bool) == Some(true)
776 })
777 })
778 .copied()
779 .collect::<Vec<_>>();
780 json!({
781 "ok": missing_or_failed.is_empty(),
782 "required_tools": required_tools,
783 "missing_or_failed": missing_or_failed,
784 "mcp_config": {
785 "mcpServers": {
786 "vela": {
787 "command": "vela",
788 "args": ["serve", source_label]
789 }
790 }
791 },
792 "prompt": "Call orient first. Then use search for the review question. Inspect important results with finding (include history/dependents/neighborhood as needed). Cite vf_* ids. Review graph mode=contradictions and orient's gaps as candidate signals. Use graph mode=traverse on a root before summarizing provenance. Preserve caveats and do not present Vela output as field consensus.",
793 "commands": [
794 format!("vela serve {source_label} --check-tools --adoption --json"),
795 format!("vela serve {source_label}")
796 ],
797 })
798}
799
800#[derive(Clone)]
801pub(crate) struct AppState {
802 pub(crate) project: Arc<Mutex<Project>>,
803 pub(crate) project_infos: Vec<ProjectInfo>,
804 pub(crate) client: Client,
805 pub(crate) profile: tool_registry::McpProfile,
808 pub(crate) source_path: Option<PathBuf>,
813}
814
815#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
818pub(crate) enum ToolErrorKind {
819 #[serde(rename = "NOT_FOUND")]
820 NotFound,
821 #[serde(rename = "INVALID_ARG")]
822 InvalidArg,
823 #[serde(rename = "PERMISSION_DENIED")]
824 PermissionDenied,
825 #[serde(rename = "INTERNAL")]
826 Internal,
827}
828
829#[derive(Debug, Clone, Serialize)]
830pub(crate) struct ToolError {
831 pub(crate) kind: ToolErrorKind,
832 pub(crate) message: String,
833 #[serde(skip_serializing_if = "Option::is_none")]
834 pub(crate) hint: Option<String>,
835}
836
837impl ToolError {
838 pub(crate) fn new(kind: ToolErrorKind, message: impl Into<String>) -> Self {
839 Self {
840 kind,
841 message: message.into(),
842 hint: None,
843 }
844 }
845
846 pub(crate) fn not_found(message: impl Into<String>) -> Self {
847 Self::new(ToolErrorKind::NotFound, message)
848 }
849
850 pub(crate) fn invalid(message: impl Into<String>) -> Self {
851 Self::new(ToolErrorKind::InvalidArg, message)
852 }
853
854 pub(crate) fn internal(message: impl Into<String>) -> Self {
855 Self::new(ToolErrorKind::Internal, message)
856 }
857
858 pub(crate) fn with_hint(mut self, hint: impl Into<String>) -> Self {
859 self.hint = Some(hint.into());
860 self
861 }
862
863 pub(crate) fn classify(message: String) -> Self {
867 let lc = message.to_lowercase();
868 let kind = if lc.contains("not found")
869 || lc.contains("no finding resolves")
870 || lc.contains("is not registered")
871 || lc.contains("no such file")
872 || lc.contains("is neither a finding")
873 {
874 ToolErrorKind::NotFound
875 } else if lc.contains("required")
876 || lc.contains("missing")
877 || lc.contains("must be")
878 || lc.contains("must start")
879 || lc.contains("must include")
880 || lc.contains("must contain")
881 || lc.contains("invalid")
882 || lc.contains("unknown edge kind")
883 || lc.contains("out of [0.0, 1.0]")
884 || lc.contains("is for agent:/ci: actors")
885 {
886 ToolErrorKind::InvalidArg
887 } else {
888 ToolErrorKind::Internal
889 };
890 Self::new(kind, message)
891 }
892}
893
894#[derive(Debug, Clone, Serialize)]
900struct ToolResult {
901 tool: String,
902 ok: bool,
903 data: Value,
904 #[serde(skip_serializing_if = "Vec::is_empty")]
905 notes: Vec<String>,
906 #[serde(skip_serializing_if = "Option::is_none")]
907 error: Option<ToolError>,
908 signals: Vec<signals::SignalItem>,
909 caveats: Vec<String>,
910 duration_ms: u128,
911}
912
913impl ToolResult {
914 fn success(
915 tool: &str,
916 data: Value,
917 notes: Vec<String>,
918 duration_ms: u128,
919 frontier: Option<&Project>,
920 ) -> Self {
921 let signal_items = frontier
922 .map(|project| signals::analyze(project, &[]).signals)
923 .unwrap_or_default();
924 Self {
925 tool: tool.to_string(),
926 ok: true,
927 data,
928 notes,
929 error: None,
930 signals: signal_items,
931 caveats: tool_registry::tool_caveats(tool),
932 duration_ms,
933 }
934 }
935
936 fn failure(tool: &str, error: ToolError, duration_ms: u128) -> Self {
937 Self {
938 tool: tool.to_string(),
939 ok: false,
940 data: Value::Null,
941 notes: Vec::new(),
942 error: Some(error),
943 signals: Vec::new(),
944 caveats: tool_registry::tool_caveats(tool),
945 duration_ms,
946 }
947 }
948
949 fn metadata(&self) -> Value {
950 json!({
951 "tool": self.tool,
952 "ok": self.ok,
953 "duration_ms": self.duration_ms,
954 "caveats": self.caveats,
955 })
956 }
957
958 fn to_json_text(&self) -> String {
959 serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
960 }
961
962 fn to_rpc(&self, id: &Option<Value>) -> Value {
963 let mut result = json!({
964 "content": [{"type": "text", "text": self.to_json_text()}],
965 "isError": !self.ok,
966 "_meta": self.metadata()
967 });
968 if self.ok && tool_registry::tool_output_schema(&self.tool).is_some() {
973 result["structuredContent"] = self.data.clone();
974 }
975 json_rpc_result(id, result)
976 }
977}
978
979fn profile_gate(name: &str, profile: tool_registry::McpProfile) -> Option<ToolError> {
985 let tool = tool_registry::get_tool(name)?;
986 if profile.allows(&tool) {
987 return None;
988 }
989 let hint = if tool_registry::McpProfile::Draft.allows(&tool) {
990 "restart `vela serve` with `--profile draft` for non-finalizing draft/work capabilities; human finalization is unavailable through MCP and remains terminal-only (`vela sign`)"
991 } else {
992 "this capability is unavailable through MCP"
993 };
994 Some(
995 ToolError::new(
996 ToolErrorKind::PermissionDenied,
997 format!(
998 "tool `{name}` ({}) is not available in the `{}` MCP profile",
999 tool.permission_level,
1000 profile.as_str()
1001 ),
1002 )
1003 .with_hint(hint),
1004 )
1005}
1006
1007async fn handle_tool_call(
1008 id: &Option<Value>,
1009 name: &str,
1010 args: &Value,
1011 frontier: &Arc<Mutex<Project>>,
1012 client: &Client,
1013 project_infos: &[ProjectInfo],
1014 source_path: Option<&Path>,
1015) -> Value {
1016 let started = std::time::Instant::now();
1017 let (result, snapshot) =
1018 execute_tool(name, args, frontier, client, project_infos, source_path).await;
1019 let elapsed = started.elapsed().as_millis();
1020 match result {
1021 Ok((data, notes)) => {
1022 ToolResult::success(name, data, notes, elapsed, snapshot.as_ref()).to_rpc(id)
1023 }
1024 Err(error) => ToolResult::failure(name, error, elapsed).to_rpc(id),
1025 }
1026}
1027
1028pub(crate) type ToolOutput = Result<(Value, Vec<String>), ToolError>;
1031
1032pub(crate) fn parse_payload(result: Result<String, String>) -> Result<Value, ToolError> {
1035 let text = result.map_err(ToolError::classify)?;
1036 serde_json::from_str(&text)
1037 .map_err(|e| ToolError::internal(format!("tool payload did not parse as JSON: {e}")))
1038}
1039
1040pub(crate) fn clamp_limit(args: &Value, default: u64, max: u64) -> usize {
1041 args.get("limit")
1042 .and_then(Value::as_u64)
1043 .unwrap_or(default)
1044 .clamp(1, max) as usize
1045}
1046
1047pub(crate) fn decode_cursor(args: &Value) -> Result<usize, ToolError> {
1050 match args.get("cursor").and_then(Value::as_str) {
1051 None => Ok(0),
1052 Some(c) => c.parse::<usize>().map_err(|_| {
1053 ToolError::invalid(format!("cursor '{c}' is not a cursor this server issued"))
1054 .with_hint("pass a previous response's next_cursor back unchanged")
1055 }),
1056 }
1057}
1058
1059pub(crate) async fn reload_served_project(
1067 frontier: &Arc<Mutex<Project>>,
1068 path: &Path,
1069) -> Result<Project, String> {
1070 let mut cached = frontier.lock().await;
1071 let mut fresh = repo::load_from_path(path)?;
1072 sources::materialize_project(&mut fresh);
1073 let snapshot = clone_project(&fresh);
1074 *cached = fresh;
1075 Ok(snapshot)
1076}
1077
1078async fn execute_tool(
1079 name: &str,
1080 args: &Value,
1081 frontier: &Arc<Mutex<Project>>,
1082 client: &Client,
1083 _project_infos: &[ProjectInfo],
1084 source_path: Option<&Path>,
1085) -> (ToolOutput, Option<Project>) {
1086 match name {
1087 "orient" => {
1088 let project = {
1089 let cached = frontier.lock().await;
1090 clone_project(&cached)
1091 };
1092 let output = tool_orient(args, &project, source_path);
1093 (output, Some(clone_project(&project)))
1094 }
1095 "finding" => {
1096 let project = frontier.lock().await;
1097 (tool_finding(args, &project), Some(clone_project(&project)))
1098 }
1099 "search" => {
1100 let project = frontier.lock().await;
1101 (tool_search(args, &project), Some(clone_project(&project)))
1102 }
1103 "graph" => {
1104 let project = frontier.lock().await;
1105 (tool_graph(args, &project), Some(clone_project(&project)))
1106 }
1107 "verify" => (tool_verify(args, source_path), None),
1108 "work" => {
1109 let result = tool_work(args, source_path);
1110 match result {
1111 Ok((data, mut notes)) => {
1112 let Some(path) = source_path else {
1113 return (
1117 Err(ToolError::new(
1118 ToolErrorKind::PermissionDenied,
1119 "work writes are unavailable without one configured frontier",
1120 )),
1121 None,
1122 );
1123 };
1124 match reload_served_project(frontier, path).await {
1125 Ok(snapshot) => (Ok((data, notes)), Some(snapshot)),
1126 Err(error) => {
1127 notes.push(format!(
1131 "write completed, but the MCP snapshot reload failed; reconnect before reading: {error}"
1132 ));
1133 (Ok((data, notes)), None)
1134 }
1135 }
1136 }
1137 Err(error) => (Err(error), None),
1138 }
1139 }
1140 "objects" => (tool_objects(args, source_path), None),
1141 "external" => {
1142 let project = frontier.lock().await;
1143 (
1144 tool_external(args, &project, client).await,
1145 Some(clone_project(&project)),
1146 )
1147 }
1148 _ => {
1149 let known: Vec<String> = tool_registry::all_tools()
1150 .into_iter()
1151 .map(|t| t.name)
1152 .collect();
1153 (
1154 Err(ToolError::not_found(format!("unknown tool `{name}`"))
1155 .with_hint(format!("this server exposes: {}", known.join(", ")))),
1156 None,
1157 )
1158 }
1159 }
1160}
1161
1162fn check_tool_result(name: &str, result: ToolOutput, started: std::time::Instant) -> Value {
1163 let duration_ms = started.elapsed().as_millis();
1164 match result {
1165 Ok((data, notes)) => {
1166 let has_data = !data.is_null();
1167 json!({
1168 "tool": name,
1169 "ok": has_data,
1170 "data": data,
1171 "notes": notes,
1172 "has_data": has_data,
1173 "caveats": tool_registry::tool_caveats(name),
1174 "duration_ms": duration_ms,
1175 })
1176 }
1177 Err(error) => json!({
1178 "tool": name,
1179 "ok": false,
1180 "data": Value::Null,
1181 "error": error,
1182 "caveats": tool_registry::tool_caveats(name),
1183 "duration_ms": duration_ms,
1184 }),
1185 }
1186}
1187
1188fn clone_project(project: &Project) -> Project {
1189 serde_json::from_value(serde_json::to_value(project).unwrap_or_default()).unwrap_or_else(|_| {
1190 project::assemble("unavailable", Vec::new(), 0, 1, "failed to clone frontier")
1191 })
1192}
1193
1194fn json_rpc_result(id: &Option<Value>, result: Value) -> Value {
1195 json!({"jsonrpc": "2.0", "id": id, "result": result})
1196}
1197
1198fn json_rpc_error(id: &Option<Value>, code: i32, message: &str) -> Value {
1199 json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
1200}
1201
1202#[cfg(test)]
1203mod mcp_service_tests {
1204 use super::*;
1205
1206 fn fixture() -> PathBuf {
1207 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../examples/erdos-formalization")
1208 }
1209
1210 fn work_fixture(root: &Path) -> PathBuf {
1211 let path = root.join("work-frontier");
1212 let mut project = vela_protocol::project::assemble("scope", vec![], 0, 0, "test");
1213 let event =
1214 vela_protocol::events::new_finding_event(vela_protocol::events::FindingEventInput {
1215 kind: "attempt.claimed",
1216 finding_id: "scope:probe",
1217 actor_id: "agent:owner",
1218 actor_type: "agent",
1219 reason: "scope test",
1220 before_hash: "sha256:null",
1221 after_hash: "sha256:null",
1222 payload: json!({
1223 "obligation_id": "scope:probe",
1224 "lease_ttl_seconds": 60,
1225 "claimant_actor": "agent:owner",
1226 "claimant_pubkey": "test"
1227 }),
1228 caveats: Vec::new(),
1229 timestamp: Some("2026-07-13T00:00:00Z"),
1230 });
1231 vela_protocol::reducer::apply_event(&mut project, &event).unwrap();
1232 project.events.push(event);
1233 vela_protocol::repo::init_repo(&path, &project).unwrap();
1234 let session = crate::workflow::session_dir(&path, "scope:probe");
1235 std::fs::create_dir_all(&session).unwrap();
1236 std::fs::write(session.join("producer-scratch.txt"), "fixture\n").unwrap();
1237 path
1238 }
1239
1240 fn service() -> McpService {
1241 let entries = vec![("erdos-formalization".to_string(), fixture())];
1242 let (service, warnings) =
1243 McpService::from_named_paths(&entries, "read-only", &McpService::hosted_exclusions())
1244 .expect("fixture frontier loads");
1245 assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1246 service
1247 }
1248
1249 #[tokio::test]
1250 async fn initialize_echoes_protocol_version_and_lists_filtered_tools() {
1251 let svc = service();
1252 let (status, body) = svc
1253 .handle_http(
1254 r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
1255 )
1256 .await;
1257 assert_eq!(status, 200);
1258 let body = body.unwrap();
1259 assert_eq!(body["result"]["protocolVersion"], "2025-06-18");
1260
1261 let (status, body) = svc
1262 .handle_http(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#)
1263 .await;
1264 assert_eq!(status, 200);
1265 let tools = body.unwrap()["result"]["tools"].clone();
1266 let names: Vec<String> = tools
1267 .as_array()
1268 .unwrap()
1269 .iter()
1270 .map(|t| t["name"].as_str().unwrap().to_string())
1271 .collect();
1272 assert_eq!(
1275 names,
1276 vec!["orient", "finding", "search", "graph", "external"],
1277 "hosted tools/list is the read-only surface minus verify/work/objects"
1278 );
1279 }
1280
1281 #[tokio::test]
1282 async fn tool_call_returns_envelope_and_excluded_tool_is_refused_by_name() {
1283 let svc = service();
1284 let (status, body) = svc
1285 .handle_http(
1286 r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"orient","arguments":{}}}"#,
1287 )
1288 .await;
1289 assert_eq!(status, 200);
1290 let body = body.unwrap();
1291 assert_eq!(body["result"]["isError"], false, "orient call succeeds");
1292 let text = body["result"]["content"][0]["text"].as_str().unwrap();
1295 let envelope: Value = serde_json::from_str(text).unwrap();
1296 assert_eq!(envelope["tool"], "orient");
1297 assert_eq!(envelope["ok"], true);
1298 assert!(envelope["data"].is_object(), "data payload present");
1299 assert!(envelope.get("markdown").is_none(), "no markdown field");
1300 assert!(envelope["duration_ms"].is_number());
1301
1302 let (status, body) = svc
1303 .handle_http(
1304 r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"verify","arguments":{}}}"#,
1305 )
1306 .await;
1307 assert_eq!(status, 200);
1308 let body = body.unwrap();
1309 assert_eq!(body["error"]["code"], -32602, "excluded tool refused");
1310 let message = body["error"]["message"].as_str().unwrap();
1311 assert!(
1312 message.contains("orient, finding, search, graph, external"),
1313 "refusal names the available tool set: {message}"
1314 );
1315 }
1316
1317 #[tokio::test]
1318 async fn errors_carry_kind_and_profile_gate_refuses_writes() {
1319 let svc = service();
1320 let (_, body) = svc
1322 .handle_http(
1323 r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"finding","arguments":{"id":"vf_does_not_exist"}}}"#,
1324 )
1325 .await;
1326 let body = body.unwrap();
1327 assert_eq!(body["result"]["isError"], true);
1328 let text = body["result"]["content"][0]["text"].as_str().unwrap();
1329 let envelope: Value = serde_json::from_str(text).unwrap();
1330 assert_eq!(envelope["ok"], false);
1331 assert_eq!(envelope["error"]["kind"], "NOT_FOUND");
1332
1333 let entries = vec![("erdos-formalization".to_string(), fixture())];
1337 let (local_svc, warnings) = McpService::from_named_paths(&entries, "read-only", &[])
1338 .expect("fixture frontier loads");
1339 assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1340 let (_, body) = local_svc
1341 .handle_http(
1342 r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"work","arguments":{}}}"#,
1343 )
1344 .await;
1345 let text = body.unwrap()["result"]["content"][0]["text"]
1346 .as_str()
1347 .unwrap()
1348 .to_string();
1349 let envelope: Value = serde_json::from_str(&text).unwrap();
1350 assert_eq!(envelope["error"]["kind"], "PERMISSION_DENIED");
1351 }
1352
1353 #[tokio::test]
1354 async fn failed_in_scope_work_does_not_refresh_the_served_snapshot() {
1355 let temp = tempfile::tempdir().unwrap();
1356 let path = work_fixture(temp.path()).canonicalize().unwrap();
1357 let project = repo::load_from_path(&path).unwrap();
1358 let frontier = Arc::new(Mutex::new(project));
1359 let args = json!({
1360 "frontier_path": path.display().to_string(),
1361 "action": "drop",
1362 "obligation_id": "scope:probe",
1363 "agent_actor": "agent:other"
1364 });
1365 let (result, snapshot) =
1366 execute_tool("work", &args, &frontier, &Client::new(), &[], Some(&path)).await;
1367 let error = result.unwrap_err();
1368 assert_eq!(error.kind, ToolErrorKind::PermissionDenied);
1369 assert!(snapshot.is_none(), "failed work must not refresh MCP reads");
1370 }
1371
1372 #[tokio::test]
1373 async fn delayed_earlier_refresh_cannot_overwrite_a_later_disk_state() {
1374 use vela_protocol::sign::ActorRecord;
1375
1376 let temp = tempfile::tempdir().unwrap();
1377 let path = temp.path().join("cache-race");
1378 let mut initial = project::assemble("cache-race", vec![], 0, 0, "initial");
1379 initial.project.description = "earlier write".to_string();
1380 repo::init_repo(&path, &initial).unwrap();
1381
1382 let frontier = Arc::new(Mutex::new(initial));
1383 let cache_guard = frontier.lock().await;
1388 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
1389 let early_frontier = Arc::clone(&frontier);
1390 let early_path = path.clone();
1391 let early_refresh = tokio::spawn(async move {
1392 started_tx.send(()).unwrap();
1393 reload_served_project(&early_frontier, &early_path).await
1394 });
1395 started_rx.await.unwrap();
1396 tokio::task::yield_now().await;
1397
1398 let mut later = repo::load_from_path(&path).unwrap();
1399 later.actors.push(ActorRecord {
1400 id: "agent:later-write".to_string(),
1401 public_key: "11".repeat(32),
1402 algorithm: "ed25519".to_string(),
1403 created_at: "2026-07-14T00:00:00Z".to_string(),
1404 tier: None,
1405 orcid: None,
1406 access_clearance: None,
1407 revoked_at: None,
1408 revoked_reason: None,
1409 });
1410 repo::save_to_path(&path, &later).unwrap();
1411 let late_frontier = Arc::clone(&frontier);
1412 let late_path = path.clone();
1413 let late_refresh =
1414 tokio::spawn(async move { reload_served_project(&late_frontier, &late_path).await });
1415
1416 drop(cache_guard);
1417 let early_snapshot = early_refresh.await.unwrap().unwrap();
1418 let late_snapshot = late_refresh.await.unwrap().unwrap();
1419 let has_later_write = |project: &Project| {
1420 project
1421 .actors
1422 .iter()
1423 .any(|actor| actor.id == "agent:later-write")
1424 };
1425 assert!(has_later_write(&early_snapshot));
1426 assert!(has_later_write(&late_snapshot));
1427 assert!(has_later_write(&*frontier.lock().await));
1428 }
1429
1430 #[tokio::test]
1431 async fn finalization_is_absent_and_unroutable_in_every_profile() {
1432 for profile in ["read-only", "draft"] {
1433 let entries = vec![("erdos-formalization".to_string(), fixture())];
1434 let (svc, warnings) = McpService::from_named_paths(&entries, profile, &[])
1435 .expect("fixture frontier loads");
1436 assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1437
1438 let (_, listed) = svc
1439 .handle_http(r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#)
1440 .await;
1441 assert!(
1442 !listed.unwrap()["result"]["tools"]
1443 .as_array()
1444 .unwrap()
1445 .iter()
1446 .any(|tool| tool["name"] == "decide"),
1447 "decide leaked into {profile} discovery"
1448 );
1449
1450 let before = serde_json::to_value(&*svc.state.project.lock().await).unwrap();
1451 let (_, body) = svc
1452 .handle_http(
1453 r#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"decide","arguments":{"proposal_id":"vpr_removed","action":"accept","reason":"must never route","reviewer_id":"reviewer:test","signature":"00"}}}"#,
1454 )
1455 .await;
1456 let text = body.unwrap()["result"]["content"][0]["text"]
1457 .as_str()
1458 .unwrap()
1459 .to_string();
1460 let envelope: Value = serde_json::from_str(&text).unwrap();
1461 assert_eq!(
1462 envelope["error"]["kind"], "NOT_FOUND",
1463 "removed finalizer must not reach a schema, profile gate, key lookup, or state handler in {profile}"
1464 );
1465 let after = serde_json::to_value(&*svc.state.project.lock().await).unwrap();
1466 assert_eq!(
1467 after, before,
1468 "removed finalizer mutated state in {profile}"
1469 );
1470 }
1471 }
1472
1473 async fn orient_envelope_normalized(svc: &McpService) -> Value {
1480 let (status, body) = svc
1481 .handle_http(
1482 r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"orient","arguments":{}}}"#,
1483 )
1484 .await;
1485 assert_eq!(status, 200);
1486 let body = body.unwrap();
1487 assert_eq!(body["result"]["isError"], false, "orient call succeeds");
1488 let text = body["result"]["content"][0]["text"].as_str().unwrap();
1489 let mut envelope: Value = serde_json::from_str(text).unwrap();
1490 envelope.as_object_mut().unwrap().remove("duration_ms");
1491 if let Some(frontier) = envelope
1492 .pointer_mut("/data/frontier")
1493 .and_then(Value::as_object_mut)
1494 {
1495 frontier.remove("compiled_at");
1496 }
1497 if let Some(replay) = envelope
1498 .pointer_mut("/data/verification/events/replay")
1499 .and_then(Value::as_object_mut)
1500 {
1501 for key in ["current_hash", "replayed_hash", "source_hash"] {
1502 replay.remove(key);
1503 }
1504 }
1505 envelope
1506 }
1507
1508 #[tokio::test]
1512 async fn from_projects_matches_from_named_paths() {
1513 let via_paths = service();
1514
1515 let project = repo::load_from_path(&fixture()).expect("fixture frontier loads raw");
1518 let (via_projects, warnings) = McpService::from_projects(
1519 vec![("erdos-formalization".to_string(), project)],
1520 "read-only",
1521 &McpService::hosted_exclusions(),
1522 )
1523 .expect("service builds from in-memory projects");
1524 assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
1525
1526 let list_req = r#"{"jsonrpc":"2.0","id":8,"method":"tools/list"}"#;
1527 let (s1, list_paths) = via_paths.handle_http(list_req).await;
1528 let (s2, list_projects) = via_projects.handle_http(list_req).await;
1529 assert_eq!(s1, 200);
1530 assert_eq!(s2, 200);
1531 assert_eq!(
1532 list_paths, list_projects,
1533 "tools/list must be identical across the two constructors"
1534 );
1535
1536 let orient_paths = orient_envelope_normalized(&via_paths).await;
1537 let orient_projects = orient_envelope_normalized(&via_projects).await;
1538 assert_eq!(
1539 orient_paths, orient_projects,
1540 "orient output must be identical across the two constructors"
1541 );
1542 }
1543
1544 #[tokio::test]
1545 async fn notifications_get_202_and_batches_collect() {
1546 let svc = service();
1547 let (status, body) = svc
1548 .handle_http(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
1549 .await;
1550 assert_eq!(status, 202);
1551 assert!(body.is_none());
1552
1553 let (status, body) = svc
1554 .handle_http(
1555 r#"[{"jsonrpc":"2.0","method":"notifications/initialized"},{"jsonrpc":"2.0","id":5,"method":"ping"}]"#,
1556 )
1557 .await;
1558 assert_eq!(status, 200);
1559 assert_eq!(body.unwrap().as_array().unwrap().len(), 1);
1560
1561 let (status, body) = svc.handle_http("not json").await;
1562 assert_eq!(status, 400);
1563 assert_eq!(body.unwrap()["error"]["code"], -32700);
1564 }
1565}