Tutorial

API_REFERENCE

MCP Server API Reference

Complete API documentation for the @muzie/mcp-server package.

Table of Contents


Initialization

createMCPServer(config)

Factory function to initialize the MCP server with dependency injection.

import { createMCPServer } from '@muzie/mcp-server';

const mcp = createMCPServer(config);

Parameters

Parameter Type Required Description
config Object Yes Configuration object
config.models Object Yes Mongoose models
config.services Object No AI and search services
config.utils Object No Utility functions
config.aiConfig Object No AI provider configuration

config.models (Required)

Model Type Description
Room Model Meeting room sessions
Schedule Model Scheduled meetings
Recording Model Recording metadata
UserProfile Model User profiles
StoredRoom Model Saved/persistent rooms
FileIndex Model File metadata and index
Transcription Model Transcription data
Transcribing Model Active transcription sessions

config.services (Optional)

Service Type Description
UnifiedAIService Class AI completion service
AISearchService Class Semantic search service
LocalEmbeddingService Class Embedding generation
GraphContextService Class Knowledge graph queries
TopicExtractionService Class Topic extraction

config.aiConfig (Optional)

Property Type Description
openaiKey string OpenAI API key
xaiKey string xAI/Grok API key (fallback)

Returns

{
  MCPClient,              // Express→MCP bridge
  SmartRouter,            // Query routing analyzer
  RouteType,              // Route type enum
  primitives,             // Primitive tool functions
  ActionTypes,            // Frontend action contracts
  buildSecurityContext,   // Security context builder
  authorization,          // Authorization helpers
  mcpIntentClassifier,    // AI intent detection
  MCPAgentOrchestrator,   // Complex query agent
  handleAgentQuery,       // Agent entry point
  shouldUseAgent,         // Pre-check if agent needed
  aiQueryGenerator,       // AI query service
  TOOLS,                  // Tool definitions
  toolHandlers            // Tool handler functions
}

Example

const mcp = createMCPServer({
  models: {
    Room, Schedule, Recording, UserProfile,
    StoredRoom, FileIndex, Transcription, Transcribing
  },
  services: {
    UnifiedAIService,
    AISearchService,
    GraphContextService
  },
  utils: { normalizeRoomName },
  aiConfig: {
    openaiKey: process.env.OPENAI_API_KEY,
    xaiKey: process.env.XAI_API_KEY
  }
});

Core Exports

MCPClient

Express→MCP bridge that spawns a child process for tool execution.

import { MCPClient } from '@muzie/mcp-server';

const client = new MCPClient();
await client.connect();

const result = await client.callTool('query_rooms', {
  limit: 10,
  apiKey: 'org_123'
}, userContext, 30000);

Methods

Method Parameters Returns Description
constructor() - MCPClient Create client instance
connect() - Promise<void> Connect to MCP server
ensureConnected() - Promise<void> Ensure connection is active
callTool(name, args, context, timeout) See below Promise<Object> Execute a tool

callTool Parameters

Parameter Type Required Description
name string Yes Tool name
args Object Yes Tool arguments
context Object Yes User context
timeout number No Timeout in ms (default: 30000)

SmartRouter

Query routing analyzer that determines the best execution path.

import { SmartRouter, RouteType } from '@muzie/mcp-server';

const analysis = SmartRouter.analyze(query);

Methods

Method Parameters Returns Description
analyze(query) string AnalysisResult Analyze query intent

AnalysisResult

{
  route: RouteType,      // DIRECT, SIMPLE, AGENT, or CLASSIFY
  tool: string,          // Recommended tool name
  params: Object,        // Extracted parameters
  confidence: number,    // Confidence score (0-1)
  reason: string         // Explanation for routing decision
}

RouteType Enum

import { RouteType } from '@muzie/mcp-server';

RouteType.DIRECT   // Single-step action (fastest)
RouteType.SIMPLE   // Single database query
RouteType.AGENT    // Multi-step reasoning required
RouteType.CLASSIFY // Ambiguous, needs classification

toolHandlers

Direct tool handler functions for in-process execution.

import { toolHandlers } from '@muzie/mcp-server';

const result = await toolHandlers.query_rooms({
  limit: 10,
  apiKey: 'org_123',
  userId: 'user_id',
  _userContext: securityContext
});

Available Handlers

See Tools Reference for complete tool documentation.


Security Context

buildSecurityContext(userContext)

Builds a security context for authorization checks.

import { buildSecurityContext } from '@muzie/mcp-server';

const securityContext = await buildSecurityContext({
  email: 'user@example.com',
  userId: 'user_example_com',
  apiKey: 'org_123456',
  isAdmin: false,
  timezone: 'UTC'
});

Input Parameters

Parameter Type Required Description
email string Yes User's email address
userId string Yes Cleaned user ID
apiKey string Yes Organization/tenant ID
isAdmin boolean No Admin privileges
timezone string No User's timezone

Returns

{
  userEmail: string,     // Original email
  userId: string,        // Cleaned user ID
  apiKey: string,        // Organization key
  isOrgOwner: boolean,   // Owner status
  orgUserIds: string[],  // Accessible user IDs
  isAdmin: boolean,      // Admin status
  timezone: string       // Timezone
}

Authorization Helpers

import { authorization } from '@muzie/mcp-server';

const {
  buildUserContext,
  MCPAuthorizationError,
  getAccessibleRoomIds,
  validateRoomAccess,
  applyAuthorizationFilters
} = authorization;

MCPAuthorizationError

Custom error class for authorization failures.

throw new MCPAuthorizationError('Access denied to room', {
  userId: 'user_123',
  resource: 'room_456',
  action: 'read'
});

ActionTypes

Frontend action contracts returned by tools.

import { ActionTypes } from '@muzie/mcp-server';

Available Actions

Action Value Description
CREATE_ROOM 'CREATE_ROOM' Create persistent room
NAVIGATE_TO_ROOM 'NAVIGATE_TO_ROOM' Start and navigate to room
CONFIRMATION_REQUIRED 'CONFIRMATION_REQUIRED' Show confirmation dialog
CREATE_SCHEDULE 'CREATE_SCHEDULE' Create schedule data
SCHEDULE_CREATED 'SCHEDULE_CREATED' Schedule creation success
CANCEL_SCHEDULE 'CANCEL_SCHEDULE' Cancel scheduled meeting
SCHEDULE_CANCELLED 'SCHEDULE_CANCELLED' Cancellation confirmation
COPY_TO_CLIPBOARD 'COPY_TO_CLIPBOARD' Copy content
SEND_INVITES 'SEND_INVITES' Send email invites
INFO_ONLY 'INFO_ONLY' Display information
NEEDS_INFO 'NEEDS_INFO' Collect missing parameters
VIEW_TRANSCRIPT 'VIEW_TRANSCRIPT' Open transcript viewer
VIEW_FILE 'VIEW_FILE' Open file viewer
VIEW_GRAPH 'VIEW_GRAPH' Display network graph

ConfirmationTypes

import { ConfirmationTypes } from '@muzie/mcp-server';

ConfirmationTypes.SCHEDULE  // Schedule confirmation type

Usage in Frontend

// Tool response
{
  success: true,
  actionType: ActionTypes.VIEW_TRANSCRIPT,
  data: {
    recordingId: 'rec_123',
    transcriptId: 'trans_456'
  }
}

// Frontend handler
switch (result.actionType) {
  case ActionTypes.VIEW_TRANSCRIPT:
    openTranscriptViewer(result.data.transcriptId);
    break;
  case ActionTypes.NAVIGATE_TO_ROOM:
    navigateToRoom(result.data.roomName);
    break;
  case ActionTypes.CONFIRMATION_REQUIRED:
    showConfirmationDialog(result.data);
    break;
}

Error Handling

Standard Error Response

{
  success: false,
  error: 'Error message',
  code: 'ERROR_CODE',       // Optional error code
  details: {}               // Optional additional context
}

Error Codes

Code Description
AUTH_REQUIRED Authentication required
ACCESS_DENIED Authorization failed
NOT_FOUND Resource not found
INVALID_PARAMS Invalid parameters
TOOL_ERROR Tool execution error
TIMEOUT Operation timeout
AI_ERROR AI service error

Handling Errors

try {
  const result = await toolHandlers.query_rooms(params);
  if (!result.success) {
    console.error('Tool error:', result.error);
  }
} catch (error) {
  if (error instanceof MCPAuthorizationError) {
    console.error('Authorization failed:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}

Response Formats

Success Response

{
  success: true,
  data: { ... },              // Tool-specific data
  actionType: ActionTypes.*, // Frontend action (optional)
  message: 'Human-readable'  // Display message (optional)
}

Query Response

{
  success: true,
  rooms: [...],      // Array of results
  total: 42,         // Total count
  page: 1,           // Current page
  limit: 10          // Results per page
}

Agent Response

{
  success: true,
  response: 'Markdown formatted response',
  steps: [
    { type: 'THINKING', content: '...' },
    { type: 'TOOL_CALL', tool: 'query_rooms', args: {...} },
    { type: 'TOOL_RESULT', data: {...} },
    { type: 'RESPONSE', content: '...' }
  ],
  tokensUsed: {
    input: 1500,
    output: 800
  }
}

Related Documentation