Skip to main content

grr_cli/
mcp.rs

1//! Model Context Protocol (MCP) server for grr.
2//!
3//! Hand-rolled JSON-RPC 2.0 over stdio — no SDK crate: a tool-only server
4//! needs four RPCs. Newline-delimited requests in, one response line
5//! per request out, logs to stderr ONLY (stdout is the MCP stream, the
6//! same discipline as the rest of grr).
7//!
8//! * `server/discover` — the stateless revision's discovery RPC: revisions
9//!   served, capabilities, identity, and it needs no prior call
10//! * `tools/list` — every method in the Discovery index as a tool
11//! * `tools/call` — one method invocation through the shared call path
12//!
13//! `2026-07-28` is the newest revision served, so the handshake is gone from
14//! the happy path — but `initialize` is answered with a minimal legacy
15//! handshake (server/discover remains the discovery RPC), because the
16//! deployed client ecosystem still opens with it. `ping` and
17//! `logging/setLevel` answer with a JSON-RPC error naming the revision to
18//! speak instead. Notifications (`notifications/initialized`, whatever the
19//! revision) carry no id, so they are never answered at all.
20//!
21//! Tool names are the dotted method ids `grr api call` takes
22//! (`gmail.users.messages.list`), so an agent reaches every method Google
23//! publishes through the same resolution the CLI uses. Errors never kill
24//! the server: a tool failure is an `isError` result (MCP's tool-error
25//! contract), a protocol failure a JSON-RPC error object.
26//!
27//! ```text
28//! {"jsonrpc":"2.0","id":1,"method":"server/discover"}
29//! {"jsonrpc":"2.0","id":2,"method":"tools/list"}
30//! {"jsonrpc":"2.0","id":3,"method":"tools/call",
31//!  "params":{"name":"gmail.users.messages.list","arguments":{"userId":"me","dry_run":true}}}
32//! ```
33
34use 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
40/// The one protocol revision this server speaks: `2026-07-28`, the current
41/// MCP revision, and a *stateless* redesign — it removed the `initialize`/
42/// `notifications/initialized` handshake, made `server/discover` mandatory,
43/// and moved the protocol version and client capabilities into per-request
44/// `_meta`.
45///
46/// Legacy revisions are deliberately not served. Their handshake shape
47/// (`ping`, `logging/setLevel`) is gone from the spec; `initialize` alone
48/// is answered with a minimal legacy handshake so standard clients
49/// (mcp-proxy, Claude Desktop, Cursor, Glama's introspector) can connect —
50/// they then use `tools/*`, or read this constant out of `server/discover`
51/// and speak the current revision.
52pub(crate) const PROTOCOL_VERSION: &str = "2026-07-28";
53
54/// Every revision this server can serve, newest first — exactly what
55/// `server/discover` reports as `supportedVersions`. One entry, on purpose:
56/// this server speaks the current revision and nothing older.
57const SUPPORTED_VERSIONS: [&str; 1] = ["2026-07-28"];
58
59/// JSON-RPC 2.0 error codes.
60const PARSE_ERROR: i64 = -32700;
61const INVALID_REQUEST: i64 = -32600;
62const METHOD_NOT_FOUND: i64 = -32601;
63
64/// One server instance: one credential, one safety profile, every tool.
65/// The stdio loop is single-tasked, so no `Arc` is needed.
66pub 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    /// How many tools the Discovery index exposes, for the startup banner.
77    pub fn tool_count(&self) -> usize {
78        discovery::services()
79            .values()
80            .map(|s| s.methods.len())
81            .sum()
82    }
83
84    /// Handle one line of JSON-RPC. `Some(response)` for requests (and for
85    /// parse errors, which answer with a null id); `None` for
86    /// notifications, which get no response. Never panics and never kills
87    /// the server: every failure is an error-shaped response.
88    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        // A message without an id is a notification (`notifications/
101        // initialized` included): it gets no response by definition.
102        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(&params).await;
120                // The stateless revision has no handshake to carry identity,
121                // so every result names the server that produced it.
122                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` compat: the stateless revision removed the
128            // handshake, but the deployed client ecosystem (mcp-proxy,
129            // Claude Desktop, Cursor, Glama's introspector) still opens
130            // with it — and several of its members REJECT an answer that
131            // names a newer revision than they asked for. Negotiate:
132            // echo the client's requested revision back when it looks
133            // like an MCP revision (dated string), otherwise answer with
134            // the newest one we speak. Either way the client then uses
135            // `tools/*`, which is revision-agnostic here.
136            // `ping` stays refused: nothing in the legacy flow needs it
137            // to connect.
138            "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    /// `tools/call`: resolve the tool name, assemble the parameters,
176    /// invoke the shared call path. EVERY error — unknown tool, refused by
177    /// the safety profile, HTTP failure — is an `isError` result, never a
178    /// process exit: the server must survive one bad call.
179    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        // The same gate the CLI dispatch honors (src/commands/safety.rs).
201        self.profile.check(&service.name, method)?;
202
203        // Assemble the parameter map: the `params` escape-hatch object goes
204        // in first, then the tool-call arguments — the arguments are the
205        // typed params and win on conflict ("typed params win", the merge
206        // order of `api::parse_params`).
207        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                // Both spellings: the input schema declares `dry_run`, but
219                // agents routinely write `dryRun`. No Discovery parameter
220                // uses either name, so consuming them is safe.
221                "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        // stdin IS the MCP stream: a `-` body_file would swallow JSON-RPC
235        // lines. Say so rather than corrupting the session.
236        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                // The verb override is `grr api call`'s escape hatch; MCP
250                // speaks the Discovery document.
251                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
264/// The server's identity, for `_meta`. With no handshake to carry it once,
265/// `io.modelcontextprotocol/serverInfo` on EVERY result is the only place a
266/// client can read it.
267fn 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
275/// `server/discover` — the mandatory RPC of the stateless revision. No body
276/// parameters, no prior call, no state: it reports the revisions served, the
277/// capabilities, and the identity, so a client can pick a revision (or just
278/// call `tools/*` inline) before doing anything else.
279fn 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
291/// Every method in the Discovery index as an MCP tool. The index grows as
292/// Google publishes APIs — the list is derived, never a hardcoded count.
293fn 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    // outputSchema: the pruned response shape for this method's $ref, when
302    // the upstream document named one (~87% of methods). GET/list tools
303    // declare their payload shape; a write tool's outputSchema describes
304    // the post-write resource state.
305    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
324/// Curated descriptions for the few Discovery methods that ship none —
325/// high-impact tools an agent must not have to guess at. Keyed by the
326/// method's index id (resource path + verb, WITHOUT the service prefix —
327/// the service name joins at tool-name assembly, not in `Method.id`);
328/// anything not listed falls through to the verb-derived text.
329const 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
339/// The resources this method's id sits among, as sibling guidance: the
340/// other verbs over the same resource path, so an agent sees the CRUD
341/// neighbourhood without leaving the tool list.
342fn sibling_summary(service: &Service, method: &Method) -> String {
343    // The method id is `resource.path.segments.verb`; siblings share every
344    // segment but the last.
345    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
370/// What the call returns, derived from the verb — the shape the shared
371/// call path actually delivers (JSON on stdout, envelope on MCP).
372fn 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
380/// The method's Discovery description, enriched with what an agent needs
381/// to pick and use the tool correctly: the resource it acts on, what comes
382/// back, how the request body is built, the auth/safety story, and the
383/// sibling methods over the same resource. Everything here is derived from
384/// the Discovery index — no hand-written per-method prose to rot.
385fn 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    // Discovery descriptions commonly end in a period; normalize so we never
405    // ship "text.. [HTTP".
406    let base = base.trim_end_matches('.');
407    let mut text = format!("{base} [HTTP {verb}]");
408
409    // Behavior: what the call does to the world, before the auth line.
410    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    // Completeness: the two things the schema cannot say.
423    // Discovery text can carry its own trailing period mid-sentence; don't
424    // let our appended clause double it. Trailing-period truncation (300
425    // chars) at distill time also leaves a bare period to normalize.
426    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
438/// The tool's input schema: a JSON-schema object built from the method's
439/// parameters plus grr's escape hatches; `required` is the method's
440/// required parameter names.
441fn 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
480/// One parameter as a JSON-schema property. Discovery's scalar kinds map
481/// to JSON-schema types; anything else (`any`, nested objects) omits the
482/// type rather than lie. A repeated parameter becomes an array of its base
483/// type, which is what `build_query` expands at call time.
484fn 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) = &param.format {
502        // Google's format names (int32, uint32, google-fieldmask,
503        // google-datetime) pass through verbatim — close enough for a
504        // consumer and honest about their origin.
505        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) = &param.pattern {
514        out.insert("pattern".into(), json!(pattern));
515    }
516    if let Some(default) = &param.default_value {
517        out.insert("default".into(), json!(default));
518    }
519    let mut description = String::new();
520    if let Some(location) = &param.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(&param.description);
530    }
531    if let (Some(values), Some(texts)) = (&param.enum_values, &param.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) = &param.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
575/// The stdio loop: newline-delimited JSON-RPC in, one response line per
576/// request out. Generic over the reader/writer so tests can run the whole
577/// handshake in-process. EOF on stdin (the client closed the session) is
578/// a clean shutdown.
579pub 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        // `GoogleAuth::with_token` is the documented test hook: it skips
612        // OAuth and persistent storage entirely. Dry-run and gate tests
613        // never touch the network.
614        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        // One response line per REQUEST; the notification got none.
647        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    /// The handshake revisions are not served at all — except `initialize`,
673    /// which gets a minimal legacy handshake so standard clients connect.
674    /// `ping` and `logging/setLevel` get an error naming the revision to
675    /// speak and the RPC that replaced the handshake.
676    #[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    /// `initialize` compat: a standard client opens with the legacy
689    /// handshake and must get a valid result — server identity, tool
690    /// capability, and the revision it asked for echoed back (several
691    /// clients reject a newer one) — instead of an error.
692    #[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        // The handshake completes; tools/* then works as usual.
707        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    /// The stateless revision has no handshake, so `server/discover` may be
716    /// a client's first call — and `tools/list` works with no prior call at
717    /// all. The server holds no handshake state to satisfy.
718    #[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        // A 2026-07-28 client may also skip discovery entirely.
743        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    /// No handshake means no `serverInfo` to carry identity, so every result
749    /// names the server — the spec asks for `_meta` on each one.
750    #[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        // The index grows as Google publishes APIs — never a hardcoded count.
772        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            // Tool names are the dotted method ids `grr api call` takes.
781            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    /// Tools whose upstream method documents a response schema declare an
793    /// `outputSchema`; its shape mirrors the pruned Discovery schema (field
794    /// names, types, array items). Tools without one omit the key rather
795    /// than fake a shape.
796    #[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        // gmail.users.threads.list responds with ListThreadsResponse.
811        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        // Methods whose upstream document names no response omit the key.
828        let empty = find("gmail.users.stop");
829        assert!(
830            empty.get("outputSchema").is_none(),
831            "no fabricated output schema"
832        );
833
834        // Schemas are pruned: no description keys anywhere in the output.
835        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    /// Parameter schemas surface what Discovery documents beyond the type:
843    /// location (path segment vs query), enum-value prose, format, default,
844    /// and bounds.
845    #[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        // calendar.events.list maxResults: format int32, default 250, min 1.
868        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    /// Descriptions carry what an agent needs to pick a tool: what the call
877    /// returns, how the request body is built, and — where the resource has
878    /// siblings — the CRUD neighbourhood. Also covers the curated overrides:
879    /// Discovery methods that ship no description still get real prose.
880    #[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        // Our appended clauses never start with a period directly after the
924        // upstream text's own: the verb tag always follows cleanly.
925        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        // Typed parameters keep their Discovery types; labelIds is repeated.
959        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        // The same dry-run payload `grr api call --dry-run` prints, via
998        // the shared plan path.
999        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, &params, 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        // The typed argument wins; the escape hatch's other key rides along.
1033        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        // Actionable: names the method, the verb and how to lift it.
1066        assert!(text.contains("gmail.users.messages.send"), "{text}");
1067        assert!(text.contains("POST"), "{text}");
1068        assert!(text.contains("Rerun without --readonly"), "{text}");
1069
1070        // A GET still runs under the same profile.
1071        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}