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 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 |
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 typical result contains the following shape. These are illustrative Linux URI values. The SDK generates the real response from the client’s directories.
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.
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.
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.
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.
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.
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.
Handle symbolic links, junctions, and TOCTOU
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.
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.
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.
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.
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.
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.
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.
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.
| 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.
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.
- Legacy Roots protocol and July 2026 Roots deprecation.
- Official C# SDK v2 announcement and MCP reference filesystem server.
- .NET file path formats, FileAttributes, and Linux openat2.
- Integrate the OpenAI API in ASP.NET Core 10 for a related AI application integration.
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
Post a Comment