How to Implement MCP Roots in ASP.NET Core 10 Using C# – Workspace Discovery, File Access Validation and Security (2026)

How to Implement MCP Roots in ASP.NET Core 10 Using C# – Workspace Discovery, File Access Validation and Security (2026)

A documentation assistant opens a project and asks an MCP server for guide/setup.md. The client can tell the server which workspace the developer is using. The server still needs to decide whether that caller can read that particular document. MCP Roots provides the workspace hint. The server’s authorization policy and operating-system permissions control file access.

This tutorial builds a read-only ASP.NET Core 10 documentation assistant and a compatible C# client. The working example pins protocol 2025-11-25 and official MCP C# SDK 2.3.1. Roots is deprecated in the 2026-07-28 revision. Use the lab to support existing clients or understand a legacy integration. For a new remote service, prefer explicit workspace identifiers mapped to an authorized server catalog. See MCP Roots in the July 2026 specification and Microsoft’s C# SDK v2 announcement.

What are MCP Roots?

MCP Roots are workspace entry points that a supporting client advertises to a server. In the November 2025 protocol, the client advertises the roots capability, the server requests the current list with roots/list, and the client returns file: URIs and optional display names. A list can include multiple workspaces or be empty. A display name is descriptive data. It does not establish ownership, permission, or a trusted mount.

The client advertises roots. The ASP.NET Core tool compares those hints with an independently authorized documentation snapshot.
The client advertises roots. The ASP.NET Core tool compares those hints with an independently authorized documentation snapshot.

The useful question Roots answers is “Which workspace is relevant to this operation?” The server still has to answer “What may this caller read?” If a client names a folder on another computer, that URI does not transfer files or create a mount. Both sides of this lab share a filesystem. A remote server needs its own authorized copy of the documentation or a separately designed storage integration.

Roots, Resources, and filesystem permissions

Mechanism Direction Purpose
Roots Client to server Identify workspace entry points in a compatible session
MCP Resources Server to client Expose application data the client can discover and read
Application authorization Server-side Decide what the authenticated caller may read
OS filesystem permissions Operating system Limit what the server process can open
Roots are advertised by the client. Resources are exposed by the server and can be discovered and read by clients.
Roots are advertised by the client. Resources are exposed by the server and can be discovered and read by clients.

Resources can be a good interface for publishing documentation. A server still needs to authorize each resource read and avoid leaking sensitive metadata in list responses. A root’s optional name and metadata are untrusted, even if they appear to describe a familiar folder. See the legacy Roots specification and MCP Resources.

How do roots/list and change notifications work?

The legacy client declares roots at initialization. If it supports reporting changes, it declares listChanged: true. The tool receives an SDK request context, checks protocol and capability, and calls RequestRootsAsync. On legacy Streamable HTTP, the context routes the server-to-client request over the originating POST response stream. The console client implements RootsHandler and replies with a ListRootsResult.

A 2025-11-25 session negotiates Roots. A tool call triggers roots/list over the session, and the client returns its current list.
A 2025-11-25 session negotiates Roots. A tool call triggers roots/list over the session, and the client returns its current list.

A typical result contains the following shape. These are illustrative Linux URI values. The SDK generates the real response from the client’s directories.

Illustrative roots/list result
{
  "roots": [
    { "uri": "file:///srv/workspace/docs", "name": "Documentation" },
    { "uri": "file:///srv/workspace/other", "name": "Other project" }
  ]
}

On Windows, a drive-rooted URI might be file:///C:/Work/docs. Treat the URI as a URL until it has been parsed. Cutting off the prefix or concatenating the decoded string with user input creates portability and security problems. The example accepts a restricted subset of local file URIs and compares their normalized paths with one independently configured directory.

A client can advertise many folders. Only the documentation root matches the server configuration. The other root grants no access.
A client can advertise many folders. Only the documentation root matches the server configuration. The other root grants no access.

What changes in the 2026 protocol?

The July protocol deprecates Roots. Its compatibility description puts the deprecated roots request inside a Multi Round-Trip Request (MRTR) and uses per-request capability metadata. The old server callback and change notification belong to the initialized legacy session. This lab does not implement the July MRTR compatibility path. The supported compatibility path in this lab is an initialized November 2025 session on stateful Streamable HTTP. Legacy stdio is another option when both components run locally. A current stateless session cannot depend on the legacy server-to-client roots/list callback. The code deliberately returns a compatibility error for newer or non-supporting clients. The official filesystem reference server chooses server-configured directories for July 2026 clients. See McpServer.RequestRootsAsync and the reference filesystem server.

The lab uses the legacy Roots path only when both the protocol revision and capability match.
The lab uses the legacy Roots path only when both the protocol revision and capability match.

What happens when the workspace changes?

A supporting client changes its local list, then sends notifications/roots/list_changed. The notification carries a signal, so the server has to query again to obtain values. The lab logs the signal and always fetches a fresh list for the next read. It has no persistent cache of client roots. The loaded documentation catalog is a separate snapshot and never expands because of a notification.

The client replaces its list and sends a notification. The next tool call asks for current roots. An already running call may have an earlier snapshot.
The client replaces its list and sends a notification. The next tool call asks for current roots. An already running call may have an earlier snapshot.

A high-throughput integration might keep short-lived per-session discovery metadata. Mark it stale on notification, re-query lazily, and use a generation number to avoid storing a response that arrived after a newer invalidation. A call already in flight may see an earlier snapshot. Never use that cache for permission revocation. Apply current application authorization independently. Do not share a cache across users just because their clients use the same project name.

How does the server prevent unsafe file access?

The safest path in this particular example is a logical document lookup backed by a trusted deployment snapshot. At startup the server loads two administrator-selected Markdown files. The tool only serves those entries from memory. It does not open a path derived from the request or a client-supplied URI.

The application authenticates the caller, checks a configured document and current workspace, then returns text from memory.
The application authenticates the caller, checks a configured document and current workspace, then returns text from memory.

Validate a logical document name

The tool accepts names such as welcome.md or guide/setup.md. It checks a strict, portable grammar and an exact allowlist. The grammar excludes absolute paths, backslashes, drive separators, percent escapes, empty segments, traversal-like names and non-Markdown extensions. Names that meet the grammar still have to appear in the catalog. A folder next to the allowed directory cannot pass an exact comparison because it starts with the same letters.

A valid logical document name reaches an exact allowlist lookup. Traversal-like paths are rejected before any lookup or I/O.
A valid logical document name reaches an exact allowlist lookup. Traversal-like paths are rejected before any lookup or I/O.

When dynamic file access is genuinely required, normalize against an explicit absolute base using Path.GetFullPath. Check containment at path component boundaries, and then handle links, mount points, hard links and filesystem races. Normalization removes lexical ambiguity. It does not resolve what an operating-system open will ultimately reach. See .NET file path formats and Path.GetFullPath.

Convert file URIs without making them authoritative

The server accepts a hostless local file URI with no query or fragment, uses Uri.LocalPath, checks that the result is fully qualified, and normalizes trailing directory separators. It rejects UNC or device-like paths and ambiguous encodings in this lab. It compares the normalized result to the configured directory using ordinal equality on both platforms. This deliberately rejects differences such as drive-letter or folder-name casing on Windows. Configure and advertise identical spellings. A production storage catalog can instead use opaque, explicitly mapped IDs.

Normalize only a local file URI, then compare it with a known server-side directory. The URI never selects a file to open.
Normalize only a local file URI, then compare it with a known server-side directory. The URI never selects a file to open.

At startup the loader checks the chosen files and their ancestors for the ReparsePoint attribute. On Windows this catches junctions and symbolic links exposed as reparse points. On Linux it rejects symlinks observed by .NET. That check has a time-of-check to time-of-use race if someone can replace a component before the open. It also does not establish that files are free of hard links, Linux bind mounts, FIFOs, or other special objects. Keep the deployment directory and all parents trusted. Load only deployment-produced regular files and give the service identity read access to the documentation tree, without write permission. Mount an approved snapshot read-only where appropriate.

An ordinary directory points to the deployed tree. A symlink or junction can redirect resolution, so the loader checks components and assumes a trusted deployment tree.
An ordinary directory points to the deployed tree. A symlink or junction can redirect resolution, so the loader checks components and assumes a trusted deployment tree.

For hostile, writable directories, use an OS-specific, handle-relative opening design and validate the opened object. On supported Linux versions, openat2 can constrain resolution beneath a trusted directory handle and disallow symlinks. Pair that with least privilege and explicit filesystem isolation. A Windows implementation needs a reviewed handle-based reparse policy. The sample uses a trusted snapshot so there is no request-time path resolution. See .NET FileAttributes and Linux openat2.

Create the ASP.NET Core 10 solution

Install .NET 10 SDK, a text editor and OpenSSL for the shell example. Run the following commands in an empty directory. The official packages are pinned to SDK 2.3.1. The compile-time warnings for Roots are suppressed only in the two intentionally legacy files. The session hook used for logging notifications is experimental in the pinned SDK, with its own narrowly scoped suppression.

Create and restore the projects
dotnet new web -n DocsServer --framework net10.0
dotnet new console -n DocsClient --framework net10.0
dotnet new console -n DocsChecks --framework net10.0
dotnet add DocsServer package ModelContextProtocol.AspNetCore --version 2.3.1
dotnet add DocsClient package ModelContextProtocol.Core --version 2.3.1
dotnet add DocsChecks reference DocsServer/DocsServer.csproj
Three projects keep transport code, the terminal client, and isolated validation checks separate.
Three projects keep transport code, the terminal client, and isolated validation checks separate.
Project layout
DocsServer/
  Program.cs
  DocsCatalog.cs
  DocsTools.cs
DocsClient/
  Program.cs
DocsChecks/
  Program.cs
workspace/
  docs/
    welcome.md
    guide/setup.md
  other/

The source and package version are documented in the SDK 2.3.1 release and Core package metadata. For MCP hosting basics, see Build an MCP server in C#.

Implement the server and document catalog

Program.cs and dependency injection

The host loads its catalog before accepting requests. Configure Docs__Directory as a fully qualified path to the trusted documentation folder. The sample uses one lab identity. It verifies a random bearer key on every request, rejects browser origins and unexpected hosts, and caps HTTP request size. These controls are for the loopback reproduction. Use standard authentication, TLS, and scoped authorization for remote deployments.

The transport uses StatefulForInitializeClients so legacy initialized clients have a session. The listener records a generic notification event. The server retrieves the actual root list inside the tool context. Logging deliberately avoids URI values, absolute paths, bearer keys, and document bodies.

DocsServer/Program.cs
using ModelContextProtocol.AspNetCore;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

var builder = WebApplication.CreateBuilder(args);
var secret = builder.Configuration["Docs:LabKey"];
if (string.IsNullOrWhiteSpace(secret) || secret.Length is < 32 or > 128)
    throw new InvalidOperationException("Set Docs__LabKey to a random 32–128 character value.");

var catalog = DocsCatalog.Load(builder.Configuration["Docs:Directory"]
    ?? throw new InvalidOperationException("Set Docs__Directory."));

var expected = SHA256.HashData(Encoding.UTF8.GetBytes("Bearer " + secret));
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 32 * 1024);
builder.Services.AddSingleton(catalog);
builder.Services.AddMcpServer().WithHttpTransport(options =>
{
    options.SessionMode = HttpServerSessionMode.StatefulForInitializeClients;
#pragma warning disable MCPEXP002 // Session hook is experimental in this pinned SDK.

    options.RunSessionHandler = async (initialRequest, server, ct) =>
    {
        var logger = initialRequest.RequestServices.GetRequiredService<ILoggerFactory>()
            .CreateLogger("RootsChange");
        await using var listener = server.RegisterNotificationHandler(
            "notifications/roots/list_changed", (_, _) =>
            {
                logger.LogInformation("Client signaled a workspace change");
                return ValueTask.CompletedTask;
            });
        await server.RunAsync(ct);
    };
#pragma warning restore MCPEXP002
}).WithTools<DocsTools>();

var app = builder.Build();
app.Use(async (context, next) =>
{
    if (context.Request.Host.Host is not ("127.0.0.1" or "localhost") ||
        context.Request.Headers.ContainsKey("Origin"))
    {
        context.Response.StatusCode = 403;
        return;
    }

    var token = context.Request.Headers.Authorization;
    if (token.Count != 1 || token.ToString().Length > 140 ||
        !CryptographicOperations.FixedTimeEquals(expected,
            SHA256.HashData(Encoding.UTF8.GetBytes(token.ToString()))))
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.WWWAuthenticate = "Bearer";
        return;
    }

    context.User = new ClaimsPrincipal(new ClaimsIdentity(
        [new Claim(ClaimTypes.NameIdentifier, "local-docs-reader")], "LabKey"));
    await next(context);
});
app.MapMcp("/mcp");
await app.RunAsync();

Startup catalog and path policy

The catalog uses an exact ordinal dictionary and fixed filenames. It reads at most 32 KiB per file and decodes UTF-8 strictly. Missing directories, oversized files and invalid data fail startup. Keep startup exception logs private since framework errors can include paths. To deploy fresh documentation, replace it through the trusted deployment process and restart the service.

DocsServer/DocsCatalog.cs
using System.Text;

public sealed class DocsCatalog
{
    private readonly Dictionary<string, string> documents = new(StringComparer.Ordinal);
    private static readonly UTF8Encoding Utf8 = new(false, true);
    private const int MaxBytes = 32 * 1024;

    private DocsCatalog(string directory)
    {
        DirectoryPath = directory;
    }

    public string DirectoryPath { get; }

    public static bool IsDocumentPath(string? path)
    {
        if (path is null || path.Length is < 4 or > 120 ||
            !path.EndsWith(".md", StringComparison.Ordinal))
            return false;

        return path.Split('/').All(part => part.Length > 0 &&
            char.IsAsciiLetterOrDigit(part[0]) &&
            char.IsAsciiLetterOrDigit(part[^1]) &&
            !part.Contains("..", StringComparison.Ordinal) &&
            part.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-'));
    }

    public static string? LocalDirectory(string? raw)
    {
        if (raw is null || raw.Length > 2048 ||
            !raw.StartsWith("file:///", StringComparison.OrdinalIgnoreCase) ||
            !Uri.TryCreate(raw, UriKind.Absolute, out var uri) ||
            !uri.IsFile || !uri.IsLoopback || uri.IsUnc || uri.Host.Length != 0 ||
            uri.Query.Length != 0 || uri.Fragment.Length != 0)
            return null;

        try
        {
            var path = uri.LocalPath;
            // Reject device/UNC spellings, controls, and double-encoding.
            if (path.StartsWith("//") || path.StartsWith(@"\\") ||
                path.Contains('%') || path.Any(char.IsControl) ||
                !Path.IsPathFullyQualified(path))
                return null;
            return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
        }
        catch (Exception ex) when (ex is ArgumentException or IOException or NotSupportedException)
        {
            return null;
        }
    }

    public static DocsCatalog Load(string directory)
    {
        if (!Path.IsPathFullyQualified(directory))
            throw new InvalidOperationException("Configure an absolute docs directory.");
        var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory));
        var catalog = new DocsCatalog(full);

        foreach (string path in new[] { "welcome.md", "guide/setup.md" })
        {
            var file = Path.Combine(full, path);
            for (FileSystemInfo? item = new FileInfo(file); item is not null;
                item = item is FileInfo f ? f.Directory : ((DirectoryInfo)item).Parent)
            {
                var attrs = File.GetAttributes(item.FullName);
                if ((attrs & FileAttributes.ReparsePoint) != 0 ||
                    (item is FileInfo && (attrs & FileAttributes.Directory) != 0))
                    throw new InvalidOperationException("Use regular files in a link-free deployment tree.");
            }

            using var input = File.OpenRead(file);
            var bytes = new byte[MaxBytes + 1];
            int count = input.ReadAtLeast(bytes, bytes.Length, false);
            if (count > MaxBytes)
                throw new InvalidOperationException("A configured document exceeds 32 KiB.");
            catalog.documents.Add(path, Utf8.GetString(bytes, 0, count));
        }
        return catalog;
    }

    public string? Read(string path) =>
        IsDocumentPath(path) && documents.TryGetValue(path, out var text) ? text : null;
}

Tool authorization and workspace discovery

The server authenticates the caller, finds an authorized catalog entry, checks the legacy capability, requests roots with a linked three-second budget, and matches the configured workspace. A client cannot use a newly advertised root to expand the catalog. The tool returns a logical name and text only. Treat returned documentation as untrusted input when it enters a model prompt. A paragraph in a Markdown file cannot grant tool permissions.

DocsServer/DocsTools.cs
using System.ComponentModel;
using System.Security.Claims;
using ModelContextProtocol;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;

#pragma warning disable MCP9005 // Intentional 2025-11-25 compatibility lab.
[McpServerToolType]
public sealed class DocsTools
{
    [McpServerTool(Name = "read_workspace_doc", ReadOnly = true, UseStructuredContent = true)]
    [Description("Read an allowlisted Markdown document from the configured workspace.")]
    public static async Task<DocResult> ReadAsync(
        RequestContext<CallToolRequestParams> context, ClaimsPrincipal principal,
        DocsCatalog catalog, ILogger<DocsTools> log, string path, CancellationToken ct)
    {
        if (principal.Identity?.IsAuthenticated != true ||
            principal.FindFirst(ClaimTypes.NameIdentifier)?.Value != "local-docs-reader")
            throw new McpException("Access denied.");

        if (catalog.Read(path) is not { } text)
            throw new McpException("Document unavailable or denied.");

        var session = context.Server;
        if (session.NegotiatedProtocolVersion != "2025-11-25" ||
            session.ClientCapabilities?.Roots is null)
            throw new McpException("This lab needs a 2025-11-25 client with Roots.");

        using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
        budget.CancelAfter(TimeSpan.FromSeconds(3));
        ListRootsResult roots;
        try
        {
            roots = await session.RequestRootsAsync(new(), budget.Token);
        }
        catch (OperationCanceledException) when (!ct.IsCancellationRequested)
        {
            throw new McpException("Workspace discovery timed out.");
        }
        catch (McpException)
        {
            throw new McpException("Workspace discovery failed.");
        }

        ct.ThrowIfCancellationRequested();
        if (roots.Roots.Count > 32 || !roots.Roots.Any(root =>
            string.Equals(DocsCatalog.LocalDirectory(root.Uri), catalog.DirectoryPath,
                StringComparison.Ordinal)))
            throw new McpException("Configured workspace was not advertised.");

        log.LogInformation("Served an allowlisted documentation snapshot");
        return new(path, text);
    }
}

public sealed record DocResult(string Path, string Text);

Configure a compatible C# client

The console client pins November 2025 and advertises two roots. A test switch replaces the list with only the unrelated workspace and sends the change notification. Another test switch removes Roots support entirely. The client disables redirects for the fixed lab endpoint, sends the same key as the server expects, and uses a 20-second overall cancellation budget.

DocsClient/Program.cs
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;

#pragma warning disable MCP9005 // Intentional 2025-11-25 compatibility lab.
if (args.Length != 3)
    throw new ArgumentException("Pass a docs directory, another directory, and a document path.");

var key = Environment.GetEnvironmentVariable("Docs__LabKey")
    ?? throw new InvalidOperationException("Set Docs__LabKey.");
var docs = Path.GetFullPath(args[0]);
var other = Path.GetFullPath(args[1]);
bool removed = false;
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
Console.CancelKeyPress += (_, e) => { e.Cancel = true; timeout.Cancel(); };
using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var transport = new HttpClientTransport(new HttpClientTransportOptions
{
    Endpoint = new Uri("http://127.0.0.1:5080/mcp"),
    TransportMode = HttpTransportMode.StreamableHttp,
    AdditionalHeaders = new Dictionary<string, string> { ["Authorization"] = "Bearer " + key }
}, http);
bool enabled = Environment.GetEnvironmentVariable("Docs__NoRoots") != "1";
var options = new McpClientOptions
{
    ProtocolVersion = "2025-11-25",
    Capabilities = new ClientCapabilities
    {
        Roots = enabled ? new RootsCapability { ListChanged = true } : null
    },
    Handlers = new McpClientHandlers
    {
        RootsHandler = enabled ? (_, _) => ValueTask.FromResult(new ListRootsResult
        {
            Roots = Volatile.Read(ref removed)
                ? [new Root { Uri = new Uri(other).AbsoluteUri, Name = "Other project" }]
                : [new Root { Uri = new Uri(docs).AbsoluteUri, Name = "Documentation" },
                   new Root { Uri = new Uri(other).AbsoluteUri, Name = "Other project" }]
        }) : null
    }
};

await using var client = await McpClient.CreateAsync(transport, options,
    cancellationToken: timeout.Token);
if (await ReadAsync() && enabled &&
    Environment.GetEnvironmentVariable("Docs__ChangeRoots") == "1")
{
    Volatile.Write(ref removed, true);
    await client.SendNotificationAsync("notifications/roots/list_changed", timeout.Token);
    await ReadAsync();
}

async Task<bool> ReadAsync()
{
    var result = await client.CallToolAsync("read_workspace_doc",
        new Dictionary<string, object?> { ["path"] = args[2] },
        cancellationToken: timeout.Token);
    if (result.IsError == true)
    {
        foreach (var block in result.Content.OfType<TextContentBlock>())
            Console.Error.WriteLine(block.Text);
        Environment.ExitCode = 2;
        return false;
    }
    Console.WriteLine(result.StructuredContent?.ToString());
    return true;
}

Run the lab and verify allowed and denied reads

Use a real, link-free working directory. The shell commands assume POSIX tooling. On Windows you can use PowerShell to create the same layout and set $env:Docs__Directory and $env:Docs__LabKey. Start the server from a local terminal using a random key.

Create sample documents and start the server
mkdir -p workspace/docs/guide workspace/other
printf '# Welcome\n' > workspace/docs/welcome.md
printf '# Setup\n' > workspace/docs/guide/setup.md
export Docs__Directory="$(pwd -P)/workspace/docs"
export Docs__LabKey="$(openssl rand -hex 32)"
dotnet run --project DocsServer --no-launch-profile -- --urls http://127.0.0.1:5080

Give the client terminal the same key without committing or logging it. Run from the same project directory. The initial tool argument is {"path":"guide/setup.md"}. The SDK constructs the MCP request envelope and handles the roots callback.

Read a permitted document
dotnet run --project DocsClient -- workspace/docs workspace/other guide/setup.md
Expected structured tool output
{"path":"guide/setup.md","text":"# Setup\n"}
Scenario Change to the client command Expected result
Allowed Markdown Use guide/setup.md Structured document text
Traversal Use ../welcome.md Tool error and exit 2
Valid name outside catalog Use other.md Tool error and exit 2
Disallowed extension Use guide/setup.txt Tool error and exit 2
Missing Roots capability Prefix Docs__NoRoots=1 Compatibility error and exit 2
Workspace removed Prefix Docs__ChangeRoots=1 First read succeeds, next read is denied
Missing bearer key Request /mcp without credentials HTTP 401

MCP tool errors can arrive within a successful HTTP response. Inspect isError and the client exit status. A client that times out during discovery should cancel the call or show a retry affordance. Avoid unbounded retries for denied paths and invalid workspaces.

Isolated path validation tests

Add this test runner to DocsChecks/Program.cs and run dotnet run --project DocsChecks. It checks the grammar independently of MCP transport. The loopback cases exercise the actual tool and server/client behavior.

DocsChecks/Program.cs
static void Check(bool passed, string scenario)
{
    if (!passed) throw new Exception($"Failed: {scenario}");
    Console.WriteLine($"PASS {scenario}");
}

Check(DocsCatalog.IsDocumentPath("guide/setup.md"), "portable nested name");
foreach (var path in new[]
{
    "../private.md", "guide/../private.md", "/etc/private.md", @"C:\docs\a.md",
    @"guide\setup.md", "guide//setup.md", "%2e%2e/private.md", "guide/setup.txt",
    "guide/setup.md:secret"
})
    Check(!DocsCatalog.IsDocumentPath(path), $"reject {path}");

var directory = Path.GetFullPath("workspace/docs");
Check(DocsCatalog.LocalDirectory(new Uri(directory).AbsoluteUri) == directory,
    "local URI round trip");
Check(DocsCatalog.LocalDirectory("file://remote/share/docs") is null, "reject UNC host");
Check(DocsCatalog.LocalDirectory("https://example.org/docs") is null, "reject HTTPS URI");
Check(DocsCatalog.LocalDirectory(new Uri(directory).AbsoluteUri + "#tag") is null,
    "reject fragment");

The example compiled with .NET SDK 10.0.100 on Linux. All 14 isolated checks passed. The seven loopback cases above produced the expected outcomes, including the notification log and a denied second read after removal. A separate startup test with a symbolic link in place of the document was rejected. Windows junction behavior, native handle-based traversal defenses, and the discovery timeout branch were outside the executed checks.

Production checklist and troubleshooting

  • Prefer explicit workspace IDs for new clients. Bind the ID to the authenticated user or tenant. Map it to a server-side catalog, then apply the same authorization regardless of client-provided metadata.
  • Keep the process account least-privileged. Only expose approved artifacts. Use a separate, read-only mount or a scoped object-store reader where it fits the deployment.
  • Plan root changes and application revocations independently. Roots are navigation context. Disabling a workspace in application policy should take effect even if a client never sends a change notification.
  • Treat documentation as data. Render Markdown safely. Prevent instructions in a retrieved document from bypassing the model or tool permission policy.
  • Protect observability. Log success, denial and latency with bounded, sanitized metadata. Avoid recording paths, document contents, and bearer keys. Rate-limit expensive operations by authenticated caller.
  • Use deployment identity in production. Review token scopes and filesystem permissions together. The ASP.NET PB JWT guide covers application authentication. The MCP authorization specification governs protected remote HTTP transports.
Symptom What to check
Client cannot list roots Confirm the negotiated protocol, initialized stateful session, and RootsHandler
Valid-looking workspace is denied Check that it is shared locally, uses a hostless URI, and has the same normalized spelling
Startup says a link is present Check the file and its parent directories for symlinks or junctions
Newly advertised folder stays unavailable The catalog is server-controlled. Configure and deploy approved documentation separately
Old documents are returned Reload the trusted snapshot through deployment and restart
HTTP 401 or 403 Confirm the shared lab key, loopback Host and absence of browser Origin

Frequently asked questions

Are MCP Roots a security sandbox?

No. Roots identify workspace context. The host process, its OS permissions and server-side authorization policy determine what can be read. A client can send an untrusted or misleading URI.

Does every MCP client support Roots?

No. Support depends on the client and the protocol revision. Use capability and version checks for legacy integrations. Design current clients so the server can safely operate with an explicit authorized workspace or return a clear compatibility error.

What is the difference between Roots and Resources?

Roots travel from a supporting client to the server as context. Resources are server-provided data that clients may list and read, subject to application rules.

Can I protect a directory by checking a path prefix?

A plain string prefix can match a neighboring folder and says nothing about symlinks, junctions, or path replacement after validation. An exact logical allowlist backed by an immutable snapshot is simpler when the content set is known.

How do I refresh roots without restarting the server?

On a legacy session the client can send the change notification after replacing its list. Fetch the current roots again. Restart only when the trusted documentation catalog itself changes in this example.

Conclusion and further reading

Legacy MCP Roots can help a server understand the client’s workspace. The useful security lesson is to keep that hint separate from access decisions. This example authorizes a small, server-configured snapshot, checks the legacy workspace context, and serves only approved Markdown text.

Useful follow-ups include migrating legacy Roots clients to workspace IDs, designing an authorized documentation Resources endpoint, and writing cross-platform integration tests for filesystem isolation.

Comments