본문으로 건너뛰기
KO
API 키 받기
문서 둘러보기

연동

MCP 클라이언트 구축

Node.js 응용 프로그램을 FlashData에 연결하고 액세스 권한을 확인하고 첫 번째 Google Search 결과를 저장하십시오.

이 페이지의 내용

시작하기 전에

Node.js 22.18+, npm 및 API 키 사용 google_search 권한. 응용 프로그램은 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 키 설정

이 맨끝에 있는 열쇠를 놓거나, 당신의 대리인은 그것의 비밀 상점에서 FLASHDATA_API_KEY를 주사합니다. 클라이언트는 호스팅 가능한 HTTP 엔드포인트에 X-API-Key 헤더로 전송합니다. 로컬 또는 서버 프로세스에서 코드를 실행합니다.

키 설정
# 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에서 키 설정한 터미널에서 실행합니다. 유효한 신용, 한 검색 및 연결. 제출 된 유료 쿼리 없음. 마지막 선은 균형이 한 검색을 다루는 것을 말한다. 0 잔액은 인증이 실패하지 않습니다.

flashdata-mcp-demo에서
node mcp-client.mjs

4. 첫 번째 검색을 실행

단계 3에서 저장된 파일을 사용하십시오. --search 플래그는 배터리 재활용 연구에 대한 Google 검색을 요청합니다. 클라이언트는 가격을 확인하고 다시 균형, 다음 응답 및 인쇄 소스 링크 및 사용 신용을 저장합니다.

1개의 검색을 제출

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를 읽고 소스 링크 및 원래 크레딧을 인쇄합니다. API 키가 필요하며 네트워크 요청을 하지 않고 다른 검색을 제출하지 않습니다.

flashdata-mcp-demo에서
node mcp-client.mjs --read

중단 된 작업을 복구

인쇄 결과를 인쇄하기 전에 검색 중지가 mcp-search-output를 유지하십시오. result.json가 요청이 실패하지 않습니다. 아래 파일을 검사하고 다른 검색이 필요한지 결정하기 전에 History를 확인하십시오.

mcp-search-output 파일당신이 말하는 것
request.json이 약관은 제출하기 전에 저장; 그것은 FlashData가 그것을 받았다는 것을 확인하지 않습니다.
mcp-receipt.json오류 또는 오염을위한 result_id를 포함하여 원래 MCP 회신. isError와 응답 몸을 검사하십시오; HTTP 200는 혼자 성공하지 않습니다.
result.json조립된 응답. 완료의 상태는 --read 보존과 함께 읽을 준비가되어 있습니다. 문제 해결을위한 request_id.

큰 결과가 수집 된 방법

클라이언트는 structuredContent, 또는 JSON 텍스트를 structuredContent가 복종 될 때 읽습니다. MCP 운송이 HTTP 200를 반환 할 때 isError를 검사합니다.

응답이 result_id를 포함할 때, completeResult는 동일한 자격 증명을 가진 get_result를 부르고 next_offset를 null일 때까지 반환합니다. 그것은 순서, concatenates 펑크를 확인하고 전체 JSON를 곱합니다. mcp-search-output/mcp-receipt.json.의 원래 영수증 숙박

이 클라이언트를 귀하의 응용 프로그램에서 사용

의논하기변화하는 것
다른 검색을 실행request.arguments.query 변경 및 새로운 작업을 위해 mcp-client.mjs에서 출력. 동일한 완료된 작업을 위한 --read 재사용; 이전 출력 디렉토리를 유지하십시오.
모델이 도구를 선택하자listTools를 사용하여 이름, 설명 및 입력 스키마를 읽으십시오. 선택한 이름과 인수를 유효성 검사한 다음 callTool를 응용 프로그램의 권한 및 지출 정책에 따라 검증합니다.
자주 묻는 질문persistent 비밀 저장에서 소유 한 자격. 일정 슬롯 당 1개의 튼튼한 기록을 지키십시오; 동일한 구멍 반복 때 저장된 산출을 읽으십시오.
다른 사용자를 연결이 키는 소유자의 계정이 청구됩니다. 각 사용자의 자신의 자격 증명을 사용 하 고 그들의 저장된 결과를 격리. OAuth 통합은 또한 클라이언트 등록, 동의 및 토큰 저장을 필요로 합니다; 이 API-key 예는 그 흐름을 구현하지 않습니다.

관련 상품

의 의조치
ERR_MODULE_NOT_FOUNDFlashdata-mcp-demo에서 npm 설치를 실행하십시오. package.json 및 node_modules 옆에 mcp-client.mjs를 유지하십시오.
FLASHDATA_API_KEYNode.js를 실행하는 동일한 터미널 또는 프로세스에서 변수를 설정한 다음 --search없이 노드 mcp-client.mjs를 다시 실행합니다.
401만료된 키 또는 수정된 키에 대한 확인. 유효한 접근을 복원 한 다음 무료 연결 체크를 다시 실행합니다.
403키의 google_search 권한 및 계정 액세스 확인. 성공적인 균형 검사는이 소스를 증명하지 않습니다.
402 / Insufficient credits다른 작업을 제출하기 전에 계정 잔고 및 현재 가격을 확인합니다.
EEXIST이전 시도는 출력 디렉토리를 소유합니다. result.json가 완료되면 노드 mcp-client.mjs --read를 실행하십시오. 그렇지 않으면 영수증과 History를 검사합니다. 본문 바로가기
ENOENT / JSON 와 --read당신은 flashdata-mcp-demo에 있고 mcp-search-output/result.json.를 검열합니다 누락되거나 불완전한 경우, 중단 된 작업을 복구하십시오. --read는 검색을 결코 제출하지 않습니다.
429제공 할 때 Retry-After에 대한 대기. 검색이 시도된 경우, 저장된 파일과 재시동하기 전에 History를 확인하십시오.
타임아웃 / result_unavailable요청 및 영수증을 유지하십시오. History 또는 기존 작업을 확인; 저장된 오염이 만료 될 수 있습니다.