Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

เร่งการพัฒนา MCP ด้วย Redis: โซลูชัน Fast และ Cost-Effective

The Model Context Protocol (MCP) กำลังกลายเป็น standard way ที่รวดเร็วในการเชื่อม AI models กับ external tools และ data sources การที่ MCP adoption โตขึ้น นักพัฒนากำลังค้นพบว่าการสร้าง MCP implementations ที่ robust และ production-ready ต้องการมากกว่าแค่ follow spec: มันต้องการ infrastructure ที่ถูกต้อง ในโพสต์นี้ เราจะสำรวจว่า Redis ให้พลังกับ MCP use cases 3 แบบที่ต่างกัน: coordinating distributed serverless functions ใน Vercel's SSE implementation, enabling event resumability สำหรับ long-running streams และ managing secure OAuth flows กับ Clerk

Understanding MCP Transports (การเข้าใจ MCP Transports)

ก่อนดำเนิน examples มา cover สั้นๆ ว่า MCP จัดการ communication อย่างไร MCP รองรับ 2 transports: Stdio สำหรับ local servers และ Streamable HTTP สำหรับ remote servers ในอดีตมี SSE (Server-Sent Events) transport สำหรับ remote servers ซึ่งตอนนี้ deprecated แล้ว

การ transition จาก SSE ไป Streamable HTTP แทน evolution ในการที่ MCP จัดการ real-time communication แตหลาย existing implementations ยังพึ่งพา SSE pattern มาดูว่า Redis ช่วยแก้หนึ่งใน key challenges ใน model นั้นอย่างไร

Use Case 1: SSE ด้วย Redis Pub/Sub

ตอน Vercel CTO Malte สร้าง MCP handler เขาเจอ classic serverless challenge: คุณ coordinate ระหว่าง multiple endpoints อย่างไรเมื่อแต่ละ request อาจถูก handle โดย serverless function ที่ต่างกัน?

ใน SSE transport model มี 2 critical endpoints: /sse สำหรับ maintain connection และ /message สำหรับรับ client messages นี่คือปัญหา: ใน serverless environment อย่าง Vercel endpoints นี้ isolated เลย พวกมันไม่ share memory และ request ไป /message อาจถูก handle โดย function instance ที่ต่างกันหมดจากตัวที่ handle /sse

The solution? Redis Pub/Sub ตามที่ Malte อธิบายบน X:

เร่งการพัฒนา MCP ด้วย Redis: โซลูชัน Fast และ Cost-Effective

Implementation ใช้ Redis channels เพื่อ coordinate ระหว่าง endpoints ตอน client ส่ง message ไป /message endpoint นั้น publish ไป Redis channel ที่ /sse endpoint subscribe อยู่ /sse endpoint process request และ publish response กลับผ่าน channel อีกตัวที่ /message กำลัง listen

เร่งการพัฒนา MCP ด้วย Redis: โซลูชัน Fast และ Cost-Effective

Pattern นี้ effectively เปลี่ยน Redis เป็น message bus ที่ bridge gap ระหว่าง isolated serverless functions ให้พวกมันทำงานร่วมกันเหมือนเป็นส่วนของ process เดียวกัน แม้ SSE จะ deprecated แล้วเพราะ Streamable HTTP (หมายถึง new MCP implementations ควรใช้ modern transport) นี่ยังคงเป็น excellent example ของการใช้ Redis สำหรับ coordination ระหว่าง isolated serverless functions

Use Case 2: Event Store สำหรับ Resumability

หนึ่งใน powerful features สุดของ MCP's Streamable HTTP transport คือ support สำหรับ resumability ฟีเจอร์นี้อนุญาตให้ clients continue stream จากที่หยุดไว้ในกรณี disconnection นี่ critical สำหรับ production applications ที่ network interruptions เป็น inevitable

Understanding MCP Streams

เพื่อเข้าใจว่าทำไม resumability important เราต้องเข้าใจว่า MCP streams ประกอบด้วยอะไร บาง operations อย่างเรียก simple tool คืนค่า single response แต tools สามารถคืนค่า multiple events ระหว่าง execution ด้วย methods อย่าง server.sendLoggingMessage multi-event streams เหล่านี้คือที่ที่ resumability กลายเป็น crucial ถ้า client disconnect ตรงกลาง ควรสามารถ resume จากที่หยุดได้แทนที่จะเริ่มใหม่

Implementing EventStore with Redis

MCP SDK กำหนด EventStore interface ที่ต้องการ 2 methods: storeEvent สำหรับเพิ่ม events และ replayEventsAfter สำหรับ retrieve events เริ่มจาก specific event ID SDK มี in-memory implementation แตสำหรับ production use คุณต้องการ persistent storage

นี่คือ Redis-based implementation ของ EventStore:

import { Redis } from '@upstash/redis'; import { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js'; import { EventStore } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; export class RedisEventStore implements EventStore { private redis: Redis; constructor(params: ConstructorParameters<typeof Redis>[0]) { this.redis = new Redis(params); } /** * Stores an event in a Redis Stream * Implements EventStore.storeEvent */ async storeEvent(streamId: string, message: JSONRPCMessage): Promise<string> { const eventId = await this.redis.xadd(`stream:${streamId}`, '*', { message: JSON.stringify(message), }); return eventId; } /** * Replays events that occurred after a specific event ID * Implements EventStore.replayEventsAfter */ async replayEventsAfter( lastEventId: string, { send }: { send: (eventId: string, message: JSONRPCMessage) => Promise<void> } ): Promise<string> { if (!lastEventId) { return ''; } // Extract the stream ID from the lastEventId const streamId = lastEventId.split('-')[0]; // Assuming the stream ID is part of the key if (!streamId) { return ''; } let nextId = lastEventId; while (true) { // Fetch events from the stream starting AFTER the next ID (exclusive) const events = await this.redis.xrange(`stream:${streamId}`, `(${nextId}`, '+', 10); // Convert the returned object to an array of entries const eventEntries = Object.entries(events); if (eventEntries.length === 0) { break; // No more events to replay } for (const [eventId, fields] of eventEntries) { // Ensure fields.message exists and parse it if (fields && typeof fields === 'object' && 'message' in fields && typeof fields.message === 'string') { const message = JSON.parse(fields.message) as JSONRPCMessage; await send(eventId, message); nextId = eventId; // Update the next ID to the current event ID } } } return streamId; } }

Implementation นี้ใช้ Redis Streams ซึ่ง perfect สำหรับ use case นี้

A Limitation (ข้อจำกัด)

มี caveat สำคัญหนึ่ง: ตอน tool ส่ง multiple events streamId ถูกตั้งเป็น _GET_stream และ constant นี้เหมือนกัน across different streams และ users หมายความว่าถ้าสอง users ใช้ tool เดียวกันที่ส่ง multiple events พร้อมกัน events ของพวกเขาอาจ mixed up ใน stream เดียวกัน

ผมเปิด issue เกี่ยวกับนี้บน official repository ขึ้นอยู่กับ resolution เราอาจต้อง adjust implementation และผมจะ update โพสต์นี้ตามถ้าจำเป็น

Use Case 3: Clerk's MCP OAuth Implementation

MCP specification รวม support สำหรับ authentication และ authorization อนุญาตให้ MCP servers authenticate clients อย่างปลอดภัยและควบคุม access ไป resources Spec รองรับ multiple authentication schemes รวมถึง OAuth 2.0 ซึ่ง useful มากสำหรับ integrate กับ existing identity providers และ enable user-scoped access ไป tools และ data

Clerk สร้าง comprehensive OAuth client สำหรับ MCP โดย implement OAuthClientProvider interface จาก MCP SDK Implementation ของพวกเขา demonstrate อีก critical use case สำหรับ Redis ใน MCP applications ถ้าอยากเริ่มกับ MCP tools ของพวกเขา check out demo repository ที่ให้ great starting point

Why Storage Matters for OAuth (ทำไม Storage สำคัญสำหรับ OAuth)

ตามที่ Clerk อธิบายใน mcp-tools repository persistent storage เป็น essential สำหรับ MCP OAuth implementations สำหรับ 2 key reasons:

  1. The OAuth flow spans multiple endpoints - initialization, OAuth callback, และ MCP requests อาจถูก handle โดย different serverless functions โดยไม่ shared memory
  2. MCP connections are long-running - พึ่งพา in-memory storage จะ bloat memory requirements ตอน scale และ server restart ใดๆ จะ invalidate ทุก sessions

What Gets Stored in Redis (อะไรถูกเก็บใน Redis)

Clerk's Redis store จัดการ 3 types ของ data แต่ละตัวมี purpose เฉพาะใน OAuth flow:

PKCE Verifiers (pkce_verifier_<...>) เก็บตอนเริ่ม OAuth flow และอ่านอีกครั้งหลัง user grants access พวกมันเป็นส่วนของ PKCE (Proof Key for Code Exchange) flow ที่ให้ additional security สำหรับ OAuth ใน public clients โดย ensure ว่า application ที่เริ่ม flow คือตัวเดียวที่ complete มัน (ตาม RFC 7636)

{ "value": "XoYQ...", "created_at": "2025-10-03T06:27:06.928Z", "updated_at": "2025-10-03T06:27:06.928Z" }

Session Data (session_<...>) เก็บทั้ง configuration และ state สำหรับ MCP session เริ่มต้นมี MCP endpoint, OAuth config, และ client credentials หลัง user grants access มัน update ด้วย access และ refresh tokens สุดท้าย authComplete flag เพิ่มตอน flow เสร็จ

{ "value": { "mcpEndpoint": "https://localhost:3001/mcp", "oauthRedirectUrl": "https://localhost:3000/oauth_callback", "oauthScopes": "openid profile email", "mcpClientName": "Clerk MCP Demo", "mcpClientVersion": "0.0.1", "oauthClientUri": "https://example.com", "oauthPublicClient": false, "clientId": "8Yb2...", "clientSecret": "64YG..." }, "created_at": "2025-10-03T06:27:06.882Z", "updated_at": "2025-10-03T06:27:06.882Z" }

State Parameters (state_<...>) map OAuth state parameters ไป session IDs ทำให้ได้ session data โดยใช้ state ID:

{ "value": "dX61...", "created_at": "2025-10-03T06:27:03.585Z", "updated_at": "2025-10-03T06:27:03.585Z" }

Architecture นี้อนุญาตให้ OAuth flow ทำงาน seamlessly across distributed serverless functions ขณะ maintain security และ session integrity

Why Redis is Perfect for MCP (ทำไม Redis เหมาะสำหรับ MCP)

ทั่วทั้ง 3 examples เราเห็น common patterns ที่ทำให้ Redis เป็น ideal choice สำหรับ MCP infrastructure:

Low Latency: MCP operations มักต้องเร็ว Redis's in-memory architecture ให้ response times ที่ต้องการสำหรับ real-time AI interactions

Pub/Sub Capabilities: ตามที่เห็นกับ Vercel's implementation Redis Pub/Sub ให้ coordination ที่ขlegant ระหว่าง distributed components โดยไม่มี complexity ของ full message queue

Rich Data Structures: Streams สำหรับ event streams, Hashes สำหรับ session data, และ simple key-value pairs สำหรับ state Redis ให้ right data structure สำหรับแต่ละ use case

Built-in Expiration: Auto cleanup ผ่าน TTLs OAuth tokens, event streams, และ session data ทั้งหมด expire อัตโนมัติโดยไม่ต้อง manual garbage collection

Serverless-Friendly: ด้วย solutions อย่าง Upstash Redis คุณได้ fully managed, serverless Redis ที่ scales to zero เมื่อไม่ใช้ Perfect สำหรับ MCP implementations ที่อาจมี variable workloads

Beyond MCP Spec Features: Redis ใน AI Ecosystem กว้างขึ้น

แม้เรา focus บน features ที่กำหนดใน MCP spec อย่างชัดเจน Redis's utility ขยายไกลกว่าที่เราสำรวจไปตอนมันมาพัฒนา AI blog posts ล่าสุดของเรา showcase several patterns นี้:

  • AI SDK integration - ใช้ Redis enhance Vercel AI SDK
  • Chat history - Persist messaging history

Beyond ตัวอย่างของเรา community สร้าง impressive Redis-powered tools สำหรับ AI applications ai-sdk-tools suite จาก Midday รวม tool result caching package ที่ใช้ Redis cache AI SDK tool results ตามตัวอย่างนี้ dramatically improving performance และ reducing costs:

เร่งการพัฒนา MCP ด้วย Redis: โซลูชัน Fast และ Cost-Effective

ไม่ว่าคุณจะสร้าง MCP servers, AI agents หรือ full AI applications Redis ให้ infrastructure layer ที่ทำให้ systems ของคุณ production-ready, scalable และ performant

Conclusion (สรุป)

The Model Context Protocol ยังเยาว์ แต่มัน quickly becoming essential infrastructure สำหรับ AI applications ตามที่เราเห็นผ่าน 3 examples นี้ Redis เล่นบทบาทสำคัญในการทำให้ MCP implementations robust และ production-ready ผ่าน:

  • Speed and Flexibility: Combination ของ speed, flexibility และ serverless-friendly architecture
  • Cost Reduction: Caching capabilities ที่ลด expensive API calls และ computations

ถ้าคุณ建設กับ MCP ไม่ว่าจะ server หรือ client side Redis ควรอยู่ใน toolkit ของคุณเป็น perfect companion สำหรับ MCP-powered AI applications ด้วย Upstash Redis คุณเริ่มได้ในวินาทีวันนี้ด้วย globally available, serverless Redis ที่ scales to zero เมื่อไม่ใช้