Research 18 min read Nov 17, 2026 7

Treat Every MCP File Tool as a Security Boundary: Containing Agent-Driven File Access

A workspace path check may not constrain the filesystem operation that follows. We examine symbolic links, path resolution, and testing the actual effects of MCP file tools.

MCPSecurity AgentSecurity AISecurity PathTraversal FileSecurity Sandboxing SecureByDesign
S
SecureHup Team
Security Researcher · SecureHup
Treat Every MCP File Tool as a Security Boundary: Containing Agent-Driven File Access

An agent asks to overwrite reports/latest.md inside its workspace. Between validation and open, reports is replaced with a symbolic link to a directory outside the workspace. A string prefix check still passes because the submitted path has not changed; the filesystem resolves the operation somewhere the tool was never authorized to write.

Path traversal is only one version of this boundary. Absolute paths, alternate separators, hard links, mount points, archive extraction, case behavior, and time-of-check/time-of-use races can all separate the validated name from the object the operating system opens. A typed JSON field proves only that the argument is a string.

The server must own the root, action, target resolution, and effect. Model output may propose a file operation, but trusted code should perform race-resistant resolution beneath a constrained directory, distinguish read from write and delete capabilities, and rely on process sandboxing as a second limit when validation fails.

Key Takeaways

  • Tool arguments are untrusted input even when they came from a trusted model, authenticated user, or schema-aware MCP client.
  • JSON Schema validates message shape, not filesystem meaning. A syntactically valid relative path can still escape through traversal, absolute-path behavior, symlinks, mount points, encoding differences, or a race.
  • File read, create, overwrite, append, rename, delete, and execute are separate capabilities and should have separate roots, policies, approvals, and audit events.
  • A 2026 agent-framework vulnerability combined insufficient path containment with dispatcher-side schema enforcement gaps; affected versions ended at 4.6.33, and 4.6.34 introduced the fix.
  • Prompt injection is a delivery mechanism, not the root authorization decision. A secure server remains bounded even when the model proposes a hostile path.
  • The strongest validation proves both logical containment and actual file-descriptor containment while the operation occurs, then verifies that denied requests have no side effects.

The Tool Is Where Intent Becomes Authority

An MCP tool description tells a model what an operation does and which arguments it expects. A client can use the schema to produce a structured call. The server receives that call and executes application code. Only the final step has operating-system authority.

This separation gives us a clean trust model:

User, document, website, message, or model output
                    |
                    v
          untrusted proposed tool call
                    |
                    v
      authenticated MCP request and policy
                    |
                    v
       server-side semantic authorization
                    |
                    v
      constrained filesystem operation

Neither the model's confidence nor the client's validation changes the first classification. The proposal is untrusted until the server checks it against an explicit capability.

Why File Tools Have Unusually High Leverage

File access connects the agent to many other trust domains:

  • Source code and build configuration.
  • Environment files and local credentials.
  • SSH, cloud, package-manager, and developer-tool state.
  • Application data and user documents.
  • Startup, plugin, hook, and task configuration.
  • CI/CD workspaces and deployment manifests.
  • Logs, prompts, conversation transcripts, and model artifacts.

A write into the wrong location may not execute immediately. It can become code when a later build, import, startup, scheduler, plugin loader, or human workflow consumes it. That delayed execution makes prevention and investigation harder: the file tool performs one action, while impact appears in a different process at a different time.

A 2026 File-Tool Boundary Failure

A 2026 maintainer advisory for an agent framework documented a critical path-control vulnerability, tracked as CVE-2026-44336. Versions through 4.6.33 were affected, and 4.6.34 was the first fixed release. The project had moved substantially beyond that version when its releases were rechecked on August 17, 2026.

The issue involved MCP-exposed file-handling tools accepting user-influenced path or filename values without reliably confining them to the intended working directory. A related dispatcher path did not consistently enforce the advertised tool input schema before invoking the operation. Under affected conditions, a write could escape the intended directory. If the surrounding environment later interpreted the resulting file, the consequence could extend to code execution in that environment.

Delivery depended on the deployment. An MCP-connected model could be influenced by untrusted content, a locally reachable HTTP transport could accept calls under relevant conditions, or a stdio client could relay a prompt-injected tool request. These are plausible paths, not proof that every installation was remotely exploitable or that every model would produce the same call.

The durable finding is independent of the specific framework: schema advertisement, client validation, and model instruction cannot replace server-side path authorization. A file tool must remain safe when every argument is adversarial.

JSON Schema Is Necessary but Not Sufficient

MCP tool definitions can describe an inputSchema, and clients can use it to validate names, types, required fields, enums, patterns, and lengths. This prevents many malformed calls and improves interoperability. It does not prove that a value is authorized in the server's environment.

A path string can satisfy a schema and still be unsafe because:

  • It is absolute when only workspace-relative paths are intended.
  • It contains parent-directory traversal.
  • Separators are interpreted differently across platforms or libraries.
  • Normalization reveals a path outside the root.
  • A symlink inside the root points outside it.
  • A path component changes between validation and use.
  • A mount or reparse point crosses into another filesystem location.
  • An encoded value is decoded after validation.
  • Case-insensitive resolution selects an unexpected object.
  • A reserved device or special file has side effects unlike an ordinary file.

Schema answers “is this a string in the accepted request shape?” Filesystem policy answers “may this principal perform this operation on the resolved object?”

Enforce the Same Schema at the Dispatcher

Tool schemas are not merely suggestions for model generation. The server's dispatch boundary should validate every call before selecting and invoking a handler, including calls from custom clients, tests, local transports, and compatibility adapters. Handler-level validation can add semantic checks, but it should not be the only defense against missing fields, extra privileged options, or type confusion.

Do not trust tool annotations such as “read-only” or “destructive” as enforcement. They are useful hints for clients and approval UX. The server must implement actual permissions regardless of what the caller or model claims.

Path Containment Is a Semantic Check

The intended policy often sounds like “allow files only under /workspace.” Correct implementation requires more than testing whether a string begins with that prefix.

Lexical Containment

The first step is parsing under one defined platform grammar. Absolute paths, inappropriate empty or special names, parent traversal, unsupported separators, invalid encodings, null-like controls, and excessive depth or length fall outside that grammar. The relative path should be normalized exactly once.

Then join it to a trusted root and compare path components, not raw string prefixes. A sibling directory whose name begins with the same characters is not inside the root.

Lexical checks are valuable, but they do not resolve filesystem indirection.

Physical Containment

Existing path components need to resolve beneath the authorized root because symlinks, junctions, reparse points, bind mounts, and platform aliases can redirect access. For a new file, the resolved parent directory becomes the object authorized before creation.

Be explicit about symlink policy:

  • Reject every symlink in an untrusted path.
  • Allow symlinks only when their fully resolved target remains in the same root.
  • Provide a separate read-only capability for controlled links.

The policy choice can vary; silent following cannot.

Race Resistance

A check followed by a separate path-based open creates a time-of-check/time-of-use gap. Another process may replace a directory component with a symlink after validation. Higher-assurance implementations open the trusted root, walk relative components using directory-relative filesystem APIs, refuse link following where supported, and operate on the resulting file descriptor rather than re-resolving the path string.

The exact primitives differ across operating systems. If the runtime cannot provide strong race resistance, isolate the workspace so untrusted actors cannot modify path components concurrently and document the residual risk.

Creation, Overwrite, and Rename Need Different Rules

For creation, validate the resolved parent and use an exclusive-create mode when replacement is not intended. For overwrite, verify the target type and ownership before opening. For rename, authorize both source and destination and account for cross-filesystem behavior. For delete, reject directory recursion unless the capability explicitly allows it.

One generic write_file(path, content, mode) tool often hides too much authority. Narrower tools make policy and approval easier to explain.

Design Capabilities, Not Generic Filesystem Access

The workflow the agent needs is a better design starting point than the host filesystem plus a growing denylist.

Capability Example Scope Default Policy Approval Expectation
Read project text Version-controlled workspace, approved extensions Read-only; bounded size; no links outside root Usually implicit within user-selected workspace
Create draft artifact Dedicated output directory New files only; no overwrite Implicit or summarized preview
Modify source Selected repository subtree Existing regular files; diff required User reviews diff or policy approves bounded edits
Write configuration Dedicated generated-config area Typed templates; no raw system paths Explicit for security-sensitive config
Rename/move Same authorized root Source and destination both authorized Required if overwrite or boundary change is possible
Delete Narrow temporary/output root No recursive delete by default Explicit, with exact target preview
Read secrets Ideally unavailable Dedicated secret broker, never generic file read Strong explicit approval and policy
Execute file Separate execution sandbox Never implied by write permission Explicit command policy and isolation

Capability separation also limits prompt injection. A model processing an untrusted document may have permission to summarize workspace text but no permission to modify source, read credentials, or execute files.

Bind Capabilities to Principal and Workspace

The server should derive an authorized root from the authenticated principal, tenant, selected project, and approved session context. An arbitrary model-chosen root would discard that relationship. Server-side capability grants can retain their expiration and action set.

For example, a grant can conceptually say:

principal P may read regular text files
under workspace W
until time T
with maximum size S
but may not follow external links or access secret-classified paths

The tool call supplies a relative path within W; it does not redefine W.

Separate Tool Servers by Trust Tier

High-risk file operations can run in a dedicated MCP server or process with a minimal filesystem view and OS identity. A read-only research tool should not share credentials and mounts with a build-and-deploy tool. Process separation makes capability differences real even if application-layer authorization fails.

Prompt Injection Changes Intent, Not Policy

An agent may read a webpage, repository file, issue, email, or document containing instructions designed to redirect its actions. The model can mistake those instructions for part of the user's goal. This is indirect prompt injection.

The wrong response is to assume a better system prompt will eliminate it. Prompt controls reduce likelihood but are not a security boundary. The file server must safely reject an unauthorized operation even if the model confidently requests it.

Keep Data and Instructions Distinct

Hosts should label untrusted content, minimize the tool context it can influence, and avoid automatically feeding tool output back as authoritative instruction. But server authorization should not depend on whether the host correctly classified a prompt.

Require Approval at the Consequence Boundary

Approval is most useful when it presents the resolved consequence:

  • Exact workspace-relative target.
  • Whether the operation creates, overwrites, appends, moves, or deletes.
  • A diff or bounded preview.
  • The requesting agent/workflow and authenticated user.
  • Whether the path or content is executable, configuration, secret-related, or outside normal patterns.

Do not ask users to approve opaque tool arguments or a broad statement such as “allow file access.” Approval must be specific enough to notice a changed target.

Approval Is Not a Substitute for Containment

Users can be rushed, confused, or manipulated. Even an approved operation must remain inside server policy and sandbox boundaries. Approval may narrow authorization; it should never expand a tool beyond the platform's maximum capability.

Sandbox for the Validation Bug You Have Not Found Yet

Application checks will eventually have defects. The operating environment should make a path-validation failure less consequential.

Filesystem Isolation

The tool process needs only its authorized workspace: read-only for read tools and a separate writable output for generated artifacts. Home directories, host roots, credential-bearing caches, runtime sockets, and broad shared volumes create unrelated authority. A task-scoped container or sandbox can also clarify ownership and cleanup.

Process Identity

An unprivileged operating-system user with no unnecessary groups or capabilities keeps file-tool authority apart from the orchestration service, CI runner, cloud CLI, and deployment agent. Separate trust tiers benefit from separate identities.

Network Isolation

A file tool may not need outbound network access. If it does, allow only explicit destinations. Blocking metadata services, internal control planes, and credential endpoints limits what a later-executed file can reach.

Execution Isolation

Writing a file should not cause automatic execution. Auto-run hooks, hot reload, plugin discovery, startup scanning, and scheduler pickup add a second effect that requires an explicit workflow and approval boundary. Build or execution can occur in another sandbox that consumes a reviewed snapshot.

Resource Limits

File size, total workspace use, file count, recursion depth, operation duration, and concurrency provide independent resource bounds in addition to traversal protection.

A Server-Side Authorization Workflow

For every file operation, apply a deterministic sequence:

  1. Authenticate the MCP request independently of tool arguments.
  2. Resolve the exact tool and validate the entire input schema; reject unknown properties unless explicitly supported.
  3. Load the principal's server-side capability grant.
  4. Confirm the requested action is included in the grant.
  5. Parse and normalize the relative path under one platform policy.
  6. Resolve existing components from a trusted root without following prohibited links.
  7. Verify target type, parent, ownership, extension, size, and classification rules.
  8. Obtain action-specific approval when required, showing the resolved consequence.
  9. Perform the operation through race-resistant, directory-relative primitives.
  10. Verify the result and emit a non-secret audit event.

Any ambiguity should deny the operation. The tool can return a bounded error that helps the agent choose an allowed target without exposing host paths or sensitive directory structure.

Test the Boundary as if the Model Were Hostile

Testing should bypass the friendly MCP client and call the dispatcher with adversarial structured input. The objective is defensive verification in an isolated workspace, not access to real host files.

Input and Schema Tests

Schema coverage includes missing fields, unexpected properties, wrong types, duplicate keys where parsers permit them, oversized values, malformed encodings, null-like characters, and nonexistent tools. The important observation is that rejection happens before handler code and produces no filesystem activity.

Path-Equivalence Tests

A synthetic sandbox with known files and links can exercise safe classes of path variation:

  • Parent and current-directory segments.
  • Absolute and rooted paths under each supported platform grammar.
  • Alternate separator and mixed-separator forms.
  • Repeated separators and normalization.
  • Case variants on case-insensitive filesystems.
  • Unicode normalization variants.
  • Links whose targets remain inside or point outside the root.
  • Existing versus new targets.
  • Rename across authorized and unauthorized parents.
  • Encoded values if any later stage decodes them.

Do not test against sensitive host locations. Canary files outside the sandbox can prove that escape attempts leave no effect.

Operation Matrix

Path Condition Read Create Overwrite Rename Delete
Regular file inside authorized root Policy-dependent allow N/A Policy-dependent allow Policy-dependent allow Explicit capability only
New file under authorized parent N/A Allow if create grant exists N/A Destination policy applies N/A
Path outside root Deny Deny Deny Deny Deny
Link resolving outside root Deny Deny via parent check Deny Deny Deny or remove link itself under explicit policy
Special device/socket/pipe Deny by default Deny Deny Deny Deny
Hidden or secret-classified file Separate explicit capability Deny by default Deny Deny Deny
Executable/startup configuration Read by policy Explicit approval and isolated output Explicit approval Explicit approval Explicit approval

Both the response and side effects belong in the oracle, including file hashes, directory entries, process launches, network activity, audit events, and workspace quotas.

Race and Concurrency Tests

In an isolated test harness, change a path component between validation and operation, race two creates, replace a regular file with a link, and retry after approval. The implementation should use atomic or descriptor-based primitives so the result cannot escape the approved object.

Prompt-Injection Evaluation

Untrusted synthetic content can ask the agent to access a forbidden canary, allowing three layers to be evaluated separately:

  • Does the model resist the instruction?
  • Does the host request approval for a high-impact call?
  • Does the server deny the call regardless of model and user-interface behavior?

Only the third result establishes the filesystem boundary.

Audit Without Logging Sensitive Content

File-tool events should support attribution and reconstruction while minimizing data exposure.

Record:

  • Authenticated principal, tenant, client, and tool-server identity.
  • Capability grant identifier and policy version.
  • Operation type and result.
  • Workspace identifier and a safe relative-path representation or keyed hash.
  • Target type, size category, and whether approval was required/granted.
  • Model/workflow correlation ID and trace ID.
  • Denial reason such as schema failure, traversal, link escape, type restriction, quota, or missing capability.
  • Resulting content hash for approved writes when appropriate.

File contents, raw secrets, full host paths, bearer tokens, model context, and excessive approval data generally do not belong in routine logs.

Alert on repeated containment failures, attempts across many workspaces, access to secret-classified patterns, unexpected executable/configuration writes, schema bypass attempts, one workflow causing high-volume changes, and file writes followed by new process or network activity.

Incident Response for an Escaping File Tool

If a file tool allowed paths outside its intended root, upgrading is necessary but does not remove files already written or credentials already read.

  1. Contain the tool. Disable high-risk operations, isolate the process, or remove network exposure while preserving evidence.
  2. Confirm exact versions and paths. Inventory every tool server, transport, dispatcher, and compatibility adapter.
  3. Define filesystem authority. Record mounts, OS identity, home directory, workspace roots, secrets, sockets, and writable executable/configuration locations.
  4. Review tool-call evidence. Correlate authenticated users, model workflows, approvals, paths, hashes, and timestamps without spreading sensitive content.
  5. Hunt for derived execution. Inspect build, startup, plugin, scheduler, CI, and deployment activity following suspicious writes.
  6. Assess confidentiality. Determine which credentials or data the process could read and rotate them when exposure is confirmed or cannot be excluded.
  7. Upgrade to a current fixed release. Verify the executing artifact, not only a dependency declaration.
  8. Remove unsafe artifacts. Quarantine suspicious files after evidence capture; rebuild clean workspaces where integrity is uncertain.
  9. Harden containment. Add server-side schema validation, capability roots, descriptor-based access, sandboxing, and approval.
  10. Retest end to end. Use forbidden canaries and prove no read, write, execution, or network side effect occurs.

The investigation must cover delayed consumers. A file written during the exposure window may execute only when a developer opens a project, a runner starts, or a service reloads later.

File-Tool Security Checklist

  • [ ] Every tool call is treated as adversarial input and authenticated independently.
  • [ ] The dispatcher enforces the complete schema before handler invocation.
  • [ ] Tool annotations are treated as UX hints, not authorization.
  • [ ] The authorized root is server-selected and bound to principal/workspace context.
  • [ ] Paths are relative, normalized once, and compared by components.
  • [ ] Symlink, junction, mount, and reparse-point behavior is explicit.
  • [ ] Filesystem access uses race-resistant directory-relative operations where available.
  • [ ] Read, create, overwrite, rename, delete, and execute are separate capabilities.
  • [ ] Sensitive and executable/configuration targets require stronger policy and approval.
  • [ ] The tool process sees only required mounts and runs under an unprivileged identity.
  • [ ] Writable locations are not automatically executed or loaded.
  • [ ] Network and resource access are bounded.
  • [ ] Denied operations are proven to cause no file, process, or network side effect.
  • [ ] Audit logs preserve attribution without contents, credentials, or full host paths.
  • [ ] Incident response covers files already written, data already read, and delayed execution.

FAQ

Is MCP tool input validation enough to secure file access?

No. Schema validation is essential for request shape, but filesystem authorization also requires a server-selected root, semantic path containment, symlink and race handling, action-specific capability checks, runtime isolation, and side-effect verification.

Why should model-generated paths be treated as untrusted?

Models can misunderstand requests or be influenced by untrusted content. Clients can also call the server directly. A trusted model is not an operating-system security principal, so every proposed path must pass the same server-side policy as hostile input.

Can resolving a path and checking its prefix prevent traversal?

It is better than raw concatenation but may still fail on sibling prefixes, symlinks, mount points, platform differences, and time-of-check/time-of-use races. Component comparison, trusted-root resolution, explicit link policy, and directory-relative descriptor operations address those different cases.

Should an MCP file tool ever access secrets?

Generic file tools should not. A workflow that genuinely requires a secret is better served by a dedicated broker or narrowly scoped capability with approval, redaction, short lifetime, and audit, without exposing credential directories to the process.

Is upgrading a vulnerable file-tool framework sufficient?

A current fixed release addresses the known flaw, while historical tool calls, unexpected writes, later process execution, and readable data shape incident scope. Exposed credentials, uncertain workspaces, sandbox hardening, and a controlled boundary replay may all form part of recovery.

The Filesystem Object Is the Boundary

A narrow root and action capability are more meaningful than a path string that merely looks contained. Race-resistant operating-system primitives can tie the decision to the object actually opened, while separate read, write, delete, and execute permissions keep one legitimate operation from becoming general filesystem authority. For higher-impact changes, the resolved target also gives a reviewer something concrete to approve.

We would pair that design with a disposable test filesystem containing external canaries and several equivalent ways to reach them. Traversal, link swaps, mount boundaries, case variants, archive entries, and concurrent renames then become observations of the same property: a proposed path should never change an object outside the workspace assigned to that tool call.

#MCPSecurity #AgentSecurity #AISecurity #PathTraversal #FileSecurity #Sandboxing #SecureByDesign

Was this helpful?
Share :

Find issues like this in your own codebase

SecureHup runs this exact exploit chain — discovery, enumeration and cross-tenant validation — on every deployment, automatically.