0Pricing
MCP Academy · Aula

Validar e higienizar tudo

Trate as entradas fornecidas pelo modelo como não confiáveis.

Validar e higienizar tudo é 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.

Inputs Are Untrusted

Every argument the model passes to a tool is untrusted input. The model may be honest, but its arguments can be shaped by injected text, so verify them. 🔎

Validate Before You Act

Check shape, type, and range before a tool does anything real. Validation at the door turns a vague bad call into a clear, safe rejection.

Let Pydantic Help

Type hints and Pydantic models reject malformed arguments before your code runs. This input must be a positive int, so a string or a negative value is refused early.

from pydantic import Field

@mcp.tool()
def get_page(n: int = Field(gt=0, le=100)) -> str:
    return load(n)

Bound the Values

Cap sizes, lengths, and counts. A limit field on a query keeps the model from asking for a million rows and turning one call into a denial of service.

Sanitize for the Destination

Sanitizing means making input safe for where it lands. A value safe in a log can be dangerous in a shell, a SQL string, or a file path.

Never Build SQL by Hand

String-concatenated SQL invites injection. Use parameterized queries so the database treats model input strictly as a value, never as executable code.

cur.execute(
    "SELECT * FROM orders WHERE id = ?",
    (order_id,),
)

Guard the Shell

If a tool runs a command, never paste arguments into a shell string. Pass an argument list and avoid shell parsing so input cannot smuggle in extra commands.

Resolve and Confine Paths

For file tools, resolve the path to its canonical form and confirm it stays inside your allowed root. Reject anything with a path traversal like dot-dot.

p = (ROOT / name).resolve()
if not p.is_relative_to(ROOT):
    raise ValueError("path escapes root")

Fail Closed

When input does not pass a check, stop and return a clear error. Failing closed beats guessing, because a wrong guess can be exactly what an attacker wants.

Do Not Trust Tool Output Either

Data your tool returns can carry injected instructions onward. Where it matters, label or escape fetched content so the model treats it as data, not orders.

Validate at Every Boundary

Check input as it enters your tool and again before it hits a database, file, or API. Each boundary is a fresh chance to catch something unsafe.

Quick Check

Which choice best protects a SQL query from injection?

Recap

Treat all tool inputs as untrusted: validate types and ranges, sanitize for the destination, confine paths, and fail closed. Distrust the input. ✅

Perguntas Frequentes

A aula “Validar e higienizar tudo” é grátis?

Sim — o texto completo de “Validar e higienizar tudo” é 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 e higienizar tudo”?

Trate as entradas fornecidas pelo modelo como não confiáveis. 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 e higienizar tudo”?

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

  1. Ameaças exclusivas do MCP
  2. Acesso às ferramentas com menor privilégio
  3. Validar e higienizar tudo
  4. Proteger ações destrutivas
← Voltar para MCP Academy