1use anyhow::Result;
6use serde_json::{Map, Value, json};
7use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
8
9use crate::{
10 client, connect,
11 reply::{Fail, envelope},
12 script,
13};
14
15const PROTOCOL_VERSION: &str = "2025-06-18";
16
17const SCRIPT_DOC: &str = "Run JavaScript that drives the phone, in one call: loops, conditions and several steps without a round trip each. \
18The commands are functions that return what the tool of the same name returns: read(opts), find(selector), tap(target, opts), swipe(direction | {from, to}, opts), \
19pinch(direction | {scale, rotate, at}, opts), scroll(direction, {until, max}), type(text, {clear, submit}), key(name), button(name), launch(app, {restart, arguments, environment}), apps(). Also waitFor(selector, {timeout_ms}), \
20readField({selector, take, regex}) → text, readList({row, columns, group, stop_below, max_scrolls}) → {rows, scrolls, ended}, sleep(ms), log(…), output(key, value). \
21syslog(\"start\" | \"read\" | \"stop\" | \"status\", {app, process, pid, level, after, grep, max}) captures the phone's log as iph_syslog does and returns what it returns; a script cannot write a file. \
22tap(target) waits up to 5 s for a selector to appear and hold still; tap([a, b, c]) presses a keypad without re-reading. \
23A call that fails throws an Error with .code, .outcome, .hint and .result (the full result object); uncaught, it ends the script and the result says which call and line. \
24After a call whose outcome is \"unknown\" the script is stopped and cannot go on. \
25For type(), verified means read back, not text matched; inspect value_changed and warning, never automatically retype. submit withholds Return with unknown / type_not_verified when the effect is uncertain. \
26No files, network or timers; Date, JSON, RegExp, Map and the rest of the language are there. The result has outputs (the returned object, plus output() calls), logs, calls and inputs_sent.";
27
28const SELECTOR_DOC: &str = "Selector: a plain string is an exact label (the name part of a \"name, value\" row also counts). \
29Or combine terms: label=\"exact\", label~=\"contains\", label/regex/, role=button, id=<identifier or element id>, \
30value~=…, within=\"<selector>\", index=N. An object works too: {label, label_contains, label_regex, value, \
31value_contains, role, id, id_contains, id_regex, within, index}. More than one match is an error that lists the candidates.";
32
33fn tool(name: &str, description: &str, properties: Value, required: &[&str]) -> Value {
34 json!({
35 "name": name,
36 "description": description,
37 "inputSchema": {
38 "type": "object",
39 "properties": properties,
40 "required": required,
41 "additionalProperties": false,
42 },
43 })
44}
45
46fn tools() -> Vec<Value> {
47 let selector = json!({ "description": SELECTOR_DOC, "type": ["string", "object"] });
48 vec![
49 tool(
50 "iph_connect",
51 "Verify and save the selected paired iPhone's IP address when automatic discovery fails. Requires prior USB trust on this computer. Checks a paired session and reported UDID before saving. Subsequent tools and scripts use the address; this does not establish developer-service readiness or repair Apple's discovery list.",
52 json!({ "ip": { "type": "string", "description": "The iPhone's IPv4 or IPv6 address. Link-local IPv6 needs the computer's numeric interface index, e.g. fe80::1234%12." } }),
53 &["ip"],
54 ),
55 tool(
56 "iph_read",
57 "Read the iPhone's current screen as a list of elements (id, role, label, value, frame in points, traits, enabled). \
58 Read before acting; coordinates and labels come from here. Only on-screen elements unless all=true.",
59 json!({
60 "app": { "type": "boolean", "description": "Only the foreground app's elements." },
61 "all": { "type": "boolean", "description": "Include elements outside the screen." },
62 "full": { "type": "boolean", "description": "Wait ~0.6 s more for accessibility identifiers." },
63 "max_age_ms": { "type": "integer", "description": "Accept a cached reading this recent instead of asking the phone (a fresh read takes about 1.2 s)." },
64 }),
65 &[],
66 ),
67 tool(
68 "iph_find",
69 "Find elements on screen that match a selector.",
70 json!({ "selector": selector, "all": { "type": "boolean" } }),
71 &["selector"],
72 ),
73 tool(
74 "iph_tap",
75 "Tap an element (selector) or a point (\"x,y\" in points). Waits for the screen to change and hold still, \
76 then returns it (`elements`, as iph_read does) and whether it changed. \
77 Never retry a tap whose outcome is \"unknown\".",
78 json!({
79 "target": { "description": format!("A selector, or \"x,y\". {SELECTOR_DOC}"), "type": ["string", "object"] },
80 "long_ms": { "type": "integer", "description": "Hold this long instead of a short tap." },
81 "double": { "type": "boolean" },
82 "no_wait": { "type": "boolean", "description": "Read the screen once right after the tap instead of waiting for it to settle; the result then has no elements." },
83 }),
84 &["target"],
85 ),
86 tool(
87 "iph_swipe",
88 "Swipe the finger up, down, left or right across the middle of the screen, or between two points.",
89 json!({
90 "direction": { "type": "string", "enum": ["up", "down", "left", "right"] },
91 "from": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
92 "to": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
93 "duration_ms": { "type": "integer" },
94 "drag": { "type": "boolean", "description": "Slow to a stop before lifting (a drag) instead of flicking." },
95 }),
96 &[],
97 ),
98 tool(
99 "iph_pinch",
100 "Two fingers on the screen: pinch in or out to zoom, turn to rotate (a map, an image, a web page). Give a direction, or a scale and/or a rotation. \
101 The fingers meet in the middle of the screen, or at `at`. `screen_changed: false` is a fair answer on a screen that does not zoom. \
102 Never retry one whose outcome is \"unknown\".",
103 json!({
104 "direction": { "type": "string", "enum": ["in", "out"], "description": "in = scale 0.5, out = scale 2. Not together with scale." },
105 "scale": { "type": "number", "minimum": 0.25, "maximum": 4, "description": "End distance between the fingers over the start distance: above 1 spreads them (zoom in), below 1 pinches (zoom out)." },
106 "rotate": { "type": "number", "minimum": -180, "maximum": 180, "description": "Degrees, positive clockwise." },
107 "at": { "description": format!("Where the fingers meet: a selector, or \"x,y\" in points. Default: the middle of the screen. {SELECTOR_DOC}"), "type": ["string", "object"] },
108 "duration_ms": { "type": "integer", "description": "How long the fingers move (default 500, 100..10000)." },
109 }),
110 &[],
111 ),
112 tool(
113 "iph_scroll",
114 "Scroll the content. \"down\" shows what is further down. With `until`, keeps scrolling until that element is on screen.",
115 json!({
116 "direction": { "type": "string", "enum": ["up", "down"] },
117 "until": selector,
118 "max": { "type": "integer", "description": "Most scrolls to try (default 10)." },
119 }),
120 &["direction"],
121 ),
122 tool(
123 "iph_type",
124 "Type text into the field that has the keyboard (tap the field first). Pasted through the clipboard, so Korean and emoji work; \
125 the user's clipboard is put back (not content copied in an app: see clipboard_note). verified means the value was read, not that it matches the intended text. \
126 Inspect value_before, value, value_changed (true/false/null) and warning. An unchanged value can mean blocked paste, masking or identical replacement; never automatically retype. \
127 screen_changed compares accessibility readings after keyboard restoration (null if unavailable). submit withholds Return with outcome unknown / type_not_verified when the input effect is uncertain.",
128 json!({
129 "text": { "type": "string" },
130 "clear": { "type": "boolean", "description": "Replace what the field holds." },
131 "submit": { "type": "boolean", "description": "Press Return only after observing a changed, nonempty value (or an empty value for clear-only). Otherwise withhold Return and return unknown; inspect before taking another action." },
132 }),
133 &["text"],
134 ),
135 tool(
136 "iph_key",
137 "Press a key: return, esc, tab, space, backspace, delete, arrows, or a combination like cmd+a.",
138 json!({ "key": { "type": "string" } }),
139 &["key"],
140 ),
141 tool(
142 "iph_button",
143 "Press a hardware button.",
144 json!({ "button": { "type": "string", "enum": ["home", "lock", "volume_up", "volume_down"] } }),
145 &["button"],
146 ),
147 tool(
148 "iph_launch",
149 "Bring an app to the front by bundle id (com.apple.Preferences) or by its name.",
150 json!({
151 "app": { "type": "string" },
152 "restart": { "type": "boolean", "description": "Quit the app first so it starts from its first screen." },
153 "arguments": {
154 "type": "array", "items": { "type": "string" },
155 "description": "Launch arguments for the app, e.g. [\"-AppleLanguages\", \"(ko)\"]. The app is restarted, since a running process takes none.",
156 },
157 "environment": {
158 "type": "object", "additionalProperties": { "type": "string" },
159 "description": "Environment variables for the app's process, e.g. {\"TZ\": \"UTC\"}. The app is restarted.",
160 },
161 }),
162 &["app"],
163 ),
164 tool("iph_apps", "List installed apps with their bundle ids.", json!({}), &[]),
165 tool(
166 "iph_dnd",
167 "Do Not Disturb on the phone, so a notification banner cannot take a tap. \"on\" before the work, \"off\" when it is done \
168 (puts back the Focus that was on).",
169 json!({ "action": { "type": "string", "enum": ["on", "off", "status"] } }),
170 &["action"],
171 ),
172 tool(
173 "iph_syslog",
174 "Capture the phone's log in the background while other calls run, to check what an app logged after a tap. \
175 \"start\" (one capture at a time; stop an ended one before starting again) keeps the entries in a buffer in memory, newest last, each with a seq; \
176 \"read\" returns the entries newer than `after` (the `cursor` of the previous read) without stopping the capture, \
177 so the loop is start, tap, read, tap, read, stop; \"stop\" ends it (with grep or max it returns the latest matching entries); \"status\". \
178 Filter with app (bundle id or name, as iph_launch takes it; matched by where the app is installed, so it survives restarts and includes its extensions), \
179 process (executable names such as Preferences; survives app restarts) or pid; an entry is kept if it is from any listed app or process; unfiltered over Wi-Fi it is thousands of entries a second, \
180 and the buffer keeps the last 100,000 entries by default. A read says how many entries were `dropped` before it could get them.",
181 json!({
182 "action": { "type": "string", "enum": ["start", "read", "stop", "status"] },
183 "app": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these apps' entries, each a bundle id or an app name; an unknown app fails before anything starts." },
184 "process": { "type": "array", "items": { "type": "string" }, "description": "start: keep only these executables. With app, an entry is kept if it matches either." },
185 "pid": { "type": "integer", "description": "start: keep only this pid (filtered on the phone)." },
186 "level": { "type": "string", "enum": ["debug", "info", "notice", "error", "fault"], "description": "start: lowest level kept." },
187 "buffer_entries": { "type": "integer", "description": "start: most entries the buffer holds, 1 to 1000000 (default 100000); the oldest are dropped." },
188 "buffer_mb": { "type": "integer", "description": "start: most memory the buffer takes in MiB, 1 to 1024 (default 64)." },
189 "output": { "type": "string", "description": "start: absolute path of a JSON Lines file that also gets every kept entry (whole messages). Without it nothing is written to disk." },
190 "max_mb": { "type": "integer", "description": "start, with output: move the file to <file>.1 at this size in MiB, 1 to 4096 (default 64)." },
191 "after": { "type": "integer", "description": "read: only entries after this seq; pass the previous read's cursor. Omit for the oldest the buffer holds." },
192 "grep": { "type": "string", "description": "read, stop: regular expression matched against each message." },
193 "max": { "type": "integer", "description": "read: most entries returned, the oldest first. stop: most entries returned, the latest. Default 50, at most 1000." },
194 }),
195 &["action"],
196 ),
197 tool(
198 "iph_screenshot",
199 "Save a PNG screenshot to a file on this computer. Use iph_read for content; this is for looks.",
200 json!({ "path": { "type": "string", "description": "Absolute path of the PNG to write." } }),
201 &["path"],
202 ),
203 tool(
204 "iph_batch",
205 "Run several steps in one call, stopping at the first failure. Each step is a one-key object: \
206 {\"launch\": \"…\"}, {\"wait_for\": selector}, {\"tap\": selector}, {\"type\": {\"text\": \"…\"}}, {\"swipe\": \"up\"}, {\"pinch\": \"out\"}, \
207 {\"scroll_until\": selector}, {\"read_field\": {\"name\", \"selector\", \"take\"}}, {\"read_list\": {\"name\", \"row\", \"columns\"}}, \
208 {\"assert\": selector}, {\"button\": \"home\"}, {\"key\": \"return\"}, {\"sleep\": ms}.",
209 json!({ "steps": { "type": "array", "items": { "type": "object" } } }),
210 &["steps"],
211 ),
212 tool(
213 "iph_script",
214 SCRIPT_DOC,
215 json!({
216 "code": { "type": "string", "description": "JavaScript. The body of a function: `return` ends it and its value becomes `outputs`." },
217 "args": { "type": "object", "description": "What the script reads as `args`." },
218 }),
219 &["code"],
220 ),
221 tool(
222 "iph_run",
223 "Run a saved script by name (see iph_scripts) in one call and get its outputs. Same result as iph_script.",
224 json!({
225 "name": { "type": "string" },
226 "args": { "type": "object", "description": "What the script reads as `args`." },
227 }),
228 &["name"],
229 ),
230 tool("iph_scripts", "List saved scripts: name, what each does, and where it lives.", json!({}), &[]),
231 tool(
232 "iph_doctor",
233 "Check that the phone is ready. Each check says what the user must do when it fails.",
234 json!({
235 "no_touch_test": { "type": "boolean", "description": "Skip the check that scrolls Settings down and back." },
236 "fix_wifi": { "type": "boolean", "description": "Enable disabled Wi-Fi connection/debugging flags over USB and briefly check Network discovery." },
237 }),
238 &[],
239 ),
240 ]
241}
242
243async fn call(udid: &str, name: &str, args: Value) -> Value {
244 let started = std::time::Instant::now();
245 let args = if args.is_null() { json!({}) } else { args };
246 match name {
247 "iph_connect" => match serde_json::from_value::<connect::Args>(args) {
248 Ok(args) => envelope(connect::run(udid, args).await, started),
249 Err(e) => envelope(Err(Fail::invalid(e.to_string())), started),
250 },
251 "iph_scripts" => envelope(script::cmd_scripts(), started),
252 "iph_syslog" if args.get("output").and_then(|o| o.as_str()).is_some_and(|o| !std::path::Path::new(o).is_absolute()) => {
253 envelope(Err(Fail::invalid("`output` must be an absolute path")), started)
254 }
255 "iph_script" | "iph_run" => match script_request(name, &args) {
256 Ok(request) => client::request(udid, "script", request).await,
257 Err(f) => envelope(Err(f), started),
258 },
259 "iph_read" | "iph_find" | "iph_tap" | "iph_swipe" | "iph_pinch" | "iph_scroll" | "iph_type" | "iph_key"
260 | "iph_button" | "iph_launch" | "iph_apps" | "iph_screenshot" | "iph_batch" | "iph_doctor"
261 | "iph_dnd" | "iph_syslog" => {
262 let cmd = name.trim_start_matches("iph_");
263 let args = if cmd == "apps" { Value::Null } else { args };
264 client::request(udid, cmd, args).await
265 }
266 other => envelope(Err(Fail::invalid(format!("unknown tool `{other}`"))), started),
267 }
268}
269
270fn script_request(tool: &str, args: &Value) -> Result<Value, Fail> {
273 let empty = Map::new();
274 let given = match args.get("args") {
275 None | Some(Value::Null) => &empty,
276 Some(Value::Object(map)) => map,
277 Some(_) => return Err(Fail::invalid("`args` takes an object")),
278 };
279 let text = |key: &str| {
280 args.get(key)
281 .and_then(|v| v.as_str())
282 .ok_or_else(|| Fail::invalid(format!("{tool} needs `{key}`")))
283 };
284 if tool == "iph_script" {
285 let code = match args.get("script").and_then(|v| v.as_str()) {
288 Some(code) if args.get("code").is_none() => code,
289 _ => text("code")?,
290 };
291 return Ok(script::request(code, given, None));
292 }
293 let name = text("name")?;
294 let (code, source) = script::load(name)?;
295 Ok(script::request(&code, given, Some((name, &source))))
296}
297
298fn response(id: &Value, result: Value) -> Value {
299 json!({ "jsonrpc": "2.0", "id": id, "result": result })
300}
301
302fn error(id: &Value, code: i64, message: &str) -> Value {
303 json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
304}
305
306fn offered(only: &[String]) -> Vec<Value> {
308 tools()
309 .into_iter()
310 .filter(|t| {
311 let name = t["name"].as_str().unwrap_or("");
312 only.is_empty() || only.iter().any(|o| o == name || format!("iph_{o}") == name)
313 })
314 .collect()
315}
316
317async fn handle(udid: &str, only: &[String], msg: &Value) -> Option<Value> {
318 let method = msg.get("method").and_then(|m| m.as_str())?;
319 let id = msg.get("id")?;
321 let empty = Map::new();
322 let params = msg.get("params").and_then(|p| p.as_object()).unwrap_or(&empty);
323 Some(match method {
324 "initialize" => {
325 let version = params
326 .get("protocolVersion")
327 .and_then(|v| v.as_str())
328 .unwrap_or(PROTOCOL_VERSION);
329 response(
330 id,
331 json!({
332 "protocolVersion": version,
333 "capabilities": { "tools": {} },
334 "serverInfo": { "name": "iph", "version": env!("CARGO_PKG_VERSION") },
335 "instructions": "Operate a real iPhone through its accessibility tree. Read the screen with iph_read, act with iph_tap / iph_type / iph_scroll, \
336 and check `screen_changed` in each result. For typing also check value_changed and warning: verified only means read back. Never automatically retype on a warning. For a known sequence prefer one iph_script (or a saved one with iph_run): one call instead of one per step. \
337 Outcome \"unknown\" means input may have gone out: read the screen, never resend.",
338 }),
339 )
340 }
341 "ping" => response(id, json!({})),
342 "tools/list" => response(id, json!({ "tools": offered(only) })),
343 "tools/call" => {
344 let Some(name) = params.get("name").and_then(|n| n.as_str()) else {
345 return Some(error(id, -32602, "tools/call needs a tool name"));
346 };
347 if !offered(only).iter().any(|t| t["name"] == name) {
348 return Some(error(id, -32602, "this server does not offer that tool"));
349 }
350 let args = params.get("arguments").cloned().unwrap_or(Value::Null);
351 let result = call(udid, name, args).await;
352 let is_error = result["ok"] != true;
353 response(
354 id,
355 json!({
356 "content": [{ "type": "text", "text": result.to_string() }],
357 "isError": is_error,
358 }),
359 )
360 }
361 "resources/list" => response(id, json!({ "resources": [] })),
362 "prompts/list" => response(id, json!({ "prompts": [] })),
363 _ => error(id, -32601, "method not found"),
364 })
365}
366
367pub async fn serve(udid: String, only: Vec<String>) -> Result<()> {
369 let mut lines = BufReader::new(tokio::io::stdin()).lines();
370 let mut stdout = tokio::io::stdout();
371 while let Some(line) = lines.next_line().await? {
372 let line = line.trim();
373 if line.is_empty() {
374 continue;
375 }
376 let reply = match serde_json::from_str::<Value>(line) {
377 Ok(msg) => handle(&udid, &only, &msg).await,
378 Err(_) => Some(error(&Value::Null, -32700, "parse error")),
379 };
380 if let Some(reply) = reply {
381 stdout.write_all(format!("{reply}\n").as_bytes()).await?;
382 stdout.flush().await?;
383 }
384 }
385 Ok(())
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn launch_offers_arguments_and_environment() {
394 let launch = tools().into_iter().find(|t| t["name"] == "iph_launch").unwrap();
395 let props = &launch["inputSchema"]["properties"];
396 assert_eq!(props["arguments"]["items"]["type"], "string");
397 assert_eq!(props["environment"]["additionalProperties"]["type"], "string");
398 }
399
400 #[test]
401 fn syslog_offers_read_with_a_cursor_and_a_file_only_on_request() {
402 let tool = tools().into_iter().find(|t| t["name"] == "iph_syslog").unwrap();
403 let props = tool["inputSchema"]["properties"].as_object().unwrap();
404 assert_eq!(props["action"]["enum"], json!(["start", "read", "stop", "status"]));
405 for key in ["after", "grep", "max", "output", "max_mb", "buffer_entries", "buffer_mb", "app", "process", "pid", "level"] {
406 assert!(props.contains_key(key), "missing {key}");
407 }
408 assert_eq!(props["app"]["items"]["type"], "string");
409 assert_eq!(tool["inputSchema"]["required"], json!(["action"]));
410 }
411
412 #[test]
413 fn tool_list_covers_the_spec() {
414 let names: Vec<String> = tools()
415 .iter()
416 .map(|t| t["name"].as_str().unwrap().to_string())
417 .collect();
418 for expected in [
419 "iph_read", "iph_find", "iph_tap", "iph_swipe", "iph_pinch", "iph_scroll", "iph_type", "iph_button",
420 "iph_launch", "iph_batch", "iph_script", "iph_run", "iph_scripts", "iph_doctor", "iph_connect",
421 ] {
422 assert!(names.contains(&expected.to_string()), "missing {expected}");
423 }
424 for t in tools() {
425 assert_eq!(t["inputSchema"]["type"], "object");
426 assert!(!t["description"].as_str().unwrap().is_empty());
427 }
428 }
429
430 #[test]
431 fn the_pinch_tool_offers_what_the_command_accepts() {
432 let tool = tools().into_iter().find(|t| t["name"] == "iph_pinch").unwrap();
433 let props = tool["inputSchema"]["properties"].as_object().unwrap();
434 let mut keys: Vec<&str> = props.keys().map(String::as_str).collect();
435 keys.sort();
436 assert_eq!(keys, ["at", "direction", "duration_ms", "rotate", "scale"]);
437 assert_eq!(props["direction"]["enum"], json!(["in", "out"]));
438 assert!(tool["inputSchema"].get("required").is_none_or(|r| r.as_array().is_some_and(|r| r.is_empty())));
439 for args in [
440 json!({"direction": "out", "rotate": 30, "at": "Map", "duration_ms": 300}),
441 json!({"scale": 0.5, "at": {"x": 100, "y": 200}}),
442 ] {
443 assert!(serde_json::from_value::<crate::actions::PinchArgs>(args).is_ok());
444 }
445 assert!(serde_json::from_value::<crate::actions::PinchArgs>(json!({"direction": "out", "zoom": 2})).is_err());
446 }
447
448 #[test]
449 fn a_script_request_takes_code_or_a_saved_name() {
450 let req = script_request("iph_script", &json!({"code": "return 1", "args": {"n": 2}})).unwrap();
451 assert_eq!(req, json!({"code": "return 1", "args": {"n": 2}}));
452 let req = script_request("iph_script", &json!({"script": "return 2"})).unwrap();
454 assert_eq!(req["code"], "return 2");
455 let req = script_request("iph_run", &json!({"name": "settings-version"})).unwrap();
456 assert_eq!(req["script"], "settings-version");
457 assert_eq!(req["source"], "builtin:settings-version");
458 assert!(req["code"].as_str().unwrap().contains("launch("));
459 for bad in [json!({}), json!({"code": 1}), json!({"code": "x", "args": [1]})] {
460 assert_eq!(script_request("iph_script", &bad).unwrap_err().code, "invalid_argument", "{bad}");
461 }
462 assert_eq!(script_request("iph_run", &json!({"name": "nope"})).unwrap_err().code, "script_not_found");
463 }
464
465 #[tokio::test]
466 async fn connect_rejects_missing_invalid_and_extra_arguments_before_contacting_a_phone() {
467 for args in [json!({}), json!({"ip": "not-an-ip"}),
468 json!({"ip": "192.0.2.1", "submit": true})] {
469 let result = call("NO-PHONE", "iph_connect", args).await;
470 assert_eq!(result["ok"], false);
471 assert_eq!(result["outcome"], "not_sent");
472 assert_eq!(result["error"]["code"], "invalid_argument");
473 }
474 }
475
476 #[tokio::test]
477 async fn initialize_and_notifications() {
478 let init = json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}});
479 let r = handle("X", &[], &init).await.unwrap();
480 assert_eq!(r["result"]["protocolVersion"], "2024-11-05");
481 assert_eq!(r["result"]["serverInfo"]["name"], "iph");
482 let note = json!({"jsonrpc":"2.0","method":"notifications/initialized"});
483 assert!(handle("X", &[], ¬e).await.is_none());
484 let unknown = json!({"jsonrpc":"2.0","id":2,"method":"nope"});
485 assert_eq!(handle("X", &[], &unknown).await.unwrap()["error"]["code"], -32601);
486 }
487
488 #[tokio::test]
489 async fn tools_can_be_limited() {
490 let only = vec!["read".to_string(), "iph_find".to_string()];
491 let list = json!({"jsonrpc":"2.0","id":1,"method":"tools/list"});
492 let r = handle("X", &only, &list).await.unwrap();
493 let names: Vec<&str> = r["result"]["tools"]
494 .as_array()
495 .unwrap()
496 .iter()
497 .map(|t| t["name"].as_str().unwrap())
498 .collect();
499 assert_eq!(names, ["iph_read", "iph_find"]);
500 let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"iph_tap","arguments":{"target":"x"}}});
502 assert_eq!(handle("X", &only, &call).await.unwrap()["error"]["code"], -32602);
503 }
504}