#!/usr/bin/env node
/**
* Example: Using the MCP Calendar Server
* This script demonstrates how to interact with the calendar server
*/
import { CalendarService } from '../src/services/CalendarService';
import { ReminderService } from '../src/services/ReminderService';
import { DatabaseManager } from '../src/database';
import { createCacheManager } from '../src/cache';
import { AuthManager } from '../src/auth/AuthManager';
import { Logger } from '../src/utils/logger';
async function exampleUsage() {
console.log('š MCP Calendar Server Example\n');
// Initialize services
const database = new DatabaseManager();
const cache = createCacheManager();
const calendarService = new CalendarService(cache, database);
const reminderService = new ReminderService(database);
const authManager = new AuthManager(database);
try {
// Initialize database
console.log('š Initializing database...');
await database.initialize();
// Connect cache if needed
if ('connect' in cache) {
await (cache as any).connect();
}
// Example 1: Create a user
console.log('\nš¤ Creating a sample user...');
const user = await database.createUser({
email: 'example@test.com',
displayName: 'Example User',
timezone: 'America/New_York',
preferences: {
defaultCalendarId: 'primary',
workingHours: {
monday: { startTime: '09:00', endTime: '17:00' },
tuesday: { startTime: '09:00', endTime: '17:00' },
wednesday: { startTime: '09:00', endTime: '17:00' },
thursday: { startTime: '09:00', endTime: '17:00' },
friday: { startTime: '09:00', endTime: '17:00' }
},
defaultEventDuration: 60,
bufferTime: 15,
autoDeclineConflicts: false,
reminderDefaults: {
defaultReminders: [15],
emailReminders: true,
pushReminders: false
}
}
});
console.log(`ā
Created user: ${user.email} (ID: ${user.id})`);
// Example 2: Create reminders
console.log('\nš Creating sample reminders...');
const reminders = [
{
title: 'Call dentist for appointment',
description: 'Schedule cleaning appointment',
priority: 'medium' as const,
dueDateTime: new Date(Date.now() + 24 * 60 * 60 * 1000), // Tomorrow
tags: ['health', 'appointment']
},
{
title: 'Review Q4 budget proposals',
description: 'Go through all department budget requests',
priority: 'high' as const,
dueDateTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // In 3 days
tags: ['work', 'budget', 'finance']
},
{
title: 'Buy groceries',
description: 'Milk, eggs, bread, vegetables',
priority: 'low' as const,
dueDateTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // In 2 days
tags: ['personal', 'shopping']
}
];
for (const reminderData of reminders) {
const reminder = await reminderService.createReminder(user.id, reminderData);
console.log(` ā Created reminder: "${reminder.data?.title}" (Priority: ${reminder.data?.priority})`);
}
// Example 3: Get and filter reminders
console.log('\nš Retrieving reminders...');
const allReminders = await reminderService.getReminders(user.id);
console.log(` š Total reminders: ${allReminders.data?.length}`);
const highPriorityReminders = await reminderService.getReminders(user.id, {
priority: 'high' as const
});
console.log(` š„ High priority reminders: ${highPriorityReminders.data?.length}`);
const workReminders = await reminderService.getReminders(user.id, {
tags: ['work']
});
console.log(` š¼ Work-related reminders: ${workReminders.data?.length}`);
// Example 4: Analyze reminder patterns
console.log('\nš Analyzing reminder patterns...');
const stats = await reminderService.getReminderStatistics(user.id, 30);
if (stats.success && stats.data) {
console.log(` š Statistics (last 30 days):`);
console.log(` Total reminders: ${stats.data.totalReminders}`);
console.log(` Completed: ${stats.data.completedReminders}`);
console.log(` Completion rate: ${stats.data.completionRate.toFixed(1)}%`);
console.log(` Overdue: ${stats.data.overdue}`);
console.log(` Due soon: ${stats.data.dueSoon}`);
console.log(` Priority breakdown:`);
Object.entries(stats.data.priorityBreakdown).forEach(([priority, count]) => {
console.log(` ${priority}: ${count}`);
});
}
// Example 5: Calendar operations (simulated)
console.log('\nš
Demonstrating calendar operations...');
// Note: In a real scenario with Google Calendar API connected:
console.log(' š Sample calendar operations:');
console.log(' - Get calendars');
console.log(' - Find free time slots');
console.log(' - Create events');
console.log(' - Check availability');
console.log(' - Analyze schedule patterns');
// Example 6: Working hours and preferences
console.log('\nā° Working hours example...');
const workingHours = await calendarService.getWorkingHours(user.id, 'primary');
if (workingHours.success) {
console.log(' š
Working hours:');
Object.entries(workingHours.data).forEach(([day, hours]: [string, any]) => {
console.log(` ${day}: ${hours.startTime} - ${hours.endTime}`);
});
}
// Example 7: Search functionality
console.log('\nš Search example...');
const searchResults = await reminderService.searchReminders(user.id, 'budget', 5);
if (searchResults.success && searchResults.data) {
console.log(` š Search results for "budget": ${searchResults.data.length} items`);
searchResults.data.forEach(reminder => {
console.log(` - ${reminder.title} (${reminder.priority})`);
});
}
// Example 8: Upcoming reminders
console.log('\nā° Upcoming reminders...');
const upcoming = await reminderService.getUpcomingReminders(user.id, 48); // Next 48 hours
if (upcoming.success && upcoming.data) {
console.log(` š
Reminders in next 48 hours: ${upcoming.data.length}`);
upcoming.data.forEach(reminder => {
const timeUntil = reminder.dueDateTime
? Math.round((reminder.dueDateTime.getTime() - Date.now()) / (1000 * 60 * 60))
: 'No due time';
console.log(` - ${reminder.title} (in ${timeUntil} hours)`);
});
}
// Example 9: Complete a reminder
console.log('\nā
Completing a reminder...');
if (allReminders.success && allReminders.data && allReminders.data.length > 0) {
const firstReminder = allReminders.data[0];
const completed = await reminderService.completeReminder(user.id, firstReminder.id);
if (completed.success) {
console.log(` ā Completed: "${firstReminder.title}"`);
}
}
// Example 10: Generate OAuth URL (for calendar connection)
console.log('\nš OAuth URL generation example...');
const authUrl = authManager.generateAuthUrl(user.id);
console.log(` š OAuth URL: ${authUrl.substring(0, 100)}...`);
console.log(' (This would be used to connect user\'s Google Calendar)');
console.log('\n⨠Example completed successfully!');
console.log('\nš Summary of what we demonstrated:');
console.log(' ⢠User creation and management');
console.log(' ⢠Reminder/task creation and organization');
console.log(' ⢠Priority and tag-based filtering');
console.log(' ⢠Statistical analysis of tasks');
console.log(' ⢠Search functionality');
console.log(' ⢠Working hours configuration');
console.log(' ⢠OAuth URL generation');
console.log(' ⢠Task completion workflow');
} catch (error) {
console.error('ā Error during example execution:', error);
} finally {
// Cleanup
try {
await database.close();
if ('disconnect' in cache) {
await (cache as any).disconnect();
}
console.log('\nš Cleaned up resources');
} catch (error) {
console.error('Error during cleanup:', error);
}
}
}
// Natural language processing example
async function naturalLanguageExample() {
console.log('\nš§ Natural Language Processing Examples\n');
const examples = [
{
input: "Schedule a dentist appointment next Tuesday at 2pm",
parsed: {
action: "create_event",
title: "Dentist appointment",
date: "next Tuesday",
time: "2:00 PM",
duration: "1 hour (default)"
}
},
{
input: "Remind me to call mom this weekend",
parsed: {
action: "create_reminder",
title: "Call mom",
due: "this weekend",
priority: "medium (default)"
}
},
{
input: "Find a 2-hour slot next week when John, Sarah, and I are all free",
parsed: {
action: "find_free_time",
duration: "2 hours",
attendees: ["John", "Sarah", "user"],
timeframe: "next week"
}
},
{
input: "What meetings do I have tomorrow?",
parsed: {
action: "get_events",
date: "tomorrow",
filter: "meetings"
}
},
{
input: "Show me all my overdue tasks",
parsed: {
action: "get_reminders",
filter: "overdue",
priority: "all"
}
}
];
console.log('These natural language inputs would be processed by the MCP tools:\n');
examples.forEach((example, index) => {
console.log(`${index + 1}. Input: "${example.input}"`);
console.log(' Parsed as:');
Object.entries(example.parsed).forEach(([key, value]) => {
console.log(` ${key}: ${value}`);
});
console.log('');
});
console.log('The MCP server translates these into structured API calls automatically! š');
}
// MCP Tool demonstration
async function mcpToolsDemo() {
console.log('\nš ļø MCP Tools Available\n');
const tools = [
{
name: 'get_calendars',
description: 'List all available calendars',
example: 'Show me my calendars'
},
{
name: 'create_calendar_event',
description: 'Create a new calendar event',
example: 'Schedule team meeting tomorrow at 10am'
},
{
name: 'find_free_time',
description: 'Find available time slots',
example: 'When am I free for a 1-hour meeting this week?'
},
{
name: 'create_reminder',
description: 'Create a task or reminder',
example: 'Remind me to submit expense report by Friday'
},
{
name: 'analyze_schedule_patterns',
description: 'Analyze scheduling habits',
example: 'How busy have I been this month?'
},
{
name: 'suggest_meeting_times',
description: 'AI-powered meeting suggestions',
example: 'Best times for a team meeting next week?'
},
{
name: 'get_contact_suggestions',
description: 'Auto-suggest frequent contacts',
example: 'Who should I invite to the project meeting?'
}
];
console.log('Available MCP Tools:\n');
tools.forEach((tool, index) => {
console.log(`${index + 1}. ${tool.name}`);
console.log(` Description: ${tool.description}`);
console.log(` Example: "${tool.example}"`);
console.log('');
});
console.log('All tools support natural language input and provide structured responses! šÆ');
}
// Run examples
async function main() {
await exampleUsage();
await naturalLanguageExample();
await mcpToolsDemo();
}
if (require.main === module) {
main().catch(console.error);
}