Browse documentation
Integrations
Connect a Node.js application to FlashData, check access and save your first Google Search result.
On this page
Before you start
Use Node.js 22.18+, npm and an API key with google_search permission. Your application is the MCP client; FlashData hosts the server at https://data.flashdata.dev/mcp. The example checks the connection for free, submits one search with --search and reads its saved result with --read.
1. Install the client SDK
Create a new project. On Windows, use npm.cmd if npm.ps1 is blocked.
node --version
mkdir flashdata-mcp-demo
cd flashdata-mcp-demo
npm init -y
npm install --save-exact @modelcontextprotocol/[email protected]2. Set your API key
Set the key in this terminal, or let your agent inject FLASHDATA_API_KEY from its secret store. The client sends it as an X-API-Key header to the hosted Streamable HTTP endpoint. Run the code in a local or server process.
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY# PowerShell 7: paste the key into a hidden prompt.
$flashdataSecureKey = Read-Host "FlashData API key" -AsSecureString
$env:FLASHDATA_API_KEY = [System.Net.NetworkCredential]::new("", $flashdataSecureKey).Password
Remove-Variable flashdataSecureKey3. Save and check the client
Save the complete file below as mcp-client.mjs inside flashdata-mcp-demo, beside package.json. All commands on this page use this file. It discovers tools, checks current pricing and balance, and collects large results.
Save mcp-client.mjs
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
const client = new Client({ name: 'flashdata-first-task', version: '1.0.0' });
const output = 'mcp-search-output';
let searchAttempted = false;
function bodyOf(reply) {
const body = reply.structuredContent ?? JSON.parse(
reply.content.filter(item => item.type === 'text').map(item => item.text).join(''));
if (reply.isError) {
throw new Error(JSON.stringify({
code: body.code, http_status: body.http_status, request_id: body.request_id,
}));
}
return body;
}
async function completeResult(reply) {
let body = bodyOf(reply);
if (!body.result_id) return body;
const id = body.result_id;
let text = body.chunk;
let offset = body.next_offset;
while (offset !== null) {
body = bodyOf(await client.callTool({
name: 'get_result', arguments: { result_id: id, offset },
}));
if (body.result_id !== id || body.offset !== offset ||
(body.next_offset !== null && body.next_offset <= offset)) {
throw new Error('Invalid continuation; preserve ' + output + '/mcp-receipt.json.');
}
text += body.chunk;
offset = body.next_offset;
}
return JSON.parse(text);
}
function printResult(response, saved = false) {
if (response.status !== 'done') throw new Error('Search is not done; inspect ' + output + '/result.json.');
const hits = (response.results ?? []).flatMap(page => page.organic ?? []);
for (const hit of hits) console.log(hit.title ?? '(no title)', hit.link ?? '(no URL)', hit.snippet ?? '');
if (!hits.length) console.log('No organic results returned.');
console.log(saved ? 'Original credits used:' : 'Credits used:', response.usage?.credits ?? 'not reported');
console.log('Saved response: ' + output + '/result.json');
}
async function main() {
const mode = process.argv[2] ?? '--check';
if (process.argv.length > 3 || !['--check', '--search', '--read'].includes(mode)) {
throw new Error('Usage: node mcp-client.mjs [--check | --search | --read]');
}
if (mode === '--read') {
printResult(JSON.parse(await readFile(output + '/result.json', 'utf8')), true);
console.log('Local file only. No API call or new charge.');
return;
}
const key = process.env.FLASHDATA_API_KEY?.trim();
if (!key) throw new Error('Set FLASHDATA_API_KEY in this terminal.');
await client.connect(new StreamableHTTPClientTransport(
new URL('https://data.flashdata.dev/mcp'),
{ requestInit: { headers: { 'X-API-Key': key } } },
));
const names = [];
let cursor;
do {
const page = await client.listTools(cursor ? { cursor } : {});
names.push(...page.tools.map(tool => tool.name));
cursor = page.nextCursor;
} while (cursor);
for (const name of ['google_search', 'get_balance', 'get_pricing']) {
if (!names.includes(name)) throw new Error('Missing tool: ' + name);
}
const balance = bodyOf(await client.callTool({ name: 'get_balance', arguments: {} }));
const pricing = bodyOf(await client.callTool({
name: 'get_pricing', arguments: { source: 'google_search', request_count: 1 },
}));
const price = pricing.prices.find(p => p.source === 'google_search' && p.available);
const cost = price?.estimatedCredits;
if (!Number.isFinite(cost) || cost < 0) throw new Error('No current price; stop here.');
if (!Number.isFinite(balance.availableCredits)) throw new Error('No current balance; stop here.');
console.log('Available credits:', balance.availableCredits, 'One search:', cost);
if (mode === '--check') {
console.log('Connected. No paid query submitted.');
console.log(balance.availableCredits >= cost ? 'Ready for one search.' : 'Add credits before searching.');
} else {
if (balance.availableCredits < cost) throw new Error('Insufficient credits.');
// Reserve a new directory before submitting. A repeat run stops here.
await mkdir(output);
const request = {
name: 'google_search',
arguments: { query: 'battery recycling research', num: 5, mode: 'realtime' },
};
await writeFile(output + '/request.json', JSON.stringify(request, null, 2), { flag: 'wx' });
searchAttempted = true;
const reply = await client.callTool(request, undefined, { timeout: 120_000 });
await writeFile(output + '/mcp-receipt.json', JSON.stringify(reply, null, 2), { flag: 'wx' });
const response = await completeResult(reply);
await writeFile(output + '/result.json', JSON.stringify(response, null, 2), { flag: 'wx' });
printResult(response);
}
}
try {
await main();
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
if (searchAttempted) console.error('Search was attempted. Preserve saved files and check History before retrying.');
else console.error('No search submitted by this run.');
process.exitCode = 1;
} finally {
await client.close();
}Check the connection for free
Run from flashdata-mcp-demo in the terminal where you set the key. Expect Available credits, One search and Connected. No paid query submitted. The final line says whether the balance covers one search. A zero balance does not mean authentication failed.
node mcp-client.mjs4. Run your first search
Use the file you saved in step 3. The --search flag requests one Google search for battery recycling research. The client checks the price and balance again, then saves the response and prints source links and credits used.
Submit one search
Run once from flashdata-mcp-demo. The client creates mcp-search-output before submitting; if that directory already exists, it stops to avoid repeating the task.
node mcp-client.mjs --searchInspect the saved result
Open mcp-search-output/result.json. Expect status: done, results[].organic with titles, links and snippets, and usage.credits. Empty organic results can be valid. The response below is abbreviated and illustrative.
{
"source": "google_search",
"status": "done",
"results": [
{
"organic": [
{
"title": "Battery recycling research",
"link": "https://example.org/recycling",
"snippet": "An example search excerpt."
}
]
}
],
"usage": {
"credits": 0.02
},
"http_status": 200,
"request_id": "example-request-id"
}Read the saved result again
Run from the same project directory. This reads result.json and prints the source links and original credits used. It needs no API key, makes no network request and does not submit another search.
node mcp-client.mjs --readRecover an interrupted task
Keep mcp-search-output if a search stops before printing results. A missing result.json does not prove the request failed. Inspect the files below and check History before deciding whether another search is needed.
| File in mcp-search-output | What it tells you |
|---|---|
| request.json | The intended tool call. Saved before submission; it does not confirm that FlashData received it. |
| mcp-receipt.json | The original MCP reply, including errors or a result_id for continuation. Check isError and the response body; HTTP 200 alone is not success. |
| result.json | The assembled response. A status of done is ready to read with --read; preserve request_id for troubleshooting. |
How large results are collected
The client reads structuredContent, or the JSON text in content when structuredContent is absent. It checks isError even when the MCP transport returns HTTP 200.
When a response contains result_id, completeResult calls get_result with the same credential and returned next_offset until it is null. It checks the sequence, concatenates chunks and parses the full JSON. The original receipt stays in mcp-search-output/mcp-receipt.json.
Use this client in your application
| Task | What to change |
|---|---|
| Run a different search | Change request.arguments.query and output in mcp-client.mjs for a new task. Reuse --read for the same completed task; keep earlier output directories. |
| Let your model choose a tool | Use listTools to read names, descriptions and input schemas. Validate the selected name and arguments, then callTool under your application's permission and spending policy. |
| Run on a schedule | Reuse an owned credential from persistent secret storage. Keep one durable record per schedule slot; read saved output when the same slot repeats. |
| Connect other users | This key charges its owner's account. Use each user's own credential and isolate their saved results. An OAuth integration also needs a client registration, consent and token storage; this API-key example does not implement that flow. |
Troubleshooting
| Problem | Action |
|---|---|
| ERR_MODULE_NOT_FOUND | Run npm install from flashdata-mcp-demo. Keep mcp-client.mjs beside package.json and node_modules. |
| FLASHDATA_API_KEY | Set the variable in the same terminal or process that runs Node.js, then rerun node mcp-client.mjs without --search. |
| 401 | Check for an expired or revoked key. Restore valid access, then rerun the free connection check. |
| 403 | Check the key's google_search permission and account access. A successful balance check does not prove this source is allowed. |
| 402 / Insufficient credits | Check account balance and current pricing before submitting another task. |
| EEXIST | A previous attempt owns the output directory. Run node mcp-client.mjs --read if result.json is complete; otherwise inspect its receipt and History. Keep the directory. |
| ENOENT / invalid JSON with --read | Check that you are in flashdata-mcp-demo and inspect mcp-search-output/result.json. If it is missing or incomplete, follow Recover an interrupted task; --read never submits a search. |
| 429 | Wait for Retry-After when provided. If a search was attempted, check its saved files and History before retrying. |
| Timeout / result_unavailable | Keep the request and receipt. Check History or an existing job; a saved continuation may have expired. |