grr-cli 2.1.4

Google tools from the terminal, at maximum performance: 401 methods across 14 Google APIs in one generated command tree, zero-config, over HTTP/3
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! Model Context Protocol (MCP) server for grr.
//!
//! Hand-rolled JSON-RPC 2.0 over stdio — no SDK crate: a tool-only server
//! needs four RPCs. Newline-delimited requests in, one response line
//! per request out, logs to stderr ONLY (stdout is the MCP stream, the
//! same discipline as the rest of grr).
//!
//! * `server/discover` — the stateless revision's discovery RPC: revisions
//!   served, capabilities, identity, and it needs no prior call
//! * `tools/list` — every method in the Discovery index as a tool
//! * `tools/call` — one method invocation through the shared call path
//!
//! `2026-07-28` is the newest revision served, so the handshake is gone from
//! the happy path — but `initialize` is answered with a minimal legacy
//! handshake (server/discover remains the discovery RPC), because the
//! deployed client ecosystem still opens with it. `ping` and
//! `logging/setLevel` answer with a JSON-RPC error naming the revision to
//! speak instead. Notifications (`notifications/initialized`, whatever the
//! revision) carry no id, so they are never answered at all.
//!
//! Tool names are the dotted method ids `grr api call` takes
//! (`gmail.users.messages.list`), so an agent reaches every method Google
//! publishes through the same resolution the CLI uses. Errors never kill
//! the server: a tool failure is an `isError` result (MCP's tool-error
//! contract), a protocol failure a JSON-RPC error object.
//!
//! ```text
//! {"jsonrpc":"2.0","id":1,"method":"server/discover"}
//! {"jsonrpc":"2.0","id":2,"method":"tools/list"}
//! {"jsonrpc":"2.0","id":3,"method":"tools/call",
//!  "params":{"name":"gmail.users.messages.list","arguments":{"userId":"me","dry_run":true}}}
//! ```

use crate::commands::api::{self, call_method};
use crate::commands::safety::{SafetyProfile, is_write_verb};
use crate::core::auth::GoogleAuth;
use crate::discovery::{self, Method, Parameter, Service};
use serde_json::{Map, Value, json};

/// The one protocol revision this server speaks: `2026-07-28`, the current
/// MCP revision, and a *stateless* redesign — it removed the `initialize`/
/// `notifications/initialized` handshake, made `server/discover` mandatory,
/// and moved the protocol version and client capabilities into per-request
/// `_meta`.
///
/// Legacy revisions are deliberately not served. Their handshake shape
/// (`ping`, `logging/setLevel`) is gone from the spec; `initialize` alone
/// is answered with a minimal legacy handshake so standard clients
/// (mcp-proxy, Claude Desktop, Cursor, Glama's introspector) can connect —
/// they then use `tools/*`, or read this constant out of `server/discover`
/// and speak the current revision.
pub(crate) const PROTOCOL_VERSION: &str = "2026-07-28";

/// Every revision this server can serve, newest first — exactly what
/// `server/discover` reports as `supportedVersions`. One entry, on purpose:
/// this server speaks the current revision and nothing older.
const SUPPORTED_VERSIONS: [&str; 1] = ["2026-07-28"];

/// JSON-RPC 2.0 error codes.
const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;

/// One server instance: one credential, one safety profile, every tool.
/// The stdio loop is single-tasked, so no `Arc` is needed.
pub struct McpServer {
    auth: GoogleAuth,
    profile: SafetyProfile,
}

impl McpServer {
    pub fn new(auth: GoogleAuth, profile: SafetyProfile) -> Self {
        Self { auth, profile }
    }

    /// How many tools the Discovery index exposes, for the startup banner.
    pub fn tool_count(&self) -> usize {
        discovery::services()
            .values()
            .map(|s| s.methods.len())
            .sum()
    }

    /// Handle one line of JSON-RPC. `Some(response)` for requests (and for
    /// parse errors, which answer with a null id); `None` for
    /// notifications, which get no response. Never panics and never kills
    /// the server: every failure is an error-shaped response.
    pub async fn handle_line(&self, line: &str) -> Option<Value> {
        let message: Value = match serde_json::from_str(line) {
            Ok(message) => message,
            Err(error) => {
                return Some(error_response(
                    &Value::Null,
                    PARSE_ERROR,
                    format!("parse error: {error}"),
                ));
            }
        };

        // A message without an id is a notification (`notifications/
        // initialized` included): it gets no response by definition.
        let id = message.get("id").cloned()?;

        let method = message.get("method").and_then(|m| m.as_str()).unwrap_or("");
        let params = message.get("params").cloned().unwrap_or(Value::Null);

        let response = match method {
            "server/discover" => json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": discover_result(),
            }),
            "tools/list" => json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": { "tools": tools_list(), "_meta": server_meta() },
            }),
            "tools/call" => {
                let mut result = self.tools_call(&params).await;
                // The stateless revision has no handshake to carry identity,
                // so every result names the server that produced it.
                if let Some(object) = result.as_object_mut() {
                    object.insert("_meta".to_owned(), server_meta());
                }
                json!({ "jsonrpc": "2.0", "id": id, "result": result })
            }
            // `initialize` compat: the stateless revision removed the
            // handshake, but the deployed client ecosystem (mcp-proxy,
            // Claude Desktop, Cursor, Glama's introspector) still opens
            // with it. Answer with a minimal legacy handshake naming the
            // newest revision we speak, so standard clients connect and
            // then use `tools/*` (or graduate to `server/discover`).
            // `ping` stays refused: nothing in the legacy flow needs it
            // to connect.
            "initialize" => {
                let requested = params
                    .get("protocolVersion")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                // Serve the requested legacy revision only if we name it;
                // anything else (unknown or absent) gets the current one.
                let version = SUPPORTED_VERSIONS
                    .iter()
                    .find(|v| **v == requested)
                    .copied()
                    .unwrap_or(PROTOCOL_VERSION);
                json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": {
                        "protocolVersion": version,
                        "capabilities": { "tools": {} },
                        "serverInfo": server_info(),
                        "instructions": discover_result()["instructions"].clone(),
                    },
                })
            }
            "logging/setLevel" => error_response(
                &id,
                METHOD_NOT_FOUND,
                format!(
                    "`{method}` is not part of MCP {PROTOCOL_VERSION} — the handshake is gone. \
                     Call `server/discover` for the revisions served, then `tools/*` inline."
                ),
            ),
            "" => error_response(&id, INVALID_REQUEST, "request has no method".to_owned()),
            other => error_response(&id, METHOD_NOT_FOUND, format!("method not found: {other}")),
        };
        Some(response)
    }

    /// `tools/call`: resolve the tool name, assemble the parameters,
    /// invoke the shared call path. EVERY error — unknown tool, refused by
    /// the safety profile, HTTP failure — is an `isError` result, never a
    /// process exit: the server must survive one bad call.
    async fn tools_call(&self, params: &Value) -> Value {
        let Some(name) = params.get("name").and_then(|n| n.as_str()) else {
            return error_result("tools/call needs a tool `name`");
        };
        let arguments = params
            .get("arguments")
            .cloned()
            .unwrap_or_else(|| Value::Object(Map::new()));
        let Value::Object(args) = arguments else {
            return error_result("tools/call `arguments` must be an object");
        };
        match self.invoke_tool(name, &args).await {
            Ok(text) => ok_result(text),
            Err(message) => error_result(message),
        }
    }

    async fn invoke_tool(&self, name: &str, args: &Map<String, Value>) -> Result<String, String> {
        let (service, method) = discovery::resolve(name)
            .map_err(|message| format!("unknown tool `{name}`: {message}"))?;

        // The same gate the CLI dispatch honors (src/commands/safety.rs).
        self.profile.check(&service.name, method)?;

        // Assemble the parameter map: the `params` escape-hatch object goes
        // in first, then the tool-call arguments — the arguments are the
        // typed params and win on conflict ("typed params win", the merge
        // order of `api::parse_params`).
        let mut merged = Map::new();
        if let Some(Value::Object(object)) = args.get("params") {
            merged.extend(object.clone());
        }

        let mut body_file: Option<String> = None;
        let mut query: Vec<String> = Vec::new();
        let mut dry_run = false;
        for (key, value) in args {
            match key.as_str() {
                "params" => {}
                // Both spellings: the input schema declares `dry_run`, but
                // agents routinely write `dryRun`. No Discovery parameter
                // uses either name, so consuming them is safe.
                "dry_run" | "dryRun" => dry_run = value.as_bool().unwrap_or(false),
                "body_file" | "bodyFile" => body_file = value.as_str().map(str::to_owned),
                "query" => {
                    if let Some(items) = value.as_array() {
                        query.extend(items.iter().filter_map(|v| v.as_str().map(str::to_owned)));
                    }
                }
                other => {
                    merged.insert(other.to_owned(), value.clone());
                }
            }
        }

        // stdin IS the MCP stream: a `-` body_file would swallow JSON-RPC
        // lines. Say so rather than corrupting the session.
        if body_file.as_deref() == Some("-") {
            return Err(
                "body_file `-` (stdin) is not available over MCP; pass a file path".to_owned(),
            );
        }

        let payload = call_method(
            Some(&self.auth),
            service,
            method,
            merged,
            api::CallOptions {
                body_file,
                // The verb override is `grr api call`'s escape hatch; MCP
                // speaks the Discovery document.
                verb_override: None,
                query_extras: query,
                dry_run,
            },
        )
        .await
        .map_err(|error| error.to_string())?;

        serde_json::to_string(&payload)
            .map_err(|error| format!("serialising the result failed: {error}"))
    }
}

/// The server's identity, for `_meta`. With no handshake to carry it once,
/// `io.modelcontextprotocol/serverInfo` on EVERY result is the only place a
/// client can read it.
fn server_info() -> Value {
    json!({ "name": "grr", "version": env!("CARGO_PKG_VERSION") })
}

fn server_meta() -> Value {
    json!({ "io.modelcontextprotocol/serverInfo": server_info() })
}

/// `server/discover` — the mandatory RPC of the stateless revision. No body
/// parameters, no prior call, no state: it reports the revisions served, the
/// capabilities, and the identity, so a client can pick a revision (or just
/// call `tools/*` inline) before doing anything else.
fn discover_result() -> Value {
    json!({
        "resultType": "complete",
        "supportedVersions": SUPPORTED_VERSIONS,
        "capabilities": { "tools": {} },
        "_meta": server_meta(),
        "instructions": "Google Workspace and Google Cloud APIs from the embedded Discovery \
                         index. Tool names are dotted method ids (gmail.users.messages.list); \
                         --readonly, --deny-service and --deny-verb gate every write.",
    })
}

/// Every method in the Discovery index as an MCP tool. The index grows as
/// Google publishes APIs — the list is derived, never a hardcoded count.
fn tools_list() -> Vec<Value> {
    discovery::services()
        .values()
        .flat_map(|service| service.methods.iter().map(|m| tool_descriptor(service, m)))
        .collect()
}

fn tool_descriptor(service: &Service, method: &Method) -> Value {
    json!({
        "name": format!("{}.{}", service.name, method.id),
        "description": tool_description(method),
        "inputSchema": input_schema(method),
    })
}

/// The method's Discovery description + its HTTP verb + a hint that write
/// verbs need auth scopes (and are gated by `--readonly`).
fn tool_description(method: &Method) -> String {
    let verb = method.http_method.to_ascii_uppercase();
    let mut text = format!("{} [HTTP {verb}]", method.description);
    if is_write_verb(&verb) {
        text.push_str(" — write verb: needs auth scopes; refused under --readonly safety profiles");
    } else {
        text.push_str(" — needs auth scopes");
    }
    text
}

/// The tool's input schema: a JSON-schema object built from the method's
/// parameters plus grr's escape hatches; `required` is the method's
/// required parameter names.
fn input_schema(method: &Method) -> Value {
    let mut properties = Map::new();
    for param in &method.parameters {
        properties.insert(param.name.clone(), param_schema(param));
    }
    properties.insert(
        "params".into(),
        json!({
            "type": "object",
            "additionalProperties": true,
            "description": "Parameter map merged into the request; typed parameters win.",
        }),
    );
    properties.insert("body_file".into(), json!({
        "type": "string",
        "description": "Read the request body from this file ('-' for stdin) instead of building one from the parameters.",
    }));
    properties.insert("query".into(), json!({
        "type": "array",
        "items": { "type": "string" },
        "description": "Extra KEY=VALUE query pairs for endpoints whose parameters Discovery does not describe.",
    }));
    properties.insert(
        "dry_run".into(),
        json!({
            "type": "boolean",
            "description": "Return the request that would be sent, without sending it.",
        }),
    );

    let mut schema = Map::new();
    schema.insert("type".into(), json!("object"));
    schema.insert("properties".into(), Value::Object(properties));
    if !method.required.is_empty() {
        schema.insert("required".into(), json!(method.required));
    }
    Value::Object(schema)
}

/// One parameter as a JSON-schema property. Discovery's scalar kinds map
/// to JSON-schema types; anything else (`any`, nested objects) omits the
/// type rather than lie. A repeated parameter becomes an array of its base
/// type, which is what `build_query` expands at call time.
fn param_schema(param: &Parameter) -> Value {
    let mut out = Map::new();
    match param.kind.as_str() {
        "string" => {
            out.insert("type".into(), json!("string"));
        }
        "integer" => {
            out.insert("type".into(), json!("integer"));
        }
        "number" => {
            out.insert("type".into(), json!("number"));
        }
        "boolean" => {
            out.insert("type".into(), json!("boolean"));
        }
        _ => {}
    }
    if !param.description.is_empty() {
        out.insert("description".into(), json!(param.description));
    }
    if let Some(values) = &param.enum_values {
        out.insert("enum".into(), json!(values));
    }
    let base = Value::Object(out);
    if param.repeated {
        json!({ "type": "array", "items": base })
    } else {
        base
    }
}

fn error_response(id: &Value, code: i64, message: String) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": { "code": code, "message": message },
    })
}

fn ok_result(text: String) -> Value {
    json!({ "content": [ { "type": "text", "text": text } ] })
}

fn error_result(message: impl Into<String>) -> Value {
    json!({ "content": [ { "type": "text", "text": message.into() } ], "isError": true })
}

/// The stdio loop: newline-delimited JSON-RPC in, one response line per
/// request out. Generic over the reader/writer so tests can run the whole
/// handshake in-process. EOF on stdin (the client closed the session) is
/// a clean shutdown.
pub async fn serve<R, W>(server: &McpServer, reader: R, writer: &mut W) -> anyhow::Result<()>
where
    R: tokio::io::AsyncBufRead + Unpin,
    W: tokio::io::AsyncWrite + Unpin,
{
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};

    let mut lines = reader.lines();
    while let Some(line) = lines.next_line().await? {
        if line.trim().is_empty() {
            continue;
        }
        if let Some(response) = server.handle_line(&line).await {
            writer.write_all(response.to_string().as_bytes()).await?;
            writer.write_all(b"\n").await?;
            writer.flush().await?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::auth::TokenStorage;
    use crate::core::config::OAuthConfig;

    async fn test_server() -> McpServer {
        test_server_with_profile(SafetyProfile::default()).await
    }

    async fn test_server_with_profile(profile: SafetyProfile) -> McpServer {
        // `GoogleAuth::with_token` is the documented test hook: it skips
        // OAuth and persistent storage entirely. Dry-run and gate tests
        // never touch the network.
        let config = OAuthConfig {
            client_id: "test-id.apps.googleusercontent.com".into(),
            client_secret: None,
            ..Default::default()
        };
        let storage = TokenStorage {
            access_token: "test-token".into(),
            refresh_token: None,
            expires_at: u64::MAX,
            token_type: "Bearer".into(),
            scope: String::new(),
        };
        let auth = GoogleAuth::with_token(config, storage).await.unwrap();
        McpServer::new(auth, profile)
    }

    fn request(id: i64, method: &str, params: &str) -> String {
        format!(r#"{{"jsonrpc":"2.0","id":{id},"method":"{method}","params":{params}}}"#)
    }

    #[tokio::test]
    async fn the_stdio_loop_pipes_the_stateless_requests() {
        let server = test_server().await;
        let input = format!(
            "{}\n{}\n{}\n",
            request(1, "server/discover", "{}"),
            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
            request(2, "tools/list", "{}"),
        );
        let mut out: Vec<u8> = Vec::new();
        serve(&server, input.as_bytes(), &mut out).await.unwrap();

        // One response line per REQUEST; the notification got none.
        let lines: Vec<Value> = String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert_eq!(lines.len(), 2);

        assert_eq!(lines[0]["jsonrpc"], "2.0");
        assert_eq!(lines[0]["id"], 1);
        assert_eq!(lines[0]["result"]["resultType"], "complete");
        assert_eq!(
            lines[0]["result"]["supportedVersions"],
            json!(["2026-07-28"])
        );
        assert!(lines[0]["result"]["capabilities"]["tools"].is_object());
        assert_eq!(
            lines[0]["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
            "grr"
        );

        assert_eq!(lines[1]["id"], 2);
        let tools = lines[1]["result"]["tools"].as_array().unwrap();
        assert_eq!(tools.len(), server.tool_count());
    }

    /// The handshake revisions are not served at all — except `initialize`,
    /// which gets a minimal legacy handshake so standard clients connect.
    /// `ping` and `logging/setLevel` get an error naming the revision to
    /// speak and the RPC that replaced the handshake.
    #[tokio::test]
    async fn legacy_handshake_methods_are_refused_with_the_revision_to_speak() {
        let server = test_server().await;

        for method in ["ping", "logging/setLevel"] {
            let line = request(1, method, "{}");
            let response = server.handle_line(&line).await.unwrap();

            assert_eq!(response["error"]["code"], METHOD_NOT_FOUND, "{method}");
        }
    }

    /// `initialize` compat: a standard client opens with the legacy
    /// handshake and must get a valid result — server identity, tool
    /// capability, the newest revision we speak — instead of an error.
    #[tokio::test]
    async fn initialize_answers_a_minimal_legacy_handshake() {
        let server = test_server().await;

        let line = request(
            1,
            "initialize",
            r#"{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"0"}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        let result = &response["result"];
        assert_eq!(result["protocolVersion"], PROTOCOL_VERSION);
        assert_eq!(result["serverInfo"]["name"], "grr");
        assert!(result["capabilities"]["tools"].is_object());
        // The handshake completes; tools/* then works as usual.
        let line = request(2, "tools/list", "{}");
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(
            response["result"]["tools"].as_array().unwrap().len(),
            server.tool_count()
        );
    }

    /// The stateless revision has no handshake, so `server/discover` may be
    /// a client's first call — and `tools/list` works with no prior call at
    /// all. The server holds no handshake state to satisfy.
    #[tokio::test]
    async fn server_discover_answers_without_a_handshake() {
        let server = test_server().await;

        let line = request(
            1,
            "server/discover",
            r#"{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"probe","version":"0"}}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        let result = &response["result"];

        assert_eq!(result["resultType"], "complete");
        assert_eq!(
            result["supportedVersions"],
            json!(["2026-07-28"]),
            "the current revision, and only it"
        );
        assert!(result["capabilities"]["tools"].is_object());
        assert_eq!(
            result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],
            "grr"
        );

        // A 2026-07-28 client may also skip discovery entirely.
        let inline = request(2, "tools/list", "{}");
        let response = server.handle_line(&inline).await.unwrap();
        assert!(response["result"]["tools"].is_array());
    }

    /// No handshake means no `serverInfo` to carry identity, so every result
    /// names the server — the spec asks for `_meta` on each one.
    #[tokio::test]
    async fn results_identify_the_server_per_request() {
        let server = test_server().await;

        for method in ["tools/list", "server/discover"] {
            let line = request(1, method, "{}");
            let response = server.handle_line(&line).await.unwrap();
            assert_eq!(
                response["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"], "grr",
                "{method} did not identify the server"
            );
        }
    }

    #[tokio::test]
    async fn tools_list_covers_every_index_method_with_an_input_schema() {
        let server = test_server().await;
        let line = request(2, "tools/list", "{}");
        let response = server.handle_line(&line).await.unwrap();
        let tools = response["result"]["tools"].as_array().unwrap();

        // The index grows as Google publishes APIs — never a hardcoded count.
        let expected: usize = discovery::services()
            .values()
            .map(|s| s.methods.len())
            .sum();
        assert_eq!(tools.len(), expected);

        for tool in tools {
            let name = tool["name"].as_str().unwrap();
            // Tool names are the dotted method ids `grr api call` takes.
            assert!(name.contains('.'), "{name} is not a dotted id");
            assert!(discovery::resolve(name).is_ok(), "{name} does not resolve");
            assert_eq!(tool["inputSchema"]["type"], "object", "{name}");
            assert!(tool["inputSchema"]["properties"].is_object(), "{name}");
            assert!(
                tool["description"].as_str().unwrap().contains("HTTP"),
                "{name}"
            );
        }
    }

    #[tokio::test]
    async fn input_schemas_carry_the_escape_hatches_and_required_params() {
        let server = test_server().await;
        let line = request(2, "tools/list", "{}");
        let response = server.handle_line(&line).await.unwrap();
        let tools = response["result"]["tools"].as_array().unwrap();
        let schema = tools
            .iter()
            .find(|t| t["name"] == "gmail.users.messages.list")
            .map(|t| t["inputSchema"].clone())
            .unwrap();

        for prop in ["params", "body_file", "query", "dry_run"] {
            assert!(schema["properties"][prop].is_object(), "missing {prop}");
        }
        let required: Vec<&str> = schema["required"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v.as_str())
            .collect();
        assert!(required.contains(&"userId"), "{required:?}");

        // Typed parameters keep their Discovery types; labelIds is repeated.
        assert_eq!(schema["properties"]["maxResults"]["type"], "integer");
        assert_eq!(schema["properties"]["labelIds"]["type"], "array");
        assert_eq!(schema["properties"]["labelIds"]["items"]["type"], "string");
    }

    #[tokio::test]
    async fn enum_values_surface_in_the_schema() {
        let server = test_server().await;
        let line = request(2, "tools/list", "{}");
        let response = server.handle_line(&line).await.unwrap();
        let tools = response["result"]["tools"].as_array().unwrap();
        let schema = tools
            .iter()
            .find(|t| t["name"] == "calendar.calendarList.list")
            .map(|t| t["inputSchema"].clone())
            .unwrap();
        let values = schema["properties"]["minAccessRole"]["enum"]
            .as_array()
            .unwrap();
        assert!(
            values.iter().any(|v| v.as_str() == Some("owner")),
            "{values:?}"
        );
    }

    #[tokio::test]
    async fn tools_call_dry_run_matches_the_api_call_payload() {
        let server = test_server().await;
        let line = request(
            3,
            "tools/call",
            r#"{"name":"gmail.users.messages.list","arguments":{"userId":"me","dry_run":true}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["result"]["isError"], Value::Null);
        let text = response["result"]["content"][0]["text"].as_str().unwrap();
        let payload: Value = serde_json::from_str(text).unwrap();

        // The same dry-run payload `grr api call --dry-run` prints, via
        // the shared plan path.
        let (service, method) = discovery::resolve("gmail.users.messages.list").unwrap();
        let mut params = Map::new();
        params.insert("userId".into(), json!("me"));
        let plan = api::plan_request(service, method, &params, None, None, &[]).unwrap();
        assert_eq!(payload, api::dry_run_payload(method, &plan));
    }

    #[tokio::test]
    async fn tools_call_accepts_the_camel_case_dry_run_spelling() {
        let server = test_server().await;
        let line = request(
            4,
            "tools/call",
            r#"{"name":"gmail.users.messages.list","arguments":{"userId":"me","dryRun":true}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        let text = response["result"]["content"][0]["text"].as_str().unwrap();
        let payload: Value = serde_json::from_str(text).unwrap();
        assert_eq!(payload["dryRun"], true);
    }

    #[tokio::test]
    async fn tool_arguments_win_over_the_params_escape_hatch() {
        let server = test_server().await;
        let line = request(
            5,
            "tools/call",
            r#"{"name":"gmail.users.messages.list","arguments":
                {"params":{"userId":"someone-else","q":"is:unread"},"userId":"me","dry_run":true}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        let text = response["result"]["content"][0]["text"].as_str().unwrap();
        let payload: Value = serde_json::from_str(text).unwrap();
        // The typed argument wins; the escape hatch's other key rides along.
        let url = payload["url"].as_str().unwrap();
        assert!(url.contains("/users/me/messages"), "{url}");
        assert!(url.contains("q=is%3Aunread"), "{url}");
        assert!(!url.contains("someone-else"), "{url}");
    }

    #[tokio::test]
    async fn an_unknown_tool_is_an_error_result_not_a_crash() {
        let server = test_server().await;
        let line = request(
            6,
            "tools/call",
            r#"{"name":"gmail.users.messages.lst","arguments":{}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["result"]["isError"], true);
        let text = response["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("unknown tool"), "{text}");
    }

    #[tokio::test]
    async fn readonly_refuses_writes_with_an_mcp_error_result() {
        let server = test_server_with_profile(SafetyProfile::new(true, [], [])).await;

        let line = request(
            7,
            "tools/call",
            r#"{"name":"gmail.users.messages.send","arguments":{"userId":"me","dry_run":true}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["result"]["isError"], true);
        let text = response["result"]["content"][0]["text"].as_str().unwrap();
        // Actionable: names the method, the verb and how to lift it.
        assert!(text.contains("gmail.users.messages.send"), "{text}");
        assert!(text.contains("POST"), "{text}");
        assert!(text.contains("Rerun without --readonly"), "{text}");

        // A GET still runs under the same profile.
        let line = request(
            8,
            "tools/call",
            r#"{"name":"gmail.users.messages.list","arguments":{"userId":"me","dry_run":true}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["result"]["isError"], Value::Null);
    }

    #[tokio::test]
    async fn a_missing_tool_name_is_an_error_result() {
        let server = test_server().await;
        let line = request(9, "tools/call", r#"{"arguments":{}}"#);
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["result"]["isError"], true);
    }

    #[tokio::test]
    async fn a_stdin_body_file_is_refused_over_mcp() {
        let server = test_server().await;
        let line = request(
            10,
            "tools/call",
            r#"{"name":"gmail.users.messages.list","arguments":{"body_file":"-"}}"#,
        );
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["result"]["isError"], true);
        let text = response["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("stdin"), "{text}");
    }

    #[tokio::test]
    async fn an_unknown_method_is_a_jsonrpc_error() {
        let server = test_server().await;
        let line = request(11, "resources/list", "{}");
        let response = server.handle_line(&line).await.unwrap();
        assert_eq!(response["error"]["code"], -32601);
        assert!(
            response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("resources/list")
        );
        assert_eq!(response["id"], 11);
    }

    #[tokio::test]
    async fn a_parse_error_answers_with_a_null_id() {
        let server = test_server().await;
        let response = server.handle_line("not json at all").await.unwrap();
        assert_eq!(response["error"]["code"], -32700);
        assert!(response["id"].is_null());
    }

    #[tokio::test]
    async fn notifications_are_never_answered() {
        let server = test_server().await;
        assert!(
            server
                .handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
                .await
                .is_none()
        );
        assert!(
            server
                .handle_line(r#"{"jsonrpc":"2.0","method":"notifications/cancelled"}"#)
                .await
                .is_none()
        );
    }
}