Tool Calling, MCP & Prompt-Injection Defense
Define MCP tool contracts, validate arguments strictly, isolate untrusted external text, detect indirect prompt injection, and verify with pytest and GitHub Actions.
Tool-calling assistants become far more useful when connected to external systems via the Model Context Protocol (MCP), but connecting tools to untrusted emails, documents, or tickets introduces indirect prompt-injection risk.
In this module, you will build strict Pydantic v2 contracts for an MCP-inspired, application-level tool registry and executor, isolate untrusted external text, detect common prompt-injection patterns, enforce tool argument allow-lists, and test everything with pytest and GitHub Actions in fde-03-1. This focused learning implementation is not a complete MCP client or server and does not implement the MCP protocol lifecycle or transport.
Enterprise Scenario: Northwind Freight
Northwind’s dispatch assistant reads carrier emails and customs notes to look up shipment status. A malicious email or customs note could embed fake system instructions attempting to trigger unauthorized actions or exfiltrate sensitive fields.
What You Will Build
- MCP-inspired tool and context schemas: Define strict Pydantic v2 models for
McpToolDefinition,McpToolCall,SanitizedContextBlock, andMcpToolExecutionResult. These model an application-level registry and executor, not the full MCP protocol. - Untrusted input isolation and injection checks: Wrap external text inside explicit data-only boundaries and detect common prompt-injection phrases.
- Validated MCP tool execution: Reject calls from untrusted origins by default, enforce required and allowed arguments, and execute approved handlers deterministically.
1. Isolating Untrusted Text and Validating Tool Calls
- Why indirect prompt injection is dangerous: Unlike direct user prompts, indirect prompt injection hides instructions inside retrieved text such as emails, PDFs, or carrier updates. If a model treats untrusted data as privileged instructions, it can misuse tools or leak data.
- Defense in depth at tool boundaries: Never rely on prompt wording alone. Pair data-only context isolation with strict argument schema validation, origin checks, and least-privilege tool handlers.
2. Step-by-Step Build Walkthrough
- Create the
fde-03-1repository and virtual environment:mkdir -p fde-03-1/src/fde_03_1 fde-03-1/tests fde-03-1/.github/workflows cd fde-03-1 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Add strict Pydantic v2 schemas in
src/fde_03_1/schemas.py: Enforceextra="forbid",strict=True, non-blank strings, unique argument lists, andrequired_argssubset validation againstallowed_args."""Strict Pydantic v2 schemas for MCP tool definitions, calls, results, and untrusted context.""" from __future__ import annotations import re from typing import Any from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator _TOOL_NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$") def _require_non_blank(value: str, field_name: str) -> str: if not value.strip(): raise ValueError(f"{field_name} must not be blank") return value class McpToolDefinition(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) name: str = Field(min_length=1) description: str = Field(min_length=1) required_args: list[str] = Field(default_factory=list) allowed_args: list[str] = Field(min_length=1) read_only: bool = True @field_validator("name") @classmethod def _validate_name(cls, value: str) -> str: _require_non_blank(value, "name") cleaned = value.strip() if not _TOOL_NAME_PATTERN.match(cleaned): raise ValueError( "name must use lowercase letters, digits, underscores, or dot namespaces" ) return cleaned @field_validator("description") @classmethod def _validate_description(cls, value: str) -> str: return _require_non_blank(value, "description") @field_validator("required_args", "allowed_args") @classmethod def _validate_arg_lists(cls, values: list[str], info) -> list[str]: cleaned: list[str] = [] for item in values: _require_non_blank(item, info.field_name) cleaned.append(item.strip()) if len(cleaned) != len(set(cleaned)): raise ValueError(f"{info.field_name} must not contain duplicate argument names") return cleaned @model_validator(mode="after") def _validate_required_args_are_allowed(self) -> "McpToolDefinition": missing_from_allow_list = sorted(set(self.required_args) - set(self.allowed_args)) if missing_from_allow_list: raise ValueError( "required_args must be a subset of allowed_args; " f"not allowed: {', '.join(missing_from_allow_list)}" ) return self class McpToolCall(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) call_id: str = Field(min_length=1) tool_name: str = Field(min_length=1) arguments: dict[str, Any] = Field(default_factory=dict) from_untrusted_source: bool = False @field_validator("call_id", "tool_name") @classmethod def _validate_non_blank_str(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) class SanitizedContextBlock(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) source_id: str = Field(min_length=1) trust_level: str = Field(default="untrusted") injection_detected: bool matched_signals: list[str] = Field(default_factory=list) isolated_text: str = Field(min_length=1) @field_validator("source_id", "trust_level", "isolated_text") @classmethod def _validate_non_blank_fields(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) @field_validator("trust_level") @classmethod def _validate_trust_level(cls, value: str) -> str: if value != "untrusted": raise ValueError("trust_level for external blocks must be 'untrusted'") return value class McpToolExecutionResult(BaseModel): model_config = ConfigDict(extra="forbid", strict=True) call_id: str = Field(min_length=1) tool_name: str = Field(min_length=1) allowed: bool reason: str = Field(min_length=1) output: dict[str, Any] | None = None @field_validator("call_id", "tool_name", "reason") @classmethod def _validate_non_blank_result(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) - Implement injection detection, context isolation, and safe tool execution in
src/fde_03_1/mcp_defense.py:"""MCP tool argument validation, untrusted context isolation, and injection defense.""" from __future__ import annotations import logging import re from html import escape from typing import Any, Callable from fde_03_1.schemas import ( McpToolCall, McpToolDefinition, McpToolExecutionResult, SanitizedContextBlock, _require_non_blank, ) logger = logging.getLogger(__name__) _INJECTION_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( ( "ignore_previous_instructions", re.compile( r"\b(ignore|disregard|forget|override)\b.{0,40}\b(previous|prior|above|system)\b.{0,20}\b(instructions?|prompt|rules?)\b", re.IGNORECASE | re.DOTALL, ), ), ( "system_role_impersonation", re.compile( r"(^\s*(system|developer|assistant)\s*:|<\s*/?\s*(system|tool_call|function)\s*>)", re.IGNORECASE | re.MULTILINE, ), ), ( "exfiltration_or_tool_override", re.compile( r"\b(send|exfiltrate|post|forward|call|invoke)\b.{0,40}\b(webhook|url|endpoint|api_key|token|secret|credentials?)\b", re.IGNORECASE | re.DOTALL, ), ), ) def detect_prompt_injection(text: str) -> list[str]: _require_non_blank(text, "text") signals: list[str] = [] for label, pattern in _INJECTION_PATTERNS: if pattern.search(text): signals.append(label) return signals def wrap_untrusted_context(source_id: str, raw_text: str) -> SanitizedContextBlock: _require_non_blank(source_id, "source_id") _require_non_blank(raw_text, "raw_text") cleaned_source_id = source_id.strip() if any(ord(char) < 32 or ord(char) == 127 for char in cleaned_source_id): raise ValueError("source_id must not contain control characters") signals = detect_prompt_injection(raw_text) safe_source_id = escape(cleaned_source_id, quote=True) escaped_text = escape(raw_text, quote=False) isolated = ( f'<untrusted_data source_id="{safe_source_id}" data_only="true">\n' f"{escaped_text}\n" f"</untrusted_data>" ) return SanitizedContextBlock( source_id=cleaned_source_id, trust_level="untrusted", injection_detected=bool(signals), matched_signals=signals, isolated_text=isolated, ) def execute_mcp_tool_safely( call: McpToolCall, registry: dict[str, McpToolDefinition], handlers: dict[str, Callable[[dict[str, Any]], dict[str, Any]]], allow_untrusted_origin: bool = False, active_logger: logging.Logger | None = None, ) -> McpToolExecutionResult: if call.from_untrusted_source and not allow_untrusted_origin: return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason="Blocked tool call originating from untrusted external content", output=None, ) tool_def = registry.get(call.tool_name) if tool_def is None: return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason=f"Unknown or unregistered MCP tool: {call.tool_name}", output=None, ) handler = handlers.get(call.tool_name) if handler is None: return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason=f"No execution handler registered for tool: {call.tool_name}", output=None, ) allowed_set = set(tool_def.allowed_args) provided_keys = set(call.arguments.keys()) unexpected = sorted(provided_keys - allowed_set) if unexpected: return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason=f"Disallowed tool arguments: {', '.join(unexpected)}", output=None, ) missing = [arg for arg in tool_def.required_args if arg not in provided_keys] if missing: return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason=f"Missing required tool arguments: {', '.join(missing)}", output=None, ) for key, val in call.arguments.items(): if isinstance(val, str) and not val.strip(): return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason=f"Argument '{key}' must not be blank", output=None, ) try: payload = handler(dict(call.arguments)) except Exception: target_logger = active_logger or logger target_logger.exception( "MCP tool handler failed for call_id=%s tool_name=%s", call.call_id, call.tool_name, ) return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=False, reason="Tool handler failed during execution", output=None, ) return McpToolExecutionResult( call_id=call.call_id, tool_name=call.tool_name, allowed=True, reason="Tool call validated and executed", output=payload, )Important implementation boundaries: The
read_onlyfield is descriptive metadata in this exercise; the executor above does not enforce it. A production executor must enforce read-only versus write-capable permissions through trusted server-side policy, authorization, and handler design rather than trusting a model-supplied flag. The HTML-like<untrusted_data>wrapper is only a formatting convention; it is not a security boundary and cannot guarantee that a model will ignore embedded instructions. Enforce security in code at the tool boundary. - Run tests and commit to Git:
python -m pytest -v git status git add . git commit -m "Complete FDE module 03.1"
3. Common Pitfalls and Operational Hygiene
- Treating heuristic injection detection as a complete security boundary: Regex detection is only a heuristic signal. It can produce false positives on harmless text and false negatives when an attack is paraphrased, encoded, or phrased unexpectedly. A match is not proof of an attack, and no match does not prove that content is safe. Pair it with authorization, strict schema validation, argument allow-lists, least-privilege handlers, and origin checks.
- Allowing unvalidated or untrusted-origin tool calls: Block calls flagged from untrusted sources by default, reject extra or missing arguments, reject duplicate argument declarations, require every required argument to be allow-listed, and forbid blank string arguments before calling a handler.
Build this
Extend the pytest suite in fde-03-1/tests/test_mcp_defense.py, keeping each test focused on one behavior and asserting structured results rather than internal exception messages:
- Reject duplicate argument names in
required_argsandallowed_args. - Reject tool definitions where
required_argsincludes a field not present inallowed_args. - Verify malicious or quote-heavy
source_idvalues are safely escaped and control characters are rejected. - Verify handler exceptions return
allowed=False, a generic failure reason, andoutput=Nonewithout exposing internal exception details, while logging server-side diagnostics. - Verify that
read_onlyis descriptive metadata only in this lab and test regex false positives on harmless text alongside false negatives on paraphrased attacks. - Retain coverage for untrusted origins, unknown tools, missing handlers, unexpected and missing arguments, blank string values, and valid handler execution, then run
python -m pytest -vand push to GitHub.
Test your understanding
- Does this lesson implement the complete MCP protocol?
- Are the untrusted-data tags a security boundary?
- Does a clean regex scan prove content is safe?
- Does
read_only=Trueprevent writes here? - What happens if a handler raises an exception?
Reveal self-review answers (attempt the questions first)
- Complete MCP protocol scope: No. This lab models an MCP-inspired, application-level tool registry and executor; full MCP protocol lifecycle and transport are outside scope.
- Untrusted-data tags: No. They are a formatting convention for separating data from instructions; enforcement happens in trusted application code.
- Regex scan limits: No. Regex heuristics can miss paraphrased or encoded attacks and flag harmless text.
read_only=Truemetadata: No. It is descriptive metadata here; a production system must enforce read versus write permissions via trusted policy, authorization, and handler design.- Handler exceptions: The executor logs the exception server-side and returns a structured failure (
allowed=False, generic reason,output=None) without leaking internal details to the model or caller.
Questions or notes on this module?