1use crate::commands::api::{self, call_method};
35use crate::commands::safety::{SafetyProfile, is_write_verb};
36use crate::core::auth::GoogleAuth;
37use crate::discovery::{self, Method, Parameter, Service};
38use serde_json::{Map, Value, json};
39
40pub(crate) const PROTOCOL_VERSION: &str = "2026-07-28";
53
54const SUPPORTED_VERSIONS: [&str; 1] = ["2026-07-28"];
58
59const PARSE_ERROR: i64 = -32700;
61const INVALID_REQUEST: i64 = -32600;
62const METHOD_NOT_FOUND: i64 = -32601;
63
64pub struct McpServer {
67 auth: GoogleAuth,
68 profile: SafetyProfile,
69}
70
71impl McpServer {
72 pub fn new(auth: GoogleAuth, profile: SafetyProfile) -> Self {
73 Self { auth, profile }
74 }
75
76 pub fn tool_count(&self) -> usize {
78 discovery::services()
79 .values()
80 .map(|s| s.methods.len())
81 .sum()
82 }
83
84 pub async fn handle_line(&self, line: &str) -> Option<Value> {
89 let message: Value = match serde_json::from_str(line) {
90 Ok(message) => message,
91 Err(error) => {
92 return Some(error_response(
93 &Value::Null,
94 PARSE_ERROR,
95 format!("parse error: {error}"),
96 ));
97 }
98 };
99
100 let id = message.get("id").cloned()?;
103
104 let method = message.get("method").and_then(|m| m.as_str()).unwrap_or("");
105 let params = message.get("params").cloned().unwrap_or(Value::Null);
106
107 let response = match method {
108 "server/discover" => json!({
109 "jsonrpc": "2.0",
110 "id": id,
111 "result": discover_result(),
112 }),
113 "tools/list" => json!({
114 "jsonrpc": "2.0",
115 "id": id,
116 "result": { "tools": tools_list(), "_meta": server_meta() },
117 }),
118 "tools/call" => {
119 let mut result = self.tools_call(¶ms).await;
120 if let Some(object) = result.as_object_mut() {
123 object.insert("_meta".to_owned(), server_meta());
124 }
125 json!({ "jsonrpc": "2.0", "id": id, "result": result })
126 }
127 "initialize" => {
139 let requested = params
140 .get("protocolVersion")
141 .and_then(|v| v.as_str())
142 .unwrap_or("");
143 let looks_like_revision =
144 |v: &str| v.len() == 10 && v.as_bytes()[4] == b'-' && v.starts_with("20");
145 let version = if looks_like_revision(requested) {
146 requested
147 } else {
148 PROTOCOL_VERSION
149 };
150 json!({
151 "jsonrpc": "2.0",
152 "id": id,
153 "result": {
154 "protocolVersion": version,
155 "capabilities": { "tools": {} },
156 "serverInfo": server_info(),
157 "instructions": discover_result()["instructions"].clone(),
158 },
159 })
160 }
161 "logging/setLevel" => error_response(
162 &id,
163 METHOD_NOT_FOUND,
164 format!(
165 "`{method}` is not part of MCP {PROTOCOL_VERSION} — the handshake is gone. \
166 Call `server/discover` for the revisions served, then `tools/*` inline."
167 ),
168 ),
169 "" => error_response(&id, INVALID_REQUEST, "request has no method".to_owned()),
170 other => error_response(&id, METHOD_NOT_FOUND, format!("method not found: {other}")),
171 };
172 Some(response)
173 }
174
175 async fn tools_call(&self, params: &Value) -> Value {
180 let Some(name) = params.get("name").and_then(|n| n.as_str()) else {
181 return error_result("tools/call needs a tool `name`");
182 };
183 let arguments = params
184 .get("arguments")
185 .cloned()
186 .unwrap_or_else(|| Value::Object(Map::new()));
187 let Value::Object(args) = arguments else {
188 return error_result("tools/call `arguments` must be an object");
189 };
190 match self.invoke_tool(name, &args).await {
191 Ok(text) => ok_result(text),
192 Err(message) => error_result(message),
193 }
194 }
195
196 async fn invoke_tool(&self, name: &str, args: &Map<String, Value>) -> Result<String, String> {
197 let (service, method) = discovery::resolve(name)
198 .map_err(|message| format!("unknown tool `{name}`: {message}"))?;
199
200 self.profile.check(&service.name, method)?;
202
203 let mut merged = Map::new();
208 if let Some(Value::Object(object)) = args.get("params") {
209 merged.extend(object.clone());
210 }
211
212 let mut body_file: Option<String> = None;
213 let mut query: Vec<String> = Vec::new();
214 let mut dry_run = false;
215 for (key, value) in args {
216 match key.as_str() {
217 "params" => {}
218 "dry_run" | "dryRun" => dry_run = value.as_bool().unwrap_or(false),
222 "body_file" | "bodyFile" => body_file = value.as_str().map(str::to_owned),
223 "query" => {
224 if let Some(items) = value.as_array() {
225 query.extend(items.iter().filter_map(|v| v.as_str().map(str::to_owned)));
226 }
227 }
228 other => {
229 merged.insert(other.to_owned(), value.clone());
230 }
231 }
232 }
233
234 if body_file.as_deref() == Some("-") {
237 return Err(
238 "body_file `-` (stdin) is not available over MCP; pass a file path".to_owned(),
239 );
240 }
241
242 let payload = call_method(
243 Some(&self.auth),
244 service,
245 method,
246 merged,
247 api::CallOptions {
248 body_file,
249 verb_override: None,
252 query_extras: query,
253 dry_run,
254 },
255 )
256 .await
257 .map_err(|error| error.to_string())?;
258
259 serde_json::to_string(&payload)
260 .map_err(|error| format!("serialising the result failed: {error}"))
261 }
262}
263
264fn server_info() -> Value {
268 json!({ "name": "grr", "version": env!("CARGO_PKG_VERSION") })
269}
270
271fn server_meta() -> Value {
272 json!({ "io.modelcontextprotocol/serverInfo": server_info() })
273}
274
275fn discover_result() -> Value {
280 json!({
281 "resultType": "complete",
282 "supportedVersions": SUPPORTED_VERSIONS,
283 "capabilities": { "tools": {} },
284 "_meta": server_meta(),
285 "instructions": "Google Workspace and Google Cloud APIs from the embedded Discovery \
286 index. Tool names are dotted method ids (gmail.users.messages.list); \
287 --readonly, --deny-service and --deny-verb gate every write.",
288 })
289}
290
291fn tools_list() -> Vec<Value> {
294 discovery::services()
295 .values()
296 .flat_map(|service| service.methods.iter().map(|m| tool_descriptor(service, m)))
297 .collect()
298}
299
300fn tool_descriptor(service: &Service, method: &Method) -> Value {
301 let output_schema = method
306 .response_ref
307 .as_deref()
308 .and_then(|name| service.schemas.get(name))
309 .map(|schema| serde_json::to_value(schema).expect("Schema serializes"));
310 let mut descriptor = json!({
311 "name": format!("{}.{}", service.name, method.id),
312 "description": tool_description(service, method),
313 "inputSchema": input_schema(method),
314 });
315 if let Some(schema) = output_schema {
316 descriptor
317 .as_object_mut()
318 .expect("descriptor is an object")
319 .insert("outputSchema".into(), schema);
320 }
321 descriptor
322}
323
324const DESCRIPTION_OVERRIDES: &[(&str, &str)] = &[(
330 "scripts.run",
331 "Executes a function in an Apps Script project (Apps Script API script.run). The script \
332 runs headlessly with the scopes its manifest declares — review them before calling: \
333 arbitrary script code executes with your authorization. Returns the script function's \
334 response (OPS_ERROR / ops for failures); script-side failures come back as tool errors, \
335 not dead servers. Prefer `script processes list` to observe running executions and \
336 `script projects get` to read a project's source before running it.",
337)];
338
339fn sibling_summary(service: &Service, method: &Method) -> String {
343 let verb = method.id.rsplit('.').next().unwrap_or("");
346 let resource = &method.id[..method.id.len().saturating_sub(verb.len()).saturating_sub(1)];
347 if resource.is_empty() {
348 return String::new();
349 }
350 let mut siblings: Vec<&str> = service
351 .methods
352 .iter()
353 .filter(|m| {
354 m.id != method.id
355 && m.id
356 .strip_suffix(&format!(".{}", m.id.rsplit('.').next().unwrap_or("")))
357 == Some(resource)
358 })
359 .map(|m| m.id.rsplit('.').next().unwrap_or(""))
360 .collect();
361 siblings.sort_unstable();
362 siblings.dedup();
363 if siblings.is_empty() {
364 String::new()
365 } else {
366 format!(" Siblings over the same resource: {}.", siblings.join(", "))
367 }
368}
369
370fn returns_summary(method: &Method) -> &'static str {
373 match method.http_method.to_ascii_uppercase().as_str() {
374 "GET" => "Returns the requested resource as JSON",
375 "DELETE" => "Returns the post-delete resource state (or empty) as JSON",
376 _ => "Returns the API's response resource as JSON",
377 }
378}
379
380fn tool_description(service: &Service, method: &Method) -> String {
386 let verb = method.http_method.to_ascii_uppercase();
387 let base = DESCRIPTION_OVERRIDES
388 .iter()
389 .find(|(id, _)| *id == method.id)
390 .map(|(_, text)| text.to_string())
391 .unwrap_or_else(|| {
392 if method.description.is_empty() {
393 format!(
394 "{}s {} via the {} API",
395 verb.to_ascii_lowercase(),
396 method.id.rsplit('.').next().unwrap_or("resource"),
397 service.name
398 )
399 } else {
400 method.description.clone()
401 }
402 });
403
404 let base = base.trim_end_matches('.');
407 let mut text = format!("{base} [HTTP {verb}]");
408
409 match verb.as_str() {
411 "POST" => text.push_str(" — creates or triggers a change"),
412 "DELETE" => text.push_str(
413 " — removes the resource; irreversible unless the API documents a trash/undo flow",
414 ),
415 "PATCH" | "PUT" => text.push_str(" — updates the resource"),
416 _ => {}
417 }
418 if is_write_verb(&verb) {
419 text.push_str("; refused under --readonly safety profiles");
420 }
421
422 if text.ends_with(' ') {
427 text.pop();
428 }
429 text.push_str(&format!(
430 ". {} — request bodies are built from the typed parameters (typed flags win over the `params` map), or read whole from `body_file`",
431 returns_summary(method)
432 ));
433
434 text.push_str(&sibling_summary(service, method));
435 text
436}
437
438fn input_schema(method: &Method) -> Value {
442 let mut properties = Map::new();
443 for param in &method.parameters {
444 properties.insert(param.name.clone(), param_schema(param));
445 }
446 properties.insert(
447 "params".into(),
448 json!({
449 "type": "object",
450 "additionalProperties": true,
451 "description": "Parameter map merged into the request; typed parameters win.",
452 }),
453 );
454 properties.insert("body_file".into(), json!({
455 "type": "string",
456 "description": "Read the request body from this file ('-' for stdin) instead of building one from the parameters.",
457 }));
458 properties.insert("query".into(), json!({
459 "type": "array",
460 "items": { "type": "string" },
461 "description": "Extra KEY=VALUE query pairs for endpoints whose parameters Discovery does not describe.",
462 }));
463 properties.insert(
464 "dry_run".into(),
465 json!({
466 "type": "boolean",
467 "description": "Return the request that would be sent, without sending it.",
468 }),
469 );
470
471 let mut schema = Map::new();
472 schema.insert("type".into(), json!("object"));
473 schema.insert("properties".into(), Value::Object(properties));
474 if !method.required.is_empty() {
475 schema.insert("required".into(), json!(method.required));
476 }
477 Value::Object(schema)
478}
479
480fn param_schema(param: &Parameter) -> Value {
485 let mut out = Map::new();
486 match param.kind.as_str() {
487 "string" => {
488 out.insert("type".into(), json!("string"));
489 }
490 "integer" => {
491 out.insert("type".into(), json!("integer"));
492 }
493 "number" => {
494 out.insert("type".into(), json!("number"));
495 }
496 "boolean" => {
497 out.insert("type".into(), json!("boolean"));
498 }
499 _ => {}
500 }
501 if let Some(format) = ¶m.format {
502 out.insert("format".into(), json!(format));
506 }
507 if let Some(minimum) = param.minimum {
508 out.insert("minimum".into(), json!(minimum));
509 }
510 if let Some(maximum) = param.maximum {
511 out.insert("maximum".into(), json!(maximum));
512 }
513 if let Some(pattern) = ¶m.pattern {
514 out.insert("pattern".into(), json!(pattern));
515 }
516 if let Some(default) = ¶m.default_value {
517 out.insert("default".into(), json!(default));
518 }
519 let mut description = String::new();
520 if let Some(location) = ¶m.location {
521 let hint = match location.as_str() {
522 "path" => "URL path segment",
523 "query" => "query parameter",
524 other => other,
525 };
526 description.push_str(&format!("[{hint}] "));
527 }
528 if !param.description.is_empty() {
529 description.push_str(¶m.description);
530 }
531 if let (Some(values), Some(texts)) = (¶m.enum_values, ¶m.enum_descriptions)
532 && values.len() == texts.len()
533 && !texts.is_empty()
534 {
535 let pairs: Vec<String> = values
536 .iter()
537 .zip(texts)
538 .map(|(v, t)| format!("`{v}` = {t}"))
539 .collect();
540 if !description.is_empty() {
541 description.push(' ');
542 }
543 description.push_str(&format!("Values: {}.", pairs.join("; ")));
544 }
545 if !description.is_empty() {
546 out.insert("description".into(), json!(description));
547 }
548 if let Some(values) = ¶m.enum_values {
549 out.insert("enum".into(), json!(values));
550 }
551 let base = Value::Object(out);
552 if param.repeated {
553 json!({ "type": "array", "items": base })
554 } else {
555 base
556 }
557}
558
559fn error_response(id: &Value, code: i64, message: String) -> Value {
560 json!({
561 "jsonrpc": "2.0",
562 "id": id,
563 "error": { "code": code, "message": message },
564 })
565}
566
567fn ok_result(text: String) -> Value {
568 json!({ "content": [ { "type": "text", "text": text } ] })
569}
570
571fn error_result(message: impl Into<String>) -> Value {
572 json!({ "content": [ { "type": "text", "text": message.into() } ], "isError": true })
573}
574
575pub async fn serve<R, W>(server: &McpServer, reader: R, writer: &mut W) -> anyhow::Result<()>
580where
581 R: tokio::io::AsyncBufRead + Unpin,
582 W: tokio::io::AsyncWrite + Unpin,
583{
584 use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
585
586 let mut lines = reader.lines();
587 while let Some(line) = lines.next_line().await? {
588 if line.trim().is_empty() {
589 continue;
590 }
591 if let Some(response) = server.handle_line(&line).await {
592 writer.write_all(response.to_string().as_bytes()).await?;
593 writer.write_all(b"\n").await?;
594 writer.flush().await?;
595 }
596 }
597 Ok(())
598}
599
600#[cfg(test)]
601mod tests {
602 use super::*;
603 use crate::core::auth::TokenStorage;
604 use crate::core::config::OAuthConfig;
605
606 async fn test_server() -> McpServer {
607 test_server_with_profile(SafetyProfile::default()).await
608 }
609
610 async fn test_server_with_profile(profile: SafetyProfile) -> McpServer {
611 let config = OAuthConfig {
615 client_id: "test-id.apps.googleusercontent.com".into(),
616 client_secret: None,
617 ..Default::default()
618 };
619 let storage = TokenStorage {
620 access_token: "test-token".into(),
621 refresh_token: None,
622 expires_at: u64::MAX,
623 token_type: "Bearer".into(),
624 scope: String::new(),
625 };
626 let auth = GoogleAuth::with_token(config, storage).await.unwrap();
627 McpServer::new(auth, profile)
628 }
629
630 fn request(id: i64, method: &str, params: &str) -> String {
631 format!(r#"{{"jsonrpc":"2.0","id":{id},"method":"{method}","params":{params}}}"#)
632 }
633
634 #[tokio::test]
635 async fn the_stdio_loop_pipes_the_stateless_requests() {
636 let server = test_server().await;
637 let input = format!(
638 "{}\n{}\n{}\n",
639 request(1, "server/discover", "{}"),
640 r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
641 request(2, "tools/list", "{}"),
642 );
643 let mut out: Vec<u8> = Vec::new();
644 serve(&server, input.as_bytes(), &mut out).await.unwrap();
645
646 let lines: Vec<Value> = String::from_utf8(out)
648 .unwrap()
649 .lines()
650 .map(|l| serde_json::from_str(l).unwrap())
651 .collect();
652 assert_eq!(lines.len(), 2);
653
654 assert_eq!(lines[0]["jsonrpc"], "2.0");
655 assert_eq!(lines[0]["id"], 1);
656 assert_eq!(lines[0]["result"]["resultType"], "complete");
657 assert_eq!(
658 lines[0]["result"]["supportedVersions"],
659 json!(["2026-07-28"])
660 );
661 assert!(lines[0]["result"]["capabilities"]["tools"].is_object());
662 assert_eq!(
663 lines[0]["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
664 "grr"
665 );
666
667 assert_eq!(lines[1]["id"], 2);
668 let tools = lines[1]["result"]["tools"].as_array().unwrap();
669 assert_eq!(tools.len(), server.tool_count());
670 }
671
672 #[tokio::test]
677 async fn legacy_handshake_methods_are_refused_with_the_revision_to_speak() {
678 let server = test_server().await;
679
680 for method in ["ping", "logging/setLevel"] {
681 let line = request(1, method, "{}");
682 let response = server.handle_line(&line).await.unwrap();
683
684 assert_eq!(response["error"]["code"], METHOD_NOT_FOUND, "{method}");
685 }
686 }
687
688 #[tokio::test]
693 async fn initialize_answers_a_minimal_legacy_handshake() {
694 let server = test_server().await;
695
696 let line = request(
697 1,
698 "initialize",
699 r#"{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}"#,
700 );
701 let response = server.handle_line(&line).await.unwrap();
702 let result = &response["result"];
703 assert_eq!(result["protocolVersion"], "2025-06-18");
704 assert_eq!(result["serverInfo"]["name"], "grr");
705 assert!(result["capabilities"]["tools"].is_object());
706 let line = request(2, "tools/list", "{}");
708 let response = server.handle_line(&line).await.unwrap();
709 assert_eq!(
710 response["result"]["tools"].as_array().unwrap().len(),
711 server.tool_count()
712 );
713 }
714
715 #[tokio::test]
719 async fn server_discover_answers_without_a_handshake() {
720 let server = test_server().await;
721
722 let line = request(
723 1,
724 "server/discover",
725 r#"{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"probe","version":"0"}}}"#,
726 );
727 let response = server.handle_line(&line).await.unwrap();
728 let result = &response["result"];
729
730 assert_eq!(result["resultType"], "complete");
731 assert_eq!(
732 result["supportedVersions"],
733 json!(["2026-07-28"]),
734 "the current revision, and only it"
735 );
736 assert!(result["capabilities"]["tools"].is_object());
737 assert_eq!(
738 result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
739 "grr"
740 );
741
742 let inline = request(2, "tools/list", "{}");
744 let response = server.handle_line(&inline).await.unwrap();
745 assert!(response["result"]["tools"].is_array());
746 }
747
748 #[tokio::test]
751 async fn results_identify_the_server_per_request() {
752 let server = test_server().await;
753
754 for method in ["tools/list", "server/discover"] {
755 let line = request(1, method, "{}");
756 let response = server.handle_line(&line).await.unwrap();
757 assert_eq!(
758 response["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"], "grr",
759 "{method} did not identify the server"
760 );
761 }
762 }
763
764 #[tokio::test]
765 async fn tools_list_covers_every_index_method_with_an_input_schema() {
766 let server = test_server().await;
767 let line = request(2, "tools/list", "{}");
768 let response = server.handle_line(&line).await.unwrap();
769 let tools = response["result"]["tools"].as_array().unwrap();
770
771 let expected: usize = discovery::services()
773 .values()
774 .map(|s| s.methods.len())
775 .sum();
776 assert_eq!(tools.len(), expected);
777
778 for tool in tools {
779 let name = tool["name"].as_str().unwrap();
780 assert!(name.contains('.'), "{name} is not a dotted id");
782 assert!(discovery::resolve(name).is_ok(), "{name} does not resolve");
783 assert_eq!(tool["inputSchema"]["type"], "object", "{name}");
784 assert!(tool["inputSchema"]["properties"].is_object(), "{name}");
785 assert!(
786 tool["description"].as_str().unwrap().contains("HTTP"),
787 "{name}"
788 );
789 }
790 }
791
792 #[tokio::test]
797 async fn output_schema_mirrors_the_response_ref() {
798 let server = test_server().await;
799 let line = request(2, "tools/list", "{}");
800 let response = server.handle_line(&line).await.unwrap();
801 let tools = response["result"]["tools"].as_array().unwrap();
802
803 let find = |name: &str| {
804 tools
805 .iter()
806 .find(|t| t["name"] == name)
807 .unwrap_or_else(|| panic!("{name} missing"))
808 };
809
810 let list = find("gmail.users.threads.list");
812 let output = &list["outputSchema"];
813 assert!(
814 output.is_object(),
815 "threads.list must carry an outputSchema"
816 );
817 assert_eq!(output["type"], "object");
818 assert!(
819 output["properties"]["nextPageToken"]["type"] == "string",
820 "list envelope fields survive distillation"
821 );
822 assert!(
823 output["properties"]["threads"]["items"]["properties"]["id"]["type"] == "string",
824 "nested array items are inlined one $ref deep"
825 );
826
827 let empty = find("gmail.users.stop");
829 assert!(
830 empty.get("outputSchema").is_none(),
831 "no fabricated output schema"
832 );
833
834 let raw = serde_json::to_string(&response).unwrap();
836 assert!(
837 !raw.contains("\"outputSchema\":{\"description"),
838 "pruned schemas carry no descriptions"
839 );
840 }
841
842 #[tokio::test]
846 async fn parameter_schemas_carry_location_enums_format_and_bounds() {
847 let server = test_server().await;
848 let line = request(2, "tools/list", "{}");
849 let response = server.handle_line(&line).await.unwrap();
850 let tools = response["result"]["tools"].as_array().unwrap();
851 let find = |name: &str| {
852 tools
853 .iter()
854 .find(|t| t["name"] == name)
855 .unwrap_or_else(|| panic!("{name} missing"))
856 };
857
858 let user_id =
859 find("gmail.users.threads.list")["inputSchema"]["properties"]["userId"]["description"]
860 .as_str()
861 .unwrap();
862 assert!(
863 user_id.starts_with("[URL path segment]"),
864 "path parameters announce their location: {user_id}"
865 );
866
867 let max_results = find("calendar.events.list")["inputSchema"]["properties"]["maxResults"]
869 .as_object()
870 .expect("maxResults present");
871 assert_eq!(max_results["format"], "int32");
872 assert_eq!(max_results["minimum"], 1.0);
873 assert_eq!(max_results["default"], "250");
874 }
875
876 #[tokio::test]
881 async fn descriptions_carry_returns_body_and_siblings() {
882 let server = test_server().await;
883 let line = request(2, "tools/list", "{}");
884 let response = server.handle_line(&line).await.unwrap();
885 let tools = response["result"]["tools"].as_array().unwrap();
886 let by_name = |name: &str| {
887 tools
888 .iter()
889 .find(|t| t["name"] == name)
890 .unwrap_or_else(|| panic!("{name} missing"))["description"]
891 .as_str()
892 .unwrap()
893 .to_owned()
894 };
895
896 let delete = by_name("gmail.users.messages.delete");
897 assert!(
898 delete.contains("irreversible"),
899 "delete should warn about irreversibility: {delete}"
900 );
901 assert!(
902 delete.contains("refused under --readonly"),
903 "write verbs name the safety gate: {delete}"
904 );
905
906 let list = by_name("calendar.events.list");
907 assert!(
908 list.contains("Siblings over the same resource"),
909 "list tools name their CRUD neighbours: {list}"
910 );
911 assert!(list.contains("as JSON"), "returns are described: {list}");
912 assert!(
913 list.contains("body_file"),
914 "body building is described: {list}"
915 );
916
917 let run = by_name("script.scripts.run");
918 assert!(
919 run.starts_with("Executes a function"),
920 "Discovery shipped no description for scripts.run; the curated override must supply one: {run}"
921 );
922
923 for tool in tools {
926 let d = tool["description"].as_str().unwrap();
927 assert!(
928 !d.contains(". [HTTP"),
929 "{}: doubled period before the verb tag in {d}",
930 tool["name"]
931 );
932 }
933 }
934
935 #[tokio::test]
936 async fn input_schemas_carry_the_escape_hatches_and_required_params() {
937 let server = test_server().await;
938 let line = request(2, "tools/list", "{}");
939 let response = server.handle_line(&line).await.unwrap();
940 let tools = response["result"]["tools"].as_array().unwrap();
941 let schema = tools
942 .iter()
943 .find(|t| t["name"] == "gmail.users.messages.list")
944 .map(|t| t["inputSchema"].clone())
945 .unwrap();
946
947 for prop in ["params", "body_file", "query", "dry_run"] {
948 assert!(schema["properties"][prop].is_object(), "missing {prop}");
949 }
950 let required: Vec<&str> = schema["required"]
951 .as_array()
952 .unwrap()
953 .iter()
954 .filter_map(|v| v.as_str())
955 .collect();
956 assert!(required.contains(&"userId"), "{required:?}");
957
958 assert_eq!(schema["properties"]["maxResults"]["type"], "integer");
960 assert_eq!(schema["properties"]["labelIds"]["type"], "array");
961 assert_eq!(schema["properties"]["labelIds"]["items"]["type"], "string");
962 }
963
964 #[tokio::test]
965 async fn enum_values_surface_in_the_schema() {
966 let server = test_server().await;
967 let line = request(2, "tools/list", "{}");
968 let response = server.handle_line(&line).await.unwrap();
969 let tools = response["result"]["tools"].as_array().unwrap();
970 let schema = tools
971 .iter()
972 .find(|t| t["name"] == "calendar.calendarList.list")
973 .map(|t| t["inputSchema"].clone())
974 .unwrap();
975 let values = schema["properties"]["minAccessRole"]["enum"]
976 .as_array()
977 .unwrap();
978 assert!(
979 values.iter().any(|v| v.as_str() == Some("owner")),
980 "{values:?}"
981 );
982 }
983
984 #[tokio::test]
985 async fn tools_call_dry_run_matches_the_api_call_payload() {
986 let server = test_server().await;
987 let line = request(
988 3,
989 "tools/call",
990 r#"{"name":"gmail.users.messages.list","arguments":{"userId":"me","dry_run":true}}"#,
991 );
992 let response = server.handle_line(&line).await.unwrap();
993 assert_eq!(response["result"]["isError"], Value::Null);
994 let text = response["result"]["content"][0]["text"].as_str().unwrap();
995 let payload: Value = serde_json::from_str(text).unwrap();
996
997 let (service, method) = discovery::resolve("gmail.users.messages.list").unwrap();
1000 let mut params = Map::new();
1001 params.insert("userId".into(), json!("me"));
1002 let plan = api::plan_request(service, method, ¶ms, None, None, &[]).unwrap();
1003 assert_eq!(payload, api::dry_run_payload(method, &plan));
1004 }
1005
1006 #[tokio::test]
1007 async fn tools_call_accepts_the_camel_case_dry_run_spelling() {
1008 let server = test_server().await;
1009 let line = request(
1010 4,
1011 "tools/call",
1012 r#"{"name":"gmail.users.messages.list","arguments":{"userId":"me","dryRun":true}}"#,
1013 );
1014 let response = server.handle_line(&line).await.unwrap();
1015 let text = response["result"]["content"][0]["text"].as_str().unwrap();
1016 let payload: Value = serde_json::from_str(text).unwrap();
1017 assert_eq!(payload["dryRun"], true);
1018 }
1019
1020 #[tokio::test]
1021 async fn tool_arguments_win_over_the_params_escape_hatch() {
1022 let server = test_server().await;
1023 let line = request(
1024 5,
1025 "tools/call",
1026 r#"{"name":"gmail.users.messages.list","arguments":
1027 {"params":{"userId":"someone-else","q":"is:unread"},"userId":"me","dry_run":true}}"#,
1028 );
1029 let response = server.handle_line(&line).await.unwrap();
1030 let text = response["result"]["content"][0]["text"].as_str().unwrap();
1031 let payload: Value = serde_json::from_str(text).unwrap();
1032 let url = payload["url"].as_str().unwrap();
1034 assert!(url.contains("/users/me/messages"), "{url}");
1035 assert!(url.contains("q=is%3Aunread"), "{url}");
1036 assert!(!url.contains("someone-else"), "{url}");
1037 }
1038
1039 #[tokio::test]
1040 async fn an_unknown_tool_is_an_error_result_not_a_crash() {
1041 let server = test_server().await;
1042 let line = request(
1043 6,
1044 "tools/call",
1045 r#"{"name":"gmail.users.messages.lst","arguments":{}}"#,
1046 );
1047 let response = server.handle_line(&line).await.unwrap();
1048 assert_eq!(response["result"]["isError"], true);
1049 let text = response["result"]["content"][0]["text"].as_str().unwrap();
1050 assert!(text.contains("unknown tool"), "{text}");
1051 }
1052
1053 #[tokio::test]
1054 async fn readonly_refuses_writes_with_an_mcp_error_result() {
1055 let server = test_server_with_profile(SafetyProfile::new(true, [], [])).await;
1056
1057 let line = request(
1058 7,
1059 "tools/call",
1060 r#"{"name":"gmail.users.messages.send","arguments":{"userId":"me","dry_run":true}}"#,
1061 );
1062 let response = server.handle_line(&line).await.unwrap();
1063 assert_eq!(response["result"]["isError"], true);
1064 let text = response["result"]["content"][0]["text"].as_str().unwrap();
1065 assert!(text.contains("gmail.users.messages.send"), "{text}");
1067 assert!(text.contains("POST"), "{text}");
1068 assert!(text.contains("Rerun without --readonly"), "{text}");
1069
1070 let line = request(
1072 8,
1073 "tools/call",
1074 r#"{"name":"gmail.users.messages.list","arguments":{"userId":"me","dry_run":true}}"#,
1075 );
1076 let response = server.handle_line(&line).await.unwrap();
1077 assert_eq!(response["result"]["isError"], Value::Null);
1078 }
1079
1080 #[tokio::test]
1081 async fn a_missing_tool_name_is_an_error_result() {
1082 let server = test_server().await;
1083 let line = request(9, "tools/call", r#"{"arguments":{}}"#);
1084 let response = server.handle_line(&line).await.unwrap();
1085 assert_eq!(response["result"]["isError"], true);
1086 }
1087
1088 #[tokio::test]
1089 async fn a_stdin_body_file_is_refused_over_mcp() {
1090 let server = test_server().await;
1091 let line = request(
1092 10,
1093 "tools/call",
1094 r#"{"name":"gmail.users.messages.list","arguments":{"body_file":"-"}}"#,
1095 );
1096 let response = server.handle_line(&line).await.unwrap();
1097 assert_eq!(response["result"]["isError"], true);
1098 let text = response["result"]["content"][0]["text"].as_str().unwrap();
1099 assert!(text.contains("stdin"), "{text}");
1100 }
1101
1102 #[tokio::test]
1103 async fn an_unknown_method_is_a_jsonrpc_error() {
1104 let server = test_server().await;
1105 let line = request(11, "resources/list", "{}");
1106 let response = server.handle_line(&line).await.unwrap();
1107 assert_eq!(response["error"]["code"], -32601);
1108 assert!(
1109 response["error"]["message"]
1110 .as_str()
1111 .unwrap()
1112 .contains("resources/list")
1113 );
1114 assert_eq!(response["id"], 11);
1115 }
1116
1117 #[tokio::test]
1118 async fn a_parse_error_answers_with_a_null_id() {
1119 let server = test_server().await;
1120 let response = server.handle_line("not json at all").await.unwrap();
1121 assert_eq!(response["error"]["code"], -32700);
1122 assert!(response["id"].is_null());
1123 }
1124
1125 #[tokio::test]
1126 async fn notifications_are_never_answered() {
1127 let server = test_server().await;
1128 assert!(
1129 server
1130 .handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
1131 .await
1132 .is_none()
1133 );
1134 assert!(
1135 server
1136 .handle_line(r#"{"jsonrpc":"2.0","method":"notifications/cancelled"}"#)
1137 .await
1138 .is_none()
1139 );
1140 }
1141}