keepcalculator

06 Numbers and Powers

Claude Tool Use in Node.js: Call Your API

Card No. 06·61349 · Updated · Standard formula, shown below

Claude can call your API from a Node.js app through tool use: you describe an available function, Claude requests it when useful, and your code executes it and returns the result. This walkthrough shows the request-and-response flow, including a small example that calls a weather API without giving Claude direct network access.

What tool use means

Tool use is a conversation pattern, not a way for Claude to run arbitrary JavaScript on your server. Your application tells the Claude API which tools exist and what input each accepts. Claude can then respond with a tool-use block naming one of them and supplying structured input. Your Node.js code decides whether to execute that request, calls the relevant API, and sends the result back to Claude.

This distinction matters: declaring a tool does not call it, and Claude does not automatically connect to an API just because you mention its URL in a prompt. The application remains responsible for execution, credentials, permissions, validation, and error handling.

The request-and-response cycle

A typical interaction has these stages:

  1. Define a tool. Provide a name, description, and JSON Schema for its input.
  2. Send a message to Claude. Include the tool definition and the user’s request.
  3. Inspect the response. If Claude returns a tool-use block, read its name and input. It may instead answer directly or request a different tool.
  4. Run your implementation. Your Node.js code validates the input and calls your API or service.
  5. Send the tool result back. Include the tool-use ID and result in a follow-up message, then ask Claude to produce the final response.

There can be more than one tool call or another round of tool use, so production code should handle the conversation as a loop rather than assuming every request has exactly one call.

Set up the Node.js client

Use a current Node.js runtime and the official Anthropic JavaScript SDK. Install the package with npm install @anthropic-ai/sdk, then set an API key in the environment rather than placing it in source code. For example, configure ANTHROPIC_API_KEY in your local environment or deployment secret manager. Never send this key to a browser or expose it in client-side JavaScript.

The model name must be one currently available to your account; model availability and names can change. Check Anthropic’s current API documentation when selecting one. The example below uses the SDK’s Messages API pattern and assumes your Node process can also access the sample weather service.

Example: let Claude request a weather lookup

This example shows the essential control flow. Replace the example endpoint and response fields with those of an API you are authorized to call. The example uses the global fetch available in modern Node.js versions.

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const tools = [{
  name: "get_weather",
  description: "Get current weather for a supported city.",
  input_schema: {
    type: "object",
    properties: {
      city: { type: "string", description: "City name" }
    },
    required: ["city"],
    additionalProperties: false
  }
}];

const messages = [{
  role: "user",
  content: "What's the weather in Boston?"
}];

let response = await client.messages.create({
  model: process.env.ANTHROPIC_MODEL,
  max_tokens: 500,
  tools,
  messages
});

while (response.stop_reason === "tool_use") {
  const toolResults = [];

  for (const block of response.content) {
    if (block.type !== "tool_use") continue;
    if (block.name !== "get_weather") {
      throw new Error(`Unknown tool: ${block.name}`);
    }

    const city = block.input.city;
    const url = new URL("https://api.example.com/weather");
    url.searchParams.set("city", city);

    const apiResponse = await fetch(url, {
      headers: { Authorization: `Bearer ${process.env.WEATHER_API_KEY}` }
    });
    if (!apiResponse.ok) {
      throw new Error(`Weather API returned ${apiResponse.status}`);
    }
    const weather = await apiResponse.json();

    toolResults.push({
      type: "tool_result",
      tool_use_id: block.id,
      content: JSON.stringify(weather)
    });
  }

  messages = [
    ...messages,
    { role: "assistant", content: response.content },
    { role: "user", content: toolResults }
  ];

  response = await client.messages.create({
    model: process.env.ANTHROPIC_MODEL,
    max_tokens: 500,
    tools,
    messages
  });
}

console.log(response.content);

The placeholder host is not a working weather provider. The important details are that the tool result references the matching tool_use_id, and the assistant’s previous content is preserved in the next request. In an application, extract and display the final text blocks rather than logging the raw response object.

Choosing tools and controlling execution

Define tools around a clear, bounded action. A useful tool might retrieve an order by ID or search a catalog; a vague tool such as “do anything” is difficult to validate and risky to expose. Descriptions should explain when the tool applies, while the schema should specify required fields, types, and meaningful constraints.

  • Use a narrow interface: accept only the fields the API actually needs.
  • Validate again in Node.js: a schema helps Claude format inputs, but it is not a substitute for application-side checks.
  • Keep authority on your server: store API credentials server-side and limit them to the necessary permissions.
  • Require confirmation for consequential actions: treat actions such as sending messages, changing records, or making purchases differently from read-only lookups.
  • Return only useful data: avoid sending large payloads or secrets back into the conversation.

Tool choice can be automatic or controlled by the request’s tool-choice setting, depending on the API options you use. Automatic choice lets Claude decide whether a tool is appropriate; a forced choice can require a particular tool. Neither setting performs the tool call for you.

Common problems and practical safeguards

If Claude answers in plain text instead of requesting a tool, check that the tool definition was included and that the prompt gives a reason to use it. Also inspect the response’s stop reason and content block types: do not assume the first block is always a tool call.

If the follow-up request fails, verify that you included the assistant response and a tool result with the exact matching ID. Each requested tool call needs a corresponding result. When a tool fails, return a concise, non-sensitive error as the result or stop and handle it explicitly; do not silently fabricate successful data.

Treat tool input and API output as untrusted data. Validate city names or identifiers, use fixed API hosts rather than accepting arbitrary URLs from model input, set timeouts, handle rate limits, and avoid logging credentials or sensitive response bodies. These measures help prevent malformed requests, accidental data exposure, and unsafe use of the integration.

Frequently Asked Questions

Can Claude call my API directly?
No. Claude requests a declared tool, but your Node.js server must make the API request and return its result.

Does the tool definition run JavaScript?
No. It describes the tool’s name and input shape. Your application supplies the implementation.

Can Claude call more than one tool?
Yes. A response can contain multiple tool-use blocks, and a conversation can require several rounds. Handle each requested call and continue until Claude returns a non-tool response.

Should my API key go in the tool schema?
No. Keep credentials in server-side environment configuration or a secret manager. The schema should describe inputs, not contain secrets.

What should I do when my API returns an error?
Check the HTTP status and handle the failure explicitly. You can provide a brief error result for Claude to explain, or end the request with an application error; never present a failed call as successful data.

When this pattern is useful

Tool use is a good fit when a conversational interface needs current or private information, such as retrieving a record from your service, or when it needs to trigger a carefully controlled action. It separates language understanding from execution: Claude interprets the request, while your code enforces the rules and connects to the systems you choose. For simple static questions, no API tool may be necessary; for sensitive or consequential operations, add explicit authorization and user confirmation in your own application.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →