Using Tools

Tools are executable functions exposed by the MCP server. They are the primary way for an AI agent or client to interact with the outside world via the server.

Listing Tools

The useMcp hook automatically fetches the list of available tools when connected. They are available via the tools property.

const { tools } = useMcp({ url: '...' });

return (
  <ul>
    {tools.map(tool => (
      <li key={tool.name}>
        <h4>{tool.name}</h4>
        <p>{tool.description}</p>
        <pre>{JSON.stringify(tool.inputSchema, null, 2)}</pre>
      </li>
    ))}
  </ul>
);

Calling Tools

Use the callTool function to execute a tool. It returns a Promise that resolves with the tool's result.

const { callTool } = useMcp({ url: '...' });

const runSearch = async () => {
  try {
    // Args must match the tool's inputSchema
    const result = await callTool('search_web', { 
      query: 'latest react news' 
    });

    // Result structure depends on the MCP server implementation
    console.log(result.content);
  } catch (error) {
    console.error('Tool call failed:', error);
  }
};

Error Handling

Calls to callTool can fail if:

  1. The client is disconnected.
  2. The arguments do not match the schema.
  3. The server encounters an internal error.
  4. Authentication expires during the call (the hook attempts to handle re-auth automatically).

Always wrap callTool in a try/catch block.