跳转到正文
中文
获取 API 密钥
浏览文档

集成

构建 MCP 客户端

将 Node.js 应用连接到 FlashData,检查访问权限并保存首次 Google 搜索结果。

本页内容

开始前准备

需要 Node.js 22.18+、npm 及具有 google_search 权限的 API Key。你的应用是 MCP 客户端,FlashData 在 https://data.flashdata.dev/mcp 托管服务端。示例先免费检查连接,使用 --search 提交一次搜索,再用 --read 读取已保存结果。

1. 安装客户端 SDK

创建新项目。Windows 若阻止 npm.ps1,请使用 npm.cmd。

新项目
node --version
mkdir flashdata-mcp-demo
cd flashdata-mcp-demo
npm init -y
npm install --save-exact @modelcontextprotocol/[email protected]

2. 设置 API Key

在当前终端设置密钥,或让智能体从密钥存储注入 FLASHDATA_API_KEY。客户端通过 X-API-Key 请求头连接托管 Streamable HTTP 端点。在本地或服务器进程中运行代码。

设置密钥
# 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

3. 保存并检查客户端

将下方完整文件保存为 flashdata-mcp-demo 目录中的 mcp-client.mjs,与 package.json 同级。本页所有命令均使用此文件。它发现工具、检查当前价格与余额,并收集大结果。

保存 mcp-client.mjs

flashdata-mcp-demo/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();
}

免费检查连接

在设置密钥的终端中,从 flashdata-mcp-demo 目录运行。预期输出 Available credits、One search 及 Connected. No paid query submitted. 最后一行说明余额是否足以支付一次搜索。余额为零不表示认证失败。

在 flashdata-mcp-demo 中运行
node mcp-client.mjs

4. 运行首次搜索

使用第 3 步保存的文件。--search 参数会请求一次关于电池回收研究的 Google 搜索。客户端再次检查价格与余额,然后保存响应并输出来源链接及 Credits 用量。

提交一次搜索

从 flashdata-mcp-demo 运行一次。客户端在提交前创建 mcp-search-output;该目录已存在时停止,避免重复执行任务。

在 flashdata-mcp-demo 中运行
node mcp-client.mjs --search

检查保存的结果

打开 mcp-search-output/result.json。预期 status: done、results[].organic 中的标题、链接及摘要,以及 usage.credits。自然搜索结果为空也可能有效。下方是精简示例响应。

mcp-search-output/result.json
{
  "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"
}

再次读取已保存结果

从同一项目目录运行。此命令读取 result.json,输出来源链接及原请求的 Credits 用量。无需 API Key,不发送网络请求,也不提交新的搜索。

在 flashdata-mcp-demo 中运行
node mcp-client.mjs --read

恢复中断的任务

搜索尚未输出结果便中断时,请保留 mcp-search-output。缺少 result.json 并不能证明请求失败。检查下列文件及请求历史,再决定是否需要重新搜索。

mcp-search-output 中的文件说明
request.json计划执行的工具调用。在提交前保存,不代表 FlashData 已收到请求。
mcp-receipt.jsonMCP 原始回复,包含错误或用于续读的 result_id。检查 isError 及响应正文,仅 HTTP 200 不代表成功。
result.json组装后的响应。status 为 done 时可用 --read 读取;保留 request_id 以便排查。

如何收集大结果

客户端读取 structuredContent;不存在时读取 content 中的 JSON 文本。即使 MCP 传输返回 HTTP 200,也检查 isError。

响应包含 result_id 时,completeResult 使用同一凭据及返回的 next_offset 调用 get_result,直到偏移为 null。它检查顺序、拼接分片并解析完整 JSON。原始回执保存在 mcp-search-output/mcp-receipt.json。

在应用中使用此客户端

任务需要调整的内容
运行不同搜索执行新任务时修改 mcp-client.mjs 中的 request.arguments.query 及 output。同一已完成任务使用 --read 读取,保留先前输出目录。
让模型选择工具使用 listTools 读取名称、描述及输入结构。校验所选名称和参数,再按应用的权限与消费规则调用 callTool。
定时运行从持久密钥存储复用已认领凭据。为每个调度时段保留持久记录,同一时段重复时读取已保存输出。
连接其他用户此密钥消耗其所有者的账户余额。使用各用户自己的凭据,并隔离保存结果。OAuth 集成还需客户端注册、授权及令牌存储,本 API Key 示例未实现该流程。

故障排查

问题处理方式
ERR_MODULE_NOT_FOUND从 flashdata-mcp-demo 运行 npm install。mcp-client.mjs 应与 package.json 和 node_modules 位于同一目录。
FLASHDATA_API_KEY在运行 Node.js 的同一终端或进程中设置环境变量,再运行 node mcp-client.mjs,不加 --search。
401检查密钥是否已过期或被撤销。恢复有效访问后,重新运行免费连接检查。
403检查密钥的 google_search 权限及账户访问状态。余额检查成功并不代表已获此来源权限。
402 / Insufficient credits提交新任务前检查账户余额及当前价格。
EEXIST此前尝试已占用输出目录。result.json 完整时运行 node mcp-client.mjs --read,否则检查回执及请求历史。保留该目录。
ENOENT / invalid JSON with --read确认当前位于 flashdata-mcp-demo,检查 mcp-search-output/result.json。文件缺失或不完整时按“恢复中断的任务”处理;--read 不会提交搜索。
429存在 Retry-After 时按其等待。若已尝试搜索,重试前先检查保存文件及请求历史。
Timeout / result_unavailable保留请求与回执。检查请求历史或现有任务,已保存续读内容可能已过期。