#Model Context Protocol (MCP) Implementation - Detailed Description
#1. Overview
The Model Context Protocol (MCP) is a standardized system that enables AI agents to interact with external tools, services, and data sources through a consistent interface. This implementation provides a comprehensive framework for registering, discovering, and executing tools, maintaining session state between interactions, and facilitating communication between AI agents and backend services.
The MCP system consists of server-side components that expose an HTTP API for tool execution and context management, and client-side components that make it easy to integrate these capabilities into web applications, particularly for the 5CRSE platform focused on premium transportation and experience enhancement around events.
#2. Architecture
#2.1 High-Level Architecture
The MCP implementation follows a client-server architecture:
- Server Side: Express-based HTTP server that exposes endpoints for tool discovery, execution, and context management
- Session Management: System for tracking and maintaining state between interactions
- Tool Registry: Centralized registry for available tools and their metadata
- Tool Execution Layer: System for validating, executing, and handling errors from tool operations
- Client Side: TypeScript/JavaScript client and React hooks for consuming the MCP services
#2.2 Component Diagram
┌─────────────────────────────────┐ ┌───────────────────────┐
│ MCP Server │ │ MCP Client │
│ │◄───────►│ │
│ ┌─────────────┐ ┌────────────┐ │ HTTP │ ┌─────────────────┐ │
│ │Tool Registry│ │ Session │ │ │ │ HTTP Client │ │
│ │ │ │ Manager │ │ │ │ │ │
│ └─────┬───────┘ └─────┬──────┘ │ │ └────────┬────────┘ │
│ │ │ │ │ │ │
│ ▼ ▼ │ │ ▼ │
│ ┌─────────────────────────┐ │ │ ┌─────────────────┐ │
│ │ Tool Execution │ │ │ │ React Hooks │ │
│ │ │ │ │ │ │ │
│ └─────────────────────────┘ │ │ └────────┬────────┘ │
│ │ │ │ │
└─────────────────────────────────┘ │ ▼ │
│ ┌─────────────────┐ │
│ │ React Components│ │
│ │ │ │
│ └─────────────────┘ │
│ │
└───────────────────────┘
#3. Core Components
#3.1 MCP Logger (MCPLogger.ts)
A specialized logging utility for MCP operations that provides structured logging with different severity levels:
-
Features:
- Log levels: debug, info, warn, error
- Timestamp prefixing
- Optional additional data context
- Production mode disabling for performance
-
Implementation:
- Simple singleton class exported as
mcpLogger - Wraps console logging with additional context
- Configurable enabled/disabled state
- Simple singleton class exported as
#3.2 Session Manager (MCPSessionManager.ts)
Manages stateful sessions for interactions between AI agents and tools:
-
Features:
- Session creation and retrieval
- Persistent context across interactions
- Memory storage for tool-specific data
- Automatic session timeout and cleanup
- UUID-based session identification
-
Implementation:
MCPSessioninterface defining session contractMCPSessionImplconcrete implementationMCPSessionManagerclass for managing session lifecycle- In-memory session storage with configurable TTL
- Background cleanup process for expired sessions
- Thread-safe operations for concurrent access
#3.3 Tool Registry (MCPToolRegistry.ts)
Registry for AI agent tools that provides discovery and validation capabilities:
-
Features:
- Agent-specific tool registration
- Tool schema metadata with parameter definitions
- JSON Schema-compatible parameter validation
- Tool builder pattern for simple registration
- Tool discovery API
-
Implementation:
MCPToolRegistrymain class with registry storageMCPToolBuilderfluent builder for tool creation- Type-safe parameter validation
- Support for various parameter types (string, number, boolean, object, array)
- Optional and required parameter handling
- Advanced validation rules (enum, min/max, pattern, etc.)
#3.4 Tool Execution (toolExecution.ts)
Handles tool execution with input validation, error handling, and context management:
-
Features:
- Parameter validation against schema
- Execution context preparation
- Error handling and standardization
- Session context updates based on results
- Automatic memory updates for certain tool types
-
Implementation:
- Type-safe execution function
- Deep parameter validation against schema
- Context preparation with session data
- Standardized error handling
- Automatic memory updates for get/search/create operations
#3.5 MCP Server (MCPServer.ts)
Express server implementation that exposes HTTP endpoints for MCP operations:
-
Features:
- RESTful API for tool discovery and execution
- Authentication via bearer tokens
- CORS support for cross-origin requests
- Session-aware request handling
- Status monitoring endpoints
- Error handling middleware
-
Implementation:
- Express-based HTTP server
- JSON request/response format
- Bearer token authentication
- CORS middleware with configurable origins
- Request logging and error handling
- API endpoints for tools, execution, context, etc.
#3.6 Client SDK (MCPClient.ts)
Client-side SDK for interacting with the MCP server:
-
Features:
- Tool execution with type safety
- Session management
- Context manipulation
- Error handling and standardization
- Tool discovery
-
Implementation:
- TypeScript-based HTTP client
- Promise-based API
- Session ID tracking
- Type-safe tool execution
- Automatic error handling and standardization
#3.7 React Hooks (useMCPTool.tsx)
React hooks for integrating MCP functionality into React components:
-
Features:
- Tool execution with React state integration
- Loading state tracking
- Error handling
- Session management
- Context synchronization
-
Implementation:
- React hooks for tool execution (
useMCPTool) - Session management hook (
useMCPSession) - Tool discovery hook (
useMCPTools) - TypeScript generics for type safety
- React state synchronization with MCP state
- React hooks for tool execution (
#4. Data Flow
#4.1 Tool Execution Flow
-
Tool Registration:
- Tool is registered in the
MCPToolRegistrywith metadata - Parameters are defined with types and validation rules
- Tool function is provided for execution
- Tool is registered in the
-
Client Request:
- Client forms a request with tool ID, arguments, and optional session ID
- Request is sent to
/executeendpoint
-
Server Processing:
- Server authenticates the request
- Server retrieves or creates a session
- Server validates arguments against tool schema
- Server executes the tool function with validated arguments
- Server captures result or error
-
Response Handling:
- Server sends success response with result or error response
- Client processes response and updates UI accordingly
- Session is updated with execution context
#4.2 Session Management Flow
-
Session Creation:
- First request comes in without session ID
- Server creates a new session with UUID
- Session is returned to client
-
Session Reuse:
- Subsequent requests include session ID
- Server retrieves existing session
- Context is maintained between requests
-
Context Updates:
- Tool execution can update session context
- Client can explicitly update context via API
- Memory storage persists tool-specific data
-
Session Cleanup:
- Idle sessions expire after TTL period
- Background process removes expired sessions
- Client can explicitly end sessions
#5. Key Features in Detail
#5.1 Tool Registration and Discovery
Tools are registered with the MCP registry using a builder pattern. Examples relevant to 5CRSE:
// Example Customer Service Agent Tool for Transportation Availability
const csBuilder = registry.createToolBuilder('customer_service');
csBuilder
.withId('get_available_vehicles')
.withName('Get Available Vehicles')
.withDescription('Check vehicle availability for an event date/time and location.')
.withParameter('eventDate', 'string', 'Event date (YYYY-MM-DD)', { required: true })
.withParameter('eventTime', 'string', 'Event time (HH:MM)', { required: true })
.withParameter('location', 'object', 'Event location coordinates', { required: true })
.withParameter('passengerCount', 'number', 'Number of passengers', { required: true })
.withFunction(async (args, context) => {
// Implementation using FleetManagementService...
const fleetService = new FleetManagementService(context.payload);
return await fleetService.getAvailableVehicles(args);
})
.register();
// Example Business Manager Agent Tool for Adding Partner Venues
const bmBuilder = registry.createToolBuilder('business_manager');
bmBuilder
.withId('add_partner_venue')
.withName('Add Partner Venue')
.withDescription('Add a new partner venue for curated experiences.')
.withParameter('name', 'string', 'Venue name', { required: true })
.withParameter('location', 'object', 'Venue location', { required: true })
.withParameter('venueType', 'string', 'Venue type', {
required: true,
enum: ['restaurant', 'bar', 'lounge', 'club', 'other']
})
.withParameter('commissionRate', 'number', 'Commission rate percentage', { required: true })
.withParameter('contactInfo', 'object', 'Contact information', { required: true })
.withFunction(async (args, context) => {
// Implementation using PartnerVenueService...
const partnerService = new PartnerVenueService(context.payload);
return await partnerService.addPartnerVenue(args);
})
.register();
Tools can be discovered through the API:
// Get all tools for an agent
const tools = await client.getTools('customer_service');
// Get a specific tool schema
const schema = await client.getToolSchema('search_events', 'customer_service');
#5.2 Parameter Validation
The MCP system validates all tool parameters against their schema:
- Type Checking: Ensures parameters match declared types
- Required Parameters: Validates presence of required parameters
- Enum Validation: Checks that values match enumerated options
- Object Validation: Recursively validates nested object properties
- Array Validation: Validates array items against item schema
- Range Validation: Checks numeric values against min/max constraints
Validation occurs before tool execution, preventing invalid arguments from reaching tool functions.
#5.3 Session and Context Management
Sessions maintain state between interactions. This is crucial for multi-step processes like booking a transportation package combined with a dining experience, allowing the agent to remember choices made in previous turns.
// Create or retrieve a session
const session = sessionManager.getOrCreateSession(sessionId, userId, agentType);
// Get context
const context = session.getContext();
// Update context after user selects a vehicle
session.updateContext({ bookingInProgress: { ...context.bookingInProgress, vehicleId: selectedVehicle.id } });
// Store intermediate results in memory
session.storeMemory('available_experiences', experienceOptions);
// Retrieve from memory
const availableExperiences = session.retrieveMemory('available_experiences');
The session manager automatically expires idle sessions after a configurable TTL (default: 30 minutes).
#5.4 React Integration
React hooks simplify MCP integration:
// Initialize client
initializeMCPClient({
serverUrl: 'http://localhost:3007',
authToken: 'your-auth-token',
defaultAgentType: 'customer_service'
});
// Use MCP tool hook
const {
data,
isLoading,
error,
executeTool
} = useMCPTool('search_events');
// Execute the tool
const handleSearch = async () => {
await executeTool({ query: 'concert', location: 'New York' });
};
// Render UI
return (
<div>
<button onClick={handleSearch} disabled={isLoading}>
{isLoading ? 'Searching...' : 'Search'}
</button>
{error && <div className="error">{error.message}</div>}
{data && (
<div className="results">
{data.map(item => (
<div key={item.id}>{item.title}</div>
))}
</div>
)}
</div>
);
#5.5 Tool Types and Categories
The MCP implementation includes tools categorized by agent type and function, aligned with the 5CRSE business model:
-
Customer Service (
customer_service) Tools:- Search & Booking:
search_events: Find events (potentially for context, less primary).get_available_vehicles: Check transportation availability.search_experience_packages: Find curated experience packages.create_booking: Initiate booking for transportation or packages.check_booking_status: Retrieve status of an existing booking.get_booking_details: Get full itinerary/details for a booking.check_dining_availability: Check availability at partner restaurants (if OpenTable integrated).
- Information Retrieval:
get_user_info: Retrieve basic customer information.get_ambassador_details: Provide details of an assigned ambassador.
- Search & Booking:
-
Business Manager (
business_manager) Tools:- Operational Management:
add_vehicle,update_vehicle,get_vehicle_status: Manage fleet.add_driver,update_driver,assign_driver: Manage drivers.add_ambassador,update_ambassador,assign_ambassador: Manage ambassadors.add_partner_venue,update_partner_venue: Manage venue partnerships.create_experience_package,update_experience_package: Manage curated experiences.
- Analytics & Reporting:
get_business_metrics: Retrieve operational metrics (e.g., fleet utilization, revenue breakdown, booking trends).generate_report: Create formatted reports on operations.track_ambassador_performance: Log or retrieve ambassador performance data.
- Content Management:
manage_content: Create/update CMS content (e.g., promotional pages).
- Operational Management:
-
System (
system) Tools: General utilities if needed.
#5.6 Error Handling
The MCP system provides comprehensive error handling:
- Validation Errors: Detailed errors for parameter validation failures
- Execution Errors: Standardized error format for tool execution failures
- Authentication Errors: Clear errors for authentication failures
- Server Errors: Sanitized internal error reporting
Errors are propagated to clients with standardized format:
{
"success": false,
"error": {
"message": "Parameter 'query' must be a string",
"code": "VALIDATION_ERROR"
}
}
#5.7 Security Features
Security is a core consideration in the MCP implementation:
- Authentication: Bearer token authentication for all API endpoints
- CORS Protection: Configurable CORS for cross-origin requests
- Input Validation: Strict validation of all parameters
- Error Sanitization: Prevention of sensitive information leakage
- Session Isolation: Separate session contexts for different users
#6. Implementation Details
#6.1 Server Implementation
The MCP server is implemented as an Express application with RESTful endpoints:
- GET /status: Server status and uptime
- GET /tools: List available tools
- GET /tools/:toolId: Get tool schema
- POST /execute: Execute a tool
- GET /context/:sessionId: Get session context
- POST /context/:sessionId: Update session context
- DELETE /context/:sessionId: Remove session
The server uses middleware for:
- Authentication
- Request logging
- CORS handling
- Error handling
#6.2 Session Storage
Sessions are stored in-memory with automatic expiration:
class MCPSessionManager {
private sessions: Map<string, MCPSession> = new Map();
constructor(
private sessionTTL: number = 30 * 60 * 1000, // 30 minutes
private cleanupInterval: number = 5 * 60 * 1000 // 5 minutes
) {
// Set up cleanup interval
setInterval(() => this.cleanupSessions(), this.cleanupInterval);
}
// Session management methods...
private cleanupSessions(): void {
const now = Date.now();
// Remove expired sessions
for (const [sessionId, session] of this.sessions.entries()) {
if (now - session.lastAccessedAt.getTime() > this.sessionTTL) {
this.sessions.delete(sessionId);
}
}
}
}
For production use, the session storage could be extended to support persistent storage (database, Redis, etc.).
#6.3 Tool Execution Logic
The tool execution process follows these steps:
- Tool Lookup: Find the tool in the registry
- Context Preparation: Create execution context with session data
- Parameter Validation: Validate arguments against schema
- Tool Execution: Execute the tool function with validated arguments
- Result Processing: Process result or handle errors
- Context Update: Update session with results
export async function executeToolOperation(
registry: MCPToolRegistry,
toolId: string,
agentType: string,
args: any,
session: MCPSession
): Promise<any> {
// Find tool
const tool = registry.getTool(toolId, agentType);
if (!tool) throw new Error(`Tool not found: ${toolId}`);
// Create context
const context = {
sessionId: session.id,
memory: session.memory,
...session.context
};
// Validate args
validateArgs(args, tool);
// Execute tool
const result = await tool.function(args, context);
// Update session
updateSessionWithToolResult(session, tool, result);
return result;
}
#6.4 React Hook Implementation
The React hooks are implemented with React's useState, useCallback, and useEffect:
export function useMCPTool<T = any, A extends Record<string, any> = Record<string, any>>(
toolId: string,
agentType?: string,
config?: MCPClientConfig
): MCPToolResult<T, A> {
const [state, setState] = useState<MCPToolState<T>>({
data: null,
isLoading: false,
error: null,
sessionId: null
});
// Get MCP client
const getMCPClientInstance = useCallback(() => {
return getMCPClient(config);
}, [config]);
// Execute tool
const executeTool = useCallback(async (args: A) => {
setState(prev => ({ ...prev, isLoading: true, error: null }));
try {
const client = getMCPClientInstance();
const result = await client.executeTool<T>({
toolId,
agentType,
args
});
setState(prev => ({
...prev,
data: result,
isLoading: false,
sessionId: client.getSessionId()
}));
return result;
} catch (error: any) {
setState(prev => ({
...prev,
isLoading: false,
error
}));
throw error;
}
}, [toolId, agentType, getMCPClientInstance]);
// Other implementation details...
return {
data: state.data,
isLoading: state.isLoading,
error: state.error,
executeTool,
sessionId: state.sessionId,
resetState
};
}
#6.5 Testing Implementation
The MCP system includes comprehensive testing:
-
Integration Tests: Test server and client together
- Start test server with known tools
- Execute tools and verify results
- Test session management
- Test error handling
-
Browser Tests: Test client in real browser
- Launch Puppeteer browser
- Interact with test page
- Execute tools via browser
- Verify results visually
-
Manual Tests: Simple script for manual testing
- Start server and run quick checks
- Log results for inspection
#7. Extension Points
The MCP implementation is designed for extensibility:
#7.1 Adding New Tools
New tools can be added by registering them with the tool registry:
// Create a function to register tools
export function registerMyTools(registry: MCPToolRegistry): void {
const builder = registry.createToolBuilder('my_agent_type');
builder
.withId('my_tool')
.withName('My Tool')
.withDescription('Description of my tool')
.withParameter('param1', 'string', 'Parameter description', { required: true })
.withFunction(async (args, context) => {
// Implement tool functionality
return { result: 'success' };
})
.register();
}
// Register tools during initialization
const toolRegistry = createMCPToolRegistry(payload);
registerMyTools(toolRegistry);
#7.2 Custom Session Storage
The session storage can be extended for persistence:
// Custom session manager with database storage
class DatabaseSessionManager extends MCPSessionManager {
constructor(private db: Database) {
super();
}
public async getSession(sessionId: string): Promise<MCPSession | undefined> {
// Load from database
const data = await this.db.getSession(sessionId);
if (!data) return undefined;
// Create session from data
return new MCPSessionImpl(
data.id,
data.userProfileId,
data.agentType,
data.context,
data.memory
);
}
// Override other methods...
}
#7.3 Custom Authentication
The authentication system can be customized:
// Custom authentication middleware
function customAuthMiddleware(req: Request, res: Response, next: NextFunction): void {
// Implement custom authentication logic
const token = req.headers.authorization?.split(' ')[1];
// Verify with external service
authService.verify(token)
.then(user => {
req.user = user; // Attach user to request
next();
})
.catch(error => {
res.status(401).json({
success: false,
error: 'Unauthorized',
message: error.message
});
});
}
// Use custom middleware
app.use(customAuthMiddleware);
#8. Deployment Considerations
#8.1 Environment Variables
The MCP server uses these environment variables:
MCP_PORT: HTTP port for the server (default: 3007)MCP_AUTH_ENABLED: Enable authentication (default: true)MCP_AUTH_SECRET: Secret key for authenticationMCP_CORS_ORIGINS: Comma-separated list of allowed originsNODE_ENV: Environment (development, production, test)
#8.2 Scaling
For high-load scenarios:
- Horizontal Scaling: Multiple MCP server instances
- Session Persistence: Redis or database for session storage
- Load Balancing: Distribute requests across instances
- Rate Limiting: Protect from abuse with rate limits
#8.3 Security Hardening
For production deployment:
- HTTPS: Always use HTTPS in production
- Strong Auth: Use robust authentication (OAuth, JWT)
- API Gateway: Consider API gateway for additional security
- Input Sanitization: Additional sanitization for user inputs
- Monitoring: Log monitoring for suspicious activity
#9. Conclusion
The Model Context Protocol (MCP) implementation provides a standardized way for AI agents to interact with external tools and services. It offers:
- Tool Discovery and Execution: Standardized API for tool operations
- Session Management: Context maintenance between interactions
- Type Safety: Strong TypeScript typing throughout
- Validation: Comprehensive parameter validation
- Client Integration: Simple React hooks for frontend use
- Extensibility: Easy extension points for customization
This implementation forms the foundation for AI-powered features in the 5CRSE platform, enabling AI agents to leverage platform capabilities – particularly transportation logistics, experience curation, and operational management – through a consistent, secure, and type-safe interface.
