This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: mcp-server-security-sandboxing

Model Context Protocol (MCP) Server Security Sandboxing & Path Traversal Defense

Production security standard for Model Context Protocol (MCP) tool servers. Enforces strict filesystem root confinement with path canonicalization (realpath), absolute prohibition of raw child_process.exec() parameter substitution, parameter schema boundaries, and timeout kill-switches.

Prohibited Anti-Pattern: AI writes MCP tool handlers that pass un-sanitized tool arguments directly to child_process.exec() or fs.readFile(), permitting host path traversal and remote code execution.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Model Context Protocol (MCP) Server Security Sandboxing & Path Traversal Defense - Production security standard for Model Context Protocol (MCP) tool servers. Enforces strict filesystem root confinement with path canonicalization (realpath), absolute prohibition of raw child_process.exec() parameter substitution, parameter schema boundaries, and timeout kill-switches.
globs: **/mcp/**/*.ts, **/tools/**/*.ts, **/mcp_server.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/mcp-server-security-sandboxing"
---

# Model Context Protocol (MCP) Server Security Sandboxing & Path Traversal Defense

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI writes MCP tool handlers that pass un-sanitized tool arguments directly to child_process.exec() or fs.readFile(), permitting host path traversal and remote code execution.

## System Constraints
You are an MCP Security and Sandboxing Architect. When authoring MCP servers and tool definitions, NEVER allow arbitrary host filesystem access or unsanitized shell execution. All file operations must be jail-checked using realpath against an explicit workspace directory whitelist, and tool processes must run through execFile/spawn with argument arrays.

## Strict Guidelines
- Always canonicalize target paths using fs.realpathSync() and verify they strictly start with the allowed workspace root prefix.
- Never use child_process.exec() with string interpolation for tool operations; use child_process.execFile() or spawn() with explicit argument arrays.
- Enforce strict per-tool execution timeouts (e.g. 30 seconds max) with SIGKILL escalation on timeout expiration.
- Truncate tool response payloads exceeding token safety limits (e.g. max 50KB or 8,000 tokens) to prevent context exhaustion attacks.
- Never expose dangerous system tools (rm -rf, git reset --hard, curl to arbitrary URLs) without interactive user approval flags.

## Bad vs Good Implementations
### Sandboxed Path Traversal Validation for MCP Filesystem Tools

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accepting un-sanitized relative or absolute file paths allows an LLM agent to read sensitive system files, environment credentials, and private SSH keys across the host operating system.
```typescript
// FATAL: Insecure MCP tool reading arbitrary user files
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === 'read_file') {
    const targetPath = request.params.arguments?.path as string;
    // VULNERABLE: path can be '../../../../etc/shadow' or 'C:\Windows\System32'
    const content = await fs.promises.readFile(targetPath, 'utf-8');
    return { content: [{ type: 'text', text: content }] };
  }
});
```

#### Production Standard (Correct)
> **Standard**: Implements defensive path jail verification with realpathSync() to eliminate symlink traversal tricks, guarantees files remain within the authorized workspace root, and truncates massive payload responses.
```typescript
import path from 'node:path';
import fs from 'node:fs/promises';
import { realpathSync } from 'node:fs';

const WORKSPACE_ROOT = realpathSync(process.env.MCP_WORKSPACE_ROOT || process.cwd());

export function resolveSafePath(userPath: string): string {
  // 1. Resolve to absolute path
  const resolved = path.resolve(WORKSPACE_ROOT, userPath);
  
  // 2. Canonicalize real path (resolves symlinks to real targets)
  let canonical: string;
  try {
    canonical = realpathSync(resolved);
  } catch (err: any) {
    if (err.code === 'ENOENT') {
      // For non-existent files to create, verify parent directory boundary
      canonical = realpathSync(path.dirname(resolved));
    } else {
      throw new Error(`Access denied: Cannot resolve path ${userPath}`);
    }
  }

  // 3. Strict Jail Boundary Check
  if (!canonical.startsWith(WORKSPACE_ROOT + path.sep) && canonical !== WORKSPACE_ROOT) {
    throw new Error(`Security Violation: Path ${userPath} escapes sandboxed workspace`);
  }

  return resolved;
}

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === 'read_file') {
    const safePath = resolveSafePath(request.params.arguments?.path as string);
    const content = await fs.readFile(safePath, 'utf-8');
    // Truncate to avoid context window explosion
    const truncated = content.length > 50000 ? content.slice(0, 50000) + '\n[Output Truncated]' : content;
    return { content: [{ type: 'text', text: truncated }] };
  }
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Model Context Protocol (MCP) Server Security Sandboxing & Path Traversal Defense

Model Context Protocol (MCP) Server Security Sandboxing & Path Traversal Defense defines an industrial-grade behavioral standard for backend engineering. Production security standard for Model Context Protocol (MCP) tool servers. Enforces strict filesystem root confinement with path canonicalization (realpath), absolute prohibition of raw child_process.exec() parameter substitution, parameter schema boundaries, and timeout kill-switches. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI writes MCP tool handlers that pass un-sanitized tool arguments directly to child_process.exec() or fs.readFile(), permitting host path traversal and remote code execution. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI writes MCP tool handlers that pass un-sanitized tool arguments directly to child_process.exec() or fs.readFile(), permitting host path traversal and remote code execution.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Always canonicalize target paths using fs.realpathSync() and verify they strictly start with the allowed workspace root prefix.

Always canonicalize target paths using fs.realpathSync() and verify they strictly start with the allowed workspace root prefix.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Never use child_process.exec() with string interpolation for tool operations

Never use child_process.exec() with string interpolation for tool operations; use child_process.execFile() or spawn() with explicit argument arrays.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Enforce strict per-tool execution timeouts (e.g. 30 seconds max) with SIGKILL escalation on timeout expiration.

Enforce strict per-tool execution timeouts (e.g. 30 seconds max) with SIGKILL escalation on timeout expiration.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Truncate tool response payloads exceeding token safety limits (e.g. max 50KB or 8,000 tokens) to prevent context exhaustion attacks.

Truncate tool response payloads exceeding token safety limits (e.g. max 50KB or 8,000 tokens) to prevent context exhaustion attacks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Never expose dangerous system tools (rm -rf, git reset --hard, curl to arbitrary URLs) without interactive user approval flags.

Never expose dangerous system tools (rm -rf, git reset --hard, curl to arbitrary URLs) without interactive user approval flags.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Model Context Protocol (MCP) Server Security Sandboxing & Path Traversal Defense critical for AI coding assistants?

Production security standard for Model Context Protocol (MCP) tool servers. Enforces strict filesystem root confinement with path canonicalization (realpath), absolute prohibition of raw child_process.exec() parameter substitution, parameter schema boundaries, and timeout kill-switches. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI writes MCP tool handlers that pass un-sanitized tool arguments directly to child_process.exec() or fs.readFile(), permitting host path traversal and remote code execution.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Model