AI Engineering: Agents and Applications › The Model Context Protocol › Day 300

Hands-on lab — Day 300: MCP Security

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/mcp_security_guard.py

Test

bash tests/run_tests.sh

File tree

examples/mcp_security_guard.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/mcp_security_guard.py
tests/run_tests.sh
tests/test_mcp_security_guard.py
troubleshooting.md

Lab README

Day 300 Lab: MCP Security

Lesson

  • Lesson title: MCP Security
  • Day number: 300 of 365
  • Lesson article: https://ai-roadmap-365.github.io/day-300-mcp-security
  • Lab files: everything you need is in this directory — follow “How to run” below.
  • Browse the course locally: from the repository root, this lab also appears in the course website at /labs/day-300-mcp-security when the site is running.

Purpose

Build an MCP Security Guard and Sandboxing Engine in Python providing path canonicalization, destructive action classification, Human-in-the-Loop gates, and audit logging.

Learning objectives

  • Implement canonical path sandboxing rejecting ../ traversal attacks.
  • Build a risk classification engine identifying destructive actions.
  • Enforce Human-in-the-Loop approval gates for high-risk operations.
  • Maintain structured security audit logs for compliance.

Prerequisites

  • Python 3.10+ installed
  • pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, pytest

Free and open-source options

  • Python Standard Library, Pytest

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/mcp_security_guard.py: Starter implementation skeleton
  • examples/mcp_security_guard.py: Verified reference implementation
  • tests/test_mcp_security_guard.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/mcp_security_guard.py

What the commands do

  • Evaluates path sandboxing, destructive tool interception, and approval workflows.

Expected output

Sandbox root: /private/tmp/mcp_sandbox
Safe read result: {'content': [{'type': 'text', 'text': 'File data'}], 'isError': False}

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • Safe path resolution within sandbox root
  • Path traversal rejection (../../etc/passwd)
  • Destructive tool blocking without human approval
  • Successful execution when human approval is granted
  • Audit log entry verification

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure sandbox root path is an absolute real path.

Security notes

Runs completely offline on local CPU.

Extension exercises

Implement network IP range filtering for HTTP request tools.

Day number: 300 of 365

Expected output

FIELDS.md

# Measured Values
- `security_blocks`: 1
- `approved_actions`: 1

examples-run.txt

Sandbox root: /private/tmp/mcp_sandbox
Safe read result: {'content': [{'type': 'text', 'text': 'File data'}], 'isError': False}

measured-values.txt

security_blocks=1
approved_actions=1

run-output.txt

Sandbox root: /private/tmp/mcp_sandbox
Safe read result: {'content': [{'type': 'text', 'text': 'File data'}], 'isError': False}

starter-run.txt

An untouched starter fails the suite. Captured from a real run:

tool_name = 'read_data', arguments = {'key': 1}
handler_fn = <function test_safe_read_tool_auto_approved.<locals>.<lambda> at 0x10b5e3480>
human_approved = False

    def authorize_and_execute(self, tool_name: str, arguments: Dict[str, Any], handler_fn: Callable, human_approved: bool=False) -> Dict[str, Any]:
>       raise NotImplementedError('TASK 2: implement authorize_and_execute.')
E       NotImplementedError: TASK 2: implement authorize_and_execute.

examples/mcp_security_guard.py:22: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_mcp_security_guard.py::test_path_sanitization_valid - NotIm...
FAILED tests/test_mcp_security_guard.py::test_path_traversal_rejection - NotI...
FAILED tests/test_mcp_security_guard.py::test_destructive_tool_blocked_without_approval
FAILED tests/test_mcp_security_guard.py::test_destructive_tool_executed_with_approval
FAILED tests/test_mcp_security_guard.py::test_safe_read_tool_auto_approved - ...
============================== 5 failed in 0.03s ===============================

Implement each TASK in starter/, copy it over examples/, and the same
suite goes green.

test-output.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-300-mcp-security
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_mcp_security_guard.py::test_path_sanitization_valid PASSED    [ 20%]
tests/test_mcp_security_guard.py::test_path_traversal_rejection PASSED   [ 40%]
tests/test_mcp_security_guard.py::test_destructive_tool_blocked_without_approval PASSED [ 60%]
tests/test_mcp_security_guard.py::test_destructive_tool_executed_with_approval PASSED [ 80%]
tests/test_mcp_security_guard.py::test_safe_read_tool_auto_approved PASSED [100%]

============================== 5 passed in 0.01s ===============================

test-run.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-300-mcp-security
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_mcp_security_guard.py::test_path_sanitization_valid PASSED    [ 20%]
tests/test_mcp_security_guard.py::test_path_traversal_rejection PASSED   [ 40%]
tests/test_mcp_security_guard.py::test_destructive_tool_blocked_without_approval PASSED [ 60%]
tests/test_mcp_security_guard.py::test_destructive_tool_executed_with_approval PASSED [ 80%]
tests/test_mcp_security_guard.py::test_safe_read_tool_auto_approved PASSED [100%]

============================== 5 passed in 0.01s ===============================

Source files

examples/mcp_security_guard.py (2345 bytes)
import os
from typing import Dict, Any, Callable, List

class MCPSecurityGuard:
    def __init__(self, sandbox_root: str):
        self.sandbox_root = os.path.realpath(sandbox_root)
        self.destructive_tools = {"delete_file", "drop_table", "execute_shell"}
        self.audit_log: List[Dict[str, Any]] = []
        
    def validate_path(self, relative_path: str) -> str:
        target = os.path.realpath(os.path.join(self.sandbox_root, relative_path))
        if os.path.commonpath([target, self.sandbox_root]) != self.sandbox_root:
            raise PermissionError(f"Path Traversal Blocked: '{relative_path}' escapes sandbox.")
        return target
        
    def authorize_and_execute(
        self,
        tool_name: str,
        arguments: Dict[str, Any],
        handler_fn: Callable,
        human_approved: bool = False
    ) -> Dict[str, Any]:
        is_destructive = tool_name in self.destructive_tools
        
        if is_destructive and not human_approved:
            self.audit_log.append({
                "tool": tool_name,
                "status": "BLOCKED_AWAITING_APPROVAL",
                "arguments": arguments
            })
            return {
                "content": [{"type": "text", "text": f"Execution blocked: Tool '{tool_name}' requires human approval."}],
                "isError": True
            }
            
        try:
            result = handler_fn(arguments)
            self.audit_log.append({
                "tool": tool_name,
                "status": "SUCCESS",
                "arguments": arguments
            })
            return {
                "content": [{"type": "text", "text": str(result)}],
                "isError": False
            }
        except Exception as e:
            self.audit_log.append({
                "tool": tool_name,
                "status": "ERROR",
                "error": str(e)
            })
            return {
                "content": [{"type": "text", "text": f"Runtime Security Error: {str(e)}"}],
                "isError": True
            }

if __name__ == "__main__":
    guard = MCPSecurityGuard("/tmp/mcp_sandbox")
    print("Sandbox root:", guard.sandbox_root)
    # Test safe execution
    res = guard.authorize_and_execute("read_file", {"path": "safe.txt"}, lambda a: "File data")
    print("Safe read result:", res)
metadata.yml (405 bytes)
lesson_id: D300
day: 300
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/mcp_security_guard.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (14 bytes)
pytest>=7.0.0
starter/mcp_security_guard.py (1199 bytes)
"""STARTER -- implement each TASK below, then run the tests.

Every function that raises NotImplementedError is yours to write. The
imports, constants and data structures are given; the logic is not.
Run `bash tests/run_tests.sh` to see which tasks are still outstanding.
"""

import os
from typing import Dict, Any, Callable, List

class MCPSecurityGuard:

    def __init__(self, sandbox_root: str):
        self.sandbox_root = os.path.realpath(sandbox_root)
        self.destructive_tools = {'delete_file', 'drop_table', 'execute_shell'}
        self.audit_log: List[Dict[str, Any]] = []

    def validate_path(self, relative_path: str) -> str:
        raise NotImplementedError('TASK 1: implement validate_path.')

    def authorize_and_execute(self, tool_name: str, arguments: Dict[str, Any], handler_fn: Callable, human_approved: bool=False) -> Dict[str, Any]:
        raise NotImplementedError('TASK 2: implement authorize_and_execute.')
if __name__ == '__main__':
    guard = MCPSecurityGuard('/tmp/mcp_sandbox')
    print('Sandbox root:', guard.sandbox_root)
    res = guard.authorize_and_execute('read_file', {'path': 'safe.txt'}, lambda a: 'File data')
    print('Safe read result:', res)
tests/run_tests.sh (253 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
if [ -n "$PYTEST" ]; then
    $PYTEST tests/test_*.py -v
elif command -v pytest &> /dev/null; then
    pytest tests/test_*.py -v
else
    python3 -m unittest discover -s tests -p 'test_*.py' -v
fi
tests/test_mcp_security_guard.py (1620 bytes)
import pytest
import tempfile
import os
from examples.mcp_security_guard import MCPSecurityGuard

def test_path_sanitization_valid():
    with tempfile.TemporaryDirectory() as tmpdir:
        guard = MCPSecurityGuard(tmpdir)
        valid_path = guard.validate_path("subfolder/data.txt")
        assert valid_path.startswith(os.path.realpath(tmpdir))

def test_path_traversal_rejection():
    with tempfile.TemporaryDirectory() as tmpdir:
        guard = MCPSecurityGuard(tmpdir)
        with pytest.raises(PermissionError) as exc:
            guard.validate_path("../../etc/passwd")
        assert "Path Traversal Blocked" in str(exc.value)

def test_destructive_tool_blocked_without_approval():
    guard = MCPSecurityGuard("/tmp")
    res = guard.authorize_and_execute("delete_file", {"target": "data.db"}, lambda a: "Deleted", human_approved=False)
    assert res["isError"] is True
    assert "requires human approval" in res["content"][0]["text"]
    assert guard.audit_log[-1]["status"] == "BLOCKED_AWAITING_APPROVAL"

def test_destructive_tool_executed_with_approval():
    guard = MCPSecurityGuard("/tmp")
    res = guard.authorize_and_execute("delete_file", {"target": "data.db"}, lambda a: "Deleted", human_approved=True)
    assert res["isError"] is False
    assert res["content"][0]["text"] == "Deleted"
    assert guard.audit_log[-1]["status"] == "SUCCESS"

def test_safe_read_tool_auto_approved():
    guard = MCPSecurityGuard("/tmp")
    res = guard.authorize_and_execute("read_data", {"key": 1}, lambda a: "Value 1")
    assert res["isError"] is False
    assert res["content"][0]["text"] == "Value 1"

Troubleshooting

Troubleshooting - Day 300

Verify sandbox root is an absolute canonical path.

Security notes

Security - Day 300

Enforce path canonicalization and human confirmation gates for all destructive tools.