← Integrations

AI agent · TypeScript

Use the AstroNode MCP server from the Gemini API

The Google Gen AI SDK turns a connected MCP client into a CallableTool. Pass it in config.tools and generateContent lists the AstroNode tools, sends them to Gemini as function declarations, runs the calls the model asks for and feeds the results back - with a few behaviours worth knowing before you ship it.

Updated

How this page was checked: Run on 5 December 2026 with @google/genai 3.7.0 and @modelcontextprotocol/sdk 1.32.2 on Node 24, against the AstroNode API in memory behind a local copy of the MCP server (the hosted server runs the same code), with a test key. Executed: connecting over Streamable HTTP, mcpToTool(...).tool() on the full server (128 declarations) and with ?groups=charts,dasha,panchang,muhurta (12), callTool for charts_birth with the sample birth (the figures quoted below), two calls in one callTool, a malformed date, an unknown tool name and a client with no key. agent.ts typechecks under tsc --strict but was not executed: no Gemini API key was used, so no model call was made and nothing on this page says how Gemini itself treats the declarations.

Wrap the MCP client

mcpToTool does not open a connection. It takes one or more MCP SDK Clients you have already connected, plus an optional config as the last argument (timeout for each tool call, behavior for the declarations). The API key goes in the transport's requestInit headers, so it reaches the AstroNode server and never the model:

npm install @google/genai @modelcontextprotocol/sdk

typescript
// astronode.ts
import { mcpToTool, type CallableTool } from "@google/genai";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const MCP_URL = "https://mcp.astronode.dev/mcp?groups=charts,dasha,panchang,muhurta";

export async function connectAstroNode(): Promise<{ client: Client; astro: CallableTool }> {
  const client = new Client({ name: "gemini-astronode", version: "1.0.0" });
  await client.connect(
    new StreamableHTTPClientTransport(new URL(MCP_URL), {
      // ASTRONODE_API_KEY=aie_live_...
      requestInit: { headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}` } },
    }),
  );
  // timeout (ms) applies to each MCP tools/call, not to the Gemini request.
  return { client, astro: mcpToTool(client, { timeout: 30_000 }) };
}

In 3.7.0 mcpToTool and its McpCallableTool are marked @experimental in the type declarations, and the README section is titled "MCP support (experimental)". Pin the version and re-check this page's behaviour notes when you upgrade.

Nothing is listed until the SDK first needs it. The first tool() or callTool() sends tools/list, and the result is cached on that object for its lifetime - a new tool on the server shows up only after you create a new CallableTool. Listing is free; see the MCP server page for what counts toward quota.

Automatic function calling

Put the CallableTool in config.tools and generateContent runs the loop for you: it converts the tool to declarations, sends the request, executes every functionCall in the reply through MCP, appends the results and asks again, until the model answers in text or the call limit is reached.

typescript
// agent.ts
import { GoogleGenAI } from "@google/genai";
import { connectAstroNode } from "./astronode.ts";

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const { client, astro } = await connectAstroNode();

try {
  const response = await ai.models.generateContent({
    model: "gemini-3.8-flash",
    contents: "What is my ascendant and Moon nakshatra? Born 24 April 1973, 5:25 pm, Mumbai.",
    config: {
      tools: [astro],
      // Counts model turns that requested tools, not individual calls. Default 10.
      automaticFunctionCalling: { maximumRemoteCalls: 4 },
    },
  });

  for (const turn of response.automaticFunctionCallingHistory ?? []) {
    for (const p of turn.parts ?? []) {
      if (p.functionCall) console.log("called", p.functionCall.name, p.functionCall.args);
    }
  }
  console.log(response.text);
} finally {
  await client.close();
}
  • `maximumRemoteCalls` counts loop rounds, not tool calls. In the SDK source the counter goes up once per model turn, and every functionCall in that turn runs. With the default of 10, a model that asks for a chart and a dasha together spends one round.
  • At the limit, the last turn's calls are not run. The loop stops and returns that response as it is, so response.text can be empty while response.functionCalls still lists unanswered calls. Check for that rather than printing an empty string.
  • The declarations go out with every round. The converted tool list is part of each request in the loop, so the narrowing below saves on every round, not just the first.
  • No mixing in one request. With automatic calling on, a CallableTool next to a plain { functionDeclarations: [...] } entry throws Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Wrap your own functions as a CallableTool too, or set automaticFunctionCalling: { disable: true } and run the calls yourself.
  • The trace is on the response. automaticFunctionCallingHistory holds each model turn and each function response, unless you set ignoreCallHistory: true.

What the SDK sends to Gemini

Conversion is a straight copy. Each MCP tool becomes one entry in a single functionDeclarations array with three fields:

From `mcpToGeminiTool` in @google/genai 3.7.0, checked against the 128 declarations it produced.
MCP tool fieldFunction declarationObserved for AstroNode
namenameUnchanged, e.g. charts_birth; longest is 32 characters
descriptiondescriptionUnchanged, including the plan line ("Needs the Free plan or above.")
inputSchemaparametersJsonSchemaByte-for-byte the server's JSON Schema; not converted to Gemini's OpenAPI-style parameters
outputSchemaresponseJsonSchemaNot set: no AstroNode tool declares an output schema
title-Dropped ("Birth Chart (Kundli)" never reaches the model)
annotations-Dropped, so readOnlyHint and the destructiveHint on the three chat-history deletes are invisible to Gemini

The full list serialises to about 122 KB of JSON. Every name fits the function-name rule in the API reference (letters, digits, underscores, colons, dots and dashes). The SDK removes nothing from the schemas, so these keywords are all sent as written:

KeywordOccurrences across 128 schemasWhere it comes from
examples554Sample values on most fields ("1993-07-04", 330)
pattern240date and time formats
additionalProperties173Every object is closed (false)
enum86Languages, verbosity, ayanamsa and similar choices
minLength / maxLength31 / 29Names and free-text fields
default29Optional settings
anyOf4Fields that accept more than one shape
format2
exclusiveMinimum1

The function-calling guide says "Only a subset of the OpenAPI schema is supported", and the Schema object behind the older parameters field has no examples (only a singular example), no additionalProperties and no exclusiveMinimum. The SDK uses parametersJsonSchema instead, which the reference describes only as JSON Schema for an object, without a keyword list. We did not send these declarations to the API, so we have not seen whether it accepts, ignores or rejects any of them.

Send fewer tools

Neither the guide nor the API reference states a maximum number of function declarations. The guide's advice is to "Keep active set to 10-20 tools maximum". ?groups= on the URL does that on the server side, before the SDK ever sees the list:

text
https://mcp.astronode.dev/mcp?groups=charts,dasha,panchang,muhurta
-> 12 declarations: charts_birth, charts_varga, dasha_char, dasha_lookup,
   dasha_vimshottari, dasha_yogini, gowri_nalla_neram, muhurta_auspicious,
   muhurta_choghadiya, muhurta_hora, muhurta_inauspicious, panchang

Use ?tools=charts_birth,dasha_vimshottari for an exact list. Two notes from the SDK source: mcpToTool(clientA, clientB) merges several clients but throws Duplicate function name if two of them expose the same tool, so give overlapping groups to one client, not two; and its pager stops after 100 tools at a page boundary. The AstroNode server returns its whole list in one page, which is why all 128 arrived unfiltered.

Call a tool without the model

callTool is the same method the automatic loop uses, and you can call it directly - handy in tests, or to check a key before spending model tokens. It takes Gemini FunctionCalls and returns Parts:

typescript
// call.ts - no model involved
import { connectAstroNode } from "./astronode.ts";

const { client, astro } = await connectAstroNode();

const tool = await astro.tool();
console.log(tool.functionDeclarations?.map((d) => d.name));

const [part] = await astro.callTool([
  {
    name: "charts_birth",
    args: { date: "1973-04-24", time: "17:25", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 },
  },
]);
const response = part?.functionResponse?.response as { content: { type: string; text: string }[] };
const { data } = JSON.parse(response.content[0]!.text);
console.log(data.ascendant, data.planets.find((p: { name: string }) => p.name === "Moon"));

await client.close();

Each part is { functionResponse: { name, response } }, and response is the MCP result unchanged: { content: [{ type: "text", text }] }, with no structuredContent. The text is the API's JSON envelope (request_id, data, meta), so Gemini receives a JSON string inside content, not parsed fields. For the sample birth, data gave:

  • Ascendant Virgo 19.76°.
  • Moon Sagittarius 26.79°, house 4, nakshatra Uttara Ashadha pada 1.
  • Sun Aries 10.67°, house 8, Ashwini pada 4; Saturn Taurus 24.28°, house 9.
  • meta: ayanamsa lahiri, house system whole_sign, engine 1.2.2.

Two calls passed in one callTool array (charts_birth and dasha_vimshottari) came back as two parts in the same order; the SDK runs them one after another, not in parallel. Field meanings are on the Birth Chart API page.

How errors reach the model

A tool error is not thrown. When the MCP result has isError: true, the SDK wraps it as response: { error: <the MCP result> } - the error key that the SDK's FunctionResponse type documents for error details - and the loop carries on, so Gemini reads the message and can fix its arguments or explain. What we saw:

CaseWhat callTool returned
date: "24/04/1973"error.content[0].text: Input validation error: Invalid arguments for tool charts_birth: data/date must match pattern "^\d{4}-\d{2}-\d{2}$" - rejected by the server before any API call
No Authorization headerListing still returned 128 declarations; the call returned an error whose text says no API key was provided and how to send one
Tool name the client does not haveAn empty array: no part at all, and no error

The last row matters inside the loop: if the model invents a tool name, that call gets no function response. Network failures and the timeout from mcpToTool are different again - they reject the callTool promise, which rejects generateContent, so keep the try/finally that closes the client.

Validation happens against tz_offset_minutes as an integer from -840 to 840, so a model that sends 5.5 hours is caught, but one that guesses the wrong offset is not. See birth time and time zones.

Connection lifecycle

The hosted server is stateless, so one Client can serve many generateContent calls; create it at start-up, not per request, and close() it on shutdown. The SDK never closes it for you. A different tool set means a different URL, which means another Client and another mcpToTool - the filter is fixed when the client connects. For the local stdio server, swap the transport for StdioClientTransport running npx -y @astronode/mcp with ASTRONODE_API_KEY and, optionally, ASTRONODE_MCP_GROUPS in its env.

Questions

Which AstroNode endpoints does the Gemini API (@google/genai) example call?
1 endpoint: Birth Chart (Kundli) (POST /v1/charts/birth).
Was the Gemini API (@google/genai) code on this page actually run?
Run on 5 December 2026 with @google/genai 3.7.0 and @modelcontextprotocol/sdk 1.32.2 on Node 24, against the AstroNode API in memory behind a local copy of the MCP server (the hosted server runs the same code), with a test key. Executed: connecting over Streamable HTTP, mcpToTool(...).tool() on the full server (128 declarations) and with ?groups=charts,dasha,panchang,muhurta (12), callTool for charts_birth with the sample birth (the figures quoted below), two calls in one callTool, a malformed date, an unknown tool name and a client with no key. agent.ts typechecks under tsc --strict but was not executed: no Gemini API key was used, so no model call was made and nothing on this page says how Gemini itself treats the declarations.