← Integrations

AI agent · TypeScript

Give a LangChain.js agent the AstroNode MCP tools

@langchain/mcp-adapters turns each tool on the AstroNode MCP server into a LangChain DynamicStructuredTool. Hand the list to createAgent and the model can compute charts, dashas and panchang; call a tool yourself and you get the API's JSON back without a model in the loop.

Updated

How this page was checked: Run on 5 December 2026 with @langchain/mcp-adapters 2.0.3, @langchain/core 1.5.2 and langchain 1.6.10 on Node 24, against the AstroNode MCP server (the same code as the hosted one) running locally over the in-memory API with a test key. Executed: listing tools (128, then 6 with ?groups=charts,dasha and 1 with ?tools=charts_birth), calling charts_birth through the LangChain tool object both directly and as a tool call, the three name-prefix settings, the bad-argument, wrong-key and missing-key errors, and createAgent's tool loop driven by LangChain's scripted fakeModel test model, with and without toolErrorMiddleware. Not executed: a real model. The agent code with ChatOpenAI was typechecked with tsc --noEmit --strict (TypeScript 7.0.2) but never called OpenAI, so which tools a real model picks, and its arguments, were not observed.

Install and connect

bash
npm install langchain @langchain/core @langchain/langgraph @langchain/mcp-adapters @langchain/openai

Version 2 of the adapter uses MCPAdapter with a servers map and listTools(); MultiServerMCPClient, mcpServers and getTools() still exist but are deprecated. A server entry with a url is Streamable HTTP, which is what the hosted server speaks, and headers carries your key:

typescript
import { createAgent } from "langchain";
import { ChatOpenAI } from "@langchain/openai";
import { MCPAdapter } from "@langchain/mcp-adapters";

const adapter = new MCPAdapter({
  servers: {
    astronode: {
      url: "https://mcp.astronode.dev/mcp?groups=charts,dasha",
      headers: { Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}` }, // aie_live_...
    },
  },
});

try {
  const tools = await adapter.listTools(); // 6 tools, named astronode_charts_birth etc.
  const agent = createAgent({
    model: new ChatOpenAI({ model: "gpt-4.1-mini" }),
    tools,
    systemPrompt:
      "Answer astrology questions only from AstroNode tool results. Pass tz_offset_minutes as whole minutes east of UTC.",
  });

  const result = await agent.invoke({
    messages: [
      {
        role: "user",
        content: "What is my ascendant? Born 24 April 1973, 17:25, Mumbai (IST).",
      },
    ],
  });
  console.log(result.messages.at(-1)?.content);
} finally {
  await adapter.close();
}

Creating the adapter opens nothing; listTools() connects. Keep it open while the agent runs - the tools call through it - and close() it when you are done. After close() the adapter can be used again: the next listTools() discovers afresh with new connections. Any chat model with tool calling can replace ChatOpenAI.

To run the server on your own machine instead, use a stdio entry: { transport: "stdio", command: "npx", args: ["-y", "@astronode/mcp"], env: { ASTRONODE_API_KEY: process.env.ASTRONODE_API_KEY! } }. The tools are the same; narrow them with ASTRONODE_MCP_GROUPS in env.

Tool names get the server name in front

In version 2, MCPAdapter prefixes every tool with the key you gave the server in servers and a single underscore (the lower-level loadMcpTools() does not). The map key is therefore part of every tool name the model sees, and of any approval rule or middleware filter that refers to a tool by name. Names observed for the server's charts_birth tool:

The adapter strips the prefix again when it sends the call, so the server always receives `charts_birth`.
Adapter optionLangChain tool name
(defaults), server key astronodeastronode_charts_birth
prefixToolNameWithServerName: falsecharts_birth
additionalToolNamePrefix: "mcp"mcp__astronode_charts_birth

If you connect several MCP servers and turn the prefix off, listTools() throws when two servers offer a tool with the same name rather than silently keeping one.

Schemas are passed through as JSON Schema

The adapter does not translate the server's input schemas into Zod. Each tool's schema is the JSON Schema the server published - for charts_birth an object with date (pattern YYYY-MM-DD), time, tz_offset_minutes (an integer from -840 to 840), lat, lng, an optional interpretation object, and additionalProperties: false. That is the schema createAgent binds to the model, examples and descriptions included.

LangChain checks arguments against the schema before anything goes over the network. tz_offset_minutes: 5.5, a date written 24/04/1973, or a call with only date each threw ToolInputParsingException ("Received tool input did not match expected schema") on a direct invoke, and no request reached the server, so none of them used an API call. The message does not say which field failed.

What a tool returns

The tools are built with responseFormat: "content_and_artifact". What you get back depends on how you call one:

typescript
const birthTool = tools.find((t) => t.name === "astronode_charts_birth")!;
const birth = { date: "1973-04-24", time: "17:25", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 };

// Plain arguments: the content only, here a JSON string.
const json = await birthTool.invoke(birth);
console.log(JSON.parse(json).data.ascendant); // { sign: "Virgo", degree: 19.759582224440123 }

// A tool call (what the agent does): a ToolMessage with content and artifact.
const msg = await birthTool.invoke({ type: "tool_call", id: "call_1", name: birthTool.name, args: birth });
console.log(msg.status, msg.artifact); // "success", [{ type: "mcp_meta", ... }]

The content is the API response as text - { request_id, data, meta }, the same body the Birth Chart API returns. For the sample birth it gave a Virgo ascendant at 19.76°, the Moon in Sagittarius at 26.79° in Uttara Ashadha pada 1 (4th house), the Sun in Aries at 10.67° in Ashwini, with ayanamsa: "lahiri", house_system: "whole_sign" and engine version 1.2.2. Because it is text, the adapter's default outputHandling routes all of it to the model (text goes to content; only resource blocks default to artifact). The artifact held one mcp_meta entry with the server's name and version, nothing the model needs.

A full birth-chart response is around 1.5 KB of JSON and goes into the conversation each time the tool runs. If you only need a few fields for the model, the adapter's afterToolCall hook can rewrite the result before it becomes the ToolMessage.

Errors inside the agent loop

With the agent driven by a scripted test model (so the exact tool calls were known), errors did not stop the run: each one came back to the model as a ToolMessage with status: "error", and the next, correct call in the same run succeeded. Called directly, the same failures throw:

Observed with the local server and a scripted model on 5 December 2026.
CaseDirect invoke(args)Inside createAgent
tz_offset_minutes: 5.5throws ToolInputParsingExceptionerror ToolMessage: "Error invoking tool 'astronode_charts_birth' with kwargs {...} with error: Error: Received tool input did not match expected schema" plus a JavaScript stack trace - about 2.3 KB
Wrong API keythrows ToolException: "MCP tool 'charts_birth' on server 'astronode' returned an error: HTTP 401. {... "code":"UNAUTHORIZED","message":"Invalid API key"}"error ToolMessage with the server's text: HTTP 401. and the API's error JSON
No Authorization headerlistTools() still returns every tool; the call throws ToolException with the server's messageerror ToolMessage: "No AstroNode API key was provided, so this tool cannot run..."

Server-side errors arrive as the server worded them, which is usually what the model should read. The schema error is the weak one: the model is told its input was wrong but not which field, and it receives a stack trace with file paths from your server. toolErrorMiddleware from langchain replaces it with something shorter:

typescript
import { createAgent, toolErrorMiddleware, ToolInvocationError } from "langchain";

const agent = createAgent({
  model,
  tools,
  middleware: [
    toolErrorMiddleware({
      onError: (error, request) => {
        if (ToolInvocationError.isInstance(error)) {
          return `Arguments for ${request.toolCall.name} do not match its schema. Check types: tz_offset_minutes is a whole number of minutes, date is YYYY-MM-DD.`;
        }
      },
    }),
  ],
});

With it, the 5.5-offset call came back as that one sentence. The middleware only sees errors that are thrown; the 401 and missing-key results never reach onError, because the adapter already turns an MCP error result into an error ToolMessage when it runs as part of a tool call.

Narrowing the tool list

All 128 tools loaded without complaint from the adapter. To give the model fewer, filter on the server rather than in LangChain, so the discarded schemas are never sent: ?groups=charts,dasha on the URL produced astronode_charts_birth, astronode_charts_varga, astronode_dasha_char, astronode_dasha_lookup, astronode_dasha_vimshottari and astronode_dasha_yogini, and ?tools=charts_birth produced the one tool. Group names and the cost of a call are on the MCP server page.

For Python, LangChain publishes a separate package, langchain-mcp-adapters; the code on this page is TypeScript only.

Questions

Which AstroNode endpoints does the LangChain.js example call?
1 endpoint: Birth Chart (Kundli) (POST /v1/charts/birth).
Was the LangChain.js code on this page actually run?
Run on 5 December 2026 with @langchain/mcp-adapters 2.0.3, @langchain/core 1.5.2 and langchain 1.6.10 on Node 24, against the AstroNode MCP server (the same code as the hosted one) running locally over the in-memory API with a test key. Executed: listing tools (128, then 6 with ?groups=charts,dasha and 1 with ?tools=charts_birth), calling charts_birth through the LangChain tool object both directly and as a tool call, the three name-prefix settings, the bad-argument, wrong-key and missing-key errors, and createAgent's tool loop driven by LangChain's scripted fakeModel test model, with and without toolErrorMiddleware. Not executed: a real model. The agent code with ChatOpenAI was typechecked with tsc --noEmit --strict (TypeScript 7.0.2) but never called OpenAI, so which tools a real model picks, and its arguments, were not observed.