mcp-methods 0.4.5

Reusable utility methods for MCP servers — pure-Rust library
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
//! MCP client-`roots` adoption (opt-in, fallback-only).
//!
//! Some hosts advertise the directory the user is working in via the MCP
//! `roots` capability — opencode does it on every connection. This module
//! consumes that advertisement so a server configured with
//! `workspace.adopt_client_roots: true` and **no** `workspace.root` can
//! bind the client's directory instead of making the operator hand-write a
//! path the client already offered.
//!
//! Three properties this module exists to preserve, in order:
//!
//! 1. **Fallback only.** Anything the operator configured — manifest
//!    `workspace.root`, `--watch`, `--source-root`, `--workspace`, or a
//!    runtime `set_root_dir` — makes the workspace
//!    [`RootOwnership::Operator`](crate::server::workspace::RootOwnership::Operator),
//!    and adoption refuses to touch it. Forever, including across later
//!    `roots/list_changed` notifications.
//! 2. **Contained.** Adoption calls
//!    [`Workspace::adopt_client_root`](crate::server::workspace::Workspace::adopt_client_root),
//!    which is the same validate-canonicalize-contain-activate path
//!    `set_root_dir` uses. A `workspace.sandbox_root` boundary therefore
//!    applies identically to a path proposed by an external party. The spec
//!    is explicit that roots are "informational guidance rather than an
//!    access-control mechanism" — the boundary is what contains them.
//! 3. **Invisible to everyone else.** The guard chain is ordered
//!    cheapest-first and exits before any I/O for a server that did not opt
//!    in or a client that does not advertise `roots`, so no `roots/list`
//!    request is ever put on the wire for such a client and no connect
//!    latency is added. The handler also runs on a task rmcp spawns, so
//!    even the opted-in path never delays the client's session.
//!
//! # Deprecated upstream
//!
//! MCP `roots` is **deprecated** as of protocol revision `2026-07-28`
//! ([SEP-2577]): *"New implementations SHOULD NOT adopt it; existing
//! implementations SHOULD migrate to passing directories or files via tool
//! parameters, resource URIs, or server configuration."* It is eligible for
//! removal in the first revision released on or after **2027-07-28**, and
//! that revision drops the server→client `roots/list` request and
//! `notifications/roots/list_changed` entirely.
//!
//! This module is built anyway, deliberately: it is opt-in, so it costs
//! deployments that do not enable it nothing, and rmcp negotiates
//! `2025-11-25`, where the mechanism is live and fully implemented. The
//! migration path when it goes away is the one the spec names — pass the
//! directory via a tool parameter, a resource URI, or server configuration
//! (`workspace.root`).
//!
//! [SEP-2577]: https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577

// `Root`, `ListRootsResult` and `Peer::list_roots` all carry
// `#[deprecated]` (SEP-2577). Referencing them is the entire point of this
// module, and `make lint` runs clippy with `-D warnings`. Scoped to this
// file, mirroring rmcp's own `handler/server.rs`.
#![expect(deprecated)]

use std::path::PathBuf;
use std::time::Duration;

use rmcp::service::Peer;
use rmcp::{model::ProtocolVersion, RoleServer};

use crate::server::server::ServerOptions;
use crate::server::workspace::{RootOwnership, Workspace};

/// Deadline for the `roots/list` round-trip.
///
/// `Peer::list_roots` is generated by rmcp's plain `peer_req` arm, **not**
/// `peer_req_with_timeout`, so it has no deadline of its own: a client that
/// accepts the request and never answers would pin this task for the life
/// of the session. Five seconds is far beyond a local host's honest
/// response time and far below anything a user would notice, since nothing
/// waits on this task.
const LIST_ROOTS_TIMEOUT: Duration = Duration::from_secs(5);

/// `notifications/initialized` arrived — adopt a client root if this
/// server is configured to and nothing is bound yet.
pub(crate) async fn on_client_initialized(options: &ServerOptions, peer: &Peer<RoleServer>) {
    let Some(ws) = adoption_candidate(options) else {
        return;
    };
    // Only a wholly unbound workspace adopts at initialize time. Anything
    // else means the operator configured a root.
    if ws.root_ownership() != RootOwnership::Unowned {
        return;
    }
    if !negotiated_protocol_supports_roots(peer) {
        return;
    }
    if !advertises_roots(peer) {
        return;
    }
    adopt_first_valid_root(ws, peer, "initialized").await;
}

/// `notifications/roots/list_changed` arrived — re-run adoption, unless
/// the operator has since claimed the root.
pub(crate) async fn on_client_roots_changed(options: &ServerOptions, peer: &Peer<RoleServer>) {
    let Some(ws) = adoption_candidate(options) else {
        return;
    };
    // `Operator` never yields; `Unowned` (adoption failed or was never
    // attempted) and `Adopted` both re-adopt.
    if ws.root_ownership() == RootOwnership::Operator {
        return;
    }
    if !negotiated_protocol_supports_roots(peer) {
        return;
    }
    // A client that advertised `roots: {}` without `listChanged` should
    // never have sent this. Ignore it rather than trust it.
    if !advertises_roots_list_changed(peer) {
        tracing::warn!(
            "ignoring roots/list_changed from a client that did not advertise \
             roots.listChanged"
        );
        return;
    }
    adopt_first_valid_root(ws, peer, "roots/list_changed").await;
}

/// The two cheapest guards: is there a workspace, and did the operator opt
/// in? Both are pure field reads — a server that never sets
/// `workspace.adopt_client_roots` exits here, before touching the peer.
fn adoption_candidate(options: &ServerOptions) -> Option<&Workspace> {
    let ws = options.workspace.as_ref()?;
    ws.adopts_client_roots().then_some(ws)
}

/// `roots` was removed from the 2026-07-28 protocol revision. A client that
/// accidentally carries its old capability forward must not make this server
/// emit a method the negotiated revision no longer defines.
fn negotiated_protocol_supports_roots(peer: &Peer<RoleServer>) -> bool {
    peer.peer_info()
        .is_some_and(|info| info.protocol_version != ProtocolVersion::V_2026_07_28)
}

/// Does the client advertise the `roots` capability at all? When it does
/// not, no `roots/list` request is ever sent — that is requirement 3
/// ("clients that do not advertise roots are wholly unaffected") enforced
/// at its only possible site.
fn advertises_roots(peer: &Peer<RoleServer>) -> bool {
    // `peer_info()` is populated before `serve()` returns, strictly before
    // any notification handler can run, so this is never spuriously `None`.
    peer.peer_info()
        .is_some_and(|info| info.capabilities.roots.is_some())
}

fn advertises_roots_list_changed(peer: &Peer<RoleServer>) -> bool {
    peer.peer_info().is_some_and(|info| {
        info.capabilities
            .roots
            .as_ref()
            .is_some_and(|roots| roots.list_changed == Some(true))
    })
}

/// Issue `roots/list`, then bind the first root that survives conversion
/// and containment.
///
/// Every failure here is contained: a warning is logged and the workspace
/// keeps whatever it had (typically nothing, i.e. it stays unanchored, and
/// the source tools behave exactly as they do with no root configured).
/// Nothing retries — a retry loop against a misbehaving client is worse
/// than an unanchored server.
async fn adopt_first_valid_root(ws: &Workspace, peer: &Peer<RoleServer>, trigger: &str) {
    let roots = match tokio::time::timeout(LIST_ROOTS_TIMEOUT, peer.list_roots()).await {
        Ok(Ok(result)) => result.roots,
        Ok(Err(err)) => {
            tracing::warn!(
                "roots/list ({trigger}) failed: {err}; \
                 continuing without a client-advertised root"
            );
            return;
        }
        Err(_) => {
            tracing::warn!(
                "roots/list ({trigger}) timed out after {}s; \
                 continuing without a client-advertised root",
                LIST_ROOTS_TIMEOUT.as_secs()
            );
            return;
        }
    };
    if roots.is_empty() {
        tracing::warn!("client advertised roots but returned none ({trigger})");
        return;
    }
    // "First valid" is client-order-dependent: no revision of the MCP
    // schema says anything about the order of `ListRootsResult.roots`, so
    // a client with several roots picks which one we bind. Operators who
    // need determinism set `workspace.root`.
    for root in &roots {
        // `Root.name` is display-only and must never influence path
        // resolution.
        let path = match file_uri_to_path(&root.uri) {
            Ok(path) => path,
            Err(reason) => {
                tracing::warn!("skipping client root {:?}: {reason}", root.uri);
                continue;
            }
        };
        // Canonicalize before the containment test — it is what makes
        // `..` and symlinks (and, on macOS, `/var` → `/private/var`)
        // resolve to the path that will actually be read.
        let canon = match path.canonicalize() {
            Ok(canon) => canon,
            Err(err) => {
                tracing::warn!(
                    "skipping client root {:?}: cannot resolve {}: {err}",
                    root.uri,
                    path.display()
                );
                continue;
            }
        };
        if !canon.is_dir() {
            tracing::warn!(
                "skipping client root {:?}: {} is not a directory",
                root.uri,
                canon.display()
            );
            continue;
        }
        match ws.adopt_client_root(&canon) {
            Ok(msg) => {
                tracing::info!(
                    "adopted client root {} ({trigger}): {}",
                    canon.display(),
                    msg.lines().next().unwrap_or_default()
                );
                return;
            }
            Err(reason) => {
                tracing::warn!("rejected client root {}: {reason}", canon.display());
                continue;
            }
        }
    }
    tracing::warn!(
        "no client-advertised root could be adopted ({trigger}); \
         the workspace is unchanged"
    );
}

/// Convert a `file://` URI to a filesystem path.
///
/// `Root.uri` **MUST** be a `file://` URI per the spec, and the spec says
/// nothing about what a server does with one it cannot interpret — so this
/// returns a reason string and the caller skips that root with a warning
/// rather than failing the connection or answering the client with a
/// protocol error.
///
/// Accepted: `file:///abs/path` (empty authority), `file://localhost/abs/path`
/// (RFC 8089's named-local form), and the authority-less `file:/abs/path`.
/// Rejected: any other scheme, a non-local host (`file://other/path` names a
/// file on *another* machine), a relative path, and malformed percent
/// escapes. Query and fragment are stripped before decoding; percent
/// decoding happens **after** the URI is split, so an encoded `/`, `?` or
/// `#` cannot change how the URI parses.
///
/// Hand-rolled rather than pulling in `url`: the rules above are the whole
/// of RFC 8089 that a `file://` root can exercise, and the crate is a
/// published library whose dependency surface is worth keeping small.
pub fn file_uri_to_path(uri: &str) -> Result<PathBuf, String> {
    let Some(rest) = strip_scheme(uri, "file") else {
        return Err(format!(
            "only file:// roots are supported (got {:?})",
            uri.split(':').next().unwrap_or(uri)
        ));
    };
    // Strip fragment then query — both are meaningless for a directory
    // root, and leaving them in would make them part of the path.
    let rest = rest.split('#').next().unwrap_or(rest);
    let rest = rest.split('?').next().unwrap_or(rest);

    let raw_path = match rest.strip_prefix("//") {
        Some(after_slashes) => {
            // `//authority/path` — the authority ends at the first `/`.
            let (authority, path) = match after_slashes.find('/') {
                Some(idx) => after_slashes.split_at(idx),
                None => (after_slashes, ""),
            };
            if !(authority.is_empty() || authority.eq_ignore_ascii_case("localhost")) {
                return Err(format!(
                    "host {authority:?} is not this machine; \
                     only file:// URIs with an empty host or `localhost` name a local path"
                ));
            }
            path
        }
        // `file:/abs/path` — no authority component at all.
        None => rest,
    };
    if raw_path.is_empty() {
        return Err("no path component".to_string());
    }
    let decoded = percent_decode(raw_path)?;
    #[cfg(windows)]
    // `file:///C:/x` decodes to `/C:/x`; the drive letter form needs the
    // leading separator removed to be a real Windows path.
    let decoded = {
        let bytes = decoded.as_bytes();
        if bytes.len() >= 3
            && bytes[0] == b'/'
            && bytes[1].is_ascii_alphabetic()
            && bytes[2] == b':'
        {
            decoded[1..].to_string()
        } else {
            decoded
        }
    };
    let path = PathBuf::from(decoded);
    if !path.is_absolute() {
        return Err(format!("path {} is not absolute", path.display()));
    }
    Ok(path)
}

/// Case-insensitive scheme strip. Schemes are ASCII and case-insensitive
/// per RFC 3986, so `FILE://` is the same root as `file://`.
fn strip_scheme<'a>(uri: &'a str, scheme: &str) -> Option<&'a str> {
    let (head, tail) = uri.split_once(':')?;
    head.eq_ignore_ascii_case(scheme).then_some(tail)
}

/// Decode `%XX` escapes. Rejects malformed escapes and any byte sequence
/// that is not UTF-8 — `file://` URIs percent-encode UTF-8, and a path we
/// cannot render as a string is a path we should not silently guess at.
fn percent_decode(s: &str) -> Result<String, String> {
    if !s.contains('%') {
        return Ok(s.to_string());
    }
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            let hex = bytes
                .get(i + 1..i + 3)
                .ok_or_else(|| format!("truncated percent-escape in {s:?}"))?;
            let text =
                std::str::from_utf8(hex).map_err(|_| format!("invalid percent-escape in {s:?}"))?;
            let byte = u8::from_str_radix(text, 16)
                .map_err(|_| format!("invalid percent-escape `%{text}` in {s:?}"))?;
            out.push(byte);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| format!("percent-decoded {s:?} is not valid UTF-8"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plain_absolute_file_uri() {
        assert_eq!(
            file_uri_to_path("file:///Users/dev/project").unwrap(),
            PathBuf::from("/Users/dev/project")
        );
    }

    #[test]
    fn localhost_host_is_local() {
        assert_eq!(
            file_uri_to_path("file://localhost/srv/code").unwrap(),
            PathBuf::from("/srv/code")
        );
        assert_eq!(
            file_uri_to_path("FILE://LOCALHOST/srv/code").unwrap(),
            PathBuf::from("/srv/code")
        );
    }

    #[test]
    fn authority_less_form_is_accepted() {
        assert_eq!(
            file_uri_to_path("file:/srv/code").unwrap(),
            PathBuf::from("/srv/code")
        );
    }

    #[test]
    fn foreign_host_rejected() {
        let err = file_uri_to_path("file://otherbox/srv/code").unwrap_err();
        assert!(err.contains("otherbox"), "unexpected error: {err}");
    }

    #[test]
    fn non_file_scheme_rejected() {
        for uri in [
            "https://example.com/repo",
            "git+ssh://host/repo",
            "/tmp/x",
            // These two are shaped exactly like an acceptable `file://`
            // URI — empty authority, absolute path — so only the scheme
            // check can reject them.
            "http:///srv/code",
            "data:/srv/code",
        ] {
            assert!(
                file_uri_to_path(uri).is_err(),
                "{uri} should not convert to a path"
            );
        }
    }

    #[test]
    fn an_encoded_separator_cannot_forge_a_local_authority() {
        // `localhost%2Fevil` is one authority component naming a host we
        // do not have, not `localhost` followed by a path. Decoding before
        // the authority split would turn it into the latter.
        let err = file_uri_to_path("file://localhost%2Fevil/path").unwrap_err();
        assert!(err.contains("localhost%2Fevil"), "unexpected error: {err}");
    }

    #[test]
    fn percent_escapes_decode_after_splitting() {
        assert_eq!(
            file_uri_to_path("file:///Users/dev/my%20project").unwrap(),
            PathBuf::from("/Users/dev/my project")
        );
        // An encoded separator stays data: it is decoded only after the
        // authority/path split, so it can never introduce a new component
        // boundary during parsing.
        assert_eq!(
            file_uri_to_path("file://localhost/a%2Fb").unwrap(),
            PathBuf::from("/a/b")
        );
        // Encoded `?` and `#` are path characters, not delimiters: they are
        // decoded only after the query and fragment have been split off, so
        // they cannot truncate the path.
        assert_eq!(
            file_uri_to_path("file:///a%3Fb/src").unwrap(),
            PathBuf::from("/a?b/src")
        );
        assert_eq!(
            file_uri_to_path("file:///a%23b/src").unwrap(),
            PathBuf::from("/a#b/src")
        );
        assert_eq!(
            file_uri_to_path("file:///caf%C3%A9/src").unwrap(),
            PathBuf::from("/café/src")
        );
    }

    #[test]
    fn malformed_percent_escape_rejected() {
        assert!(file_uri_to_path("file:///a%2").is_err());
        assert!(file_uri_to_path("file:///a%zz/b").is_err());
    }

    #[test]
    fn query_and_fragment_stripped() {
        assert_eq!(
            file_uri_to_path("file:///srv/code?ref=main#L10").unwrap(),
            PathBuf::from("/srv/code")
        );
    }

    #[test]
    fn empty_and_relative_paths_rejected() {
        assert!(file_uri_to_path("file://").is_err());
        assert!(file_uri_to_path("file://localhost").is_err());
        assert!(file_uri_to_path("file:relative/path").is_err());
    }
}