Validate tool output before showing it to a model
In this article (5 sections)
Tool responses are external input. A successful HTTP or protocol response can still contain a wrong type, missing unit, stale source or injected instruction.
Reject an invalid result
The MCP contract lab checks two authored objects.
from mcp_cases import output_validation_case
result = output_validation_case()
assert result["accepted_indices"] == [0]
assert result["outputs"][1]["valid"] is False
assert result["invalid_shown_to_model"] is FalseNumeric 27 with unit/source passes. String twenty-seven and missing unit fail. No model sees the invalid row.
Validate multiple layers
Parse transport/protocol, enforce schema, check business invariants and verify source identity/freshness. Bound arrays and text lengths before adding them to context. Treat returned prose as content, never as system authority.
Use allowlisted fields to build a model-facing representation. Redact unnecessary personal data and secrets. Preserve opaque receipts for audit without exposing credentials.
Test drift and attacks
Include new fields, missing fields, type changes, oversized output, cross-tenant records, prompt injection and stale versions. Map failure to structured state and abstain/escalate rather than passing raw exceptions into the prompt.
The Generative & Agentic AI course applies input and output validation around every integration boundary.
Exercise
Create 20 tool responses across schema, semantic and authorization failures. Prove only validated, minimized records enter the rendered model request.
Continue learning
This article is part of the MCP and integration contracts sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Build a read-only business-metrics tool contract.
- Continue with MCP authentication: distinguish user identity from service identity.
Reference: MCP tools specification.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our Generative & Agentic AI programme — 3 months. Add practical GenAI, retrieval and agent-building skills to your existing toolkit.
Explore Generative & Agentic AI