Model Context Protocol Model Context Protocol Model Context Protocol · Lab 5/7 Lab 5/7 Lab 5/7 · 30 phút · 30 min · 30 នាទី

05

Lưu trữ Cloudflare KV Cloudflare KV Storage ការផ្ទុក Cloudflare KV

Cấu hình KV để lưu bền. Viết tool đọc/ghi data giữa các session. Set up Cloudflare KV for persistent data storage. Create tools that can store and retrieve data across sessions. កំណត់ KV ដើម្បីរក្សាទុកជាប់។ សរសេរ tool អាន/សរសេរ data រវាង session។

Nội dung bước (lệnh, code) giữ nguyên tiếng Anh từ nguồn chính thức. Step body (commands, code) stays in English from the official source. ខ្លឹមសារជំហាន (ពាក្យបញ្ជា និង code) រក្សាភាសាអង់គ្លេសពីប្រភពផ្លូវការ។ labs.cloudflare.dev ↗

Cần trước Prerequisites តម្រូវការជាមុន

  • Đã xong bước 4 Completed Step 4 បានបញ្ចប់ជំហាន 4
  • Đã deploy lên Cloudflare Workers Deployed to Cloudflare Workers បាន deploy ទៅ Cloudflare Workers
  • Hiểu lưu key-value Understanding of key-value storage យល់ការផ្ទុក key-value

Bạn sẽ làm được Learning objectives គោលបំណងសិក្សា

  • Tạo và cấu hình namespace Cloudflare KV Create and configure Cloudflare KV namespaces បង្កើត និងកំណត់ namespace Cloudflare KV
  • Làm persistence data trong MCP tool Implement data persistence in MCP tools ធ្វើ persistence data ក្នុង MCP tool
  • Xử lý thao tác lưu trữ và lỗi Handle storage operations and errors ដោះស្រាយប្រតិបត្តិការផ្ទុក និង error
  • Xây app có state bằng KV Build stateful applications with KV សង់កម្មវិធីមាន state ដោយ KV

Bước 1: Tạo và cấu hình namespace KV Step 1: Create and Configure KV Namespace ជំហាន 1: បង្កើត និងកំណត់ namespace KV

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
A KV namespace bound to your MCP server, giving your tools persistent, globally distributed storage.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
KV storage enables stateful applications where data persists between AI conversations and user sessions.
bash
# Create a new KV namespace for our MCP server and choose the options below
npx wrangler kv namespace create "TODO_STORE"

 ⛅️ wrangler 4.64.0
───────────────────
Resource location: remote

🌀 Creating namespace with title "TODO_STORE"
✨ Success!
To access your new KV Namespace in your Worker, add the following snippet to your configuration file:
{
  "kv_namespaces": [
    {
      "binding": "TODO_STORE",
      "id": "abc1234567890defghij"
    }
  ]
}
✔ Would you like Wrangler to add it on your behalf? … yes
✔ What binding name would you like to use? … TODO_STORE
✔ For local dev, do you want to connect to the remote resource instead of a local resource? … no

Answer yes to let wrangler add the binding, use TODO_STORE as the binding name, and no for remote local dev.

Answer yes to let wrangler add the binding, use TODO_STORE as the binding name, and no for remote local dev.

Answer yes to let wrangler add the binding, use TODO_STORE as the binding name, and no for remote local dev.

Bước 2: Thêm tool lưu trữ Step 2: Add a Storage Tool ជំហាន 2: បន្ថែម tool ផ្ទុក

Add a simple store_value tool to verify KV is working. Make sure your MyMCP class has the <Env> generic so this.env works:

Add a simple store_value tool to verify KV is working. Make sure your MyMCP class has the <Env> generic so this.env works:

Add a simple store_value tool to verify KV is working. Make sure your MyMCP class has the <Env> generic so this.env works:

typescript
export class MyMCP extends McpAgent<Env> {
  server = new McpServer({
    name: "My MCP Server",
    version: "1.0.0",
  });

  async init() {
    this.server.tool(
        "store_value",
        "Store a simple key-value pair in Cloudflare KV",
        {
            key: z.string().describe("Key to store the value under"),
            value: z.string().describe("Value to store")
        },
        async ({ key, value }) => {
            try {
                await this.env.TODO_STORE.put(key, value);

                return {
                    content: [{
                        type: "text",
                        text: "Value stored successfully"
                    }]
                };
            } catch (error: any) {
                throw new Error(`Failed to store value: ${error}`);
            }
        }
    );

Save the file, click the refresh button next to “Available Tools” in the MCP Inspector, and test with {"key": "test", "value": "hello world"}.

Save the file, click the refresh button next to “Available Tools” in the MCP Inspector, and test with {"key": "test", "value": "hello world"}.

Save the file, click the refresh button next to “Available Tools” in the MCP Inspector, and test with {"key": "test", "value": "hello world"}.