# สร้างไคลเอนต์ MCP

เชื่อมต่อ Node.js โปรแกรมต่าง ๆ ไปยัง FlashDataเช็กการเข้าถึงและบันทึกครั้งแรกของคุณ Google Search ได้ผล

อ้างอิงทางคลอง: https://flashdata.dev/th/docs/guides/mcp-custom-client
Recorder: 2026-11-05 โดย FlashData

<a id="prepare"></a>

## ก่อนจะเริ่ม

ใช้ Node.js 22.18+, npm และ API กุญแจพร้อม google_search อนุญาต แอพพลิเคชันของคุณก็คือ MCP ลูกค้า; FlashData โฮสต์เซิร์ฟเวอร์ที่ https://data.flashdata.dev/mcp. ตัวอย่างการตรวจสอบการเชื่อมต่อสําหรับฟรีส่งหนึ่งการค้นหาด้วย --search และอ่านผลที่บันทึกไว้ --read.

- [ติดตั้ง Node.js](https://nodejs.org/en/download)
- [สร้างรายการ API กุญแจ](https://flashdata.dev/app/api-keys)
- [เชื่อมต่อไปยังรายการที่มีอยู่แล้ว MCP โปรแกรม](https://flashdata.dev/th/docs/integrations/mcp-clients/reference.md)

<a id="client"></a>

## 1. ติดตั้งไคลเอนต์ SDK

สร้างโครงการใหม่ เปิด Windowsใช้ npm.cmd ถ้า npm.ps1 ถูกบล็อก

### โครงการใหม่

```bash
node --version
mkdir flashdata-mcp-demo
cd flashdata-mcp-demo
npm init -y
npm install --save-exact @modelcontextprotocol/sdk@1.30.0
```


<a id="authenticate"></a>

## 2. ตั้งค่าของคุณ API กุญแจ

ตั้งค่ากุญแจในเทอร์มินัลนี้ หรือให้ตัวแทนของคุณฉีด FLASHDATA_API_KEY จากร้านลับ ลูกความส่งมันมา X-API-Key หัวกระดาษสําหรับสายข้อมูลโฮสต์ HTTP จุดปลาย ประมวลผลโค้ดในโพรเซสท้องถิ่นหรือเซิร์ฟเวอร์

### Bash

#### ตั้งค่าคีย์

```bash
# 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

#### ตั้งค่าคีย์

```powershell
# 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 flashdataSecureKey
```



<a id="client-run"></a>

## 3. บันทึกและตรวจสอบไคลเอนต์

บันทึกแฟ้มที่สมบูรณ์ด้านล่างนี้เป็น mcp-client.mjs ภายในแฟลชดาต้า-ม.ค.-ดีโมเมะ, ข้าง ๆ package.json. คําสั่งทั้งหมดในหน้านี้ ใช้แฟ้มนี้ มันค้นพบเครื่องมือ ตรวจสอบค่าสถิติในปัจจุบันและความสมดุล และรวบรวมผลลัพธ์ที่มากมาย


<a id="client-source"></a>

### บันทึก mcp-client.mjs

#### flashdata-mcp-demo/mcp-client.mjs

```javascript
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();
}
```


<a id="check-output"></a>

### ตรวจสอบการเชื่อมต่อเพื่อใช้ฟรี

เรียกใช้จากแฟลชดาต้า-ม.ค.-เดโมส์ ในเทอร์มินัลที่คุณตั้งปุ่ม คาดว่าจะมีหน่วยกิตติคุณ การค้นหาและเชื่อมต่อ ไม่มีการส่งคําร้องขอ บรรทัดสุดท้ายบอกว่า สมดุลครอบคลุมการค้นหาหนึ่ง ความสมดุลศูนย์ไม่ได้หมายความว่าการตรวจสอบสิทธิ์ล้มเหลว

#### ในแฟลชดาต้า- mcp- demo

```bash
node mcp-client.mjs
```

- [เช็คเครดิต](https://flashdata.dev/app/billing)

<a id="first-task"></a>

## 4. สืบค้นครั้งแรกของคุณ

ใช้แฟ้มที่คุณบันทึกในขั้นตอน 3 เดอะ --search แฟล็กร้องขอหนึ่ง Google ค้นหาการรีไซเคิลของแบตเตอรี ลูกค้าตรวจสอบราคาและความสมดุลอีกครั้ง แล้วบันทึกการตอบรับและหลักฐาน เชื่อมโยงและเครดิตที่ใช้


<a id="submit"></a>

### ส่งการค้นหาหนึ่งรายการ

เรียกใช้หนึ่งครั้งจากแฟลชดาต้า-แมคพี-ดีโมส์ โปรแกรมลูกข่ายสร้างโปรแกรม Mcp- Auttate ก่อนทําการส่งข้อมูล หากไดเร็กทอรีดังกล่าวมีอยู่แล้ว ก็จะหยุดไม่ให้ทํางานซ้ํา

#### ในแฟลชดาต้า- mcp- demo

```bash
node mcp-client.mjs --search
```


<a id="result"></a>

### แสดงผลลัพธ์การบันทึก

เปิด mcp-search-output/result.json. คาด status: done, results[].organic มีชื่อเรื่อง ลิงก์ และสัญลักษณ์ และ usage.credits. ผลของออร์แกนิกว่างเปล่า สามารถใช้ได้ การ ตอบ สนอง ข้าง ล่าง นี้ เป็น การ ย่อ และ เป็น แบบ ย่อ ๆ.

#### mcp-search-output/result.json

```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"
}
```


<a id="read-saved"></a>

### อ่านผลที่ได้บันทึกอีกครั้ง

ประมวลผลจากไดเรกทอรีโครงการเดียวกัน อ่านนี่ result.json และพิมพ์ตําแหน่งเชื่อมโยงของแหล่ง และหน่วยกิตดั้งเดิมที่ใช้ มันไม่ต้องการ API กุญแจ, ไม่ต้องร้องขอการใช้งานเครือข่าย และไม่ส่งข้อมูลการค้นหาอีก

#### ในแฟลชดาต้า- mcp- demo

```bash
node mcp-client.mjs --read
```


<a id="saved-files"></a>

## เรียกคืนงานที่ขัดจังหวะ

เก็บการค้นหา Mcp- output ไว้หากหยุดการค้นหาก่อนผลการพิมพ์ หายตัวไป result.json ไม่พิสูจน์ว่าคําขอนี้ล้มเหลว แสดงเฉพาะแฟ้มด้านล่างนี้และตรวจสอบ History ก่อน ตัดสิน ใจ ว่า จําเป็น ต้อง มี การ ค้น หา อีก หรือ ไม่.

| แฟ้มในโปรแกรม Mcp- สืบค้น | สิ่งที่มันบอกคุณ |
| --- | --- |
| request.json | เครื่องมือที่ตั้งใจเรียก บันทึกก่อนทําการส่งข้อมูล; มันไม่ได้ยืนยัน FlashData รับมา |
| mcp-receipt.json | ตัวเดิม MCP ตอบกลับ, รวมข้อผิดพลาด หรือ result_id เพื่อความหลัง ตรวจสอบ isError และ (มะลาอิกะฮฺ) ผู้ควบคุมอย่างรัดกุม HTTP 200 การอยู่คนเดียวไม่สําเร็จ |
| result.json | การตอบสนองที่ชุมนุม สถานะของการกระทําพร้อมที่จะอ่านด้วย --readสืบค้นเมื่อ: request_id สําหรับการยิงปัญหา |

- [ต้องการประวัติ](https://flashdata.dev/app/jobs)
- [รายละเอียดการอ้างอิง](https://flashdata.dev/th/docs/guides/mcp-custom-client/reference.md#continuations)

<a id="continuations"></a>

## ผลการเก็บสะสมใหญ่แค่ไหน

ลูกความอ่าน structuredContentหรือ JSON ข้อความอยู่ในเนื้อหาเมื่อ structuredContent ไม่อยู่ มันตรวจแล้ว isError แม้เมื่อ MCP การส่งค่ากลับ HTTP 200.

เมื่อมีการตอบสนอง result_id, completeResult เรียก get_result ด้วยความเชื่อเดียวกัน และกลับมา next_offset จนกว่ามันจะเป็น null. มันตรวจสอบลําดับ, concategates parts และวิเคราะห์เต็ม JSON ใบเสร็จเดิมอยู่ที่ mcp-search-output/mcp-receipt.json.

- [MCP เครื่องมือและเขียนแบบร่างName](https://flashdata.dev/th/docs/mcp/reference.md)

<a id="reuse"></a>

## ใช้ไคลเอนต์นี้ในโปรแกรมของคุณ

| งาน | จะเปลี่ยนอะไร |
| --- | --- |
| ประมวลผลการค้นหาอื่น | เปลี่ยน request.arguments.query และผลลัพธ์ที่ออกมา mcp-client.mjs สําหรับงานใหม่ ใช้อีกครั้ง --read สําหรับทาสก์ที่เสร็จสมบูรณ์แล้ว โดยให้คงไว้ซึ่งไดเรกทอรีการแสดงผลก่อนหน้า |
| ให้นางแบบเลือกเครื่องมือ | ใช้ listTools เพื่ออ่านชื่อ คําบรรยาย และข้อมูลเข้า ตรวจสอบชื่อและอาร์กิวเมนต์ที่เลือกไว้ callTool ภายใต้คําอนุญาตและใช้นโยบายของคุณ |
| ประมวลผลตามตาราง | ใช้ความเป็นเจ้าของจากที่เก็บลับอย่างถาวร เก็บแผ่นเสียงหนึ่งแผ่นต่อช่องกําหนดการไว้; อ่านค่าผลลัพธ์ที่ออกมาเมื่อช่องเดียวกันซ้ํา |
| เชื่อมต่อผู้ใช้อื่น ๆ | กุญแจนี่คิดเงินจากบัญชีของเจ้าของมัน ใช้ความเชื่อถือของผู้ใช้งานแต่ละคน และแยกผลลัพธ์การบันทึกไว้ ขนาด OAuth การผนวกรวมต้องลงทะเบียนลูกค้า ยินยอม และเก็บป้าย API- ตัวอย่างคีย์ไม่ได้ทําหน้าที่ที่ไหล |

- [งานที่ทำซ้ำตามกำหนด](https://flashdata.dev/th/docs/guides/recurring-tasks/reference.md)
- [ตัวเลือกการตรวจสอบสิทธิ์](https://flashdata.dev/th/docs/guides/agent-access/reference.md)

<a id="operate"></a>

## การยิงปัญหา

| ปัญหา | การกระทํา |
| --- | --- |
| ERR_MODULE_NOT_FOUND | ทํางาน npm ติดตั้งจาก flashdata-mcp-Demo เก็บไว้ mcp-client.mjs ข้าง package.json ถึง node_modules. |
| FLASHDATA_API_KEY | ตั้งค่าตัวแปรในเทอร์มินัลหรือโพรเซสที่ทํางานอยู่ Node.jsโหนดการเรียกอีกครั้ง mcp-client.mjs ไม่มี --search. |
| 401 | โปรดตรวจสอบกุญแจที่หมดอายุแล้วหรือถูกยกเลิก เรียกคืนสิทธิ์ในการใช้งานที่ถูกต้อง แล้วเรียกตรวจสอบการเชื่อมต่ออีกครั้ง |
| 403 | ตรวจสอบกุญแจ google_search และสิทธิ์ในการใช้งานบัญชีผู้ใช้ การตรวจสอบดุลยภาพที่ประสบความสําเร็จ ไม่ได้พิสูจน์ว่าแหล่งดังกล่าวสามารถใช้ได้ |
| 402 / Insufficient credits | Checknown hyperbolic และค่าอัตราปัจจุบัน ก่อนที่จะส่งข้อมูลอื่น ๆ |
| EEXIST | ความพยายามก่อนหน้านี้มีไดเร็กทอรีสําหรับส่งออก ประมวลผลโหนด mcp-client.mjs --read ถ้า result.json เสร็จสมบูรณ์; มิฉะนั้นการตรวจสอบใบเสร็จและ History. เก็บไดเรกทอรีไว้ |
| ไม่ใช้ / ใช้ไม่ได้ JSON ด้วย --read | โปรดตรวจสอบว่าคุณอยู่ใน flashdata-mcp-Demo และตรวจสอบ mcp-search-output/result.json. หากมันขาดหายไปหรือยังไม่สมบูรณ์ โปรดติดตามงานที่ขัดจังหวะไป; --read ไม่เคยส่งการค้นหา |
| 429 | รอ Retry-After เมื่อมีการตั้งค่า หากมีการพยายามค้นหา โปรดตรวจสอบแฟ้มที่ถูกบันทึกและ History ก่อนที่จะลองใหม่ |
| หมดเวลา / result_unavailable | เก็บคําขอและใบเสร็จไว้ ตรวจสอบ History หรืองานที่มีอยู่แล้ว; การทําซ้ําอาจจะหมดอายุไปแล้ว |

- [ต้องการประวัติ](https://flashdata.dev/app/jobs)
- [MCP การยิงปัญหา](https://flashdata.dev/th/docs/guides/troubleshooting/reference.md#mcp)
