0Pricing
MCP Academy · Lección

Validar y sanear todo

Trate las entradas proporcionadas por el modelo como no confiables.

Validar y sanear todo es una lección gratuita de MCP Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de MCP Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de MCP Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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. ✅

Preguntas frecuentes

¿La lección «Validar y sanear todo» es gratis?

Sí — el texto completo de «Validar y sanear todo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de MCP Academy, actualiza a CoddyKit PRO. El curso de MCP Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Validar y sanear todo»?

Trate las entradas proporcionadas por el modelo como no confiables. Practicas MCP Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar MCP Academy?

No se requiere experiencia previa. MCP Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Validar y sanear todo»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de MCP Academy?

Sí. Cada lección de MCP Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Amenazas específicas de MCP
  2. Acceso a herramientas con privilegios mínimos
  3. Validar y sanear todo
  4. Proteger las acciones destructivas
← Volver a MCP Academy