> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloud.cdata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js

> This page outlines the steps to connect Node.js to Connect AI Embed, either through the MCP server or directly through the Connect AI Embed REST API.

## Prerequisites

Before you can configure and use Node.js with Connect AI Embed, you must first do the following:

* Generate an [OAuth JWT bearer token](/en/API/Authentication-Embedded). Copy this down, as it acts as your password during authentication.
* Install Node.js 18 or later (required for built-in `fetch`).
* If you plan to use the LangChain.js / LangGraph example below, obtain an OpenAI API key: [https://platform.openai.com/](https://platform.openai.com/).

## Connect through LangChain.js and LangGraph

LangChain.js and LangGraph can call the Connect AI Embed MCP server through the `@langchain/mcp-adapters` package. The example below uses `@langchain/langgraph` to build a ReAct-style agent on top of the MCP tools — the agent discovers the MCP tools and uses them to answer prompts.

<Steps>
  <Step>
    Create a folder for the project and initialize it:

    ```bash theme={null}
    mkdir connect-ai-mcp
    cd connect-ai-mcp
    npm init -y
    ```
  </Step>

  <Step>
    Install the LangChain.js and MCP adapter packages:

    ```bash theme={null}
    npm install @langchain/mcp-adapters @langchain/openai @langchain/langgraph
    ```
  </Step>

  <Step>
    Create a file called `langchain.mjs` and paste the following. Replace `OAUTH_JWT_TOKEN` with the token from the prerequisites and `YOUR_OPENAI_API_KEY` with your OpenAI API key:

    ```javascript expandable wrap theme={null}
    import { MultiServerMCPClient } from "@langchain/mcp-adapters";
    import { ChatOpenAI } from "@langchain/openai";
    import { createReactAgent } from "@langchain/langgraph/prebuilt";

    const mcpClient = new MultiServerMCPClient({
      mcpServers: {
        default: {
          transport: "streamable_http",
          url: "https://mcp.cloud.cdata.com/mcp",
          headers: {
            Authorization: "Bearer OAUTH_JWT_TOKEN", // Replace with your OAuth JWT token
          },
        },
      },
    });

    // Load remote MCP tools exposed by the Connect AI Embed server
    const tools = await mcpClient.getTools();
    console.log("Discovered MCP tools:", tools.map((t) => t.name));

    // Create and run the ReAct-style agent
    const llm = new ChatOpenAI({
      model: "gpt-4o",
      temperature: 0.2,
      apiKey: "YOUR_OPENAI_API_KEY", // Replace with your OpenAI API key
    });

    const agent = createReactAgent({ llm, tools });

    const userPrompt = "Tell me how many sales I had in Q1 for the current fiscal year.";
    console.log(`\nUser prompt: ${userPrompt}`);

    const response = await agent.invoke({
      messages: [{ role: "user", content: userPrompt }],
    });

    console.log("Agent final response:", response.messages.at(-1).content);
    ```
  </Step>

  <Step>
    Run the script:

    ```bash theme={null}
    node langchain.mjs
    ```

    The script discovers the Connect AI Embed MCP tools and uses them to answer the prompt.
  </Step>
</Steps>

## Connect Directly to the Connect AI Embed REST API

If you do not want to go through the MCP server, you can call the Connect AI Embed REST API directly from Node.js with `fetch`. The API accepts a JSON body with a `query` field and the JWT bearer token in the `Authorization` header. See [REST API](/en/API/REST-API-Embedded) for the full response format.

<Steps>
  <Step>
    Create a file called `connect-ai-client.mjs` and paste the following. Replace `OAUTH_JWT_TOKEN` with the token from the prerequisites:

    ```javascript expandable wrap theme={null}
    const API_URL = "https://cloud.cdata.com/api/query";
    const JWT = "OAUTH_JWT_TOKEN"; // Replace with your OAuth JWT token

    async function runQuery(query) {
      const response = await fetch(API_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${JWT}`,
        },
        body: JSON.stringify({ query }),
      });

      if (!response.ok) {
        throw new Error(`Request failed: ${response.status} ${await response.text()}`);
      }

      const data = await response.json();

      // The API returns a 200 even when a partial-result error occurs, so always check for error.
      if (data.error) {
        throw new Error(`${data.error.code}: ${data.error.message}`);
      }

      return data.results[0];
    }

    const result = await runQuery("SELECT * FROM Salesforce1.Salesforce.Account LIMIT 5");
    console.log("Columns:", result.schema.map((c) => c.columnName));
    console.log("Rows:", result.rows);
    ```
  </Step>

  <Step>
    Run the script:

    ```bash theme={null}
    node connect-ai-client.mjs
    ```
  </Step>
</Steps>
