AI Hints
Home›MCP Tutorial›Auth and Validation
MCP · Lesson 98 of 120

Validating Input

Never trust arguments.

⏱ 2 min read▶ Video at 1:27:51🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

Tool arguments come from a model, and the model may have been tricked. So never trust them. Check every argument, before using it.

Validating Input
From the video: Validating Input
  • Arguments come from a model
  • It may be tricked
  • Check everything

Rules in the schema

Field adds rules to each argument. Order numbers must be between one thousand and ninety nine thousand. Notes are limited to two hundred characters. Run it. The good call works, and the bad ones are rejected before our code runs.

validate.pypython
from typing import Annotated
from pydantic import Field
from mcp.server.mcpserver import MCPServer
from tester import call

mcp = MCPServer("northwind")

@mcp.tool()
def add_note(order_id: Annotated[int, Field(ge=1000, le=99999)],
             note: Annotated[str, Field(max_length=200)]) -> str:
    """Add a short note to an order."""
    return f"note added to {order_id}"

for args in [{"order_id": 1042, "note": "Leave at the door"},
             {"order_id": -1, "note": "hi"},
             {"order_id": 1042, "note": "x" * 500}]:
    r = call(mcp, "add_note", args)
    lines = r.content[0].text.splitlines()
    print("ERROR |", lines[1]) if r.is_error else print("OK    |", lines[0])
Output
OK    | note added to 1042
ERROR | order_id
ERROR | note
Also uses tester.py
import asyncio
from mcp import Client

def call(server, tool, args=None, **options):
    async def go():
        async with Client(server, **options) as client:
            return await client.call_tool(tool, args or {})
    return asyncio.run(go())

def tools(server):
    async def go():
        async with Client(server) as client:
            return (await client.list_tools()).tools
    return asyncio.run(go())

Beyond the schema

Also check that the user may see this order. Use parameters in SQL, never string building. Resolve file paths, and keep them inside one folder. And refuse anything unexpected, with a clear error.

keyvalue
Ownershipmay they see it?
SQLparameters
Pathsresolve and check
Unexpectedrefuse

Summary

Never trust arguments. Use schema rules, and check ownership, SQL, and paths in code. Next, a security checklist.

Key takeaways
  • Field rules
  • SQL parameters
  • Path checks
Next up: Security Checklist — before you ship