Tutorial

AGENT_GUIDE

MCP Agent Guide

Guide for using the MCPAgentOrchestrator for complex, multi-step queries.

Overview

The MCPAgentOrchestrator handles queries that require multiple tool calls and reasoning steps. It uses AI to decompose complex questions, execute tools sequentially, and synthesize results.

When to Use the Agent

Use Agent For:

  • Multi-step queries: "Find meetings with John and summarize what we discussed"
  • Analysis requests: "Who do I collaborate with most and on what topics?"
  • Comparative queries: "Compare my meeting frequency this month vs last month"
  • Synthesis tasks: "Give me an overview of project alpha progress"

Use Direct Tools For:

  • Simple queries: "Show my meetings" → query_rooms
  • Single data fetch: "Get the transcript for meeting X" → get_transcript
  • Direct actions: "Start a meeting" → start_meeting

Quick Start

import { handleAgentQuery, shouldUseAgent } from '@muzie/mcp-server';

const query = "Find all my meetings with the marketing team and summarize key decisions";

// Check if agent is needed
if (shouldUseAgent(query)) {
  const result = await handleAgentQuery(query, userContext, {
    maxIterations: 5,
    timeout: 30000
  });

  console.log(result.response);  // Markdown formatted answer
  console.log(result.steps);     // Execution trace
}

Configuration Options

handleAgentQuery Options

Option Type Default Description
maxIterations number 7 Maximum reasoning steps
timeout number 55000 Timeout in milliseconds
model string 'gpt-4o-mini' AI model to use
temperature number 0.3 AI temperature
maxTokens number 1500 Max tokens per step
verbose boolean false Enable detailed logging

Example Configuration

const result = await handleAgentQuery(query, userContext, {
  maxIterations: 10,          // Allow more steps for complex queries
  timeout: 60000,             // 60 second timeout
  model: 'gpt-4o',            // Use more capable model
  temperature: 0.2,           // More deterministic
  maxTokens: 2000,            // Longer responses
  verbose: true               // Debug logging
});

Step Types

The agent produces a trace of steps during execution:

THINKING

AI reasoning about what to do next.

{
  type: 'THINKING',
  content: 'The user wants to find meetings with John. I should first query rooms to find meetings where John was a participant.',
  timestamp: '2026-01-11T10:00:00Z'
}

TOOL_CALL

Decision to execute a specific tool.

{
  type: 'TOOL_CALL',
  tool: 'query_rooms',
  args: {
    limit: 50,
    participantFilter: 'john@example.com'
  },
  timestamp: '2026-01-11T10:00:01Z'
}

TOOL_RESULT

Result from tool execution.

{
  type: 'TOOL_RESULT',
  tool: 'query_rooms',
  success: true,
  data: {
    rooms: [...],
    total: 23
  },
  timestamp: '2026-01-11T10:00:02Z'
}

RESPONSE

Final formatted response to user.

{
  type: 'RESPONSE',
  content: '## Meetings with John\n\nI found 23 meetings with John...',
  timestamp: '2026-01-11T10:00:05Z'
}

ERROR

Error during execution.

{
  type: 'ERROR',
  error: 'Timeout waiting for AI response',
  timestamp: '2026-01-11T10:00:55Z'
}

Response Format

{
  success: true,
  response: '## Analysis Results\n\n...',  // Markdown formatted
  steps: [
    { type: 'THINKING', content: '...' },
    { type: 'TOOL_CALL', tool: 'query_rooms', args: {...} },
    { type: 'TOOL_RESULT', data: {...} },
    { type: 'THINKING', content: '...' },
    { type: 'TOOL_CALL', tool: 'summarize_transcript', args: {...} },
    { type: 'TOOL_RESULT', data: {...} },
    { type: 'RESPONSE', content: '...' }
  ],
  tokensUsed: {
    input: 3500,
    output: 1200
  },
  iterationsUsed: 4,
  executionTime: 4523  // milliseconds
}

Using with SmartRouter

The SmartRouter helps decide when to use the agent:

import { smartRouter, RouteType, handleAgentQuery, toolHandlers } from '@muzie/mcp-server';

async function handleQuery(query, userContext) {
  const analysis = smartRouter.analyze(query);

  switch (analysis.route) {
    case RouteType.DIRECT:
    case RouteType.SIMPLE:
      // Use tool directly
      const handler = toolHandlers[analysis.tool];
      return await handler({
        ...analysis.params,
        apiKey: userContext.apiKey,
        userId: userContext.userId,
        _userContext: userContext
      });

    case RouteType.AGENT:
      // Use agent for complex query
      return await handleAgentQuery(query, userContext);

    case RouteType.CLASSIFY:
      // Need to classify intent first
      const classified = await mcpIntentClassifier.classifyAndExtract(query, userContext);
      // Re-route based on classification
      break;
  }
}

Token Optimization

Strategies to Reduce Token Usage

  1. Limit iterations: Set maxIterations based on query complexity
  2. Use smaller models: gpt-4o-mini is often sufficient
  3. Reduce context: Filter results before sending to AI
  4. Early termination: Agent stops when answer is found

Monitoring Token Usage

const result = await handleAgentQuery(query, userContext);

console.log('Token usage:', result.tokensUsed);
// { input: 3500, output: 1200 }

console.log('Iterations:', result.iterationsUsed);
// 4

// Estimate cost (gpt-4o-mini pricing)
const inputCost = result.tokensUsed.input * 0.00015 / 1000;
const outputCost = result.tokensUsed.output * 0.0006 / 1000;
console.log('Estimated cost: $', (inputCost + outputCost).toFixed(4));

Error Handling

Timeout Handling

try {
  const result = await handleAgentQuery(query, userContext, {
    timeout: 30000
  });
} catch (error) {
  if (error.message.includes('timeout')) {
    // Agent took too long
    console.log('Query too complex, try breaking it down');
  }
}

Iteration Limit

const result = await handleAgentQuery(query, userContext, {
  maxIterations: 5
});

if (result.iterationsUsed >= 5 && !result.success) {
  console.log('Agent reached iteration limit without completing');
}

Tool Errors

const result = await handleAgentQuery(query, userContext);

// Check steps for tool errors
const errors = result.steps.filter(s => s.type === 'ERROR');
if (errors.length > 0) {
  console.log('Tool errors:', errors.map(e => e.error));
}

Best Practices

1. Set Appropriate Limits

// Simple analysis: 3-5 iterations
const simpleAnalysis = await handleAgentQuery(
  "Who did I meet with most this week?",
  userContext,
  { maxIterations: 5, timeout: 20000 }
);

// Complex synthesis: 7-10 iterations
const complexSynthesis = await handleAgentQuery(
  "Analyze all my project meetings and create a progress report",
  userContext,
  { maxIterations: 10, timeout: 60000 }
);

2. Provide Clear Queries

Good:

  • "Find meetings with John from last week and list the main topics"
  • "Compare my meeting time this month vs last month"

Less Good:

  • "Tell me about John" (too vague)
  • "Help with meetings" (unclear intent)

3. Handle Partial Results

const result = await handleAgentQuery(query, userContext);

if (result.success) {
  // Full result available
  displayResult(result.response);
} else if (result.steps.length > 0) {
  // Partial progress made
  const lastResult = result.steps
    .filter(s => s.type === 'TOOL_RESULT' && s.success)
    .pop();

  if (lastResult) {
    displayPartialResult(lastResult.data);
  }
}

4. Log for Debugging

const result = await handleAgentQuery(query, userContext, {
  verbose: true
});

// Log execution trace
console.log('Agent execution trace:');
result.steps.forEach((step, i) => {
  console.log(`${i + 1}. [${step.type}] ${step.tool || ''}`);
  if (step.type === 'THINKING') {
    console.log(`   ${step.content.substring(0, 100)}...`);
  }
});

Examples

Finding and Summarizing

const result = await handleAgentQuery(
  "Find my meetings with the engineering team from last month and summarize the key decisions",
  userContext
);

// Agent will:
// 1. THINKING: Need to find meetings with engineering team
// 2. TOOL_CALL: query_rooms with participant filter
// 3. TOOL_RESULT: Found 12 meetings
// 4. THINKING: Now need to get transcripts and summarize
// 5. TOOL_CALL: get_transcript for each meeting
// 6. TOOL_CALL: summarize_text on combined content
// 7. RESPONSE: Formatted summary with decisions

Network Analysis

const result = await handleAgentQuery(
  "Show me my collaboration network and identify who I should meet with more",
  userContext
);

// Agent will:
// 1. TOOL_CALL: get_graph_stats
// 2. TOOL_CALL: find_collaborators
// 3. THINKING: Analyze patterns
// 4. RESPONSE: Network analysis with recommendations

Comparative Analysis

const result = await handleAgentQuery(
  "How has my meeting load changed over the past 3 months?",
  userContext
);

// Agent will:
// 1. TOOL_CALL: query_rooms for month 1
// 2. TOOL_CALL: query_rooms for month 2
// 3. TOOL_CALL: query_rooms for month 3
// 4. THINKING: Calculate trends
// 5. RESPONSE: Trend analysis with comparison

Related Documentation