Connecting, Listing, Calling Tools, and Reading Resources

By — 7+ years building ML / AI agent systems, founder of agent-engineering.dev & sandx.ai.
Published: Last updated:
mcp clientlist toolscall toolread resourceget prompt

Module 3 — Building Clients

Once a Client is connected (see the previous article on transports), you have a small set of high-level methods that map directly to the MCP protocol verbs. This article shows how to list everything a server offers and then invoke the three core primitives: tools, resources, and prompts.

All examples use @modelcontextprotocol/client and the 2026-07-28 protocol era.

MCP Client Verbs

After connect(), the client can list tools, resources, and prompts, then call, read, or get them.

After connect()

connect() completes the initialize handshake. Immediately afterward you can inspect what the server declared:

console.log(client.getServerVersion());       // { name: '...', version: '...' }
console.log(client.getServerCapabilities());  // { tools: {...}, resources: {...}, prompts: {...} }
console.log(client.getInstructions());        // optional usage guide for the model

getServerCapabilities() tells you which verbs are safe to call. A server that never registered any tools will not advertise the tools capability.

Listing What the Server Offers

The four list methods are:

Method

Returns

Used for

listTools()

{ tools }

Discover actions the model can call

listResources()

{ resources }

Discover static resources by URI

listResourceTemplates()

{ resourceTemplates }

Discover parameterized URI patterns

listPrompts()

{ prompts }

Discover user-selectable message templates

Each method aggregates pages automatically. When a server paginates its list, the SDK follows the cursors and returns a single combined result. You rarely need to handle pagination yourself.

const { tools } = await client.listTools();
const { resources } = await client.listResources();
const { resourceTemplates } = await client.listResourceTemplates();
const { prompts } = await client.listPrompts();

console.log('Tools:', tools.map(t => t.name));
console.log('Resources:', resources.map(r => r.uri));
console.log('Templates:', resourceTemplates.map(t => t.uriTemplate));
console.log('Prompts:', prompts.map(p => p.name));

Controlling Pagination (Optional)

Pass a cursor to receive only one raw page:

const page = await client.listTools({ cursor: someCursor });

ClientOptions.listMaxPages (default 64) caps the automatic walk. Set it to 0 to remove the limit. Explicit-cursor calls are never capped.

Calling a Tool

callTool takes the tool name and a plain arguments object that must satisfy the tool’s inputSchema.

const result = await client.callTool({
  name: 'search',
  arguments: { query: 'mug' }
});

// result.content is the array of content blocks the handler returned
for (const block of result.content) {
  if (block.type === 'text') {
    console.log(block.text);
  }
}

Important: A failed tool call is still a normal result. Check isError before trusting content:

if (result.isError) {
  console.error('Tool failed:', result.content);
} else {
  // use result.content
}

Arguments that violate the input schema, and handlers that throw, both come back with isError: true. Only protocol-level failures (unknown tool name, timeout, etc.) throw.

When a tool declares an outputSchema, the result also contains structuredContent. We cover that in the next article.

Reading a Resource

Resources are addressed by URI. List them first, then read a specific one:

const { resources } = await client.listResources();

const { contents } = await client.readResource({
  uri: 'config://app'
});

for (const item of contents) {
  console.log(item.uri, item.mimeType);
  if (item.text) console.log(item.text);
  if (item.blob) console.log('(binary)', item.blob.length, 'bytes base64');
}

Each entry in contents has a uri, an optional mimeType, and either text or a base64 blob.

For parameterized resources, call listResourceTemplates(), expand the template into a concrete URI, then pass that URI to readResource.

Getting a Prompt

Prompts are user-selected message templates. List them, then request one with arguments:

const { prompts } = await client.listPrompts();

const prompt = await client.getPrompt({
  name: 'summarize',
  arguments: { topic: 'orders', tone: 'terse' }
});

// prompt.messages is ready to send to a model
for (const msg of prompt.messages) {
  console.log(msg.role, msg.content);
}

The server validates the arguments against its argsSchema and returns a messages array with the template filled in.

Complete Runnable Example

This example reuses the factory pattern from earlier modules. The server exposes one tool, one static resource, and one prompt. The client connects over stdio, lists everything, then exercises each primitive.

Shared factory (src/factory.ts)

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

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

  // Tool
  server.registerTool(
    'lookup-order',
    {
      description: 'Look up an order by ID',
      inputSchema: z.object({
        id: z.string().describe('Order ID')
      })
    },
    async ({ id }) => ({
      content: [{
        type: 'text',
        text: `Order ${id}: 3 items, shipped`
      }]
    })
  );

  // Static resource
  server.registerResource(
    'recent',
    'orders://recent',
    {
      title: 'Recent Orders',
      mimeType: 'application/json'
    },
    async (uri) => ({
      contents: [{
        uri: uri.href,
        mimeType: 'application/json',
        text: JSON.stringify(['A-1041', 'A-1042'])
      }]
    })
  );

  // Prompt
  server.registerPrompt(
    'summarize-order',
    {
      title: 'Summarize Order',
      description: 'Create a short status update for an order',
      argsSchema: z.object({
        id: z.string(),
        tone: z.string().optional()
      })
    },
    ({ id, tone }) => ({
      messages: [{
        role: 'user',
        content: {
          type: 'text',
          text: `Write a ${tone ?? 'neutral'} status update for order ${id}.`
        }
      }]
    })
  );

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

    console.log('Connected to:', client.getServerVersion());
    console.log('Capabilities:', client.getServerCapabilities());

    // List everything
    const { tools } = await client.listTools();
    const { resources } = await client.listResources();
    const { prompts } = await client.listPrompts();

    console.log('\nTools:', tools.map(t => t.name));
    console.log('Resources:', resources.map(r => r.uri));
    console.log('Prompts:', prompts.map(p => p.name));

    // Call a tool
    const toolResult = await client.callTool({
      name: 'lookup-order',
      arguments: { id: 'A-1041' }
    });

    if (toolResult.isError) {
      console.error('Tool error:', toolResult.content);
    } else {
      console.log('\nTool result:');
      for (const block of toolResult.content) {
        if (block.type === 'text') console.log(block.text);
      }
    }

    // Read a resource
    const { contents } = await client.readResource({
      uri: 'orders://recent'
    });
    console.log('\nResource contents:', contents[0]?.text);

    // Get a prompt
    const prompt = await client.getPrompt({
      name: 'summarize-order',
      arguments: { id: 'A-1041', tone: 'terse' }
    });
    console.log('\nPrompt messages:', prompt.messages);

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

main().catch(console.error);

Run it

npm install @modelcontextprotocol/server @modelcontextprotocol/client zod
npm install -D tsx

npx tsx src/client.ts

Expected output (abbreviated):

Connected to: { name: 'orders-demo', version: '1.0.0' }
Capabilities: { tools: {}, resources: {}, prompts: {} }

Tools: [ 'lookup-order' ]
Resources: [ 'orders://recent' ]
Prompts: [ 'summarize-order' ]

Tool result:
Order A-1041: 3 items, shipped

Resource contents: ["A-1041","A-1042"]

Prompt messages: [
  {
    role: 'user',
    content: {
      type: 'text',
      text: 'Write a terse status update for order A-1041.'
    }
  }
]

The same client code works with Streamable HTTP — only the transport construction and shutdown change (see the previous article).

Recap

After connect(), inspect the server with getServerVersion(), getServerCapabilities(), and getInstructions().

listTools(), listResources(), listResourceTemplates(), and listPrompts() aggregate pages for you.

callTool({ name, arguments }) returns content blocks; always check isError.

readResource({ uri }) returns a contents array (text or blob).

getPrompt({ name, arguments }) returns ready-to-use messages.

Always close the client in a finally block.

Next up: handling structured content, errors, and pagination in more depth.

Get new posts by Nelson Lin

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