# Give Claude an astrology API with tool use

> Claude decides when it needs a panchang or the user's current dasha; your code makes the AstroNode call and returns the result as a `tool_result`. Nothing astrological is left to the model's memory. The loop below uses the official TypeScript SDK and handles the case that trips most first implementations: two tool calls in one turn.

Source: https://astronode.dev/integrations/claude-tool-use · Updated: 2026-12-01

**How this page was verified:** Executed with the official `@anthropic-ai/sdk` against a local stub of the Messages API that returned two `tool_use` blocks in one turn (no Anthropic request was made): both handlers called the in-memory API and both `tool_result` blocks went back in one message. Typechecks under `tsc --strict` against the SDK's types. The model's own behaviour was not tested.

## What runs where

This is ordinary client-side tool use: the tools are defined in your request, executed by your code, and AstroNode is called from your server with your key. There is no AstroNode MCP server yet; if you want one, these two tool definitions are what you would wrap. As on the [OpenAI page](https://astronode.dev/integrations/openai-function-calling), the tools take no birth data - your code supplies the stored profile.

## Tools and the loop

`npm install @anthropic-ai/sdk` - `ANTHROPIC_API_KEY` and `ASTRONODE_API_KEY` in the environment:

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

const client = new Anthropic(); // reads ANTHROPIC_API_KEY
const ASTRONODE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";

type Place = { tz_offset_minutes: number; lat: number; lng: number };
type Birth = Place & { date: string; time: string };

async function astronode(path: string, body: unknown): Promise<{ ok: boolean; body: unknown }> {
  const res = await fetch(`${ASTRONODE}${path}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });
  const json = await res.json();
  return { ok: res.ok, body: res.ok ? json.data : json.error };
}

const tools: Anthropic.Tool[] = [
  {
    name: "get_panchang",
    description:
      "Panchang (vara, tithi, nakshatra, yoga, karana, sunrise, sunset) for one civil date at the user's home location. Times in the result are UTC instants.",
    input_schema: {
      type: "object",
      properties: { date: { type: "string", description: "YYYY-MM-DD" } },
      required: ["date"],
      additionalProperties: false,
    },
    strict: true,
  },
  {
    name: "get_current_dasha",
    description:
      "The user's running Vimshottari periods (mahadasha to pran) at a UTC moment, from their stored birth details.",
    input_schema: {
      type: "object",
      properties: { at: { type: "string", description: "ISO 8601 UTC datetime" } },
      required: ["at"],
      additionalProperties: false,
    },
    strict: true,
  },
];

async function runTool(block: Anthropic.ToolUseBlock, birth: Birth, home: Place) {
  const input = block.input as { date?: string; at?: string };
  const r =
    block.name === "get_panchang"
      ? await astronode("/v1/panchang", { date: input.date, ...home })
      : block.name === "get_current_dasha"
        ? await astronode("/v1/dasha/lookup", { birth_input: birth, date: input.at, system: "vimshottari" })
        : { ok: false, body: { code: "UNKNOWN_TOOL" } };
  return {
    type: "tool_result" as const,
    tool_use_id: block.id,
    content: JSON.stringify(r.body),
    is_error: !r.ok,
  };
}

export async function ask(question: string, birth: Birth, home: Place): Promise<string> {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }];
  for (let turn = 0; turn < 5; turn++) {
    const response = await client.messages.create({
      model: "claude-sonnet-5-5",
      max_tokens: 4096,
      system: `Today is ${new Date().toISOString().slice(0, 10)}. Use the tools for every date, period or position; never work them out yourself.`,
      tools,
      messages,
    });
    if (response.stop_reason !== "tool_use") {
      return response.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
    }
    messages.push({ role: "assistant", content: response.content });
    const calls = response.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
    // Every tool_use needs its tool_result, all in the next user message.
    const results = await Promise.all(calls.map((b) => runTool(b, birth, home)));
    messages.push({ role: "user", content: results });
  }
  throw new Error("Too many tool rounds");
}
```

- `messages.push({ role: "assistant", content: response.content })` appends the **whole** content array - text, `tool_use` blocks and anything else - not just the text.
- A failed AstroNode call becomes a `tool_result` with `is_error: true` and the API's error object as content, so Claude can tell the user the date was invalid instead of inventing an answer.
- Any `stop_reason` other than `tool_use` ends the loop - including `max_tokens` and `refusal`, which a production version should handle explicitly.

## Two tools in one turn

A question like "Is today good to start something, given my dasha?" needs both tools, and Claude can request both in a single response. In the executed run the two `tool_use` blocks (`get_panchang` for 2026-12-01, `get_current_dasha` at 06:00 UTC) were answered with one user message holding two `tool_result` blocks:

*What went back to the model*

| tool_use | tool_result content (from AstroNode) |
| --- | --- |
| `get_panchang` | Mangalavara, Krishna Ashtami, Magha, Vaidhriti, Balava; sunrise `01:25:17Z` |
| `get_current_dasha` | Jupiter mahadasha (2014-2030), Moon antardasha ending 2026-12-04 |

Panchang is computed for a place, so `get_panchang` uses the user's home coordinates from your database. If your product lets users ask about other cities, add a `city_id` parameter that your code resolves to coordinates and an offset - still never raw numbers from the model.

## The mistake that bites first: splitting the results

The natural first implementation loops over the `tool_use` blocks and sends one request per result. The Messages API expects every `tool_use` in an assistant turn to be answered by a `tool_result` in the **next** user message, so sending only the first result makes the request invalid - and returning them across several messages teaches the model to stop calling tools in parallel. Collect all results (the `Promise.all` above runs the AstroNode calls concurrently) and send them together.

The other early failure is not an error at all: without today's date in the system prompt, "today" means whatever date the model assumes, and the panchang comes back for the wrong day - correctly computed, and wrong.

## Questions

**Which AstroNode endpoints does the Claude tool use example call?**

2 endpoints: Panchang (`POST /v1/panchang`); Current Dasha Lookup (`POST /v1/dasha/lookup`).

**Was the Claude tool use code on this page actually run?**

Executed with the official `@anthropic-ai/sdk` against a local stub of the Messages API that returned two `tool_use` blocks in one turn (no Anthropic request was made): both handlers called the in-memory API and both `tool_result` blocks went back in one message. Typechecks under `tsc --strict` against the SDK's types. The model's own behaviour was not tested.

## Endpoints

- [`POST /v1/panchang`](https://astronode.dev/capabilities/vedic/panchang) - Panchang API
- [`POST /v1/dasha/lookup`](https://astronode.dev/capabilities/vedic/dasha-lookup) - Current Dasha Lookup API
