Skip to content
MCPA · Chapter 5 of 21 Day 3: Schemas and structured data

Day 3: Schemas and structured data

Goal: build tools with precise input and output schemas, deliver structured results, let the schema validate inputs, and describe tools with titles and annotations · Duration: approx. 2 h · Prerequisite: Day 2

Where we start

The response file from Day 2, Drill 1 is still in the directory:

# on cp1, in ~/mcpa/tag02
jq .error.code version-antwort.jsonl

Expected: -32022

If the file is missing, create it as in Day 2, Drill 1, steps 3 and 4. For today you only need the project ~/mcpa with the SDK.

Introduction

A tool is only as good as its description. The model sees exactly three things about a tool: name, description and input schema. The more precisely the schema says which values are allowed, the less often the model calls a tool incorrectly – and the more bad input the server catches before its code even runs. On the other side is the output schema: it tells the host what structure the result has, so that programs can process it reliably instead of parsing text.

Today you rebuild the Leitstand: it gets three tools with Pydantic models, enumerations, limits and patterns. You see which JSON Schema the SDK generates from them, what structured results look like, and how a pattern in the schema fends off an attempt to inject commands.

Today you learn:

  • what JSON Schema is and which keywords occur most often in MCP tools,
  • how the Python SDK generates a schema from types, Annotated, Field and Literal,
  • what outputSchema and structuredContent are and why there is additional text in content,
  • which content types a result may contain,
  • what title and the annotations readOnlyHint, destructiveHint, idempotentHint and openWorldHint mean – and why a client must not trust them blindly.

Background

The picture for today: the order form

Stay in the hotel. A tool is a bookable service of a provider – “wash a shirt”, “call a taxi”. So that the front desk (the host, more precisely the language model behind it) orders correctly, the provider supplies an order form:

  • The input schema is the form itself: fields with names, required fields, checkboxes with fixed options (“starch: light / normal” – an enumeration), limits (“1 to 20 shirts”) and writing rules (“letters and digits only” – a pattern).
  • Anyone who fills in the form wrong gets it back at the door, before anyone in the laundry lifts a finger. The schema is the provider’s bouncer.
  • The output schema is the template of the delivery note: the front desk knows in advance which fields come back.
  • structuredContent is the delivery note for reading into the hotel software, the text in content the same delivery note for reading out loud.
  • Annotations are warning stickers the provider puts on its own service: “changes nothing”, “careful, final”. The front desk reads them but believes them only from providers it trusts.

The terms

Term Meaning in the picture
Input schema (inputSchema) JSON Schema of a tool’s arguments order form
enum / Literal only fixed values allowed checkboxes
minimum/maximum, pattern limits, pattern “1 to 20”, writing rule
Output schema (outputSchema) JSON Schema of the result template of the delivery note
structuredContent result as JSON for programs delivery note for reading in
content (text) the same as text delivery note for reading out
Annotations hints about behavior, not trustworthy the provider’s stickers

Remember: The form stops wrong orders at the door. The front desk believes the provider’s stickers only if it trusts the provider.

JSON Schema

JSON Schema is a language for describing in JSON what other JSON data must look like. MCP uses it for tool inputs and outputs. Since 2026-07-28: if a schema specifies no version, it is JSON Schema 2020-12, and all keywords of that version are allowed. The most important ones:

Keyword Meaning Example
type data type string, integer, number, boolean, object, array, null
properties fields of an object with their schemas {"pfad": {"type": "string"}}
required required fields ["name"]
default value if the field is missing "/"
enum allowed values ["GB", "MB"]
minimum, maximum limits for numbers 1, 20
pattern, maxLength regular expression, maximum length for text ^[a-z]+$
items schema of an array’s elements {"type": "string"}
anyOf one of several types text or null
description explanation for human and model –

Two rules of the specification are exam-relevant: a tool’s inputSchema must describe an object ("type": "object"), even if the tool has no parameters; the specification then recommends {"type": "object", "additionalProperties": false}. And a client must not automatically fetch references ($ref) to network addresses – otherwise a server could make it retrieve arbitrary addresses.

From Python type to schema

The SDK generates schemas with Pydantic, the most widely used Python library for validating data. You write Python, Pydantic turns it into JSON Schema:

Python JSON Schema
x: str "type": "string", required field
x: int = 5 "type": "integer", "default": 5, not required
x: Literal["GB", "MB"] "enum": ["GB", "MB"]
x: Annotated[int, Field(ge=1, le=20)] "minimum": 1, "maximum": 20
x: Annotated[str, Field(pattern=…, max_length=64)] "pattern": …, "maxLength": 64
x: str \| None = None "anyOf": [{"type": "string"}, {"type": "null"}]
-> list[str] array of strings
-> Speicher (a class with BaseModel) object with the class’s fields

Annotated[Typ, Zusatz] from the standard library attaches additional information to a type; Field(…) from Pydantic is such information – with description, limits or pattern.

Structured results

A tools/call result can have two parts:

  • content – a list of content blocks for the model. Allowed are text (text), image (image, Base64 with mimeType), audio (audio), a link to a resource (resource_link with uri) and an embedded resource (resource). Each block may carry annotations (audience, priority, lastModified, Day 6).
  • structuredContent – the result as a JSON value, for programs. Since 2026-07-28 this may be any JSON value, not just an object. If a tool specifies an outputSchema, structuredContent must match it.

So that older clients that only know content can also do something with it, a tool with a structured result should additionally deliver the same as text in content. The SDK does this automatically.

Titles and annotations

Besides the technical name (letters, digits, _, -, ., at most 128 characters), a tool can have a title for humans – hosts show it in menus and prompts. On top of that come four annotations that describe behavior:

Annotation Meaning Default if not specified
readOnlyHint changes nothing false
destructiveHint can destroy or overwrite data (only meaningful if not read-only) true
idempotentHint repeated calls with the same arguments have no further effect false
openWorldHint talks to the outside world (internet, external systems) instead of a closed environment true

The defaults are deliberately cautious: a tool without annotations is considered modifying, destructive, non-repeatable and open to the outside. Hosts use the hints, for example, to avoid asking for consent every time for read-only tools. But: they are hints, not guarantees. The specification requires a client to treat annotations as untrusted unless they come from a server it trusts. A malicious server can advertise a delete tool as readOnlyHint: true (Day 11).

Drill 1: The Leitstand with schemas

Where you are: on cp1, in the directory ~/mcpa/tag03.

What you have afterwards: leitstand.py in version 1.1.0 with the tools speicher (storage), dienst (service) and groesste_dateien (largest files).

Step 1 – create the directory.

# on cp1
mkdir -p ~/mcpa/tag03
# on cp1
cd ~/mcpa/tag03

Step 2 – write the server. Create the file from scratch:

# on cp1, in ~/mcpa/tag03
nano leitstand.py
~/mcpa/tag03/leitstand.py new file
import shutil
import subprocess
from typing import Annotated, Literal

from mcp.server import MCPServer
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field

mcp = MCPServer(
    name="leitstand",
    version="1.1.0",
    instructions="Werkzeuge für den Betrieb der Labor-Rechner: Plattenplatz, Laufzeit, Dienste.",
)


class Speicher(BaseModel):
    """Belegung eines Dateisystems."""

    pfad: str
    gesamt: float = Field(description="Größe des Dateisystems in der gewählten Einheit")
    frei: float = Field(description="Freier Platz in der gewählten Einheit")
    einheit: Literal["GB", "MB"]
    belegt_prozent: float = Field(ge=0, le=100)


class Dienst(BaseModel):
    """Zustand eines systemd-Dienstes."""

    name: str
    aktiv: bool
    zustand: str = Field(description="ActiveState von systemd, z. B. active, inactive, failed")
    seit: str | None = Field(default=None, description="Zeitpunkt des letzten Zustandswechsels")


@mcp.tool(
    title="Plattenplatz",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def speicher(
    pfad: Annotated[str, Field(description="Verzeichnis, dessen Dateisystem geprüft wird")] = "/",
    einheit: Literal["GB", "MB"] = "GB",
) -> Speicher:
    """Liefert Größe, freien Platz und Belegung des Dateisystems unter einem Pfad."""
    teiler = 1024**3 if einheit == "GB" else 1024**2
    nutzung = shutil.disk_usage(pfad)
    return Speicher(
        pfad=pfad,
        gesamt=round(nutzung.total / teiler, 1),
        frei=round(nutzung.free / teiler, 1),
        einheit=einheit,
        belegt_prozent=round(nutzung.used / nutzung.total * 100, 1),
    )


@mcp.tool(
    title="Dienststatus",
    annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
)
def dienst(
    name: Annotated[str, Field(pattern=r"^[a-zA-Z0-9@._-]+$", max_length=64, description="Name der systemd-Unit, z. B. ollama")],
) -> Dienst:
    """Liefert den Zustand eines systemd-Dienstes auf diesem Rechner."""
    ausgabe = subprocess.run(
        ["systemctl", "show", name, "--property=ActiveState,StateChangeTimestamp"],
        capture_output=True, text=True, check=True,
    ).stdout
    werte = dict(zeile.split("=", 1) for zeile in ausgabe.strip().splitlines())
    return Dienst(
        name=name,
        aktiv=werte["ActiveState"] == "active",
        zustand=werte["ActiveState"],
        seit=werte.get("StateChangeTimestamp") or None,
    )


@mcp.tool(title="Größte Dateien", annotations=ToolAnnotations(read_only_hint=True))
def groesste_dateien(
    verzeichnis: str,
    anzahl: Annotated[int, Field(ge=1, le=20)] = 5,
) -> list[str]:
    """Listet die größten Dateien unterhalb eines Verzeichnisses, größte zuerst."""
    ausgabe = subprocess.run(
        ["find", verzeichnis, "-xdev", "-type", "f", "-printf", "%s %p\n"],
        capture_output=True, text=True,
    ).stdout
    zeilen = sorted(ausgabe.splitlines(), key=lambda z: int(z.split(" ", 1)[0]), reverse=True)
    return [z.split(" ", 1)[1] for z in zeilen[:anzahl]]


if __name__ == "__main__":
    mcp.run()

The server has grown. Go through it section by section:

Imports. subprocess starts other programs (here systemctl and find). Annotated and Literal come from the standard library typing. ToolAnnotations is the class for the annotations. BaseModel and Field come from Pydantic, which was installed with the SDK.

The class Speicher. A class that inherits from BaseModel describes an object with fixed fields (pfad path, gesamt total, frei free, einheit unit, belegt_prozent percent used). Each line name: Typ is a field. Field(description=…) attaches a description, Field(ge=0, le=100) limits (ge = greater or equal; le = less or equal). The class docstring becomes the description of the whole object. Because speicher returns this class (-> Speicher), it becomes the output schema.

The class Dienst. seit: str | None = Field(default=None, …) means: text or nothing, nothing by default – so the field is optional. The fields are aktiv (active), zustand (state) and seit (since).

The tool speicher.

  • @mcp.tool(title=…, annotations=…) – this time with arguments: a title for humans and the annotations. read_only_hint=True says “changes nothing”, open_world_hint=False “talks only to this machine”. The SDK writes the names in Python style; in JSON they are called readOnlyHint and openWorldHint.
  • pfad: Annotated[str, Field(description=…)] = "/" – a string with a description and default value.
  • einheit: Literal["GB", "MB"] = "GB" – only these two values are allowed.
  • In the body, teiler (divisor) converts the unit, shutil.disk_usage returns total, used and free in bytes, and Speicher(…) builds the result.

The tool dienst.

  • name has no default value, so it is required. pattern=r"^[a-zA-Z0-9@._-]+$" allows only letters, digits and the characters @ . _ - – exactly what occurs in systemd unit names. r"…" is a Python raw string in which \ is not treated specially. max_length=64 limits the length.
  • subprocess.run([…], capture_output=True, text=True, check=True) starts systemctl show <name> --property=ActiveState,StateChangeTimestamp. systemctl show prints properties of a unit as lines Name=Value; --property= selects the two you need. capture_output=True captures the output, text=True returns it as text instead of bytes, check=True raises an error if systemctl exits with an error code.
  • The command line is a list – each argument a separate element. As a result nothing is interpreted by a shell; a name like ollama; rm -rf / would simply be a strange unit name. The pattern in the schema catches it even earlier (Drill 4).
  • dict(zeile.split("=", 1) for zeile in …) turns the lines into a dictionary; split("=", 1) splits only at the first =.

The tool groesste_dateien.

  • anzahl: Annotated[int, Field(ge=1, le=20)] = 5 – an integer (anzahl, count) between 1 and 20.
  • find <directory> -xdev -type f -printf "%s %p\n" lists files: -xdev stays on the same file system, -type f regular files only, -printf "%s %p\n" prints size in bytes and path.
  • sorted(…, key=…, reverse=True) sorts by the number at the start of the line, largest first.
  • The return type list[str] becomes an array of strings.

Check:

# on cp1, in ~/mcpa/tag03
uv run python -c "import leitstand; print(leitstand.mcp.name)"

Expected: leitstand

Remember: You write Python types, Pydantic turns them into the form: Literal → checkboxes, Field(ge, le) → limits, Field(pattern) → writing rule, BaseModel → delivery-note template.

Save your progress? Sign up for free

Drill 2: Reading the generated schema

Where you are: on cp1, in ~/mcpa/tag03.

What you have afterwards: the file anfragen.jsonl with seven requests and the responses in t.out.

Today you write all requests into one file and then evaluate the responses one by one.

Step 1 – Seven orders. Three are correct, three violate the form, and the first one asks for the tool list:

# on cp1, in ~/mcpa/tag03
nano anfragen.jsonl
~/mcpa/tag03/anfragen.jsonl new file
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"speicher","arguments":{"einheit":"MB"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"dienst","arguments":{"name":"ollama"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"groesste_dateien","arguments":{"verzeichnis":"/var/log","anzahl":3},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"speicher","arguments":{"einheit":"TB"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"dienst","arguments":{"name":"ollama; rm -rf /"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"groesste_dateien","arguments":{"verzeichnis":"/etc","anzahl":50},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}

Step 2 – Send them. The responses end up in t.out:

# on cp1, in ~/mcpa/tag03
(cat anfragen.jsonl; sleep 5) | uv run python leitstand.py 2>/dev/null > t.out
  • sleep 5 – one second more than yesterday, because find in request 4 needs some time.

Step 3 – Are all responses there?

# on cp1, in ~/mcpa/tag03
wc -l t.out
  • wc -l counts the lines of the file – one line per response.

Expected:

7 t.out

Look at the order of the responses with jq -c .id t.out. It is not necessarily that of the requests: the server processes requests concurrently, and the slow find in request 4 can finish after the fast rejections 5 to 7. That is exactly why each response carries the id of its request.

Step 4 – The form of speicher. Now the input schema:

# on cp1, in ~/mcpa/tag03
jq 'select(.id==1) | .result.tools[0].inputSchema' t.out

.result.tools[0] is the first tool in the list, .inputSchema its input schema.

Expected:

{
  "type": "object",
  "properties": {
    "pfad": {
      "default": "/",
      "description": "Verzeichnis, dessen Dateisystem geprüft wird",
      "title": "Pfad",
      "type": "string"
    },
    "einheit": {
      "default": "GB",
      "enum": [
        "GB",
        "MB"
      ],
      "title": "Einheit",
      "type": "string"
    }
  },
  "title": "speicherArguments"
}

Compare with the Python code: the description from Field appears under pfad, Literal became enum. Both fields have a default value, so there is no required. Pydantic built title from the names; it is meant for humans and has no significance for validating the values.

Step 5 – The delivery-note template. And the output schema:

# on cp1, in ~/mcpa/tag03
jq -c 'select(.id==1) | .result.tools[0].outputSchema | {required, belegt: .properties.belegt_prozent}' t.out

Expected:

{"required":["pfad","gesamt","frei","einheit","belegt_prozent"],"belegt":{"maximum":100,"minimum":0,"title":"Belegt Prozent","type":"number"}}

All five fields of the class Speicher are required, and belegt_prozent carries the limits 0 and 100 from Field(ge=0, le=100). With this, a host knows exactly what comes back before the first call.

Remember: tools/list shows the form (inputSchema) and delivery-note template (outputSchema) of every service before anyone orders. Responses can arrive in a different order – the id matches them up.

Save your progress? Sign up for free

Drill 3: Structured results

Where you are: on cp1, in ~/mcpa/tag03.

What you have afterwards: the three successful calls in structured and in text form.

Step 1 – The delivery notes for reading in.

# on cp1, in ~/mcpa/tag03
jq -c 'select(.id==2 or .id==3) | .result.structuredContent' t.out
  • or combines two conditions: responses with id 2 or 3.

Expected (your numbers and times will be different):

{"pfad":"/","gesamt":78284.0,"frei":61348.9,"einheit":"MB","belegt_prozent":21.6}
{"name":"ollama","aktiv":true,"zustand":"active","seit":"Sat 2026-11-28 09:28:50 UTC"}

Step 2 – The same delivery note for reading out. The text block of response 3:

# on cp1, in ~/mcpa/tag03
jq -r 'select(.id==3) | .result.content[0].text' t.out

Expected:

{
  "name": "ollama",
  "aktiv": true,
  "zustand": "active",
  "seit": "Sat 2026-11-28 09:28:50 UTC"
}

structuredContent is the object according to the output schema. The text block in content contains the same as formatted JSON – for clients and models that only read text.

Step 3 – A list as result. With a list the SDK behaves a little differently:

# on cp1, in ~/mcpa/tag03
jq -c 'select(.id==4) | .result | {bloecke: (.content | length), structuredContent}' t.out

length counts the elements of a list.

Expected (shortened; your files will be different):

{"bloecke":3,"structuredContent":{"result":["/var/log/haproxy.log.1","/var/log/journal/c184f4bf…/system@b7dd5bba…-0000000000367b86-000660f9dcb2237d.journal","/var/log/journal/c184f4bf…/system@b7dd5bba…-00000000003395cd-000660f9cc6fea75.journal"]}}

For each list element there is a separate text block in content (bloecke = blocks), and structuredContent wraps the list in an object with the field result – just as the outputSchema describes it.

Remember: One result, two versions: structuredContent for programs, the same content as text in content for models and older clients.

Save your progress? Sign up for free

Drill 4: The schema as bouncer

Where you are: on cp1, in ~/mcpa/tag03.

What you have afterwards: three rejected calls – one of them an attack attempt.

You read the three rejected orders one by one. The messages can be longer than shown here – in Day 2, Drill 4 there was another line with a link to the Pydantic docs. Below are the first three lines of each.

Step 1 – Response 5: unit TB.

# on cp1, in ~/mcpa/tag03
jq -r 'select(.id==5) | .result.content[0].text' t.out

Expected (excerpt – the first three lines):

Error executing tool speicher: 1 validation error for speicherArguments
einheit
  Input should be 'GB' or 'MB' [type=literal_error, input_value='TB', input_type=str]

Step 2 – Response 6: a service name with an appended command.

# on cp1, in ~/mcpa/tag03
jq -r 'select(.id==6) | .result.content[0].text' t.out

Expected (excerpt – the first three lines):

Error executing tool dienst: 1 validation error for dienstArguments
name
  String should match pattern '^[a-zA-Z0-9@._-]+$' [type=string_pattern_mismatch, input_value='ollama; rm -rf /', input_type=str]

Step 3 – Response 7: 50 files.

# on cp1, in ~/mcpa/tag03
jq -r 'select(.id==7) | .result.content[0].text' t.out

Expected (excerpt – the first three lines):

Error executing tool groesste_dateien: 1 validation error for groesste_dateienArguments
anzahl
  Input should be less than or equal to 20 [type=less_than_equal, input_value=50, input_type=int]

None of the three calls reached the tool’s code – Pydantic rejected them based on the schema, and the SDK turned that into execution errors with isError: true:

  • TB is not in the enumeration,
  • ollama; rm -rf / doesn’t match the pattern – a typical attempt to inject a second command via an argument (command injection),
  • 50 is above the limit of 20.

This is the most important idea of the day: the input schema is a server’s first line of defense. The model that calls a tool can be influenced by texts from the internet, from documents or from other tools. Every value a tool receives is therefore untrusted input – just like a form field on a web page. Tight schemas, patterns and limits reduce the attack surface; they do not replace validation in the code (Day 11).

Remember: The input schema is the bouncer: anything that doesn’t fit the form never reaches the code. Every argument is untrusted input.

Save your progress? Sign up for free

Drill 5: Titles and annotations

Where you are: on cp1, in ~/mcpa/tag03.

What you have afterwards: an overview of the annotations of all three tools.

# on cp1, in ~/mcpa/tag03
jq -c 'select(.id==1) | .result.tools[] | {name, title, annotations}' t.out

.tools[] – the square brackets without a number – passes on each element of the list individually.

Expected:

{"name":"speicher","title":"Plattenplatz","annotations":{"openWorldHint":false,"readOnlyHint":true}}
{"name":"dienst","title":"Dienststatus","annotations":{"openWorldHint":false,"readOnlyHint":true}}
{"name":"groesste_dateien","title":"Größte Dateien","annotations":{"readOnlyHint":true}}

Annotations that are not set are missing from the output – then the cautious defaults from the background apply. For groesste_dateien, openWorldHint is missing, so true applies. That is wrong, because this tool also stays on the machine; a host would treat it more cautiously than necessary. The challenge doesn’t fix this – but think about how you would do it.

Remember: Missing stickers mean “careful”: changing, destructive, not repeatable, open to the outside. Stickers that are set are hints, not promises.

Save your progress? Sign up for free

If it doesn’t work

  • ModuleNotFoundError: No module named 'pydantic': you are not starting the server with uv run but with the system Python. Pydantic lives in the project’s virtual environment.
  • t.out has fewer than 7 lines: on a full file system find takes longer than the pause. Increase sleep 5.
  • dienst reports "aktiv":false,"zustand":"inactive" for a typo: systemctl show has no error for unknown units – for gibtsnicht it returns ActiveState=inactive and exits with exit code 0. So the tool cannot distinguish “stopped” from “doesn’t exist”. Check the name with systemctl list-units --all | grep <name>. A better version would additionally query the LoadState property (not-found for unknown units).
  • The list from groesste_dateien is shorter than expected: the server runs as your user and skips directories it is not allowed to read. capture_output=True captures the messages from find; they don’t appear anywhere.

Exercise: A tool without structure (15 min)

Copy the server to uebung.py and add a tool rechnername (machine name) with the title “Rechnername” that returns the machine’s name as text (socket.gethostname()) but has no output schema. Hint: @mcp.tool(structured_output=False). Compare the tool list and result with speicher.

Solution

In uebung.py, add import socket at the top and the tool before if __name__:

@mcp.tool(title="Rechnername", structured_output=False)
def rechnername() -> str:
    """Liefert den Namen dieses Rechners."""
    return socket.gethostname()

structured_output=False turns off the automatic output schema even though the function has a return type. Send tools/list and a call with empty arguments ("arguments":{}).

Expected (tool entry and result):

{"description":"Liefert den Namen dieses Rechners.","inputSchema":{"type":"object","properties":{},"title":"rechnernameArguments"},"name":"rechnername","title":"Rechnername"}
{"content":[{"text":"cp1","type":"text"}],"isError":false,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"leitstand","version":"1.1.0"}}}

No outputSchema, no structuredContent – only text. Despite having no parameters, the input schema is an object ("type": "object"), as the specification requires. The SDK does not set the recommended "additionalProperties": false.

Save your progress? Sign up for free

Challenge: Restricting paths (10 min)

A freely selectable path allows probing arbitrary parts of the file system. In uebung.py, change the tool speicher so that only /, /var and /home are allowed, and show that /etc is rejected.

Solution

Replace the line with pfad: Annotated[…] = "/", with:

    pfad: Literal["/", "/var", "/home"] = "/",

In the schema this becomes {"default":"/","enum":["/","/var","/home"],"title":"Pfad","type":"string"}, and a call with "pfad":"/etc" returns:

Error executing tool speicher: 1 validation error for speicherArguments
pfad
  Input should be '/', '/var' or '/home' [type=literal_error, input_value='/etc', input_type=str]

An enumeration is the strictest form of restriction: the model already sees the allowed values in the schema and doesn’t have to guess. Where an enumeration is too narrow, patterns help – or a check in the code that resolves the path with os.path.realpath and compares it against a list of allowed roots.

Save your progress? Sign up for free

Checkpoint

# on cp1, in ~/mcpa/tag03
jq -r 'select(.id==1) | .result.tools[].name' t.out

Expected:

speicher
dienst
groesste_dateien
# on cp1, in ~/mcpa/tag03
jq -s -c 'sort_by(.id)[] | [.id, .result.isError]' t.out

-s (slurp) reads all lines as one list, sort_by(.id) sorts them by identifier, [] outputs them individually again.

Expected:

[1,null]
[2,false]
[3,false]
[4,false]
[5,true]
[6,true]
[7,true]

Exam questions

1. A tool has an outputSchema. What applies to its result?

    1. structuredContent must conform to the schema.
    1. content must be empty.
    1. The result must not contain any text.
    1. The client must reload the schema before every call.

2. A tool has no parameters. Which inputSchema does the specification recommend?

    1. null
    1. {}
    1. {"type": "object", "additionalProperties": false}
    1. {"type": "array"}

3. A server reports the annotation readOnlyHint: true for the tool daten_loeschen (delete data). How should a host behave?

    1. It calls it without asking, because it only reads.
    1. It treats the annotation as unreliable as long as it doesn’t trust the server.
    1. It rejects the server, because annotations are forbidden.
    1. It automatically sets destructiveHint to false.

4. Which assumption applies to a tool without annotations?

    1. read-only, harmless
    1. modifying, potentially destructive, not idempotent, open to the outside
    1. idempotent and closed
    1. none – the host must not call it

5. Why should a tool with a structured result additionally deliver the same as text in content?

    1. because structuredContent may only contain numbers
    1. for clients and models that only evaluate content
    1. because JSON Schema requires text
    1. so that the result can be cached

Solutions

  1. A. With an outputSchema, structuredContent must match; text in content is additionally desirable (B and C are wrong).
  2. C. The input schema must be an object; additionalProperties: false explicitly says that no fields are expected.
  3. B. Annotations are hints and are considered untrusted as long as the server isn’t trusted. Calling supposedly read-only tools without asking (A) would be fatal here.
  4. B. The defaults are the most cautious: readOnlyHint false, destructiveHint true, idempotentHint false, openWorldHint true.
  5. B. Backward compatibility: older clients only know content.

Interview Note

“How do you protect an MCP server against malicious arguments?” – In layers. First a tight input schema: enumerations instead of free text, patterns, length and number limits. Then in the code: never pass arguments to a shell, start commands as a list, resolve paths and check them against allowed roots. And finally permissions: the server runs with as few privileges as possible. The schema helps twice – it keeps out nonsense and at the same time shows the model what is valid.

Enterprise Note

Output schemas are a contract. As soon as other teams or automations rely on structuredContent, removing or renaming a field is a breaking change. So version servers visibly (version in MCPServer), only add fields instead of changing them, and introduce new tool names when behavior changes fundamentally. Annotations belong in the approval review: whoever sets readOnlyHint: true must be able to prove it.

Summary

  • Tools describe inputs and outputs with JSON Schema (default 2020-12); the inputSchema is always an object.
  • The Python SDK generates schemas from types: Literal → enum, Field(ge, le) → minimum/maximum, Field(pattern, max_length) → pattern/maxLength, BaseModel → object with required fields.
  • An outputSchema requires matching structuredContent; in addition, the result belongs as text in content. Content types: text, image, audio, resource_link, resource.
  • Inputs that don’t match the schema don’t reach the code – the schema is the first line of defense against malicious arguments.
  • title is for humans; the annotations readOnlyHint, destructiveHint, idempotentHint, openWorldHint are hints with cautious defaults and are considered untrusted as long as the server isn’t trusted.

Commands at a glance

For review: all commands and SDK calls of this day with the parameters you used.

Command / call What it does Parameters
class X(BaseModel): feld: typ describes an object; as a return type it becomes the output schema docstring = description
Field(description=…, ge=…, le=…, pattern=…, max_length=…, default=…) additional information for a field ge/le limits, pattern pattern
Annotated[typ, Field(…)] attaches Field to a parameter type –
Literal["a", "b"] allows only these values (enum) –
typ \| None = None optional field (anyOf with null) –
@mcp.tool(title=…, annotations=ToolAnnotations(…), structured_output=…) tool with title, hints, with/without output schema read_only_hint, destructive_hint, idempotent_hint, open_world_hint
subprocess.run([…], capture_output=True, text=True, check=True) starts a program without a shell list = one element per argument
systemctl show <unit> --property=A,B properties of a unit as Name=Wert --property selection
find <dir> -xdev -type f -printf "%s %p\n" files with size -xdev same file system, -type f files
nano <file> create the server or requests as a file –
wc -l <file> counts lines –
jq '… \| .result.tools[0].inputSchema' schema of the first tool [0] first element
jq -c '.result.tools[] \| {name, title, annotations}' one line per tool [] each element
jq 'select(.id==2 or .id==3)' select several responses or, and
jq '(.content \| length)' number of elements length
jq -s 'sort_by(.id)[]' read all responses and sort by id -s slurp

Contents

More