Handling Structured Content, Errors, and Pagination

By — 7+ years building ML / AI agent systems, founder of agent-engineering.dev & sandx.ai.
Published: Last updated:
mcp client errorsmcp structured contentmcp paginationmcp tool errorsmcp protocol errors

Module 3 — Building Clients

After you connect a Client and start calling tools, reading resources, and listing what the server offers, three practical details become important: how to consume structured tool results, how to distinguish tool-level failures from protocol failures, and how the SDK handles (and lets you control) pagination.

This article covers all three on the client side, with a complete runnable example.

Client result handling

Structured content for your app, isError for the model, and automatic page aggregation.

Structured Content

When a tool declares an outputSchema, the result of callTool contains two related pieces:

content — the usual array of content blocks (almost always including a text block with a human-readable or JSON representation). This is what the model sees.

structuredContent — a JSON value that matches the output schema. This is for your application code.

structuredContent is typed as unknown. Always check that it is present and narrow it before use:

const result = await client.callTool({
  name: 'order-total',
  arguments: { id: 'A-1041' }
});

if (result.isError) {
  // handle tool error (see next section)
  return;
}

const data: unknown = result.structuredContent;
if (typeof data === 'object' && data !== null && 'total' in data && 'currency' in data) {
  const total = data as { id: string; total: number; currency: string };
  console.log(`${total.total} ${total.currency}`);
}

If you previously called listTools() (or the SDK has the tool’s schema in its response cache), callTool validates structuredContent against the outputSchema. A mismatch causes the call to reject.

Servers are expected to also put a stringified version of the structured data into a text content block for backwards compatibility with hosts that do not yet consume structuredContent.

Handling Errors

There are two distinct kinds of failure:

Tool errors (isError: true)

A tool failure is still a successful JSON-RPC response. The result has isError: true and the failure message lives in content. The model sees this message and can usually recover (retry with different arguments, ask the user, etc.).

This covers:

Arguments that fail the tool’s inputSchema

Handlers that return { isError: true, content: [...] }

Handlers that throw an ordinary Error (the SDK converts the exception message into an isError result)

Always check the flag before trusting the result:

const result = await client.callTool({ name: 'lookup-order', arguments: { id: 'missing' } });

if (result.isError) {
  console.error('Tool reported failure:');
  for (const block of result.content) {
    if (block.type === 'text') console.error(block.text);
  }
} else {
  // safe to use content / structuredContent
}

Protocol errors

Protocol-level failures (unknown tool name, invalid resource URI that the server rejects with a ProtocolError, timeouts, capability mismatches, etc.) cause the client method to reject. The model never sees these.

On the client they appear as rejected promises carrying a ProtocolError (or a subclass such as ResourceNotFoundError):

try {
  await client.readResource({ uri: 'note://archived' });
} catch (err) {
  // err is a ProtocolError (or subclass)
  console.error(err.code, err.message, err.data);
}

Only protocol-level problems throw. Tool-level problems never throw out of callTool.

The list methods (listTools, listResources, listResourceTemplates, listPrompts) automatically walk every page and return a single aggregated result with no nextCursor. You almost never need to handle cursors yourself.

// Aggregates all pages automatically
const { tools } = await client.listTools();

If you need a single raw page (for example, to implement your own incremental UI), pass a cursor:

const page = await client.listTools({ cursor: heldCursor });
console.log(page.tools);
console.log(page.nextCursor); // undefined when this is the last page

Controlling the automatic walk

ClientOptions.listMaxPages (default 64) caps how many pages the auto-aggregate path will follow. A server that never stops emitting a nextCursor causes the call to reject with an SdkError whose code is LIST_PAGINATION_EXCEEDED.

const client = new Client(
  { name: 'my-client', version: '1.0.0' },
  { listMaxPages: 32 } // or 0 to remove the cap
);

Explicit-cursor calls are never capped.

Complete Runnable Example

This example reuses the factory pattern. The server exposes:

A tool with an outputSchema that returns structuredContent

A tool that returns isError: true for a missing order

A resource that throws ResourceNotFoundError for an unknown URI

The client demonstrates structured content consumption, tool-error handling, and a protocol-error catch.

Shared factory (src/factory.ts)

// src/factory.ts
import { McpServer, ResourceNotFoundError } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';

const orders = new Map([
  ['A-1041', { id: 'A-1041', total: 61.5, currency: 'EUR', status: 'shipped' }],
  ['A-1042', { id: 'A-1042', total: 24.0, currency: 'USD', status: 'pending' }]
]);

export function createServer() {
  const server = new McpServer({
    name: 'orders-demo',
    version: '1.0.0'
  });

  // Tool with structured output
  server.registerTool(
    'order-total',
    {
      description: 'Get the total for an order',
      inputSchema: z.object({ id: z.string() }),
      outputSchema: z.object({
        id: z.string(),
        total: z.number(),
        currency: z.string()
      })
    },
    async ({ id }) => {
      const order = orders.get(id);
      if (!order) {
        return {
          content: [{ type: 'text', text: `No order with id "${id}"` }],
          isError: true
        };
      }
      const output = { id: order.id, total: order.total, currency: order.currency };
      return {
        content: [{ type: 'text', text: JSON.stringify(output) }],
        structuredContent: output
      };
    }
  );

  // Tool that can fail with isError
  server.registerTool(
    'lookup-order',
    {
      description: 'Look up full order details',
      inputSchema: z.object({ id: z.string() })
    },
    async ({ id }) => {
      const order = orders.get(id);
      if (!order) {
        return {
          content: [{
            type: 'text',
            text: `Order "${id}" not found. Known ids: ${[...orders.keys()].join(', ')}`
          }],
          isError: true
        };
      }
      return {
        content: [{
          type: 'text',
          text: `${order.id}: ${order.total} ${order.currency} (${order.status})`
        }]
      };
    }
  );

  // Resource that throws a protocol error for unknown URIs
  server.registerResource(
    'order',
    'order://{id}',
    { description: 'Full order as JSON', mimeType: 'application/json' },
    async (uri, { id }) => {
      const order = orders.get(String(id));
      if (!order) {
        throw new ResourceNotFoundError(uri.href);
      }
      return {
        contents: [{
          uri: uri.href,
          mimeType: 'application/json',
          text: JSON.stringify(order)
        }]
      };
    }
  );

  return server;
}

stdio server (src/stdio-server.ts)

import { serveStdio } from '@modelcontextprotocol/server/stdio';
import { createServer } from './factory.js';

serveStdio(createServer);

Client (src/client.ts)

import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';

async function main() {
  const client = new Client({ name: 'orders-client', version: '1.0.0' });

  const transport = new StdioClientTransport({
    command: 'npx',
    args: ['tsx', 'src/stdio-server.ts']
  });

  try {
    await client.connect(transport);

    // 1. Structured content
    const totalResult = await client.callTool({
      name: 'order-total',
      arguments: { id: 'A-1041' }
    });

    if (!totalResult.isError && totalResult.structuredContent) {
      const data = totalResult.structuredContent as {
        id: string;
        total: number;
        currency: string;
      };
      console.log('Structured total:', data.total, data.currency);
    }

    // 2. Tool error (isError: true)
    const missing = await client.callTool({
      name: 'lookup-order',
      arguments: { id: 'DOES-NOT-EXIST' }
    });

    if (missing.isError) {
      console.log('Tool error (expected):', missing.content[0]);
    }

    // 3. Protocol error (throws)
    try {
      await client.readResource({ uri: 'order://missing' });
    } catch (err: any) {
      console.log('Protocol error (expected):', err.message);
      // err.code === -32602, err.data?.uri === 'order://missing'
    }

    // 4. Pagination (automatic aggregation)
    const { tools } = await client.listTools();
    console.log('All tools (aggregated):', tools.map(t => t.name));

  } finally {
    await client.close();
  }
}

main().catch(console.error);

Run it

npx tsx src/client.ts

You should see the structured total, the expected tool-error message, the protocol-error message, and the list of tool names.

Recap

Prefer structuredContent (after narrowing) when a tool declares an outputSchema; always keep content for the model.

Check result.isError before using a tool result. Tool failures never throw.

Protocol errors cause client methods to reject with a ProtocolError (or subclass). Catch them around readResource, getPrompt, etc.

listTools / listResources / listPrompts / listResourceTemplates aggregate every page automatically. Pass { cursor } for a single raw page. Control the walk with listMaxPages.

Next we will look at handling server-initiated requests (sampling, elicitation, roots) and progress notifications.

Get new posts by Nelson Lin

Subscribe to receive email notifications when a new article is published.