One of the primary use cases for the Model Context Protocol (MCP) is providing structured context to AI models. This guide explains how to integrate MCP with AI features in your Zopio application.
Always validate your context before sending it to AI models:
Copy
import { validateResource } from '@repo/mcp';import { userSchema } from '@repo/mcp';// Validate user contextif (!validateResource(userContext, userSchema)) { throw new Error('Invalid user context');}
Here’s a complete example of using MCP to build a personalized AI assistant:
Copy
import { MCPClient } from '@repo/mcp';import { generateText } from '@repo/ai';import { models } from '@repo/ai/lib/models';export async function getPersonalizedAssistant(userId: string) { const mcpClient = new MCPClient({ serverUrl: '/api/mcp' }); // Build comprehensive user context const [user, preferences, history] = await Promise.all([ mcpClient.readResource('user', userId), mcpClient.readResource('preferences', userId), mcpClient.readResource('conversation-history', userId) ]); // Create a system prompt using the context const systemPrompt = ` You are a personal assistant for ${user.attributes.name}. Preferred language: ${preferences.attributes.language || 'English'} Communication style: ${preferences.attributes.communicationStyle || 'Friendly'} Areas of interest: ${preferences.attributes.interests?.join(', ') || 'Not specified'} Please provide personalized assistance based on this information. `; // Return a function that generates responses return async (userMessage: string) => { return generateText({ model: models.chat, systemPrompt, prompt: userMessage, context: { user, preferences, recentConversations: history.attributes.recent || [] } }); };}// Usageconst assistant = await getPersonalizedAssistant('user-123');const response = await assistant('What should I do this weekend?');