Tutorials & Integrations

JavaScript Integration

Written by , Product docsLast updated

Use Hive from browsers, serverless functions, and Node.js 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.

The official TypeScript MCP adapter is published on npm as hive-mcp-client@0.1.5 (npm install hive-mcp-client); its source is mirrored at github.com/hive-intel/hive-sdk under client/. 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(price.meta.fetched_at);

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;
  category?: string;
  duration_ms?: number;
  fetched_at?: string;
  provider?: string;
  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(price.meta.fetched_at);

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 official adapter is published on npm as hive-mcp-client@0.1.5. Its source is mirrored in the public github.com/hive-intel/hive-sdk repository under client/ and maintained from packages/mcp-client in the canonical Hive MCP source tree. Install it from npm, 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, and optional structuredContent. Use normalizeHiveToolResult only when you call the lower-level client.callTool() method directly.

Adapter API map

Export pathUse it forSource-backed API
hive-mcp-clientServer-side MCP clients that need discovery, resources, prompts, schema lookup, endpoint invocation, aliases, and metadata.createHiveMcpClient, searchHiveTools, getHiveEndpointSchema, invokeHiveEndpoint, normalizeHiveToolCall, resolveHiveEndpointName, normalizeHiveEndpointArgs, readHiveMetadataSnapshot, rankHiveCategoriesForQuery, 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
Root-tool constantsHIVE_CORE_TOOL_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, resolveHiveEndpointName, normalizeHiveEndpointArgs, normalizeHiveToolCall, rankHiveCategoriesForQuery
Runtime contract checksisHiveCurrentRootToolName, isRemovedHiveCategoryToolName, inspectHiveRootContract
Metadata cacheisHiveMetadataResourceUri, readHiveMetadataSnapshot, resetHiveMetadataCache
Result and source handlingnormalizeHiveToolResult, stringifyHiveToolResult, extractHiveSources, inferHiveProvider, inferHiveCategory, stableHiveCacheKey
Subject signingHIVE_TENANT_ID_HEADER, HIVE_END_USER_ID_HEADER, HIVE_SUBJECT_TIMESTAMP_HEADER, HIVE_SUBJECT_SIGNATURE_HEADER, 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, 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, protocol metadata, and discovery responses so user traffic does not burn unnecessary credits.


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.
  • Use GET /api/v1/tools or Live Catalog when choosing tool names.
  • Prefer the MCP endpoint if your runtime already supports tool discovery natively.