Tutorials & Integrations
JavaScript Integration
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
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:
// 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
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
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
const gainers = await client.execute("get_gainers_losers", {
vs_currency: "usd",
duration: "24h",
});
console.log(gainers.data);Wallet analysis
const balances = await client.execute("get_wallet_balances", {
network: "eth",
address: "0x1234...",
});
console.log(balances.data);DeFi monitoring
const pools = await client.execute("get_yield_pools", {
chain: "ethereum",
});
console.log(pools.data);Prediction markets
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.
npm install hive-mcp-clientimport {
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/b2bfor 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-sdkfor 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/langchainforcreateHiveLangChainTools; install@langchain/coreonly 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 path | Use it for | Source-backed API |
|---|---|---|
hive-mcp-client | Server-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/b2b | Partner 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-sdk | Vercel AI SDK MCP tool loading without sending every category tool to the model. | buildAiSdkHiveMcpTransportConfig, selectHiveMcpToolDefinitions, prepareHiveAiSdkTools |
hive-mcp-client/langchain | LangChain 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.
| Area | Runtime exports |
|---|---|
| Client and auth | createHiveMcpClient, buildHiveAuthHeaders, HIVE_DEFAULT_MCP_URL, HIVE_MCP_CLIENT_VERSION |
| Root-tool constants | HIVE_CORE_TOOL_NAMES, HIVE_STATEFUL_WRITE_ENDPOINT_NAMES, HIVE_CATEGORY_TOOL_NAMES, HIVE_REMOVED_CATEGORY_TOOL_NAMES |
| Metadata constants | HIVE_COMPACT_METADATA_RESOURCE_URIS, HIVE_METADATA_RESOURCE_URIS, HIVE_PROVIDER_NAMES |
| Discovery and aliases | HIVE_ENDPOINT_ALIASES, searchHiveTools, getHiveEndpointSchema, invokeHiveEndpoint, invokeHiveStatefulEndpoint, resolveHiveEndpointName, normalizeHiveEndpointArgs, normalizeHiveToolCall, rankHiveCategoriesForQuery |
| Runtime contract checks | isHiveCurrentRootToolName, isRemovedHiveCategoryToolName, inspectHiveRootContract |
| Metadata cache | isHiveMetadataResourceUri, readHiveMetadataSnapshot, resetHiveMetadataCache |
| Result and source handling | normalizeHiveToolResult, stringifyHiveToolResult, extractHiveExecutionReceipt, extractHiveSources, inferHiveProvider, inferHiveCategory, stableHiveCacheKey |
| Subject signing | HIVE_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 adapter | HIVE_B2B_RECOMMENDED_MONITOR_KINDS, checkHiveB2BReadiness, createHiveB2BAdapter, createHiveB2BAdapterFromClient |
| Vercel AI SDK | buildAiSdkHiveMcpTransportConfig, selectHiveMcpToolDefinitions, prepareHiveAiSdkTools |
| LangChain | createHiveLangChainTools |
Runtime controls
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
toolandargs. - REST execution returns
{ ok, data, meta }; read provider fields fromdata, not from the response root. fetched_atis Hive retrieval completion;observed_atandcache_age_msdescribe 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_idandreceipt_versionin application logs and user-visible provenance so an exact execution can be traced. - Use
GET /api/v1/toolsor Live Catalog when choosing tool names. - Prefer the MCP endpoint if your runtime already supports tool discovery natively.