# Give a LlamaIndex.TS agent the AstroNode astrology tools over MCP

> `mcp()` from `@llamaindex/tools` turns every tool on the AstroNode server into a LlamaIndex `FunctionTool`. It needs two adjustments before an agent should use it: the API key goes in `requestInit`, and the results are worth unwrapping, because the defaults hand the model escaped JSON and report server-side errors as successes.

Source: https://astronode.dev/integrations/mcp-llamaindex · Updated: 2026-12-05

**How this page was verified:** Run on Node 24 on 5 December 2026 with llamaindex 0.12.1, @llamaindex/tools 0.2.0, @llamaindex/workflow 1.1.24 and @llamaindex/core 0.6.22, against a local copy of the MCP server backed by the AstroNode API running in memory. Executed: listing tools through `mcp()` (128 unfiltered, 6 with `?groups=charts,dasha`, 1 with `?tools=charts_birth`), `toolNamePrefix`, calling `charts_birth` and `dasha_vimshottari` with the sample birth through the LlamaIndex tool objects (raw and wrapped), the same `callTool()` the agent workflow uses, a malformed date, a missing key and an unreachable server. `astronode-tools.ts` and `agent.ts` typecheck under `tsc --noEmit --strict` with @llamaindex/openai 0.4.22. The model call in `agent.ts` was not executed: no LLM provider key was used.

## Install

```bash
npm install llamaindex @llamaindex/tools @llamaindex/workflow @llamaindex/openai
```

`mcp()` lives in `@llamaindex/tools`, `agent()` in `@llamaindex/workflow`. The provider package must peer on the same `@llamaindex/core` as the rest: on 5 December 2026, `@llamaindex/openai` 0.4.23 wanted core 0.6.23 while `llamaindex` 0.12.1 ships 0.6.22, so this page pins `@llamaindex/openai@0.4.22` to keep every package on one core.

## Connect with the API key

The `mcp()` options have no `headers` field of their own, but for a `url` they are handed whole to the MCP SDK's `StreamableHTTPClientTransport`, so its `requestInit.headers` carries the `Authorization` header to every request. Streamable HTTP is the default; `useSSETransport` is deprecated in the package's types and this server does not need it. No custom MCP client is required.

```typescript
// astronode-tools.ts
import { mcp } from "@llamaindex/tools";
import { FunctionTool, type JSONValue } from "llamaindex";

const MCP_URL = "https://mcp.astronode.dev/mcp";

/** The MCP result shape that @llamaindex/tools passes through untouched. */
type McpResult = { content: { type: string; text?: string }[]; isError?: boolean };

export async function astronodeTools(groups = "charts,dasha") {
  // Listing tools works without a key, so a missing key would only show up
  // as failed tool calls. Fail at startup instead.
  const key = process.env.ASTRONODE_API_KEY;
  if (!key) throw new Error("Set ASTRONODE_API_KEY");

  const server = mcp({
    url: `${MCP_URL}?groups=${groups}`,
    // Spread into the MCP SDK's StreamableHTTPClientTransport options.
    requestInit: {
      headers: { Authorization: `Bearer ${key}` },
    },
    clientName: "my-astrology-agent",
  });

  const raw = await server.tools(); // connects on first call

  // Unwrap each result: return the API's `data`, and throw on an MCP error
  // so the agent records the call as failed instead of as a success.
  const tools = raw.map((t) =>
    FunctionTool.from(async (input: unknown): Promise<JSONValue> => {
      const result = (await t.call(input)) as unknown as McpResult;
      const text = result.content.map((c) => c.text ?? "").join("\n");
      if (result.isError) throw new Error(text);
      try {
        return (JSON.parse(text) as { data: JSONValue }).data;
      } catch {
        return text;
      }
    }, {
      name: t.metadata.name,
      description: t.metadata.description,
      parameters: t.metadata.parameters, // the server's JSON Schema, passed through
    }),
  );

  return { tools, close: () => server.cleanup() };
}
```

Put the key in `ASTRONODE_API_KEY` (`aie_live_...` or a test key). The guard matters more than it looks: the server lists its tools without a key, so a forgotten variable produced a working-looking agent whose every call failed.

## How a tool is converted

*From @llamaindex/tools 0.2.0 against the local server, 5 December 2026.*

| MCP tool field | LlamaIndex `FunctionTool` | Observed with `charts_birth` |
| --- | --- | --- |
| `name` | `metadata.name`, or `prefix_name` with `toolNamePrefix` | `charts_birth`; with `toolNamePrefix: "astro"` the longest name is 38 characters |
| `description` | `metadata.description` | "Compute the D1 (Lagna) birth chart." plus the plan it needs |
| `inputSchema` | `metadata.parameters`, the JSON Schema verbatim | `date`, `time`, `tz_offset_minutes`, `lat`, `lng` required; `interpretation` optional |
| `tools/call` result | the tool's return value, unchanged | `{ content: [{ type: "text", text: "{...}" }] }`; no `structuredContent` |
| `isError: true` | nothing - still a successful return | the flag stays inside the returned object |

Because the schema is passed as plain JSON Schema rather than Zod, LlamaIndex does not check arguments before sending them; the server does. `tools()` lists again each time you call it and the client connects on the first call, so call it once at startup and reuse the array.

## Why the wrapper unwraps results

The agent workflow turns a tool's return value into the message the model reads with `stringifyJSONToMessageContent()`, which pretty-prints the JSON and then deletes every double quote. With the raw tools the API's JSON is a string inside `content[0].text`, so its escaped quotes survive as backslashes. The start of what the model received for the sample birth:

Raw mcp() tool, as stringified by the workflow.

```text
text: {\request_id\:\req_01M92P23EGTP5CAQCTJDAQCEQ2\,\data\:{\ascendant\:{\sign\:\Virgo\,\degree\:19.759582224440123},...
```

Returning the parsed `data` object instead gives the model the same figures as readable, quote-free nesting - `ascendant: { sign: Virgo, degree: 19.759582224440123 }` - and drops the envelope's `request_id` and `meta`, which the model has no use for. Return a string from the wrapper if a tool's text is not JSON; the `catch` above does that.

## The result for the sample birth

Called through the wrapped `charts_birth` tool with 24 April 1973, 17:25, Mumbai (`tz_offset_minutes: 330`), the tool returned a **Virgo** ascendant at 19.76 degrees and the Moon in **Sagittarius**, Uttara Ashadha pada 1, with the Sun in Aries in the 8th house (whole-sign houses, Lahiri ayanamsa, engine 1.2.2). `dasha_vimshottari` for the same birth opened with a Sun mahadasha balance of 5.94 years, ending April 1979 - consistent with a Moon in the Sun-ruled Uttara Ashadha. The same figures are on the [Birth Chart API](https://astronode.dev/capabilities/vedic/charts-birth) page.

## What the agent sees when a call fails

*Observed with the local server on 5 December 2026. A rejected call makes no API call and is not billed.*

| Failure | Raw `mcp()` tool | Wrapped tool, inside `agent()` |
| --- | --- | --- |
| Date sent as `24/04/1973` | Returned normally, with `isError: true` and "Input validation error: ... data/date must match pattern" | Logged as failed; the model gets `Error: ...` with the same validation message |
| No `Authorization` header | Tools still list (128); each call returns `isError: true` with "No AstroNode API key was provided..." | Never reached: the startup guard throws |
| Server unreachable | `tools()` throws `TypeError: fetch failed` | Same - before the agent is built |

The difference in the first row is the reason for the `throw`. LlamaIndex marks a tool call as failed only when the function throws, and only a failed call is flagged as an error in the tool-result message the model receives. With the raw tools a schema rejection, or an API error such as `PLAN_REQUIRED` (which the server also returns with `isError: true`), arrives looking like any other output.

## The agent

```typescript
// agent.ts
import { agent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";
import { astronodeTools } from "./astronode-tools";

const { tools, close } = await astronodeTools("charts,dasha");

const astrologer = agent({
  name: "astrologer",
  llm: openai({ model: "gpt-4.1-mini" }),
  tools,
  systemPrompt:
    "Answer Vedic astrology questions with the AstroNode tools. Quote figures from tool results; never estimate a position.",
});

try {
  const result = await astrologer.run(
    "What is my ascendant and current Vimshottari dasha? Born 24 April 1973, 17:25, Mumbai (UTC+5:30).",
  );
  console.log(result.data.result);
} finally {
  await close();
}
```

`agent()` takes any LlamaIndex LLM that supports tool calls; swap `openai()` for your provider's package. This file typechecks against the versions above, but the model call itself was not run for this page. `close()` ends the MCP client; the server keeps no session, so a dropped connection loses nothing.

## Fewer tools per agent

The `groups` argument above becomes `?groups=` on the URL. `charts,dasha` gave the agent 6 tools - `charts_birth`, `charts_varga`, `dasha_char`, `dasha_lookup`, `dasha_vimshottari`, `dasha_yogini` - instead of 128, which keeps the tool list the model reads short. `?tools=charts_birth` narrows to single tools. For several agents in one `multiAgent()` workflow, give each its own `astronodeTools()` with its own groups, or set `toolNamePrefix` so names cannot collide with other servers' tools. The group names, and what a call costs, are on the [MCP server page](https://astronode.dev/mcp).

For Python, LlamaIndex publishes the `llama-index-tools-mcp` package; it was not tested for this page.

## Questions

**Which AstroNode endpoints does the LlamaIndex.TS example call?**

2 endpoints: Birth Chart (Kundli) (`POST /v1/charts/birth`); Vimshottari Dasha (`POST /v1/dasha/vimshottari`).

**Was the LlamaIndex.TS code on this page actually run?**

Run on Node 24 on 5 December 2026 with llamaindex 0.12.1, @llamaindex/tools 0.2.0, @llamaindex/workflow 1.1.24 and @llamaindex/core 0.6.22, against a local copy of the MCP server backed by the AstroNode API running in memory. Executed: listing tools through `mcp()` (128 unfiltered, 6 with `?groups=charts,dasha`, 1 with `?tools=charts_birth`), `toolNamePrefix`, calling `charts_birth` and `dasha_vimshottari` with the sample birth through the LlamaIndex tool objects (raw and wrapped), the same `callTool()` the agent workflow uses, a malformed date, a missing key and an unreachable server. `astronode-tools.ts` and `agent.ts` typecheck under `tsc --noEmit --strict` with @llamaindex/openai 0.4.22. The model call in `agent.ts` was not executed: no LLM provider key was used.

## Endpoints

- [`POST /v1/charts/birth`](https://astronode.dev/capabilities/vedic/charts-birth) - Birth Chart (Kundli) API
- [`POST /v1/dasha/vimshottari`](https://astronode.dev/capabilities/vedic/dasha-vimshottari) - Vimshottari Dasha API
