Tutorials & Integrations

JavaScript Integration

Written by , Product docsLast updated

Use Hive from server-side Node.js, serverless functions, and trusted backend runtimes with fetch. This guide covers bearer authentication, REST execution, tool discovery, reusable client code, and TypeScript shapes for apps that need live crypto market, wallet, DeFi, and security data. Browser code must call your own backend so the Hive API key never reaches the client.

The TypeScript MCP adapter source is at the 0.2.0 release candidate and mirrored at github.com/hive-intel/hive-sdk under client/. The npm package may remain on 0.1.5 until the ordered release completes, so verify the published version before depending on the new stateful-router helpers. Use REST for non-TypeScript stacks.


Quick start

javascript
const baseUrl = "https://mcp.hiveintelligence.xyz";
const apiKey = process.env.HIVE_API_KEY;

async function execute(tool, args = {}) {
  const response = await fetch(`${baseUrl}/api/v1/execute`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({ tool, args }),
  });

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

  const payload = await response.json();

  if (payload.ok === false) {
    throw new Error(payload.error?.message ?? "Hive execution failed");
  }

  return payload;
}

const price = await execute("get_price", {
  ids: "bitcoin",
  vs_currencies: "usd",
});

console.log(price.data.bitcoin.usd);
console.log({
  retrievedAt: price.meta.fetched_at,
  observedAt: price.meta.observed_at,
  cacheAgeMs: price.meta.cache_age_ms,
  receiptId: price.meta.receipt_id,
  receiptVersion: price.meta.receipt_version,
});

fetched_at records when Hive completed the retrieval, observed_at is Hive's first observation, and cache_age_ms is Hive cache age. Before presenting a value as current, inspect any provider timestamp, block, slot, or candle close inside data; if none exists, label source recency unknown. Keep the receipt fields with logs and user-visible provenance.


Browser-facing applications

Do not call Hive directly from browser JavaScript. Keep the key in a server route, allowlist the tools your UI needs, and have the browser call that route:

typescript
// app/api/market-data/route.ts
import { NextResponse } from "next/server";

const ALLOWED_TOOLS = new Set(["get_price", "get_coins_market_data"]);

export async function POST(request: Request) {
  const apiKey = process.env.HIVE_API_KEY;
  if (!apiKey) {
    return NextResponse.json({ error: "Hive is not configured" }, { status: 503 });
  }

  const { tool, args } = await request.json();
  if (typeof tool !== "string" || !ALLOWED_TOOLS.has(tool)) {
    return NextResponse.json({ error: "Tool is not allowed" }, { status: 400 });
  }

  const response = await fetch("https://mcp.hiveintelligence.xyz/api/v1/execute", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({ tool, args: args ?? {} }),
  });

  return new NextResponse(await response.text(), {
    status: response.status,
    headers: { "Content-Type": "application/json" },
  });
}

The browser sends only the selected tool and arguments to /api/market-data; it never receives HIVE_API_KEY. Protect this route with your application's authentication and rate limits, and validate each allowed tool's argument shape before exposing it to untrusted callers.


Reusable client

javascript
class HiveClient {
  constructor({
    apiKey,
    baseUrl = "https://mcp.hiveintelligence.xyz",
  }) {
    this.apiKey = apiKey;
    this.baseUrl = baseUrl;
  }

  async execute(tool, args = {}) {
    const response = await fetch(`${this.baseUrl}/api/v1/execute`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify({ tool, args }),
    });

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

    const payload = await response.json();

    if (payload.ok === false) {
      throw new Error(payload.error?.message ?? "Hive execution failed");
    }

    return payload;
  }

  async listTools(limit = 50) {
    const response = await fetch(`${this.baseUrl}/api/v1/tools?limit=${limit}`, {
      headers: { Authorization: `Bearer ${this.apiKey}` },
    });

    if (!response.ok) {
      throw new Error(`Tool discovery failed: ${response.status}`);
    }

    return response.json();
  }
}

const client = new HiveClient({ apiKey: process.env.HIVE_API_KEY });

const market = await client.execute("get_coins_market_data", {
  vs_currency: "usd",
  order: "market_cap_desc",
  per_page: 5,
});

const wallet = await client.execute("alchemy_get_token_balances_by_wallet", {
  address: "0x1234...",
  network: "eth-mainnet",
});

console.log(market.data);
console.log(wallet.data);

TypeScript shape

typescript
type ExecuteArgs = Record<string, unknown>;

interface HiveExecutionMeta {
  cache_status?: string;
  cache_age_ms?: number | null;
  category?: string;
  duration_ms?: number;
  fetched_at?: string;
  observed_at?: string | null;
  provider?: string;
  receipt_id?: string;
  receipt_version?: "1.0";
  runtime_status?: string;
  source?: string;
  tool?: string;
  truncated?: boolean;
  warnings?: string[];
}

type HiveExecuteResponse<T> =
  | {
      ok: true;
      data: T;
      meta: HiveExecutionMeta;
    }
  | {
      ok: false;
      error: {
        code?: string;
        doc_url?: string;
        message: string;
        request_id?: string;
        type?: string;
      };
    };

interface HiveClientOptions {
  apiKey: string;
  baseUrl?: string;
}

class HiveClient {
  constructor(private options: HiveClientOptions) {}

  async execute<T>(
    tool: string,
    args: ExecuteArgs = {},
  ): Promise<Extract<HiveExecuteResponse<T>, { ok: true }>> {
    const response = await fetch(`${this.options.baseUrl ?? "https://mcp.hiveintelligence.xyz"}/api/v1/execute`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${this.options.apiKey}`,
      },
      body: JSON.stringify({ tool, args }),
    });

    if (!response.ok) {
      throw new Error(`Hive request failed: ${response.status}`);
    }

    const payload = (await response.json()) as HiveExecuteResponse<T>;

    if (!payload.ok) {
      throw new Error(payload.error.message);
    }

    return payload;
  }
}

type PriceResponse = {
  bitcoin?: { usd?: number };
  _hive?: HiveExecutionMeta;
};

const price = await new HiveClient({
  apiKey: process.env.HIVE_API_KEY!,
}).execute<PriceResponse>("get_price", {
  ids: "bitcoin",
  vs_currencies: "usd",
});

console.log(price.data.bitcoin?.usd);
console.log({
  retrievedAt: price.meta.fetched_at,
  observedAt: price.meta.observed_at,
  cacheAgeMs: price.meta.cache_age_ms,
  receiptId: price.meta.receipt_id,
  receiptVersion: price.meta.receipt_version,
});

Common patterns

Market monitoring

javascript
const gainers = await client.execute("get_gainers_losers", {
  vs_currency: "usd",
  duration: "24h",
});

console.log(gainers.data);

Wallet analysis

javascript
const balances = await client.execute("get_wallet_balances", {
  network: "eth",
  address: "0x1234...",
});

console.log(balances.data);

DeFi monitoring

javascript
const pools = await client.execute("get_yield_pools", {
  chain: "ethereum",
});

console.log(pools.data);

Prediction markets

javascript
const markets = await client.execute("codex_prediction_markets", {
  networkId: 1,
});

console.log(markets.data);

TypeScript MCP adapter

The currently published adapter is hive-mcp-client@0.1.5; the source-backed 0.2.0 release candidate adds stateful invoker routing and resource-template support. Its source is mirrored in the public github.com/hive-intel/hive-sdk repository under client/. Check npm view hive-mcp-client version before depending on 0.2.0 APIs, then keep the Hive API key and any subject-signing secret on the server.

bash
npm install hive-mcp-client
typescript
import {
  createHiveMcpClient,
  getHiveEndpointSchema,
  invokeHiveEndpoint,
  rankHiveCategoriesForQuery,
  readHiveMetadataSnapshot,
  searchHiveTools,
} from "hive-mcp-client";

const hive = await createHiveMcpClient({
  apiKey: process.env.HIVE_API_KEY,
  clientName: "my-backend",
});

try {
  await searchHiveTools(hive, {
    query: "wallet malicious risk",
    limit: 10,
  });

  const schema = await getHiveEndpointSchema(hive, "check_malicious_address");
  const result = await invokeHiveEndpoint(hive, "check_malicious_address", {
    chainId: "1",
    address: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
  });

  const metadata = await readHiveMetadataSnapshot(hive);
  const ranked = rankHiveCategoriesForQuery("wallet approvals risk", metadata);

  console.log(schema.json, result.json ?? result.text, metadata.status, ranked[0]?.toolName);
} finally {
  await hive.close();
}

The adapter covers the production path a TypeScript backend needs:

  • core helpers for root MCP discovery, tool search, schema lookup, endpoint invocation, endpoint alias normalization, result normalization, metadata snapshots, category ranking, retries, and timeouts.
  • hive-mcp-client/b2b for readiness checks, signed subject headers, hive-mcp doctor, and adapter methods for watchlist digest monitors, risk watches, token discovery risk, alerts, reports, memory facts, monitor cleanup, forSubject(), callForSubject(), and subject audit reads.
  • hive-mcp-client/ai-sdk for Vercel AI SDK MCP transport config and ranked/core/all tool selection so models do not receive every category tool at once.
  • hive-mcp-client/langchain for createHiveLangChainTools; install @langchain/core only in apps that use that export.

searchHiveTools, getHiveEndpointSchema, and invokeHiveEndpoint already return normalized results with isError, json, text, raw, optional structuredContent, and a validated receipt when the result carries the complete server-issued _hive contract. Use normalizeHiveToolResult only when you call the lower-level client.callTool() method directly; use extractHiveExecutionReceipt when you need to validate and extract a receipt from an already parsed tool payload.

Adapter API map

Export pathUse it forSource-backed API
hive-mcp-clientServer-side MCP clients that need discovery, resources, prompts, schema lookup, read-only or approved stateful invocation, aliases, and metadata.createHiveMcpClient, searchHiveTools, getHiveEndpointSchema, invokeHiveEndpoint, invokeHiveStatefulEndpoint, normalizeHiveToolCall, resolveHiveEndpointName, normalizeHiveEndpointArgs, readHiveMetadataSnapshot, rankHiveCategoriesForQuery, extractHiveExecutionReceipt, extractHiveSources, normalizeHiveToolResult, stringifyHiveToolResult
hive-mcp-client/b2bPartner backends that isolate downstream customer state with signed subject context.Named exports: checkHiveB2BReadiness, createHiveB2BAdapter, createHiveB2BAdapterFromClient. Adapter methods: createWatchlistDigestMonitor, createRiskWatchMonitor, createTokenDiscoveryRiskMonitor, createMonitor, listMonitors, archiveMonitor, listAlerts, acknowledgeAlert, resolveAlert, updateAlertStatus, rememberFact, listMemoryFacts, forgetMemoryFact, generateMonitorReport, callForSubject, forSubject, listSubjectAuditEvents, close
hive-mcp-client/ai-sdkVercel AI SDK MCP tool loading without sending every category tool to the model.buildAiSdkHiveMcpTransportConfig, selectHiveMcpToolDefinitions, prepareHiveAiSdkTools
hive-mcp-client/langchainLangChain apps that want Hive's compact root tools plus category discovery tools.createHiveLangChainTools

Full runtime export coverage

The adapter also exports lower-level helpers for backends that need custom transports, subject signing, result normalization, or contract checks. Treat these as server-side utilities unless your application has already isolated secrets away from browser code.

AreaRuntime exports
Client and authcreateHiveMcpClient, buildHiveAuthHeaders, HIVE_DEFAULT_MCP_URL, HIVE_MCP_CLIENT_VERSION
Root-tool constantsHIVE_CORE_TOOL_NAMES, HIVE_STATEFUL_WRITE_ENDPOINT_NAMES, HIVE_CATEGORY_TOOL_NAMES, HIVE_REMOVED_CATEGORY_TOOL_NAMES
Metadata constantsHIVE_COMPACT_METADATA_RESOURCE_URIS, HIVE_METADATA_RESOURCE_URIS, HIVE_PROVIDER_NAMES
Discovery and aliasesHIVE_ENDPOINT_ALIASES, searchHiveTools, getHiveEndpointSchema, invokeHiveEndpoint, invokeHiveStatefulEndpoint, resolveHiveEndpointName, normalizeHiveEndpointArgs, normalizeHiveToolCall, rankHiveCategoriesForQuery
Runtime contract checksisHiveCurrentRootToolName, isRemovedHiveCategoryToolName, inspectHiveRootContract
Metadata cacheisHiveMetadataResourceUri, readHiveMetadataSnapshot, resetHiveMetadataCache
Result and source handlingnormalizeHiveToolResult, stringifyHiveToolResult, extractHiveExecutionReceipt, extractHiveSources, inferHiveProvider, inferHiveCategory, stableHiveCacheKey
Subject signingHIVE_TENANT_ID_HEADER, HIVE_END_USER_ID_HEADER, HIVE_SUBJECT_TIMESTAMP_HEADER, HIVE_SUBJECT_BODY_SHA256_HEADER, HIVE_SUBJECT_SIGNATURE_HEADER, buildHiveSubjectBodyDigest, buildHiveSubjectSignaturePayload, signHiveSubjectHeaders, buildHiveSubjectHeaders
B2B adapterHIVE_B2B_RECOMMENDED_MONITOR_KINDS, checkHiveB2BReadiness, createHiveB2BAdapter, createHiveB2BAdapterFromClient
Vercel AI SDKbuildAiSdkHiveMcpTransportConfig, selectHiveMcpToolDefinitions, prepareHiveAiSdkTools
LangChaincreateHiveLangChainTools

Runtime controls

typescript
const hive = await createHiveMcpClient({
  apiKey: process.env.HIVE_API_KEY,
  clientName: "my-backend",
  connectTimeoutMs: 18_000,
  requestTimeoutMs: 22_000,
  retry: {
    attempts: 2,
    baseDelayMs: 500,
  },
});

createHiveMcpClient() exposes listTools, listResources, listResourceTemplates, readResource, listPrompts, getPrompt, callTool, withSubject, and close. Tool calls retry with exponential backoff; validation errors, missing keys, plan limits, and user-input mistakes should be handled by your application logic instead of retried blindly.

Install the adapter with npm install hive-mcp-client for TypeScript backends. Use REST for non-TypeScript stacks.


Production usage

Keep the Hive API key server-side for browser-facing apps. Browser code should call your own backend or serverless route, then that route should call Hive with Authorization: Bearer YOUR_HIVE_API_KEY. Add short TTL caching for prices and protocol metadata. Discovery calls are free of execution credits, but caching stable catalogs still reduces latency.


Notes

  • The current REST request payload keys are tool and args.
  • REST execution returns { ok, data, meta }; read provider fields from data, not from the response root.
  • fetched_at is Hive retrieval completion; observed_at and cache_age_ms describe Hive's capture/cache timeline. Use provider-native timestamps, blocks, slots, or candle closes for source recency, and label it unknown when absent.
  • Preserve receipt_id and receipt_version in application logs and user-visible provenance so an exact execution can be traced.
  • Use GET /api/v1/tools or Live Catalog when choosing tool names.
  • Prefer the MCP endpoint if your runtime already supports tool discovery natively.