Skip to main content

offline_mcp/
lib.rs

1//! # offline-mcp
2//!
3//! MCP server over stdio for the Offline Protocol registry.
4//! Run via `offline mcp serve`.
5
6pub mod account;
7pub mod lookup;
8pub mod mode;
9pub mod prompts;
10pub mod protocol;
11pub mod resources;
12pub mod server;
13pub mod tools;
14
15pub use mode::DeploymentMode;
16pub use server::{AccountTools, McpServer};
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21    use offline_registry::Registry;
22    use serde_json::{json, Value};
23
24    fn server() -> McpServer {
25        McpServer::new(Registry::load_embedded().unwrap())
26    }
27
28    fn call(server: &McpServer, msg: Value) -> Value {
29        let raw = server
30            .handle_message(&msg.to_string())
31            .expect("expected a response");
32        serde_json::from_str(&raw).unwrap()
33    }
34
35    #[test]
36    fn initialize_negotiates_version() {
37        let s = server();
38        let resp = call(
39            &s,
40            json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",
41                   "params": {"protocolVersion": "2025-03-26", "capabilities": {}}}),
42        );
43        assert_eq!(resp["result"]["protocolVersion"], "2025-03-26");
44        assert_eq!(resp["result"]["serverInfo"]["name"], "offline-protocol");
45        // Unknown version falls back to latest.
46        let resp = call(
47            &s,
48            json!({"jsonrpc": "2.0", "id": 2, "method": "initialize",
49                   "params": {"protocolVersion": "1999-01-01"}}),
50        );
51        assert_eq!(resp["result"]["protocolVersion"], "2025-06-18");
52    }
53
54    #[test]
55    fn notifications_get_no_response() {
56        let s = server();
57        assert!(s
58            .handle_message(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
59            .is_none());
60    }
61
62    #[test]
63    fn hosted_mode_omits_write_tools() {
64        use crate::mode::DeploymentMode;
65        use crate::tools::{call_tool_for, tool_definitions_for};
66
67        let registry = Registry::load_embedded().unwrap();
68        let tools = tool_definitions_for(DeploymentMode::Hosted);
69        let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
70        for blocked in ["scaffold_project", "integrate_packages", "init_project"] {
71            assert!(
72                !names.contains(&blocked),
73                "hosted tools/list must not include {blocked}"
74            );
75        }
76        assert!(names.contains(&"preview_scaffold"));
77        assert!(names.contains(&"generate_architecture"));
78
79        let err = call_tool_for(
80            &registry,
81            "scaffold_project",
82            &json!({"name": "x", "platform": "nextjs"}),
83            DeploymentMode::Hosted,
84        )
85        .unwrap_err();
86        assert!(err.contains("hosted MCP"));
87    }
88
89    #[test]
90    fn hosted_server_tools_list_via_rpc() {
91        let registry = Registry::load_embedded().unwrap();
92        let s = McpServer::with_mode(registry, DeploymentMode::Hosted);
93        let resp = call(
94            &s,
95            json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}),
96        );
97        let names: Vec<&str> = resp["result"]["tools"]
98            .as_array()
99            .unwrap()
100            .iter()
101            .map(|t| t["name"].as_str().unwrap())
102            .collect();
103        assert!(!names.contains(&"scaffold_project"));
104    }
105
106    #[test]
107    fn tools_list_and_call_roundtrip() {
108        let s = server();
109        let resp = call(
110            &s,
111            json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}),
112        );
113        let tools = resp["result"]["tools"].as_array().unwrap();
114        assert!(tools.len() >= 16);
115        let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
116        for required in [
117            "list_packages",
118            "get_package",
119            "search_packages",
120            "search_capabilities",
121            "search_workflows",
122            "search_skills",
123            "search_examples",
124            "resolve_packages",
125            "get_template",
126            "generate_architecture",
127            "get_skill",
128            "preview_scaffold",
129            "scaffold_project",
130            "integrate_packages",
131            "init_project",
132        ] {
133            assert!(names.contains(&required), "missing tool {required}");
134        }
135
136        let resp = call(
137            &s,
138            json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call",
139                   "params": {"name": "get_package",
140                              "arguments": {"name": "@offline-protocol/mesh-sdk"}}}),
141        );
142        assert_eq!(resp["result"]["isError"], false);
143        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
144        assert!(text.contains("mesh-networking"));
145    }
146
147    #[test]
148    fn generate_architecture_tool_plans_social_app() {
149        let s = server();
150        let resp = call(
151            &s,
152            json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call",
153                   "params": {"name": "generate_architecture",
154                              "arguments": {"prompt": "Build an offline social network"}}}),
155        );
156        assert_eq!(resp["result"]["isError"], false);
157        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
158        let parsed: Value = serde_json::from_str(text).unwrap();
159        assert_eq!(parsed["plan"]["workflow"], "offline-social-network");
160        assert!(parsed["documents"]["architecture.md"]
161            .as_str()
162            .unwrap()
163            .contains("# Architecture"));
164        assert!(!parsed["nextActions"].as_array().unwrap().is_empty());
165        assert_eq!(
166            parsed["nextActions"][0]["tool"].as_str().unwrap(),
167            "scaffold_project"
168        );
169    }
170
171    #[test]
172    fn preview_and_scaffold_project() {
173        let s = server();
174        let dir = tempfile::tempdir().unwrap();
175        let target = dir.path().join("pulse-social");
176
177        let resp = call(
178            &s,
179            json!({"jsonrpc": "2.0", "id": 20, "method": "tools/call",
180            "params": {"name": "preview_scaffold",
181                       "arguments": {
182                           "prompt": "Build an offline social network",
183                           "platform": "nextjs",
184                           "name": "pulse-social",
185                           "dir": target.to_string_lossy()
186                       }}}),
187        );
188        assert_eq!(resp["result"]["isError"], false);
189        let preview: Value =
190            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
191        assert_eq!(preview["dryRun"], true);
192        assert_eq!(preview["template"], "nextjs-social");
193        assert!(!target.exists() || !target.join("package.json").exists());
194
195        let resp = call(
196            &s,
197            json!({"jsonrpc": "2.0", "id": 21, "method": "tools/call",
198            "params": {"name": "scaffold_project",
199                       "arguments": {
200                           "prompt": "Build an offline social network",
201                           "platform": "nextjs",
202                           "name": "pulse-social",
203                           "dir": target.to_string_lossy(),
204                           "projectId": "proj_test"
205                       }}}),
206        );
207        assert_eq!(resp["result"]["isError"], false);
208        let created: Value =
209            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
210        assert_eq!(created["dryRun"], false);
211        assert!(target.join("package.json").exists());
212        assert!(target.join("architecture.md").exists());
213
214        // Generated MCP config runs this release through npx, not a global binary.
215        let mcp: Value =
216            serde_json::from_str(&std::fs::read_to_string(target.join(".mcp.json")).unwrap())
217                .unwrap();
218        assert_eq!(mcp["mcpServers"]["offline-protocol"]["command"], "npx");
219        assert_eq!(
220            mcp["mcpServers"]["offline-protocol"]["args"][1],
221            format!("@offline-protocol/cli@{}", offline_registry::CLI_VERSION)
222        );
223        let providers = std::fs::read_to_string(target.join("src/app/providers.tsx")).unwrap();
224        assert!(providers.contains("<OfflineAppProvider appId={APP_ID}>"));
225    }
226
227    #[test]
228    fn scaffold_react_native_mesh_app() {
229        let s = server();
230        let dir = tempfile::tempdir().unwrap();
231        let target = dir.path().join("mesh-test-app");
232
233        let resp = call(
234            &s,
235            json!({"jsonrpc": "2.0", "id": 30, "method": "tools/call",
236            "params": {"name": "scaffold_project",
237                       "arguments": {
238                           "template": "react-native-mesh-app",
239                           "platform": "react-native",
240                           "name": "mesh-test-app",
241                           "dir": target.to_string_lossy(),
242                           "appId": "mesh-test-app",
243                           "enableMesh": true
244                       }}}),
245        );
246        assert_eq!(resp["result"]["isError"], false);
247        let created: Value =
248            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
249        assert_eq!(created["dryRun"], false);
250        assert_eq!(created["template"], "react-native-mesh-app");
251        assert_eq!(created["meshEnabled"], true);
252
253        assert!(target.join("package.json").exists());
254        assert!(target.join("src/context/ProtocolContext.tsx").exists());
255        assert!(target.join("src/constants.ts").exists());
256        assert!(target.join("android").is_dir());
257        assert!(target.join("ios").is_dir());
258
259        let protocol_ctx =
260            std::fs::read_to_string(target.join("src/context/ProtocolContext.tsx")).unwrap();
261        assert!(
262            protocol_ctx.contains("mlsGetOrCreateKeyPackage"),
263            "scaffolded mesh app must attach MLS key packages on connection requests"
264        );
265        assert!(
266            protocol_ctx.contains("connection_request_undeliverable"),
267            "scaffolded mesh app must handle connection_request_undeliverable"
268        );
269        assert!(
270            protocol_ctx.contains("localAddressRef"),
271            "scaffolded mesh app must wait for local off1 address before sending connection requests"
272        );
273        assert!(
274            protocol_ctx.contains("BLE_DESTROY_SETTLE_MS"),
275            "scaffolded mesh app must pause after native destroy before recreate (iOS BLE settle)"
276        );
277
278        let people = std::fs::read_to_string(target.join("src/screens/PeopleScreen.tsx")).unwrap();
279        assert!(
280            people.contains("PROTOCOL_CONFIG.appId"),
281            "People screen must remind users both devices need the same appId"
282        );
283
284        let manifest =
285            std::fs::read_to_string(target.join("android/app/src/main/AndroidManifest.xml"))
286                .unwrap();
287        assert!(manifest.contains("BLUETOOTH_SCAN"));
288
289        let podfile = std::fs::read_to_string(target.join("ios/Podfile")).unwrap();
290        assert!(
291            !podfile.contains("pod 'MeshSdk'"),
292            "scaffolded Podfile must not add a manual MeshSdk pod (autolinking uses package-root podspec)"
293        );
294        assert!(
295            podfile.contains("FMT_USE_CONSTEVAL"),
296            "scaffolded iOS Podfile must include Xcode 26 fmt build patch"
297        );
298    }
299
300    #[test]
301    fn scaffold_offline_id_mesh_chat_routes_to_social_with_mesh() {
302        let s = server();
303        let dir = tempfile::tempdir().unwrap();
304        let target = dir.path().join("id-mesh-chat-app");
305
306        let resp = call(
307            &s,
308            json!({"jsonrpc": "2.0", "id": 31, "method": "tools/call",
309            "params": {"name": "preview_scaffold",
310                       "arguments": {
311                           "prompt": "Create a React Native mesh chat app using Offline ID",
312                           "platform": "react-native",
313                           "name": "id-mesh-chat-app",
314                           "dir": target.to_string_lossy(),
315                           "projectId": "proj_test"
316                       }}}),
317        );
318        assert_eq!(resp["result"]["isError"], false);
319        let preview: Value =
320            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
321        assert_eq!(preview["template"], "react-native-social");
322        assert_eq!(preview["meshEnabled"], true);
323        assert_eq!(preview["offlineIdEnabled"], true);
324        let skills = preview["skills"].as_array().unwrap();
325        assert!(
326            skills
327                .iter()
328                .any(|s| s.as_str() == Some("offline-id-mesh-integration")),
329            "offline-id mesh scaffolds must recommend offline-id-mesh-integration skill first"
330        );
331    }
332
333    #[test]
334    fn entrance_prompts_plan_and_scaffold_their_workflows() {
335        let s = server();
336        let cases = [
337            ("Durable equipment handoff between field engineers, with persistence and backend reconciliation", "local-handoff", "react-native-mesh-handoff"),
338            ("Retain sensor telemetry during outages and deliver it to a backend with explicit acceptance", "backend-delivery", "react-native-mesh-event-delivery"),
339            ("Discover and invoke an authorised nearby service from an existing application", "nearby-service", "react-native-mesh-service"),
340        ];
341        for (i, (prompt, workflow, template)) in cases.into_iter().enumerate() {
342            let resp = call(
343                &s,
344                json!({"jsonrpc": "2.0", "id": 80 + i, "method": "tools/call",
345                       "params": {"name": "generate_architecture", "arguments": {"prompt": prompt}}}),
346            );
347            assert_eq!(resp["result"]["isError"], false, "{prompt}");
348            let parsed: Value =
349                serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap())
350                    .unwrap();
351            assert_eq!(parsed["plan"]["workflow"], workflow);
352            assert_eq!(parsed["plan"]["template"], template);
353            let actions = parsed["nextActions"].as_array().unwrap();
354            let first = actions[0]["tool"].as_str().unwrap();
355            if workflow == "nearby-service" {
356                // "from an existing application": brownfield first.
357                assert_eq!(first, "integrate_packages");
358                assert_eq!(actions[1]["tool"], "init_project");
359            } else {
360                assert_eq!(first, "scaffold_project");
361            }
362
363            let preview = call(
364                &s,
365                json!({"jsonrpc": "2.0", "id": 90 + i, "method": "tools/call",
366                       "params": {"name": "preview_scaffold", "arguments": {"prompt": prompt, "name": "field-app"}}}),
367            );
368            assert_eq!(preview["result"]["isError"], false, "{prompt}");
369            let preview: Value =
370                serde_json::from_str(preview["result"]["content"][0]["text"].as_str().unwrap())
371                    .unwrap();
372            assert_eq!(preview["template"], template);
373            assert_eq!(preview["meshEnabled"], true);
374            let skills: Vec<&str> = preview["skills"]
375                .as_array()
376                .unwrap()
377                .iter()
378                .filter_map(Value::as_str)
379                .collect();
380            assert_eq!(skills[0], workflow, "{skills:?}");
381            assert!(!skills.contains(&"groups"), "{skills:?}");
382        }
383    }
384
385    #[test]
386    fn workflow_templates_always_enable_mesh() {
387        let s = server();
388        for (id, template) in [
389            (60, "react-native-mesh-handoff"),
390            (61, "react-native-mesh-event-delivery"),
391            (62, "react-native-mesh-service"),
392        ] {
393            let resp = call(
394                &s,
395                json!({"jsonrpc": "2.0", "id": id, "method": "tools/call",
396                "params": {"name": "preview_scaffold",
397                           "arguments": {"template": template, "name": "field-app"}}}),
398            );
399            assert_eq!(resp["result"]["isError"], false, "{template}");
400            let preview: Value =
401                serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap())
402                    .unwrap();
403            assert_eq!(preview["template"], template);
404            assert_eq!(preview["meshEnabled"], true, "{template}");
405            assert_eq!(preview["offlineIdEnabled"], false, "{template}");
406
407            let refused = call(
408                &s,
409                json!({"jsonrpc": "2.0", "id": id + 10, "method": "tools/call",
410                "params": {"name": "preview_scaffold",
411                           "arguments": {"template": template, "name": "field-app", "enableMesh": false}}}),
412            );
413            assert_eq!(refused["result"]["isError"], true, "{template}");
414        }
415    }
416
417    #[test]
418    fn scaffold_mesh_with_offline_id_switches_template() {
419        let s = server();
420        let dir = tempfile::tempdir().unwrap();
421        let target = dir.path().join("mesh-id-switch");
422
423        let resp = call(
424            &s,
425            json!({"jsonrpc": "2.0", "id": 32, "method": "tools/call",
426            "params": {"name": "preview_scaffold",
427                       "arguments": {
428                           "template": "react-native-mesh-app",
429                           "platform": "react-native",
430                           "name": "mesh-id-switch",
431                           "dir": target.to_string_lossy(),
432                           "enableOfflineId": true,
433                           "projectId": "proj_test"
434                       }}}),
435        );
436        assert_eq!(resp["result"]["isError"], false);
437        let preview: Value =
438            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
439        assert_eq!(preview["template"], "react-native-social");
440        assert_eq!(preview["offlineIdEnabled"], true);
441    }
442
443    #[test]
444    fn scaffold_mesh_without_offline_id_routes_to_mesh_app() {
445        let s = server();
446        let dir = tempfile::tempdir().unwrap();
447        let target = dir.path().join("mesh-no-id");
448
449        let resp = call(
450            &s,
451            json!({"jsonrpc": "2.0", "id": 33, "method": "tools/call",
452            "params": {"name": "preview_scaffold",
453                       "arguments": {
454                           "workflow": "offline-id-mesh-chat",
455                           "platform": "react-native",
456                           "name": "mesh-no-id",
457                           "dir": target.to_string_lossy(),
458                           "enableOfflineId": false,
459                           "enableMesh": true
460                       }}}),
461        );
462        assert_eq!(resp["result"]["isError"], false);
463        let preview: Value =
464            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
465        assert_eq!(preview["template"], "react-native-mesh-app");
466        assert_eq!(preview["offlineIdEnabled"], false);
467    }
468
469    #[test]
470    fn integrate_and_init_existing_project() {
471        let s = server();
472        let dir = tempfile::tempdir().unwrap();
473        let pkg = json!({
474            "name": "existing-app",
475            "dependencies": {"next": "14.0.0", "react": "18.0.0"}
476        });
477        std::fs::write(
478            dir.path().join("package.json"),
479            serde_json::to_string_pretty(&pkg).unwrap(),
480        )
481        .unwrap();
482
483        let resp = call(
484            &s,
485            json!({"jsonrpc": "2.0", "id": 22, "method": "tools/call",
486            "params": {"name": "integrate_packages",
487                       "arguments": {
488                           "packages": ["id-react"],
489                           "dir": dir.path().to_string_lossy()
490                       }}}),
491        );
492        assert_eq!(resp["result"]["isError"], false);
493        let integrated: Value =
494            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
495        assert!(!integrated["added"].as_array().unwrap().is_empty());
496
497        let pkg_after: Value = serde_json::from_str(
498            &std::fs::read_to_string(dir.path().join("package.json")).unwrap(),
499        )
500        .unwrap();
501        assert!(pkg_after["dependencies"]["@offline-protocol/id-react"].is_string());
502
503        let resp = call(
504            &s,
505            json!({"jsonrpc": "2.0", "id": 23, "method": "tools/call",
506            "params": {"name": "init_project",
507                       "arguments": {
508                           "dir": dir.path().to_string_lossy(),
509                           "projectId": "proj_abc"
510                       }}}),
511        );
512        assert_eq!(resp["result"]["isError"], false);
513        assert!(dir.path().join(".mcp.json").exists());
514        assert!(dir.path().join("offline.config.json").exists());
515        assert!(dir.path().join("AGENTS.md").exists());
516    }
517
518    fn tool_text(resp: &Value) -> String {
519        resp["result"]["content"][0]["text"]
520            .as_str()
521            .unwrap()
522            .to_string()
523    }
524
525    #[test]
526    fn every_tool_declares_annotations_matching_side_effects() {
527        use crate::tools::tool_definitions_for;
528
529        let local = tool_definitions_for(DeploymentMode::Local);
530        assert_eq!(local.len(), 18);
531        for tool in &local {
532            let name = tool["name"].as_str().unwrap();
533            let a = &tool["annotations"];
534            for hint in [
535                "readOnlyHint",
536                "destructiveHint",
537                "idempotentHint",
538                "openWorldHint",
539            ] {
540                assert!(a[hint].is_boolean(), "{name} lacks {hint}");
541            }
542            assert!(
543                !a["title"].as_str().unwrap().is_empty(),
544                "{name} lacks title"
545            );
546            let writes = ["scaffold_project", "integrate_packages", "init_project"].contains(&name);
547            assert_eq!(a["readOnlyHint"], !writes, "{name} readOnlyHint");
548            assert_eq!(a["destructiveHint"], false, "{name} destructiveHint");
549        }
550        let scaffold = local
551            .iter()
552            .find(|t| t["name"] == "scaffold_project")
553            .unwrap();
554        assert_eq!(scaffold["annotations"]["openWorldHint"], true);
555        assert_eq!(scaffold["annotations"]["idempotentHint"], false);
556
557        let hosted = tool_definitions_for(DeploymentMode::Hosted);
558        assert_eq!(hosted.len(), 15);
559        assert!(hosted
560            .iter()
561            .all(|t| t["annotations"]["readOnlyHint"] == true));
562    }
563
564    #[test]
565    fn unsupported_framework_prompt_returns_limitation_not_react_native_plan() {
566        let s = server();
567        for (id, prompt, framework) in [
568            (60, "Build a Flutter app that hands off kitchen orders between two Android tablets over Bluetooth", "Flutter"),
569            (61, "Native Android Kotlin app that sends files between phones over Wi-Fi Direct", "Kotlin"),
570            (62, "A SwiftUI iPhone app for nearby chat", "SwiftUI"),
571        ] {
572            let resp = call(
573                &s,
574                json!({"jsonrpc": "2.0", "id": id, "method": "tools/call",
575                       "params": {"name": "generate_architecture", "arguments": {"prompt": prompt}}}),
576            );
577            // A correct answer ("not supported"), not a tool failure, and no plan.
578            assert_eq!(resp["result"]["isError"], false, "{prompt}");
579            let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
580            assert_eq!(out["supported"], false, "{out}");
581            assert_eq!(out["planGenerated"], false, "{out}");
582            assert!(out.get("plan").is_none(), "{out}");
583            assert_eq!(out["framework"], framework);
584            let reason = out["reason"].as_str().unwrap();
585            assert!(reason.starts_with("no plan generated"), "{reason}");
586            assert!(reason.contains("platform \"react-native\""), "{reason}");
587            assert_eq!(out["alternatives"][0]["arguments"]["platform"], "react-native");
588            assert!(out["supportedPlatforms"]
589                .as_array()
590                .unwrap()
591                .contains(&json!("react-native")));
592
593            let resp = call(
594                &s,
595                json!({"jsonrpc": "2.0", "id": id + 10, "method": "tools/call",
596                       "params": {"name": "preview_scaffold",
597                                  "arguments": {"prompt": prompt, "name": "orders"}}}),
598            );
599            assert_eq!(resp["result"]["isError"], false, "preview: {prompt}");
600            let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
601            assert_eq!(out["supported"], false, "{out}");
602            assert_eq!(out["planGenerated"], false, "{out}");
603            assert!(out.get("template").is_none(), "{out}");
604        }
605
606        // A framework passed as the platform is answered the same way.
607        for tool in [
608            "generate_architecture",
609            "resolve_packages",
610            "preview_scaffold",
611        ] {
612            let resp = call(
613                &s,
614                json!({"jsonrpc": "2.0", "id": 65, "method": "tools/call",
615                       "params": {"name": tool,
616                                  "arguments": {"prompt": "nearby chat", "name": "x",
617                                                "platform": "flutter", "workflow": "nearby-chat"}}}),
618            );
619            assert_eq!(resp["result"]["isError"], false, "{tool}");
620            let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
621            assert_eq!(out["supported"], false, "{tool}: {out}");
622            assert_eq!(out["requestedPlatform"], "flutter");
623            // From SDK 0.30.0 `flutter` is a package-only platform (the plugin
624            // preview), answered like `kotlin`: no plan, the platform named.
625            assert!(
626                out["reason"]
627                    .as_str()
628                    .unwrap()
629                    .to_lowercase()
630                    .contains("flutter"),
631                "{tool}: {out}"
632            );
633        }
634
635        // An explicit platform is the caller's choice: plan, with a notice.
636        let resp = call(
637            &s,
638            json!({"jsonrpc": "2.0", "id": 70, "method": "tools/call",
639                   "params": {"name": "generate_architecture",
640                              "arguments": {"prompt": "Port our Flutter kitchen app: hand off orders over Bluetooth",
641                                            "platform": "react-native"}}}),
642        );
643        assert_eq!(resp["result"]["isError"], false);
644        let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
645        assert_eq!(out["plan"]["platform"], "react-native");
646        assert!(out["plan"]["resolution"]["warnings"][0]
647            .as_str()
648            .unwrap()
649            .contains("Flutter"));
650
651        // React Native with a Kotlin native module is still React Native.
652        let resp = call(
653            &s,
654            json!({"jsonrpc": "2.0", "id": 71, "method": "tools/call",
655                   "params": {"name": "generate_architecture",
656                              "arguments": {"prompt": "React Native nearby chat app with a Kotlin native module"}}}),
657        );
658        assert_eq!(resp["result"]["isError"], false);
659    }
660
661    #[test]
662    fn platform_errors_use_the_callers_platform_name() {
663        let s = server();
664        let resp = call(
665            &s,
666            json!({"jsonrpc": "2.0", "id": 80, "method": "tools/call",
667                   "params": {"name": "resolve_packages",
668                              "arguments": {"platform": "web", "packages": ["@offline-protocol/mesh-sdk"]}}}),
669        );
670        assert_eq!(resp["result"]["isError"], false);
671        let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
672        assert_eq!(out["supported"], false);
673        let reason = out["reason"].as_str().unwrap();
674        assert!(reason.contains("not `web`"), "{reason}");
675        assert!(
676            reason.contains("supports platforms [react-native]"),
677            "{reason}"
678        );
679        assert!(out["alternatives"]
680            .as_array()
681            .unwrap()
682            .iter()
683            .any(|a| a["arguments"]["platform"] == "react-native"));
684
685        let resp = call(
686            &s,
687            json!({"jsonrpc": "2.0", "id": 81, "method": "tools/call",
688                   "params": {"name": "generate_architecture",
689                              "arguments": {"prompt": "Browser web app that discovers nearby phones over Bluetooth and chats offline",
690                                            "platform": "web"}}}),
691        );
692        assert_eq!(resp["result"]["isError"], false);
693        let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
694        assert_eq!(out["supported"], false);
695        assert_eq!(out["planGenerated"], false);
696        assert!(out.get("plan").is_none());
697        let reason = out["reason"].as_str().unwrap();
698        assert!(reason.starts_with("no plan generated: "), "{reason}");
699        assert!(reason.contains("not `web`"), "{reason}");
700        assert_eq!(
701            out["alternatives"][0]["arguments"]["platform"],
702            "react-native"
703        );
704    }
705
706    #[test]
707    fn integrate_packages_preserves_package_json_layout() {
708        let s = server();
709        let dir = tempfile::tempdir().unwrap();
710        let original = "{\n    \"name\": \"kitchen\",\n    \"private\": true,\n    \"scripts\": {\n        \"dev\": \"vite\"\n    },\n    \"dependencies\": {\n        \"react\": \"^19.0.0\",\n        \"react-dom\": \"^19.0.0\"\n    },\n    \"devDependencies\": {\n        \"vite\": \"^7.0.0\"\n    }\n}\n";
711        std::fs::write(dir.path().join("package.json"), original).unwrap();
712        let resp = call(
713            &s,
714            json!({"jsonrpc": "2.0", "id": 90, "method": "tools/call",
715                   "params": {"name": "integrate_packages",
716                              "arguments": {"packages": ["id-react"], "dir": dir.path().to_string_lossy()}}}),
717        );
718        assert_eq!(resp["result"]["isError"], false);
719        let after = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
720        let core = offline_registry::Registry::load_embedded()
721            .unwrap()
722            .package("@offline-protocol/core")
723            .unwrap()
724            .version
725            .clone();
726        let id_react = offline_registry::Registry::load_embedded()
727            .unwrap()
728            .package("@offline-protocol/id-react")
729            .unwrap()
730            .version
731            .clone();
732        let expected = original.replace(
733            "    \"dependencies\": {\n",
734            &format!(
735                "    \"dependencies\": {{\n        \"@offline-protocol/core\": \"^{core}\",\n        \"@offline-protocol/id-react\": \"^{id_react}\",\n"
736            ),
737        );
738        assert_eq!(after, expected);
739    }
740
741    #[test]
742    fn init_project_respects_existing_mcp_json() {
743        let s = server();
744        let dir = tempfile::tempdir().unwrap();
745        std::fs::write(
746            dir.path().join("package.json"),
747            r#"{"name":"x","dependencies":{"react":"^19.0.0"}}"#,
748        )
749        .unwrap();
750        let existing_mcp = r#"{"mcpServers":{"github":{"command":"npx","args":["-y","@modelcontextprotocol/server-github"]}}}"#;
751        std::fs::write(dir.path().join(".mcp.json"), existing_mcp).unwrap();
752        std::fs::write(dir.path().join("AGENTS.md"), "# Team rules\n").unwrap();
753
754        let resp = call(
755            &s,
756            json!({"jsonrpc": "2.0", "id": 100, "method": "tools/call",
757                   "params": {"name": "init_project", "arguments": {"dir": dir.path().to_string_lossy()}}}),
758        );
759        assert_eq!(resp["result"]["isError"], false);
760        let out: Value = serde_json::from_str(&tool_text(&resp)).unwrap();
761        assert_eq!(out["mcpServer"]["registered"], false);
762        assert_eq!(
763            std::fs::read_to_string(dir.path().join(".mcp.json")).unwrap(),
764            existing_mcp
765        );
766        let agents = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
767        assert!(agents.starts_with("# Team rules\n"));
768        assert!(agents.contains("does not register the Offline Protocol MCP"));
769        assert!(!agents.contains("is registered in `.mcp.json`"));
770
771        // A second run appends nothing more.
772        call(
773            &s,
774            json!({"jsonrpc": "2.0", "id": 101, "method": "tools/call",
775                   "params": {"name": "init_project", "arguments": {"dir": dir.path().to_string_lossy()}}}),
776        );
777        assert_eq!(
778            std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap(),
779            agents
780        );
781    }
782
783    #[test]
784    fn init_project_writes_npx_mcp_json() {
785        let s = server();
786        let dir = tempfile::tempdir().unwrap();
787        std::fs::write(dir.path().join("package.json"), r#"{"name":"x"}"#).unwrap();
788        let resp = call(
789            &s,
790            json!({"jsonrpc": "2.0", "id": 110, "method": "tools/call",
791                   "params": {"name": "init_project", "arguments": {"dir": dir.path().to_string_lossy()}}}),
792        );
793        assert_eq!(resp["result"]["isError"], false);
794        let mcp: Value =
795            serde_json::from_str(&std::fs::read_to_string(dir.path().join(".mcp.json")).unwrap())
796                .unwrap();
797        let server = &mcp["mcpServers"]["offline-protocol"];
798        assert_eq!(server["command"], "npx");
799        assert_eq!(
800            server["args"][1],
801            format!("@offline-protocol/cli@{}", offline_registry::CLI_VERSION)
802        );
803        let agents = std::fs::read_to_string(dir.path().join("AGENTS.md")).unwrap();
804        assert!(agents.contains("is registered in `.mcp.json`"));
805    }
806
807    #[test]
808    fn init_project_wires_a_python_project() {
809        let s = server();
810        let dir = tempfile::tempdir().unwrap();
811        std::fs::write(
812            dir.path().join("pyproject.toml"),
813            "[project]\nname = \"gateway\"\n",
814        )
815        .unwrap();
816        let resp = call(
817            &s,
818            json!({"jsonrpc": "2.0", "id": 111, "method": "tools/call",
819                   "params": {"name": "init_project", "arguments": {"dir": dir.path().to_string_lossy()}}}),
820        );
821        assert_eq!(resp["result"]["isError"], false);
822        let config: Value = serde_json::from_str(
823            &std::fs::read_to_string(dir.path().join("offline.config.json")).unwrap(),
824        )
825        .unwrap();
826        assert_eq!(config["platform"], "python");
827        assert_eq!(config["projectName"], "gateway");
828        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
829        assert!(text.contains("pip install offline-protocol-sdk=="));
830        assert!(text.contains("mesh-sdk/python"));
831    }
832
833    #[test]
834    fn init_project_names_supported_manifests_in_an_empty_dir() {
835        let s = server();
836        let dir = tempfile::tempdir().unwrap();
837        let resp = call(
838            &s,
839            json!({"jsonrpc": "2.0", "id": 112, "method": "tools/call",
840                   "params": {"name": "init_project", "arguments": {"dir": dir.path().to_string_lossy()}}}),
841        );
842        assert_eq!(resp["result"]["isError"], true);
843        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
844        assert!(text.contains("Package.swift"));
845        assert!(text.contains("scaffold_project"));
846    }
847
848    #[test]
849    fn unknown_tool_reports_is_error_not_rpc_error() {
850        let s = server();
851        let resp = call(
852            &s,
853            json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call",
854                   "params": {"name": "nope", "arguments": {}}}),
855        );
856        assert!(resp["error"].is_null());
857        assert_eq!(resp["result"]["isError"], true);
858    }
859
860    #[test]
861    fn resources_list_and_read() {
862        let s = server();
863        let resp = call(
864            &s,
865            json!({"jsonrpc": "2.0", "id": 5, "method": "resources/list"}),
866        );
867        let resources = resp["result"]["resources"].as_array().unwrap();
868        assert!(resources.len() > 15);
869
870        let resp = call(
871            &s,
872            json!({"jsonrpc": "2.0", "id": 6, "method": "resources/read",
873                   "params": {"uri": "offline://skills/mesh-networking"}}),
874        );
875        let text = resp["result"]["contents"][0]["text"].as_str().unwrap();
876        assert!(text.contains("OfflineProtocol"));
877
878        let resp = call(
879            &s,
880            json!({"jsonrpc": "2.0", "id": 7, "method": "resources/read",
881                   "params": {"uri": "offline://llms.txt"}}),
882        );
883        let text = resp["result"]["contents"][0]["text"].as_str().unwrap();
884        assert!(text.contains("# Offline Protocol"));
885    }
886
887    #[test]
888    fn prompts_list_and_get() {
889        let s = server();
890        let resp = call(
891            &s,
892            json!({"jsonrpc": "2.0", "id": 8, "method": "prompts/list"}),
893        );
894        assert_eq!(resp["result"]["prompts"].as_array().unwrap().len(), 3);
895
896        let resp = call(
897            &s,
898            json!({"jsonrpc": "2.0", "id": 9, "method": "prompts/get",
899                   "params": {"name": "plan-app",
900                              "arguments": {"description": "nearby chat for festivals"}}}),
901        );
902        let text = resp["result"]["messages"][0]["content"]["text"]
903            .as_str()
904            .unwrap();
905        assert!(text.contains("generate_architecture"));
906    }
907
908    #[test]
909    fn generate_architecture_custom_p2p_game() {
910        let s = server();
911        let resp = call(
912            &s,
913            json!({"jsonrpc": "2.0", "id": 40, "method": "tools/call",
914                   "params": {"name": "generate_architecture",
915                              "arguments": {"prompt": "tic tac toe game over BLE for two phones"}}}),
916        );
917        assert_eq!(resp["result"]["isError"], false);
918        let parsed: Value =
919            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
920        assert_eq!(parsed["plan"]["workflow"], "custom-p2p-app");
921        assert!(parsed["plan"]["p2pProfile"]["syncModel"]
922            .as_str()
923            .unwrap()
924            .contains("host-authority"));
925        assert!(parsed["documents"]["architecture.md"]
926            .as_str()
927            .unwrap()
928            .contains("## P2P profile"));
929    }
930
931    #[test]
932    fn scaffold_custom_p2p_app() {
933        let s = server();
934        let dir = tempfile::tempdir().unwrap();
935        let target = dir.path().join("p2p-game");
936
937        let resp = call(
938            &s,
939            json!({"jsonrpc": "2.0", "id": 41, "method": "tools/call",
940            "params": {"name": "scaffold_project",
941                       "arguments": {
942                           "prompt": "offline Ludo game for two phones over BLE",
943                           "workflow": "custom-p2p-app",
944                           "platform": "react-native",
945                           "name": "p2p-game",
946                           "dir": target.to_string_lossy()
947                       }}}),
948        );
949        assert_eq!(resp["result"]["isError"], false);
950        let created: Value =
951            serde_json::from_str(resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
952        assert_eq!(created["template"], "react-native-mesh-custom-app");
953        assert!(target.join("src/domain/index.ts").exists());
954        assert!(target.join("src/wire.ts").exists());
955        assert!(target.join("src/session.ts").exists());
956        assert!(target.join("src/mesh.ts").exists());
957        assert!(target.join("src/meshEstablishment.ts").exists());
958        assert!(target.join("__tests__/mesh.test.ts").exists());
959        assert!(target.join("src/debug.ts").exists());
960        assert!(target.join("src/ui/PeerDiscovery.tsx").exists());
961        assert!(target.join("AGENTS.md").exists());
962        let arch = std::fs::read_to_string(target.join("architecture.md")).unwrap();
963        assert!(arch.contains("P2P profile"));
964        let mesh = std::fs::read_to_string(target.join("src/mesh.ts")).unwrap();
965        assert!(
966            mesh.contains("waitForLocalAddress"),
967            "custom P2P scaffold must wait for off1 identity before joining"
968        );
969        assert!(
970            mesh.contains("keyPackage"),
971            "custom P2P scaffold must attach MLS key packages on connection requests"
972        );
973        assert!(
974            mesh.contains("beginJoin"),
975            "custom P2P scaffold must use beginJoin before connection requests"
976        );
977        assert!(
978            mesh.contains("maybeInferHostFromNeighbors"),
979            "custom P2P scaffold must infer host when service discovery is slow"
980        );
981        assert!(
982            mesh.contains("TRANSPORT_IDENTITY_MISMATCH"),
983            "custom P2P scaffold must handle BLE identity mismatch"
984        );
985        assert!(
986            mesh.contains("connection_request_undeliverable"),
987            "custom P2P scaffold must handle connection_request_undeliverable"
988        );
989        assert!(
990            mesh.contains("requireEncryption: false"),
991            "custom P2P scaffold must not require MLS for app-level traffic"
992        );
993    }
994
995    fn tool_call(s: &McpServer, tool: &str, args: Value) -> (bool, Value) {
996        let resp = call(
997            s,
998            json!({"jsonrpc": "2.0", "id": 500, "method": "tools/call",
999                   "params": {"name": tool, "arguments": args}}),
1000        );
1001        assert!(resp["error"].is_null(), "{resp}");
1002        let is_error = resp["result"]["isError"].as_bool().unwrap();
1003        let text = tool_text(&resp);
1004        let value = serde_json::from_str(&text).unwrap_or(Value::String(text));
1005        (is_error, value)
1006    }
1007
1008    #[test]
1009    fn exact_names_answer_exactly_as_before() {
1010        let s = server();
1011        let r = Registry::load_embedded().unwrap();
1012        for skill in r.skills() {
1013            let (err, v) = tool_call(&s, "get_skill", json!({"name": skill.name}));
1014            assert!(!err);
1015            assert_eq!(v, json!(skill), "{}", skill.name);
1016        }
1017        for p in r.packages() {
1018            let (err, v) = tool_call(&s, "get_package", json!({"name": p.name}));
1019            assert!(!err);
1020            assert_eq!(v, json!(p), "{}", p.name);
1021        }
1022        for w in r.workflows() {
1023            let (err, v) = tool_call(&s, "get_workflow", json!({"name": w.name}));
1024            assert!(!err);
1025            assert_eq!(v, json!(w), "{}", w.name);
1026            for platform in w.packages.keys() {
1027                let (err, v) = tool_call(
1028                    &s,
1029                    "resolve_packages",
1030                    json!({"workflow": w.name, "platform": platform}),
1031                );
1032                assert!(!err);
1033                assert_eq!(v, json!(r.resolve_workflow(&w.name, platform).unwrap()));
1034            }
1035        }
1036        for t in r.templates() {
1037            let (err, v) = tool_call(&s, "get_template", json!({"name": t.name}));
1038            assert!(!err);
1039            assert_eq!(v["meta"], json!(t));
1040            assert!(v.get("note").is_none());
1041        }
1042        let (err, v) = tool_call(
1043            &s,
1044            "resolve_packages",
1045            json!({"platform": "web", "packages": ["@offline-protocol/id-react"]}),
1046        );
1047        assert!(!err);
1048        assert_eq!(
1049            v,
1050            json!(r
1051                .resolve_packages(&["@offline-protocol/id-react".to_string()], "nextjs")
1052                .unwrap())
1053        );
1054        let (err, v) = tool_call(
1055            &s,
1056            "generate_architecture",
1057            json!({"prompt": "Plan a nearby chat app", "platform": "react-native"}),
1058        );
1059        assert!(!err);
1060        assert!(v.get("note").is_none());
1061        let (err, v) = tool_call(
1062            &s,
1063            "preview_scaffold",
1064            json!({"prompt": "Plan a nearby chat app", "name": "fieldchat"}),
1065        );
1066        assert!(!err);
1067        assert_eq!(v["project"], "fieldchat");
1068        assert_eq!(v["notes"].as_array().unwrap().len(), 2, "{v}");
1069    }
1070
1071    #[test]
1072    fn near_miss_names_resolve_with_a_note() {
1073        let s = server();
1074        for (tool, input, expected) in [
1075            ("get_skill", "offline-messaging", "messaging"),
1076            ("get_skill", "Mesh Networking", "mesh-networking"),
1077            ("get_package", "mesh-sdk", "@offline-protocol/mesh-sdk"),
1078            ("get_package", "id-react", "@offline-protocol/id-react"),
1079            ("get_workflow", "nearby chat", "nearby-chat"),
1080            ("get_workflow", "NEARBY_CHAT", "nearby-chat"),
1081            ("get_template", "nextjs", "nextjs-social"),
1082        ] {
1083            let (err, v) = tool_call(&s, tool, json!({"name": input}));
1084            assert!(!err, "{tool} {input}: {v}");
1085            let name = if tool == "get_template" {
1086                &v["meta"]["name"]
1087            } else {
1088                &v["name"]
1089            };
1090            assert_eq!(name, expected, "{tool} {input}");
1091            let note = v["note"].as_str().unwrap();
1092            assert!(
1093                note.starts_with(&format!("resolved `{input}` to `{expected}`")),
1094                "{note}"
1095            );
1096        }
1097        // Resolution also applies to names inside other tools' arguments.
1098        let (err, v) = tool_call(
1099            &s,
1100            "resolve_packages",
1101            json!({"platform": "react-native", "packages": ["mesh-sdk"]}),
1102        );
1103        assert!(!err);
1104        assert_eq!(v["packages"][0]["name"], "@offline-protocol/mesh-sdk");
1105        assert!(v["note"].as_str().unwrap().contains("mesh-sdk"));
1106        let (err, v) = tool_call(
1107            &s,
1108            "preview_scaffold",
1109            json!({"template": "mesh handoff", "name": "x"}),
1110        );
1111        assert!(!err, "{v}");
1112        assert_eq!(v["template"], "react-native-mesh-handoff");
1113        assert!(v["notes"]
1114            .as_array()
1115            .unwrap()
1116            .iter()
1117            .any(|n| n.as_str().unwrap().starts_with("resolved `mesh handoff`")));
1118    }
1119
1120    #[test]
1121    fn ambiguous_and_unknown_names_are_answers_not_errors() {
1122        let s = server();
1123        let (err, v) = tool_call(&s, "get_template", json!({"name": "react-native"}));
1124        assert!(!err);
1125        assert_eq!(v["found"], false);
1126        assert!(v["message"]
1127            .as_str()
1128            .unwrap()
1129            .starts_with("Several matches:"));
1130        let names: Vec<&str> = v["matches"]
1131            .as_array()
1132            .unwrap()
1133            .iter()
1134            .map(|m| m["name"].as_str().unwrap())
1135            .collect();
1136        assert!(names.contains(&"react-native-mesh-app"));
1137        assert!(names.contains(&"react-native-mesh-handoff"));
1138        assert!(!names.contains(&"nextjs-social"));
1139
1140        for (tool, input, noun) in [
1141            ("get_skill", "quantum-teleport", "skill"),
1142            ("get_package", "@offline-protocol/flutter-sdk", "package"),
1143            ("get_workflow", "space-elevator", "workflow"),
1144            ("get_template", "flutter-starter", "template"),
1145        ] {
1146            let (err, v) = tool_call(&s, tool, json!({"name": input}));
1147            assert!(!err, "{tool} {input}");
1148            assert_eq!(v["found"], false);
1149            let message = v["message"].as_str().unwrap();
1150            assert!(
1151                message.starts_with(&format!(
1152                    "There is no Offline Protocol {noun} named `{input}`."
1153                )),
1154                "{message}"
1155            );
1156            assert!(!v["validNames"].as_array().unwrap().is_empty());
1157            assert!(v["closestMatches"].is_array());
1158        }
1159        let (err, v) = tool_call(&s, "get_skill", json!({"name": "mesh-netwrking"}));
1160        assert!(!err);
1161        assert_eq!(v["closestMatches"][0]["name"], "mesh-networking", "{v}");
1162
1163        let (err, v) = tool_call(&s, "get_package", json!({"name": "@offline-protocol/cli"}));
1164        assert!(!err);
1165        assert_eq!(v["supported"], false);
1166        assert_eq!(v["cli"]["package"], "@offline-protocol/cli");
1167
1168        let (err, v) = tool_call(
1169            &s,
1170            "resolve_packages",
1171            json!({"platform": "react-native", "packages": ["nope-sdk"]}),
1172        );
1173        assert!(!err);
1174        assert_eq!(v["found"], false);
1175    }
1176
1177    /// SDK 0.29.0 added the HTTP front in the Python service. Agents asking
1178    /// how a program without the SDK calls another device find it.
1179    #[test]
1180    fn sdk_0_29_http_front_questions_get_correct_answers() {
1181        let s = server();
1182        for query in ["http", "curl", "http front", "docker"] {
1183            let (err, v) = tool_call(&s, "search_capabilities", json!({"query": query}));
1184            assert!(!err);
1185            assert_eq!(v[0]["name"], "http-front", "{query}: {v}");
1186        }
1187        let (err, v) = tool_call(&s, "get_skill", json!({"name": "http-front"}));
1188        assert!(!err, "{v}");
1189        let body = v.to_string();
1190        assert!(body.contains("X-Offline-Protocol-Sender"), "{body}");
1191        assert!(body.contains("does not authorize"), "{body}");
1192    }
1193
1194    /// SDK 0.30.0 added a Flutter plugin (from source), a Java binding on
1195    /// Maven Central and a C API in the release archives. Agents asking for
1196    /// them get the package and its install line, never a React Native plan.
1197    #[test]
1198    fn sdk_0_30_bindings_get_correct_answers() {
1199        let s = server();
1200        for (query, first) in [
1201            ("flutter", "native-mobile"),
1202            ("java", "server-runtime"),
1203            ("cgo", "server-runtime"),
1204        ] {
1205            let (err, v) = tool_call(&s, "search_capabilities", json!({"query": query}));
1206            assert!(!err);
1207            assert_eq!(v[0]["name"], first, "{query}: {v}");
1208        }
1209        for (platform, package, expected) in [
1210            (
1211                "java",
1212                "java",
1213                "implementation(\"com.offlineprotocol:offline-protocol-java:0.34.0\")",
1214            ),
1215            (
1216                "jvm",
1217                "offline-protocol-java",
1218                "offline-protocol-java:0.34.0",
1219            ),
1220            ("c", "offline-protocol-c", "releases/tag/v0.34.0"),
1221            ("flutter", "flutter", "bindings/flutter/offline_protocol"),
1222            ("dart", "offline-protocol-flutter", "v0.34.0"),
1223        ] {
1224            let (err, v) = tool_call(
1225                &s,
1226                "resolve_packages",
1227                json!({"platform": platform, "packages": [package]}),
1228            );
1229            assert!(!err, "{platform}: {v}");
1230            let commands = v["installCommands"]
1231                .as_array()
1232                .unwrap_or_else(|| panic!("{platform}: {v}"))
1233                .iter()
1234                .map(|c| c.as_str().unwrap())
1235                .collect::<Vec<_>>()
1236                .join("\n");
1237            assert!(commands.contains(expected), "{platform}: {commands}");
1238            assert!(!commands.contains("npm install"), "{platform}: {commands}");
1239        }
1240        let (_, v) = tool_call(&s, "get_package", json!({"name": "flutter"}));
1241        assert_eq!(v["name"], "offline-protocol-flutter", "{v}");
1242        assert_eq!(v["registry"], "source", "{v}");
1243        assert_eq!(v["status"], "preview", "{v}");
1244        let (_, v) = tool_call(&s, "get_package", json!({"name": "offline_protocol.h"}));
1245        assert_eq!(v["name"], "offline-protocol-c", "{v}");
1246
1247        // A Flutter or Java prompt: no React Native plan, the package named.
1248        for (prompt, needle) in [
1249            (
1250                "Build a Flutter app for nearby chat",
1251                "offline-protocol-flutter 0.34.0",
1252            ),
1253            (
1254                "A Java service that relays messages between laptops",
1255                "com.offlineprotocol:offline-protocol-java",
1256            ),
1257        ] {
1258            let (err, v) = tool_call(&s, "generate_architecture", json!({"prompt": prompt}));
1259            assert!(!err);
1260            assert_eq!(v["planGenerated"], false, "{v}");
1261            let reason = v["reason"].as_str().unwrap();
1262            assert!(reason.contains(needle), "{reason}");
1263        }
1264    }
1265
1266    /// SDK 0.31.0 added a Ruby binding on RubyGems and an experimental
1267    /// browser engine (the crate on crates.io, the JavaScript client from a
1268    /// checkout). Agents asking for them get the package and its install
1269    /// line, never a React Native plan or an npm line.
1270    #[test]
1271    fn sdk_0_31_bindings_get_correct_answers() {
1272        let s = server();
1273        for (query, first) in [("ruby", "server-runtime"), ("webrtc", "browser-node")] {
1274            let (err, v) = tool_call(&s, "search_capabilities", json!({"query": query}));
1275            assert!(!err);
1276            assert_eq!(v[0]["name"], first, "{query}: {v}");
1277        }
1278        for (platform, package, expected) in [
1279            ("ruby", "ruby", "gem \"offline_protocol\", \"~> 0.34.0\""),
1280            ("rb", "offline-protocol-ruby", "releases/tag/v0.34.0"),
1281            (
1282                "web",
1283                "offline-protocol-web",
1284                "cargo add offline-protocol-web@0.34.0",
1285            ),
1286        ] {
1287            let (err, v) = tool_call(
1288                &s,
1289                "resolve_packages",
1290                json!({"platform": platform, "packages": [package]}),
1291            );
1292            assert!(!err, "{platform}: {v}");
1293            let commands = v["installCommands"]
1294                .as_array()
1295                .unwrap_or_else(|| panic!("{platform}: {v}"))
1296                .iter()
1297                .map(|c| c.as_str().unwrap())
1298                .collect::<Vec<_>>()
1299                .join("\n");
1300            assert!(commands.contains(expected), "{platform}: {commands}");
1301            assert!(!commands.contains("npm install"), "{platform}: {commands}");
1302        }
1303        let (_, v) = tool_call(&s, "get_package", json!({"name": "ruby"}));
1304        assert_eq!(v["name"], "offline-protocol-ruby", "{v}");
1305        assert_eq!(v["registry"], "rubygems", "{v}");
1306        let (_, v) = tool_call(&s, "get_package", json!({"name": "offline-protocol-web"}));
1307        assert_eq!(v["status"], "experimental", "{v}");
1308
1309        // A Ruby prompt: no React Native plan, the gem named.
1310        let (err, v) = tool_call(
1311            &s,
1312            "generate_architecture",
1313            json!({"prompt": "A Ruby service that relays messages between laptops"}),
1314        );
1315        assert!(!err);
1316        assert_eq!(v["planGenerated"], false, "{v}");
1317        assert!(
1318            v["reason"]
1319                .as_str()
1320                .unwrap()
1321                .contains("offline_protocol gem"),
1322            "{v}"
1323        );
1324
1325        // A browser mesh prompt on `web`: no plan, and the browser engine is
1326        // offered after the React Native alternative.
1327        let (err, v) = tool_call(
1328            &s,
1329            "generate_architecture",
1330            json!({"prompt": "Browser web app that discovers nearby phones over Bluetooth and chats offline",
1331                   "platform": "web"}),
1332        );
1333        assert!(!err);
1334        assert_eq!(v["planGenerated"], false, "{v}");
1335        assert!(
1336            v["alternatives"]
1337                .as_array()
1338                .unwrap()
1339                .iter()
1340                .any(|a| a["arguments"]["packages"][0] == "offline-protocol-web"),
1341            "{v}"
1342        );
1343    }
1344
1345    /// SDK 0.28.0 added Python on PyPI, a Swift package and an Android
1346    /// download (both early previews), the local API, custody and leaf
1347    /// builds for ESP32 and Cortex-M. Agents ask for them by these words.
1348    /// SDK 0.32.0 added service subscriptions and a C# binding (a project
1349    /// reference from a checkout, not NuGet). Agents asking for either get
1350    /// the right skill or package, never a React Native plan or an npm line.
1351    #[test]
1352    fn sdk_0_32_answers() {
1353        let s = server();
1354        for (query, first) in [
1355            ("subscribe to a service topic", "service-subscriptions"),
1356            ("csharp", "server-runtime"),
1357        ] {
1358            let (err, v) = tool_call(&s, "search_capabilities", json!({"query": query}));
1359            assert!(!err);
1360            assert_eq!(v[0]["name"], first, "{query}: {v}");
1361        }
1362        for platform in ["csharp", "C#", "dotnet"] {
1363            let (err, v) = tool_call(
1364                &s,
1365                "resolve_packages",
1366                json!({"platform": platform, "packages": ["offline-protocol-csharp"]}),
1367            );
1368            assert!(!err, "{platform}: {v}");
1369            let commands = v["installCommands"]
1370                .as_array()
1371                .unwrap_or_else(|| panic!("{platform}: {v}"))
1372                .iter()
1373                .map(|c| c.as_str().unwrap())
1374                .collect::<Vec<_>>()
1375                .join("\n");
1376            assert!(commands.contains("v0.34.0"), "{platform}: {commands}");
1377            assert!(
1378                commands.contains("OfflineProtocol.Sdk.csproj"),
1379                "{platform}: {commands}"
1380            );
1381            assert!(!commands.contains("npm install"), "{platform}: {commands}");
1382        }
1383        let (_, v) = tool_call(&s, "get_package", json!({"name": "csharp"}));
1384        assert_eq!(v["name"], "offline-protocol-csharp", "{v}");
1385        assert_eq!(v["status"], "preview", "{v}");
1386
1387        // A C# prompt: no React Native plan, the binding named.
1388        let (err, v) = tool_call(
1389            &s,
1390            "generate_architecture",
1391            json!({"prompt": "A C# desktop app that syncs state between laptops offline"}),
1392        );
1393        assert!(!err);
1394        assert_eq!(v["planGenerated"], false, "{v}");
1395        assert!(
1396            v["reason"]
1397                .as_str()
1398                .unwrap()
1399                .contains("offline-protocol-csharp"),
1400            "{v}"
1401        );
1402
1403        // The nearby-service skill teaches subscriptions.
1404        let (_, v) = tool_call(&s, "get_skill", json!({"name": "nearby-service"}));
1405        let body = v["body"].as_str().unwrap_or_default();
1406        assert!(body.contains("subscribeService"), "{v}");
1407        assert!(body.contains("service_subscribe_received"), "{v}");
1408    }
1409
1410    #[test]
1411    fn sdk_0_28_questions_get_correct_answers() {
1412        let s = server();
1413        for (query, first) in [
1414            ("python", "server-runtime"),
1415            ("swift", "native-mobile"),
1416            ("kotlin", "native-mobile"),
1417            ("android native", "native-mobile"),
1418            ("esp32", "embedded-leaf"),
1419            ("local api", "local-api"),
1420            ("custody", "custody"),
1421        ] {
1422            let (err, v) = tool_call(&s, "search_capabilities", json!({"query": query}));
1423            assert!(!err);
1424            assert_eq!(v[0]["name"], first, "{query}: {v}");
1425        }
1426
1427        // Install lines come from the registry, on the right channel.
1428        for (platform, package, expected, absent) in [
1429            (
1430                "python",
1431                "python",
1432                "pip install offline-protocol-sdk==0.34.0",
1433                "npm install",
1434            ),
1435            (
1436                "swift",
1437                "swift",
1438                "offline-protocol-swift.git\", from: \"0.33.0\")",
1439                "npm install",
1440            ),
1441            (
1442                "kotlin",
1443                "kotlin",
1444                "implementation(\"com.offlineprotocol:offline-protocol-sdk:0.34.0\")",
1445                "npm install",
1446            ),
1447            (
1448                "esp32",
1449                "esp32",
1450                "cargo add offline-protocol-leaf@0.34.0 --no-default-features",
1451                "npm install",
1452            ),
1453            (
1454                "rust",
1455                "offline-protocol",
1456                "cargo add offline-protocol@0.34.0",
1457                "npm install",
1458            ),
1459            (
1460                "react-native",
1461                "mesh-sdk",
1462                "npm install @offline-protocol/mesh-sdk@0.34.0",
1463                "pip",
1464            ),
1465        ] {
1466            let (err, v) = tool_call(
1467                &s,
1468                "resolve_packages",
1469                json!({"platform": platform, "packages": [package]}),
1470            );
1471            assert!(!err, "{platform}: {v}");
1472            let commands = v["installCommands"]
1473                .as_array()
1474                .unwrap()
1475                .iter()
1476                .map(|c| c.as_str().unwrap())
1477                .collect::<Vec<_>>()
1478                .join("\n");
1479            assert!(commands.contains(expected), "{platform}: {commands}");
1480            assert!(!commands.contains(absent), "{platform}: {commands}");
1481        }
1482        let (_, v) = tool_call(
1483            &s,
1484            "resolve_packages",
1485            json!({"platform": "swift", "packages": ["swift"]}),
1486        );
1487        assert!(
1488            v["warnings"][0].as_str().unwrap().contains("preview"),
1489            "{v}"
1490        );
1491
1492        // A native app prompt: no React Native plan, and the preview named.
1493        for (prompt, package) in [
1494            (
1495                "A SwiftUI iPhone app for nearby chat",
1496                "offline-protocol-swift",
1497            ),
1498            (
1499                "Native Android Kotlin app for nearby chat",
1500                "offline-protocol-android",
1501            ),
1502        ] {
1503            let (err, v) = tool_call(&s, "generate_architecture", json!({"prompt": prompt}));
1504            assert!(!err);
1505            assert_eq!(v["planGenerated"], false, "{v}");
1506            let reason = v["reason"].as_str().unwrap();
1507            assert!(reason.contains(package), "{reason}");
1508            assert!(reason.contains("early preview"), "{reason}");
1509        }
1510        let (_, v) = tool_call(
1511            &s,
1512            "generate_architecture",
1513            json!({"prompt": "Native Android Kotlin app for nearby chat"}),
1514        );
1515        assert!(v["reason"]
1516            .as_str()
1517            .unwrap()
1518            .contains("on Maven Central (com.offlineprotocol:offline-protocol-sdk"));
1519
1520        // Python passed explicitly with a prompt its one starter (nearby-chat)
1521        // does not cover: no plan, the starter it has, and the package.
1522        let (err, v) = tool_call(
1523            &s,
1524            "generate_architecture",
1525            json!({"prompt": "share notes between desktop apps", "platform": "python"}),
1526        );
1527        assert!(!err);
1528        assert_eq!(v["planGenerated"], false, "{v}");
1529        assert!(v["alternatives"]
1530            .as_array()
1531            .unwrap()
1532            .iter()
1533            .any(|a| a["description"] == "Workflows available on python: nearby-chat"));
1534        assert!(v["alternatives"]
1535            .as_array()
1536            .unwrap()
1537            .iter()
1538            .any(|a| a["arguments"]["packages"][0] == "offline-protocol-sdk"));
1539
1540        // The leaf says what CI builds and what the firmware brings, and
1541        // points to the IntelligenceMesh Relay for a ready device.
1542        let (_, v) = tool_call(&s, "get_package", json!({"name": "esp32"}));
1543        let note = v["notes"][0].as_str().unwrap();
1544        assert!(note.starts_with("CI builds and lints the crate"), "{note}");
1545        assert!(note.contains("IntelligenceMesh Relay"), "{note}");
1546        let (_, v) = tool_call(&s, "get_skill", json!({"name": "esp32"}));
1547        let body = v["body"].as_str().unwrap();
1548        assert!(body.contains("links it into a"), "{body}");
1549        assert!(body.contains("IntelligenceMesh Relay"), "{body}");
1550
1551        // The Android preview resolves to its Maven Central coordinates at
1552        // the pinned version, still marked as a preview.
1553        let (_, v) = tool_call(&s, "get_package", json!({"name": "kotlin"}));
1554        assert_eq!(v["registry"], "maven", "{v}");
1555        assert_eq!(v["status"], "preview", "{v}");
1556        assert!(v["install"]
1557            .as_str()
1558            .unwrap()
1559            .contains("implementation(\"com.offlineprotocol:offline-protocol-sdk:0.34.0\")"));
1560    }
1561
1562    #[test]
1563    fn platform_aliases_resolve_with_a_note() {
1564        let s = server();
1565        let (err, v) = tool_call(
1566            &s,
1567            "resolve_packages",
1568            json!({"platform": "ios", "workflow": "nearby-chat"}),
1569        );
1570        assert!(!err, "{v}");
1571        assert_eq!(v["platform"], "react-native");
1572        assert!(v["note"]
1573            .as_str()
1574            .unwrap()
1575            .contains("native packages are early previews"));
1576        for (alias, resolved) in [
1577            ("android", "react-native"),
1578            ("react", "react-vite"),
1579            ("vite", "react-vite"),
1580            ("next", "nextjs"),
1581            ("browser", "nextjs"),
1582        ] {
1583            let (err, v) = tool_call(
1584                &s,
1585                "resolve_packages",
1586                json!({"platform": alias, "packages": ["@offline-protocol/core"]}),
1587            );
1588            assert!(!err, "{alias}: {v}");
1589            assert_eq!(v["platform"], resolved, "{alias}");
1590            assert!(v["note"].as_str().unwrap().contains(alias), "{alias}");
1591        }
1592        // Only the platform, nothing to resolve: what is available there.
1593        let (err, v) = tool_call(&s, "resolve_packages", json!({"platform": "ios"}));
1594        assert!(!err, "{v}");
1595        assert_eq!(v["resolved"], false);
1596        assert!(v["packages"]
1597            .as_array()
1598            .unwrap()
1599            .iter()
1600            .any(|p| p["name"] == "@offline-protocol/mesh-sdk"));
1601        assert!(v["note"].is_string());
1602        // A value that maps to nothing is still a tool error listing the valid values.
1603        let (err, v) = tool_call(
1604            &s,
1605            "resolve_packages",
1606            json!({"platform": "windows95", "packages": ["mesh-sdk"]}),
1607        );
1608        assert!(err);
1609        assert!(v
1610            .as_str()
1611            .unwrap()
1612            .contains("react-native, nextjs, react-vite, web, rust"));
1613        // generate_architecture takes the same aliases.
1614        let (err, v) = tool_call(
1615            &s,
1616            "generate_architecture",
1617            json!({"prompt": "nearby chat", "platform": "android"}),
1618        );
1619        assert!(!err);
1620        assert_eq!(v["plan"]["platform"], "react-native");
1621        assert!(v["note"].is_string());
1622    }
1623
1624    #[test]
1625    fn incompatible_requests_are_structured_answers() {
1626        let s = server();
1627        let (err, v) = tool_call(
1628            &s,
1629            "resolve_packages",
1630            json!({"platform": "web", "workflow": "nearby-chat"}),
1631        );
1632        assert!(!err);
1633        assert_eq!(v["supported"], false);
1634        assert!(v["reason"].as_str().unwrap().contains(
1635            "workflow `nearby-chat` supports platforms [java, python, react-native], not `web`"
1636        ));
1637        let offered: Vec<&str> = v["alternatives"]
1638            .as_array()
1639            .unwrap()
1640            .iter()
1641            .filter_map(|a| a["arguments"]["platform"].as_str())
1642            .collect();
1643        assert_eq!(offered, ["java", "python", "react-native"], "{v}");
1644        let (err, v) = tool_call(
1645            &s,
1646            "resolve_packages",
1647            json!({"platform": "web", "packages": ["@offline-protocol/id-react-native"]}),
1648        );
1649        assert!(!err);
1650        assert!(v["alternatives"]
1651            .as_array()
1652            .unwrap()
1653            .iter()
1654            .any(|a| a["arguments"]["packages"][0] == "@offline-protocol/id-react"));
1655    }
1656
1657    #[test]
1658    fn preview_without_a_name_uses_a_placeholder() {
1659        let s = server();
1660        let (err, v) = tool_call(
1661            &s,
1662            "preview_scaffold",
1663            json!({"prompt": "Plan a nearby chat app"}),
1664        );
1665        assert!(!err, "{v}");
1666        assert_eq!(v["dryRun"], true);
1667        assert_eq!(v["project"], crate::tools::DEFAULT_PREVIEW_NAME);
1668        assert!(v["notes"]
1669            .as_array()
1670            .unwrap()
1671            .iter()
1672            .any(|n| n.as_str().unwrap().contains("no `name` given")));
1673        // Writing still needs a name.
1674        let (err, v) = tool_call(
1675            &s,
1676            "scaffold_project",
1677            json!({"prompt": "Plan a nearby chat app"}),
1678        );
1679        assert!(err);
1680        assert!(v
1681            .as_str()
1682            .unwrap()
1683            .contains("missing required argument `name`"));
1684        // A multi-platform workflow without a platform lists the starters.
1685        let (err, v) = tool_call(
1686            &s,
1687            "preview_scaffold",
1688            json!({"workflow": "offline-social-network"}),
1689        );
1690        assert!(!err, "{v}");
1691        assert_eq!(v["matches"].as_array().unwrap().len(), 3);
1692    }
1693
1694    #[test]
1695    fn malformed_json_yields_parse_error() {
1696        let s = server();
1697        let raw = s.handle_message("{not json").unwrap();
1698        let resp: Value = serde_json::from_str(&raw).unwrap();
1699        assert_eq!(resp["error"]["code"], -32700);
1700    }
1701
1702    #[test]
1703    fn unknown_method_yields_method_not_found() {
1704        let s = server();
1705        let resp = call(&s, json!({"jsonrpc": "2.0", "id": 10, "method": "wat"}));
1706        assert_eq!(resp["error"]["code"], -32601);
1707    }
1708
1709    #[test]
1710    fn run_loop_processes_stream() {
1711        let s = server();
1712        let input = concat!(
1713            r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
1714            "\n",
1715            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
1716            "\n",
1717            r#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#,
1718            "\n"
1719        );
1720        let mut output = Vec::new();
1721        s.run(input.as_bytes(), &mut output).unwrap();
1722        let lines: Vec<&str> = std::str::from_utf8(&output).unwrap().lines().collect();
1723        // Two responses: initialize + ping (notification skipped).
1724        assert_eq!(lines.len(), 2);
1725    }
1726
1727    struct FakeAccount;
1728    impl crate::AccountTools for FakeAccount {
1729        fn definitions(&self) -> Vec<serde_json::Value> {
1730            vec![
1731                serde_json::json!({"name": "app_status", "description": "d", "inputSchema": {"type": "object"}}),
1732            ]
1733        }
1734        fn call(
1735            &self,
1736            name: &str,
1737            _args: &serde_json::Value,
1738        ) -> Option<Result<serde_json::Value, String>> {
1739            (name == "app_status").then(|| Ok(serde_json::json!({"ready": true})))
1740        }
1741    }
1742
1743    #[test]
1744    fn account_tools_are_listed_and_called_only_on_the_local_server() {
1745        let local = McpServer::new(offline_registry::Registry::load_embedded().unwrap())
1746            .with_account_tools(Box::new(FakeAccount));
1747        let list = local
1748            .handle_message(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#)
1749            .unwrap();
1750        assert!(list.contains("\"app_status\""));
1751        let call = local
1752            .handle_message(r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"app_status","arguments":{}}}"#)
1753            .unwrap();
1754        assert!(call.contains("ready"));
1755        // Registry tools still answer.
1756        let other = local
1757            .handle_message(r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_packages","arguments":{}}}"#)
1758            .unwrap();
1759        assert!(other.contains("\"isError\":false"));
1760
1761        let hosted = McpServer::with_mode(
1762            offline_registry::Registry::load_embedded().unwrap(),
1763            DeploymentMode::Hosted,
1764        )
1765        .with_account_tools(Box::new(FakeAccount));
1766        let list = hosted
1767            .handle_message(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#)
1768            .unwrap();
1769        assert!(!list.contains("\"app_status\""));
1770    }
1771}