Validar entradas antes de agir
Rejeite argumentos inválidos com mensagens claras.
Validar entradas antes de agir é uma aula grátis de MCP Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MCP Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MCP Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Trust Nothing the Model Sends
The arguments your tool receives come from an AI, which can guess. Validate every input before you touch a file, a database, or an API.
Check First, Act Second
Run your checks at the very top of the function. Confirm the input is sane before doing any real or irreversible work.
@mcp.tool()
def set_age(age: int) -> str:
if age < 0 or age > 130:
raise ValueError("age out of range")Reject With a Clear Reason
When input fails a check, say exactly why. A precise message lets the model send a corrected value on the next attempt.
Type Hints Catch a Lot
Your parameter hints become the tool schema, so basic type mismatches are caught before your code even runs. Lean on them first.
@mcp.tool()
def repeat(text: str, times: int) -> str:
return text * timesHints Are Not Enough
Types alone cannot express ranges, formats, or allowed values. You still validate that a count is positive or a status is one you accept.
Bound Your Ranges
Guard numeric inputs against extremes. A limit on page size or loop count stops the model from accidentally overloading your server.
if limit > 100:
raise ValueError("limit must be 100 or less")Whitelist Allowed Values
For fixed choices, check membership instead of trusting free text. A whitelist rejects anything outside the options you actually support.
if status not in {"open", "closed"}:
raise ValueError("status must be open or closed")Sanitize Paths and Queries
Model input that becomes a file path or SQL query is dangerous. Sanitize it so a stray .. or quote cannot reach beyond what you intend.
Required Fields Must Exist
Confirm that anything mandatory is actually present and non-empty. An early guard beats a confusing failure deep inside your logic.
if not query.strip():
raise ValueError("query cannot be empty")Validation Doubles as Docs
Clear checks teach the model your rules. After one rejection it learns the format and sends valid input the rest of the session.
Fail Before Side Effects
The golden rule: never start an irreversible action until every input has passed. Validate up front so half-done writes never happen.
Quick Check
Why validate inputs before performing the tool's real work?
Recap
Treat model input as untrusted: validate types, ranges, and choices at the top, reject with clear reasons, and never act before checks pass. ✅
Perguntas Frequentes
A aula “Validar entradas antes de agir” é grátis?
Sim — o texto completo de “Validar entradas antes de agir” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MCP Academy, atualize para CoddyKit PRO. O curso de MCP Academy inclui 4 aulas no total.
O que vou aprender em “Validar entradas antes de agir”?
Rejeite argumentos inválidos com mensagens claras. Você pratica MCP Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar MCP Academy?
Nenhuma experiência prévia é necessária. MCP Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Validar entradas antes de agir”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de MCP Academy?
Sim. Cada aula de MCP Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Erros de ferramentas visíveis para o modelo
- Erros de protocolo e falhas de ferramentas
- Validar entradas antes de agir
- Falhar com segurança, sem nunca travar