← Integrations

AI agent · TypeScript

Use the AstroNode MCP server from the Vercel AI SDK

createMCPClient from @ai-sdk/mcp turns the hosted server's tools into AI SDK tools you pass straight to streamText. The key stays in your route handler; the browser only sees the streamed answer.

Updated

How this page was checked: Run on 5 December 2026 with ai 7.1.1 and @ai-sdk/mcp 2.0.110 on Node 24, against the MCP HTTP server (the same code as the hosted one) backed by the AstroNode API running in memory. The tool-listing script and the typed-schemas script ran as shown and printed the figures quoted here. The route handler ran with the AI SDK's own MockLanguageModelV4 from ai/test in place of the OpenAI model, scripted to call charts_birth: the tool call went to the server, the result reached the second model step, the response streamed, and onEnd closed the client. No real model was called - there was no provider key - so the model's own choice of tool and arguments was not tested. All three files typecheck under tsc --strict (TypeScript 7.0.2, with @ai-sdk/openai 4.0.130 and noUncheckedIndexedAccess). The error cases in the table were each produced by a run; the outputSchema mismatch row is from the package source, not a run.

Connect and call one tool

bash
npm install ai @ai-sdk/mcp @ai-sdk/openai zod

The built-in HTTP transport takes the URL and a headers object, so the key goes in as a normal Authorization header - no custom transport and no OAuth provider. This script lists the narrowed tool set and runs charts_birth through the AI SDK tool object, without a model:

check-tools.ts

typescript
import { createMCPClient } from "@ai-sdk/mcp";

const mcp = await createMCPClient({
  transport: {
    type: "http",
    url: "https://mcp.astronode.dev/mcp?groups=charts,dasha",
    headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}` },
  },
});

try {
  const tools = await mcp.tools();
  console.log(Object.keys(tools)); // the 6 charts_* and dasha_* tools

  const chartsBirth = tools["charts_birth"];
  if (!chartsBirth) throw new Error("charts_birth not offered - check ?groups=");

  const result = await chartsBirth.execute(
    { date: "1973-04-24", time: "17:25", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 },
    { toolCallId: "check-1", messages: [], context: {} },
  );
  // execute() is typed to allow a streamed result; MCP tools return one value.
  if (Symbol.asyncIterator in result) throw new Error("unexpected stream");
  if ("toolResult" in result || result.isError) throw new Error(JSON.stringify(result));

  const first = result.content[0];
  if (first?.type !== "text" || typeof first.text !== "string") throw new Error("expected a text block");
  const { data } = JSON.parse(first.text);
  console.log(data.ascendant);
} finally {
  await mcp.close();
}

Output

text
[
  'charts_birth',
  'charts_varga',
  'dasha_char',
  'dasha_lookup',
  'dasha_vimshottari',
  'dasha_yogini'
]
{ sign: 'Virgo', degree: 19.759582224440123 }

The handshake picked MCP protocol 2026-07-28, which is stateless: the client sends no session id and there is nothing to resume, so the session options in the AI SDK docs (initialSessionId, terminateSessionOnClose) do not apply to this server.

What tools() hands to the model

  • Names are unchanged. Each key is the server's tool name - charts_birth, dasha_vimshottari - with no prefix, so two MCP servers with the same tool name would collide in one tools object.
  • Dynamic tools. Without schemas, every tool is a dynamic tool typed unknown in and CallToolResult out. Its input schema is the server's JSON Schema wrapped in jsonSchema(), with additionalProperties: false forced on.
  • The server validates, not the SDK. A scripted model that sent an extra place field got back Input validation error: ... data must NOT have additional properties from the server as a tool result; a date of 24/04/1973 got data/date must match pattern. Neither threw.
  • Annotations come along. charts_birth carries metadata.title "Birth Chart (Kundli)" and readOnlyHint: true, idempotentHint: true, destructiveHint: false. The AI SDK does not act on them by itself; its docs show reading them in a toolApproval policy, Of the 128 tools, 120 are marked read-only; the other eight include the three that delete chat history or memory (destructiveHint: true), which such a policy would hold for approval.
  • What execute returns. The raw CallToolResult: content with one text block holding the API's { request_id, data, meta } JSON, isError: false, and _meta. This server sends no structuredContent.
  • What the model sees. toModelOutput turns that into a content part with the same text, so the model reads the full response JSON - 1,559 bytes for the sample chart.
Counts from Object.keys() on each run. The query parameters narrow the list on the server; `schemas` narrows it in the client after listing.
Client setupTools offered
url: "https://mcp.astronode.dev/mcp"128
?groups=charts,dasha6
?groups=charts,dasha,panchang (the route below)7
?tools=charts_birth1
full URL + tools({ schemas: { charts_birth } })1 (the other 127 are listed, then dropped)

Narrow on the server when you can: the model is sent every tool you pass, with its schema, on every step. The groups are listed on the MCP server page.

A Next.js route handler with streamText

app/api/chat/route.ts, in the shape the AI SDK's Next.js App Router guide uses. The key is read from the server's environment; the client component calling /api/chat never has it.

app/api/chat/route.ts

typescript
import { openai } from "@ai-sdk/openai";
import { createMCPClient } from "@ai-sdk/mcp";
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  isStepCount,
  streamText,
  toUIMessageStream,
  type UIMessage,
} from "ai";

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const mcp = await createMCPClient({
    transport: {
      type: "http",
      url: "https://mcp.astronode.dev/mcp?groups=charts,dasha,panchang",
      headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}` },
    },
  });

  let tools;
  try {
    tools = await mcp.tools();
  } catch (err) {
    await mcp.close();
    throw err;
  }

  const result = streamText({
    model: openai("gpt-6.2-astra"),
    system:
      "Use the AstroNode tools for every chart figure. tz_offset_minutes is the UTC offset in minutes at the birth moment (330 for India).",
    messages: await convertToModelMessages(messages),
    tools,
    stopWhen: isStepCount(5),
    // The tools' execute() calls the MCP server, so the client must stay open
    // until the last step has run - close it when the stream ends, not here.
    onEnd: async () => {
      await mcp.close();
    },
    onAbort: async () => {
      await mcp.close();
    },
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}

Where you close the client matters. streamText returns before any tool has run, so a try/finally around it would close the client while the model is still deciding to call charts_birth. A tool executed on a closed client throws MCPClientError: Attempted to send a request from a closed client. The AI SDK docs close in onEnd; the route also closes in onAbort for a client that disconnects mid-stream.

With the scripted model, the UI message stream carried tool-input-available with the five birth fields, then tool-output-available with the whole CallToolResult, then the answer text. That means the browser receives the full chart JSON as well as the answer - fine for a chart, but worth knowing before you expose tools whose output you would rather keep server-side.

Typed tools with schemas

Passing schemas gives you static types for the tools you name, and an outputSchema validates the result. Because this server returns its JSON as text rather than structuredContent, the client takes the documented fallback: it parses the first text block and validates that against your zod schema.

typed-tools.ts

typescript
import { createMCPClient } from "@ai-sdk/mcp";
import { z } from "zod";

const Birth = z.object({
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
  time: z.string().regex(/^\d{2}:\d{2}(:\d{2})?$/),
  tz_offset_minutes: z.number().int().min(-840).max(840),
  lat: z.number().min(-90).max(90),
  lng: z.number().min(-180).max(180),
});

const Envelope = z.object({
  request_id: z.string(),
  data: z.object({
    ascendant: z.object({ sign: z.string(), degree: z.number() }),
    planets: z.array(
      z.object({ name: z.string(), sign: z.string(), house: z.number(), nakshatra: z.string() }),
    ),
  }),
});

const mcp = await createMCPClient({
  transport: {
    type: "http",
    url: "https://mcp.astronode.dev/mcp",
    headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}` },
  },
});

try {
  // Only the tools named here are converted; the other 127 are dropped.
  const tools = await mcp.tools({
    schemas: { charts_birth: { inputSchema: Birth, outputSchema: Envelope } },
  });

  const chart = await tools.charts_birth.execute(
    { date: "1973-04-24", time: "17:25", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 },
    { toolCallId: "typed-1", messages: [], context: {} },
  );
  if (Symbol.asyncIterator in chart) throw new Error("unexpected stream");
  // An isError result skips outputSchema and arrives as the raw MCP result,
  // whatever the static type says - check before reading .data.
  if ("isError" in chart) throw new Error(JSON.stringify(chart));
  const moon = chart.data.planets.find((p) => p.name === "Moon");
  console.log(chart.data.ascendant.sign, moon?.sign, moon?.nakshatra);
} finally {
  await mcp.close();
}

Output

text
Virgo Sagittarius Uttara Ashadha

The static type says execute returns your Envelope, but an isError result is returned before the output schema is applied. Run with an invalid key and without the isError check, chart.data is undefined and the script crashes with Cannot read properties of undefined (reading 'planets'). Keep the check.

Your zod schema only needs the fields you read - zod drops the rest - but if the response stops matching it, execute throws MCPClientError instead of returning, so a too-strict schema turns into a failed step rather than a tool result the model can read.

How errors arrive

Caseexecute()What the model gets
Date as 24/04/1973returns isError: trueerror-text: Input validation error: ... data/date must match pattern
Extra argument (place)returns isError: trueerror-text: ... must NOT have additional properties
No key in the headerreturns isError: true (listing still works: 128 tools)error-text: "No AstroNode API key was provided, so this tool cannot run..."
Invalid keyreturns isError: trueerror-text: HTTP 401 with UNAUTHORIZED / Invalid API key
Client already closedthrows MCPClientErrora failed tool call, not a result
outputSchema mismatch (source, not run)throws MCPClientErrora failed tool call, not a result

The first four come back as an ordinary tool-result in the step, so generateText and streamText carry on and the model can correct the date or tell the user to check the key. maxRetries on createMCPClient does not retry them - the docs limit it to transient transport failures - which is right here: retrying a bad date or a bad key gives the same answer.

Because listing works without a key, a missing ASTRONODE_API_KEY does not fail at startup; it shows up only on the first tool call. Check the variable when the route starts if you want it to fail early. What each call costs is on the MCP server page.

Questions

Which AstroNode endpoints does the Vercel AI SDK example call?
1 endpoint: Birth Chart (Kundli) (POST /v1/charts/birth).
Was the Vercel AI SDK code on this page actually run?
Run on 5 December 2026 with ai 7.1.1 and @ai-sdk/mcp 2.0.110 on Node 24, against the MCP HTTP server (the same code as the hosted one) backed by the AstroNode API running in memory. The tool-listing script and the typed-schemas script ran as shown and printed the figures quoted here. The route handler ran with the AI SDK's own MockLanguageModelV4 from ai/test in place of the OpenAI model, scripted to call charts_birth: the tool call went to the server, the result reached the second model step, the response streamed, and onEnd closed the client. No real model was called - there was no provider key - so the model's own choice of tool and arguments was not tested. All three files typecheck under tsc --strict (TypeScript 7.0.2, with @ai-sdk/openai 4.0.130 and noUncheckedIndexedAccess). The error cases in the table were each produced by a run; the outputSchema mismatch row is from the package source, not a run.