October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Let Claude Call Your API from Node.js: A Tool-Use Tutorial

Claude tool use lets a model request a structured operation; your Node.js application validates and executes it, then returns a matching tool result.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To let Claude call an API from Node.js, define a tool the model may request, inspect Claude’s structured request, and have your server-side code execute it. Claude does not directly run functions inside your Node.js process. Your application controls which operations are available, validates the arguments, and sends the result back to Claude.

What Claude tool use does

Anthropic calls this capability tool use; it is also commonly called function calling. The model can return a structured tool_use block asking for an operation, such as looking up an order. Your application receives that request, performs the operation, and returns a result. Claude can then use the result to write a response.

As an Amazon Associate I earn from qualifying purchases.

This is a request-and-response protocol, not permission for Claude to reach into your process or invoke arbitrary functions. The application decides what tools exist and what code runs for each one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install the SDK and prepare Node.js

Use Anthropic’s official TypeScript SDK, @anthropic-ai/sdk. Its current documentation lists Node.js 20 LTS or later non-end-of-life releases as supported; check the SDK documentation for the requirements in effect when you deploy.

npm install @anthropic-ai/sdk

Keep the API key on the server. The SDK’s browser support is disabled by default to help prevent exposure of secret credentials. Store ANTHROPIC_API_KEY in your server environment or a secrets manager, rather than embedding it in browser code.

Define a narrowly scoped tool

A custom tool definition gives Claude a name, a description, and an input_schema that describes the expected structured input. Anthropic says the description is optional but strongly recommends it: explain when the tool should be used and what its inputs mean. Keep the schema aligned with the operation your code actually supports.

This example exposes a read-only order lookup. Replace the model identifier with one currently available to your account, as model names and availability can change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import Anthropic from "@anthropic-ai/sdk";

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

const tools = [
  {
    name: "get_order_status",
    description: "Look up the status of an order using its order ID.",
    input_schema: {
      type: "object",
      properties: {
        order_id: {
          type: "string",
          description: "The order ID to look up",
        },
      },
      required: ["order_id"],
      additionalProperties: false,
    },
  },
];

The tool-definition guide explains the schema format and how Claude uses descriptions. A schema describes the shape of a request; it does not grant access to a customer’s data or authorize a write.

Send a message and inspect Claude’s response

Pass the tool definitions and user message to client.messages.create(). A tool being available does not guarantee Claude will call it. Inspect the returned stop_reason and content blocks; when the response contains tool_use, read its name, id, and input.

const firstResponse = await client.messages.create({
  model: "YOUR_CURRENT_MODEL_ID",
  max_tokens: 1024,
  tools,
  messages: [
    { role: "user", content: "Can you check order A123?" },
  ],
});

if (firstResponse.stop_reason === "tool_use") {
  const toolCall = firstResponse.content.find(
    (block) => block.type === "tool_use",
  );

  if (toolCall) {
    // Validate and dispatch this request in application code.
  }
}

Use a model identifier from the current Messages API reference. Do not treat every non-tool response as a failure: Claude may finish with a normal response, while other stop reasons can indicate limits or another stopping condition. The implementation guide describes stop reasons, including output limited by max_tokens.

Validate, dispatch, and execute the request

Only dispatch tool names your application explicitly recognizes. Treat tool_use.input as model-generated input: check its type and allowed values, apply the requesting user’s permissions, and use normal timeouts and API error handling before any side effect. A JSON schema helps specify expected input but does not replace application-level validation or authorization.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
async function runTool(name, input, user) {
  if (name !== "get_order_status") {
    throw new Error("Unknown tool");
  }

  if (
    typeof input !== "object" ||
    input === null ||
    typeof input.order_id !== "string" ||
    !/^[A-Za-z0-9-]{1,40}$/.test(input.order_id)
  ) {
    throw new Error("Invalid order ID");
  }

  // Check that this user may access the requested order.
  await assertCanReadOrder(user, input.order_id);

  // Implement this function with your API client and a request timeout.
  return await fetchOrderStatus(input.order_id);
}

The authorization check and API function above are application-specific. Add equivalent checks for every exposed operation; a tool that changes data needs authorization for that precise action, not merely a valid-looking input.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Return a matching tool result to Claude

After your code executes the operation, append Claude’s assistant response containing the tool-use block to the conversation history. Then send a new user message with a tool_result block whose tool_use_id exactly matches the original tool-use block’s id. The result must immediately follow the corresponding tool-use message in the history. If the result message also contains text, put its tool-result blocks before the text.

const toolCall = firstResponse.content.find(
  (block) => block.type === "tool_use",
);

if (!toolCall) {
  throw new Error("Expected a tool-use block");
}

let resultContent;
let isError = false;

try {
  const result = await runTool(toolCall.name, toolCall.input, currentUser);
  resultContent = JSON.stringify(result);
} catch (error) {
  isError = true;
  resultContent = error instanceof Error ? error.message : "Tool failed";
}

const secondResponse = await client.messages.create({
  model: "YOUR_CURRENT_MODEL_ID",
  max_tokens: 1024,
  tools,
  messages: [
    { role: "user", content: "Can you check order A123?" },
    { role: "assistant", content: firstResponse.content },
    {
      role: "user",
      content: [
        {
          type: "tool_result",
          tool_use_id: toolCall.id,
          content: resultContent,
          is_error: isError,
        },
      ],
    },
  ],
});

In a real application, preserve the full conversation history rather than reconstructing only this short example. The second response may be Claude’s user-facing answer, or it may request another client-side tool. If it requests another, validate and execute that request and continue the cycle. Report tool failures as errors in the result rather than returning fabricated success. See Anthropic’s tool-use implementation guide for the required message ordering and result format.

Choose the right execution model

This walkthrough uses a custom, client-side tool: your Node.js application makes the API request or runs the local function. Anthropic’s server-side tools are a different execution model; do not assume your Node.js dispatcher runs them or that they have identical pricing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Custom client-side tool: Your code executes the operation. This lets your application apply its own permissions, validation, retries, and API handling.
  • Server-side tool: Anthropic provides the tool behavior under its own terms and usage model. Check the current tool documentation and pricing before choosing one.

A manual loop is a useful starting point because it makes the control flow visible. SDK helpers or a tool runner may reduce boilerplate, but confirm their availability and behavior against the installed SDK version before building around them.

Understand what contributes to cost

Anthropic’s pricing documentation says client-side tool use is charged like other API requests, while server-side tools can have additional usage-based charges. Tool descriptions and the tool-use and tool-result content also contribute tokens. Model prices can change, so consult the current pricing page rather than relying on an older quoted rate.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.