MCP Structured Outputs and Tool Annotations
Define typed MCP tool responses with outputSchema and structuredContent. Configure safety annotations (readOnlyHint, destructiveHint) and resource_link.
Generate & Validate Multi-Client MCP Config
One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.
MCP Structured Tool Outputs, Safety Annotations, and Resource Links
Early Model Context Protocol servers returned every tool response as an untyped string inside content: [{ type: "text", text: "..." }]. Downstream client workflows had to regex-parse prose or parse arbitrary JSON blobs without a machine-readable contract, while IDE hosts treated every tool with the same conservative security policy—forcing developers to manually approve harmless read-only inspections because the client had no standardized signal distinguishing a SELECT health check from a destructive DELETE operation.
Modern MCP tool definitions close both gaps at the protocol level using three primitives: outputSchema with structuredContent for validated typed payloads, annotations (ToolAnnotations) for behavioral risk signaling, and resource_link content blocks to reference large artifacts without blowing up the LLM context window.
1. Architecture of Typed Tool Execution
When a host connects and sends tools/list (with per-request _meta on 2026-07-28), each tool definition can publish three separate contracts: what arguments the model must supply (inputSchema), how the host should classify the tool's risk profile (annotations), and the exact JSON Schema of the returned payload (outputSchema).
Notice the distinction between LLM structured outputs (constraining tokens generated by a foundation model) and MCP structured tool outputs: outputSchema constrains data produced by your MCP server, validated at runtime by the SDK before the JSON-RPC frame leaves the server process.
2. outputSchema and structuredContent Wire Format
Advertising outputSchema in tools/list
A tool declares outputSchema alongside inputSchema using JSON Schema (2020-12 by default, or the dialect named by $schema). The root is not limited to objects: the current MCP tools specification (opens in a new tab) allows any JSON Schema 2020-12 keywords and shows array-rooted examples. An object root is the common case:
{
"name": "inspect_cluster_quotas",
"title": "Cluster Quota Inspector",
"description": "Return CPU, memory, and PVC usage metrics for a Kubernetes namespace.",
"inputSchema": {
"type": "object",
"properties": {
"namespace": { "type": "string", "minLength": 1 }
},
"required": ["namespace"]
},
"outputSchema": {
"type": "object",
"properties": {
"namespace": { "type": "string" },
"cpuUsedMillicores": { "type": "integer" },
"cpuLimitMillicores": { "type": "integer" },
"memoryUtilizationPct": { "type": "number" },
"healthy": { "type": "boolean" }
},
"required": [
"namespace",
"cpuUsedMillicores",
"cpuLimitMillicores",
"memoryUtilizationPct",
"healthy"
]
},
"annotations": {
"title": "Inspect Cluster Quotas",
"readOnlyHint": true,
"destructiveHint": false,
"idempotentHint": true,
"openWorldHint": false
}
}Returning structuredContent in tools/call
When a tool defines an outputSchema, the server MUST return a conforming JSON value inside structuredContent. The specification (opens in a new tab) defines structured content as "any JSON value (object, array, string, number, boolean, or null) that conforms to the tool's outputSchema if one is defined." For backward compatibility with legacy clients that do not yet read structuredContent, the MCP specification says a tool returning structured content SHOULD also serialize the JSON payload as a text block in content:
{
"jsonrpc": "2.0",
"id": 12,
"result": {
"resultType": "complete",
"content": [
{
"type": "text",
"text": "{\"namespace\":\"payments\",\"cpuUsedMillicores\":1420,\"cpuLimitMillicores\":4000,\"memoryUtilizationPct\":61.4,\"healthy\":true}"
}
],
"structuredContent": {
"namespace": "payments",
"cpuUsedMillicores": 1420,
"cpuLimitMillicores": 4000,
"memoryUtilizationPct": 61.4,
"healthy": true
}
}
}This dual-field pattern guarantees strict programmatic parsing for workflow engines, LangChain/LangGraph adapters, and IDE UIs while keeping plain-text reasoning models compatible without breaking older hosts.
3. Tool Annotations and the Behavioral Risk Vocabulary
The optional annotations block attaches standardized behavioral metadata to a tool definition so MCP hosts can adjust confirmation UX, auto-approval rules, and retry policies:
| Annotation Field | Type | Spec Default | Operational Meaning |
|---|---|---|---|
title | string | None | Human-readable display label shown in host approval modals instead of snake_case tool names. |
readOnlyHint | boolean | false | true indicates the tool makes zero persistent state changes to its environment. |
destructiveHint | boolean | true | Applies only when readOnlyHint is false. true means updates may delete or overwrite data; false indicates strictly additive writes. |
idempotentHint | boolean | false | Applies only when readOnlyHint is false. true confirms repeated calls with identical arguments produce no extra side effects. |
openWorldHint | boolean | true | true means the tool interacts with external, unbounded systems (public web search, third-party SaaS); false indicates a closed internal boundary. |
Trust Boundary: Advisory Hints Only
Clients MUST consider tool annotations to be untrusted unless they come from trusted servers; the schema notes that all annotation properties are hints and that clients should never make tool-use decisions based on annotations received from untrusted servers — so they are not access control. A malicious or buggy remote server could mark a drop_table tool with readOnlyHint: true. Production hosts use annotations to improve user ergonomics on vetted internal servers (for example, auto-approving readOnlyHint: true lookups while highlighting destructiveHint: true actions in red), while enforcing actual authorization via OAuth scopes, filesystem sandboxing, and database read-only roles. For database and OS-level hardening, review our MCP Security Best Practices guide.
4. Avoiding Context Overflow with resource_link Content Blocks
Even with strict outputSchema contracts, some tools generate multi-megabyte artifacts—such as full SQL EXPLAIN ANALYZE traces, Terraform state diffs, or compiler build logs. Inlining 50 KB of log text inside content or structuredContent wastes input tokens across every subsequent turn in the session.
MCP supports the resource_link block inside CallToolResult.content, allowing a tool to return a compact summary in structuredContent paired with a URI pointer to the full artifact:
{
"type": "resource_link",
"uri": "internal://migrations/logs/mig_20261121_04",
"name": "Migration Execution Log",
"description": "Full PostgreSQL DDL execution trace and lock wait timings (48 KB)",
"mimeType": "text/plain"
}When the model needs to inspect only summary metrics (appliedCount, status), it reads a short structuredContent summary rather than the full log (token counts are model-dependent). If a step fails and the model needs the detailed stack trace, it explicitly reads internal://migrations/logs/mig_20261121_04 via resources/read on demand.
5. Production TypeScript Implementation (registerTool)
Install the official TypeScript SDK and Zod:
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node tsxThe server below registers two tools and a companion resource handler:
- ▸
check_service_health: DeclaresreadOnlyHint: true,openWorldHint: false, and an explicit ZodoutputSchema, returning compile-time checkedstructuredContent. - ▸
apply_schema_migration: DeclaresreadOnlyHint: false,destructiveHint: false, andidempotentHint: true, returning typed migration metadata plus aresource_linkpointing to the stored log resource.
// structured-tools-server.ts
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "ops-typed-server",
version: "2.1.0",
});
// In-memory log store surfaced via resources/read for resource_link targets
const migrationLogs = new Map<string, string>();
server.registerResource(
"migration-log",
new ResourceTemplate("internal://migrations/logs/{logId}", { list: undefined }),
{
title: "Migration Execution Log",
description: "Detailed DDL trace produced by apply_schema_migration",
mimeType: "text/plain",
},
async (uri, { logId }) => {
const key = String(logId);
const body = migrationLogs.get(key) ?? `No migration log found for ${key}`;
return {
contents: [
{
uri: uri.href,
mimeType: "text/plain",
text: body,
},
],
};
}
);
// 1. Read-only tool with strict outputSchema + structuredContent
server.registerTool(
"check_service_health",
{
title: "Check Service Health",
description: "Inspect latency, error rate, and pool saturation for an internal service.",
inputSchema: {
service: z.string().min(1).describe("Microservice name"),
region: z.enum(["us-east-1", "eu-west-1"]).default("us-east-1"),
},
outputSchema: {
service: z.string(),
region: z.string(),
status: z.enum(["healthy", "degraded", "down"]),
p95LatencyMs: z.number(),
errorRatePct: z.number(),
},
annotations: {
title: "Check Service Health",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
},
async ({ service, region }) => {
const metrics = {
service,
region,
status: "healthy" as const,
p95LatencyMs: 18.4,
errorRatePct: 0.02,
};
return {
content: [
{
type: "text",
text: JSON.stringify(metrics),
},
],
structuredContent: metrics,
};
}
);
// 2. Idempotent additive write tool returning structuredContent + resource_link
server.registerTool(
"apply_schema_migration",
{
title: "Apply Schema Migration",
description: "Run an idempotent SQL migration file and emit a resource_link to the full DDL trace.",
inputSchema: {
migrationId: z.string().regex(/^\d{4}_[a-z0-9_]+$/).describe("Migration identifier"),
dryRun: z.boolean().default(false),
},
outputSchema: {
migrationId: z.string(),
dryRun: z.boolean(),
appliedStatements: z.number().int(),
durationMs: z.number(),
state: z.enum(["applied", "already_present", "planned"]),
},
annotations: {
title: "Apply Schema Migration",
readOnlyHint: false,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
},
async ({ migrationId, dryRun }) => {
const logId = `${migrationId}_${Date.now()}`;
migrationLogs.set(
logId,
`BEGIN;\n-- Executing ${migrationId} (dryRun=${dryRun})\nCREATE INDEX CONCURRENTLY IF NOT EXISTS idx_orders_created_at ON orders (created_at);\nCOMMIT;\n`
);
const summary = {
migrationId,
dryRun,
appliedStatements: dryRun ? 0 : 1,
durationMs: 42.6,
state: dryRun ? ("planned" as const) : ("applied" as const),
};
return {
content: [
{
type: "text",
text: JSON.stringify(summary),
},
{
type: "resource_link",
uri: `internal://migrations/logs/${logId}`,
name: `${migrationId} DDL Log`,
description: "Full SQL transaction trace and index build timings",
mimeType: "text/plain",
},
],
structuredContent: summary,
};
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("ops-typed-server listening on stdio");
}
main().catch((err) => {
console.error("Fatal error:", err);
process.exit(1);
});Notice how registerTool handles Zod schemas natively in @modelcontextprotocol/sdk: the SDK converts both inputSchema and outputSchema into JSON Schema for tools/list, enforces TypeScript return types at compile time, and validates structuredContent at runtime. For foundational server patterns, see How to Build a Custom MCP Server.
6. Multi-Host Client Setup and Troubleshooting
OpenAI Codex CLI (~/.codex/config.toml)
[mcp_servers.ops_typed]
command = "npx"
args = ["-y", "tsx", "/absolute/path/to/structured-tools-server.ts"]Claude Desktop and Cursor (mcp.json)
{
"mcpServers": {
"ops-typed": {
"command": "npx",
"args": ["-y", "tsx", "/absolute/path/to/structured-tools-server.ts"]
}
}
}Remote Streamable HTTP Client Entry
[mcp_servers.remote_ops_typed]
url = "https://mcp.internal.example.com/mcp"
bearer_token_env_var = "MCP_OPS_TOKEN"Verify emitted outputSchema definitions, annotations, and resource_link URIs directly in the MCP Inspector:
npx @modelcontextprotocol/inspector npx -y tsx /absolute/path/to/structured-tools-server.tsCommon Schema & Annotation Errors
- ▸
-32602 Invalid params: An unknown tool name or a malformedtools/callrequest. AstructuredContentvalue that is missing required fields or mismatches the ZodoutputSchemais a tool execution error, not-32602; return it asisError: trueand check union literals (as const) and.nullable()fields. - ▸Tool declares
outputSchemabut omitsstructuredContent: When an error occurs, setisError: trueon theCallToolResult. Returning a normal result withoutstructuredContentwhenoutputSchemais set violates the MCP contract and fails strict client validation. - ▸Read-only tool still triggers confirmation dialogs: Ensure
readOnlyHint: trueis explicitly set insideannotations. By specification default,readOnlyHintisfalseanddestructiveHintistrue, so omittingannotationscauses conservative hosts to assume destructive write behavior. - ▸Large
outputSchemadefinitions inflating prompt token spend: KeepoutputSchemafields flat and concise, and pair verbose servers with deferred loading strategies covered in Gemini 4 MCP: Deferred Tool Retrieval.
7. External References
- ▸Model Context Protocol Tools Specification (opens in a new tab) — Official definitions for
outputSchema,structuredContent,ToolAnnotations, andresource_link. - ▸Official MCP TypeScript SDK (
@modelcontextprotocol/sdk) (opens in a new tab) —McpServer.registerToolimplementation and runtime schema validation. - ▸JSON Schema Draft 2020-12 Specification (opens in a new tab) — Default schema dialect used by MCP
inputSchemaandoutputSchema. - ▸How to Build a Custom MCP Server — Transport-agnostic server architecture and
isErrorhandling. - ▸MCP Security Best Practices — Defense-in-depth beyond advisory tool annotations.
Build your full agent toolstack in the Visual Generator
Combine MCP servers with databases, search APIs, and memory graphs in a single configuration file.
Did this setup guide work with your AI host?
Help test this configuration across Claude, Cursor, and Codex CLI. Be the first to report:
MCP Structured Outputs and Tool Annotations FAQ
Why should a tool return text content alongside structuredContent when outputSchema is set?
While modern hosts validate and pass structuredContent directly to downstream programmatic workflows, older MCP clients and plain-text LLM loops still read only the content array. Serializing the same JSON object into a type: 'text' block guarantees backward compatibility without dropping typed schema enforcement.
Do MCP tool annotations like readOnlyHint enforce server security?
No. Tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) are advisory hints for client UX and approval prompts. Compliant hosts treat annotations from untrusted servers as unverified and rely on OAuth scopes, sandboxed containers, and read-only database roles for real enforcement.
How does a resource_link content block prevent context window overflow?
Instead of inlining a 50 KB build log or SQL EXPLAIN plan inside CallToolResult.content, the server returns a lightweight resource_link pointing to an MCP resource URI plus concise summary metrics in structuredContent. The agent fetches the full artifact via resources/read only when debugging requires it.
Written by Rad Tome
Independent maintainer, MCP Codex
Specializing in Model Context Protocol (MCP) integrations, autonomous AI agent orchestration, and distributed developer toolchains. Researches and benchmarks production MCP client-server architectures across OpenAI Codex, Claude, and Cursor.
Related Guides
OpenCode Free AI Agent Guide
Guide to running OpenCode coding agent without API charges using free Console models, local LLMs, and OAuth accounts.
Dev ToolsAutomated Doc Verification Loops with Claude CLI
Build automated documentation verification loops with Claude CLI and MCP. Validate code snippets, test tool schemas, and sync SDK docs in CI/CD.
Dev ToolsSelf-Correcting Verification Loops in Agents
Build robust self-correcting /loop verification harnesses for AI agents using Test-Driven Agent Development, dual-agent critics, and MCP test sandboxes.