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.
# 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:
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"}.