Dev Tools·
intermediate
·13 min read·Nov 21, 2026·Updated Nov 24, 2026
·Independent maintainer·Verification Charter

MCP Structured Outputs and Tool Annotations

Define typed MCP tool responses with outputSchema and structuredContent. Configure safety annotations (readOnlyHint, destructiveHint) and resource_link.

MCPJSON SchemaTypeScripttoolssecurityCodexClaudeCursor
Interactive Tool
1-Click Export

Generate & Validate Multi-Client MCP Config

One-click export with environment variables & path locators for Claude Desktop, Cursor, Windsurf, and OpenAI Codex CLI.

Open in Generator

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).

diagram

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:

json
{
  "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:

json
{
  "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 FieldTypeSpec DefaultOperational Meaning
titlestringNoneHuman-readable display label shown in host approval modals instead of snake_case tool names.
readOnlyHintbooleanfalsetrue indicates the tool makes zero persistent state changes to its environment.
destructiveHintbooleantrueApplies only when readOnlyHint is false. true means updates may delete or overwrite data; false indicates strictly additive writes.
idempotentHintbooleanfalseApplies only when readOnlyHint is false. true confirms repeated calls with identical arguments produce no extra side effects.
openWorldHintbooleantruetrue 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:

json
{
  "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:

bash
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node tsx

The server below registers two tools and a companion resource handler:

  1. ▸check_service_health: Declares readOnlyHint: true, openWorldHint: false, and an explicit Zod outputSchema, returning compile-time checked structuredContent.
  2. ▸apply_schema_migration: Declares readOnlyHint: false, destructiveHint: false, and idempotentHint: true, returning typed migration metadata plus a resource_link pointing to the stored log resource.
typescript
// 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)

toml
[mcp_servers.ops_typed]
command = "npx"
args = ["-y", "tsx", "/absolute/path/to/structured-tools-server.ts"]

Claude Desktop and Cursor (mcp.json)

json
{
  "mcpServers": {
    "ops-typed": {
      "command": "npx",
      "args": ["-y", "tsx", "/absolute/path/to/structured-tools-server.ts"]
    }
  }
}

Remote Streamable HTTP Client Entry

toml
[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:

bash
npx @modelcontextprotocol/inspector npx -y tsx /absolute/path/to/structured-tools-server.ts

Common Schema & Annotation Errors

  • ▸-32602 Invalid params: An unknown tool name or a malformed tools/call request. A structuredContent value that is missing required fields or mismatches the Zod outputSchema is a tool execution error, not -32602; return it as isError: true and check union literals (as const) and .nullable() fields.
  • ▸Tool declares outputSchema but omits structuredContent: When an error occurs, set isError: true on the CallToolResult. Returning a normal result without structuredContent when outputSchema is set violates the MCP contract and fails strict client validation.
  • ▸Read-only tool still triggers confirmation dialogs: Ensure readOnlyHint: true is explicitly set inside annotations. By specification default, readOnlyHint is false and destructiveHint is true, so omitting annotations causes conservative hosts to assume destructive write behavior.
  • ▸Large outputSchema definitions inflating prompt token spend: Keep outputSchema fields flat and concise, and pair verbose servers with deferred loading strategies covered in Gemini 4 MCP: Deferred Tool Retrieval.

7. External References

Ready to Deploy?

Build your full agent toolstack in the Visual Generator

Combine MCP servers with databases, search APIs, and memory graphs in a single configuration file.

Customize in Generator
Developer Verification & Feedback
0 reports

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.

RT✓

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.

Editorial Integrity: Package names verified via npm registry API. Repositories verified via GitHub REST API.
Verification Charter →

Related Guides