MCP-Agent icon

MCP-Agent

Composable framework for building intelligent agents using Model Context Protocol with modular architecture and extensible capabilities

View Source

MCP-Agent

MCP-Agent is a simple yet powerful composable framework designed for building intelligent agents using the Model Context Protocol. It provides a modular architecture that allows developers to create sophisticated AI agents by composing various MCP tools and resources in a flexible, extensible manner.

Features

  • Composable Architecture: Build complex agents by combining simple, reusable components
  • MCP Native: Built specifically for the Model Context Protocol ecosystem
  • Plugin System: Extensible plugin architecture for custom functionality
  • State Management: Built-in state management for agent memory and context
  • Tool Orchestration: Intelligent tool selection and chaining capabilities
  • Resource Management: Efficient handling of MCP resources and data sources
  • Event-Driven: Reactive architecture with event-driven communication
  • Configuration-Based: Define agents through declarative configuration

Installation

npm install @lastmile-ai/mcp-agent
# or
yarn add @lastmile-ai/mcp-agent

Getting Started

Basic Agent Setup

import { MCPAgent, AgentBuilder } from '@lastmile-ai/mcp-agent';

// Create a simple agent
const agent = new AgentBuilder()
  .withName('DataAnalyzer')
  .withDescription('Intelligent data analysis agent')
  .addMCPServer('http://localhost:3000/mcp')
  .addCapability('data-processing')
  .addCapability('visualization')
  .build();

// Initialize and start the agent
await agent.initialize();
const result = await agent.process('Analyze the sales data from Q4 2024');
console.log(result);

Configuration-Based Agent

# agent-config.yaml
name: "Research Assistant"
description: "AI agent for research and analysis tasks"

mcp_servers:
  - url: "http://localhost:3000/mcp"
    name: "research-tools"
    capabilities: ["web-search", "document-analysis"]
  - url: "http://localhost:3001/mcp"
    name: "data-tools"
    capabilities: ["data-processing", "visualization"]

workflows:
  research_workflow:
    steps:
      - tool: "web_search"
        params:
          query: "{{user_query}}"
          max_results: 10
      - tool: "summarize_results"
        params:
          content: "{{previous_step.results}}"
          max_length: 500
      - tool: "generate_report"
        params:
          summary: "{{previous_step.summary}}"
          format: "markdown"

memory:
  type: "persistent"
  storage: "sqlite"
  context_window: 4000
import { MCPAgent } from '@lastmile-ai/mcp-agent';
import fs from 'fs';

// Load agent from configuration
const config = fs.readFileSync('agent-config.yaml', 'utf8');
const agent = MCPAgent.fromConfig(config);

// Use the agent
const result = await agent.executeWorkflow('research_workflow', {
  user_query: 'Latest developments in quantum computing'
});

Core Concepts

Agent Components

Tools

// Define custom tools
const customTool = {
  name: 'sentiment_analyzer',
  description: 'Analyze sentiment of text content',
  parameters: {
    type: 'object',
    properties: {
      text: { type: 'string' },
      model: { type: 'string', default: 'default' }
    }
  },
  execute: async (params) => {
    // Tool implementation
    return {
      sentiment: 'positive',
      confidence: 0.95,
      details: { ... }
    };
  }
};

// Add tool to agent
agent.addTool(customTool);

Resources

// Define data resources
const databaseResource = {
  name: 'sales_database',
  type: 'database',
  connection: {
    type: 'postgresql',
    url: process.env.DATABASE_URL
  },
  tables: ['sales', 'customers', 'products'],
  permissions: ['read', 'aggregate']
};

// Register resource
agent.addResource(databaseResource);

Memory Systems

// Configure agent memory
const memoryConfig = {
  type: 'hybrid', // 'working', 'episodic', 'semantic', 'hybrid'
  working: {
    capacity: 10, // Number of recent interactions
    persistence: false
  },
  episodic: {
    storage: 'sqlite',
    database: './agent_memory.db',
    retention_days: 30
  },
  semantic: {
    embedding_model: 'sentence-transformers',
    vector_store: 'chroma',
    similarity_threshold: 0.8
  }
};

agent.configureMemory(memoryConfig);

Advanced Features

Workflow Orchestration

// Define complex workflows
const analysisWorkflow = {
  name: 'comprehensive_analysis',
  steps: [
    {
      id: 'data_ingestion',
      tool: 'fetch_data',
      params: {
        source: '{{workflow.input.data_source}}',
        format: 'json'
      }
    },
    {
      id: 'data_cleaning',
      tool: 'clean_data',
      params: {
        data: '{{steps.data_ingestion.result}}',
        rules: ['remove_nulls', 'normalize_dates']
      },
      depends_on: ['data_ingestion']
    },
    {
      id: 'statistical_analysis',
      tool: 'statistical_analyzer',
      params: {
        data: '{{steps.data_cleaning.result}}',
        methods: ['descriptive', 'correlation']
      },
      depends_on: ['data_cleaning']
    },
    {
      id: 'visualization',
      tool: 'create_charts',
      params: {
        data: '{{steps.data_cleaning.result}}',
        stats: '{{steps.statistical_analysis.result}}',
        chart_types: ['histogram', 'scatter', 'correlation_matrix']
      },
      depends_on: ['data_cleaning', 'statistical_analysis']
    },
    {
      id: 'report_generation',
      tool: 'generate_report',
      params: {
        data: '{{steps.data_cleaning.result}}',
        analysis: '{{steps.statistical_analysis.result}}',
        charts: '{{steps.visualization.result}}',
        template: 'comprehensive_analysis'
      },
      depends_on: ['statistical_analysis', 'visualization']
    }
  ],
  error_handling: {
    retry_attempts: 3,
    fallback_strategy: 'partial_results'
  }
};

// Register workflow
agent.addWorkflow(analysisWorkflow);

// Execute workflow
const result = await agent.executeWorkflow('comprehensive_analysis', {
  data_source: 'https://api.example.com/sales-data'
});

Plugin System

// Create custom plugin
class LLMIntegrationPlugin {
  constructor(options) {
    this.apiKey = options.apiKey;
    this.model = options.model || 'gpt-4';
  }
  
  async initialize(agent) {
    // Add LLM-based tools to the agent
    agent.addTool({
      name: 'llm_reasoning',
      description: 'Use LLM for complex reasoning tasks',
      execute: async (params) => {
        return await this.callLLM(params.prompt, params.context);
      }
    });
    
    // Add event handlers
    agent.on('tool_error', this.handleToolError.bind(this));
  }
  
  async callLLM(prompt, context) {
    // LLM integration logic
  }
  
  handleToolError(error, context) {
    // Error handling logic
  }
}

// Use plugin
const llmPlugin = new LLMIntegrationPlugin({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4'
});

agent.use(llmPlugin);

State Management

// Agent state management
class AgentState {
  constructor() {
    this.context = new Map();
    this.history = [];
    this.goals = [];
  }
  
  setContext(key, value) {
    this.context.set(key, value);
  }
  
  getContext(key) {
    return this.context.get(key);
  }
  
  addGoal(goal) {
    this.goals.push({
      id: crypto.randomUUID(),
      description: goal,
      status: 'pending',
      created_at: Date.now()
    });
  }
  
  updateGoal(goalId, status, result = null) {
    const goal = this.goals.find(g => g.id === goalId);
    if (goal) {
      goal.status = status;
      goal.result = result;
      goal.updated_at = Date.now();
    }
  }
}

// Configure state management
agent.configureState({
  persistence: {
    enabled: true,
    storage: 'redis',
    connection: 'redis://localhost:6379'
  },
  context_sharing: {
    enabled: true,
    scope: 'session' // 'global', 'session', 'workflow'
  }
});

Integration Examples

Web Application Integration

// Express.js integration
import express from 'express';
import { MCPAgent } from '@lastmile-ai/mcp-agent';

const app = express();
const agent = new MCPAgent({
  name: 'WebAssistant',
  mcpServers: ['http://localhost:3000/mcp']
});

app.post('/api/agent/query', async (req, res) => {
  try {
    const { query, context } = req.body;
    const result = await agent.process(query, { 
      sessionId: req.session.id,
      userContext: context 
    });
    res.json({ success: true, result });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3000);

Real-time Integration

// WebSocket integration for real-time agent interactions
import WebSocket from 'ws';

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  const agentSession = agent.createSession();
  
  ws.on('message', async (message) => {
    const { type, data } = JSON.parse(message);
    
    switch (type) {
      case 'query':
        const result = await agentSession.process(data.query);
        ws.send(JSON.stringify({ type: 'result', data: result }));
        break;
        
      case 'workflow':
        const workflowResult = await agentSession.executeWorkflow(
          data.workflow, 
          data.params
        );
        ws.send(JSON.stringify({ type: 'workflow_result', data: workflowResult }));
        break;
    }
  });
  
  // Send agent events to client
  agentSession.on('tool_start', (toolName) => {
    ws.send(JSON.stringify({ type: 'tool_start', tool: toolName }));
  });
  
  agentSession.on('tool_complete', (toolName, result) => {
    ws.send(JSON.stringify({ type: 'tool_complete', tool: toolName, result }));
  });
});

Testing and Debugging

Agent Testing

// Test agent functionality
import { AgentTester } from '@lastmile-ai/mcp-agent/testing';

const tester = new AgentTester(agent);

// Test individual tools
await tester.testTool('data_processor', {
  input: 'sample data',
  expected: { processed: true }
});

// Test workflows
await tester.testWorkflow('analysis_workflow', {
  input: { data_source: 'test_data.json' },
  assertions: [
    (result) => result.steps_completed === 5,
    (result) => result.final_output.charts.length > 0
  ]
});

// Generate test report
const report = tester.generateReport();
console.log(`Tests passed: ${report.passed}/${report.total}`);

Debug Mode

// Enable debugging
const agent = new MCPAgent({
  debug: {
    enabled: true,
    level: 'verbose',
    output: 'console', // 'console', 'file', 'webhook'
    filters: ['tool_calls', 'memory_operations', 'state_changes']
  }
});

// Debug specific components
agent.debug.tool('data_processor', true);
agent.debug.workflow('analysis_workflow', true);

Use Cases

  • Research Assistants: Build AI agents for research and data analysis
  • Customer Support: Create intelligent customer service agents
  • Data Processing: Automate complex data processing pipelines
  • Content Creation: Build agents for content generation and editing
  • Business Intelligence: Create agents for business data analysis
  • Personal Assistants: Build personalized AI assistants

Best Practices

Agent Design

  • Single Responsibility: Each agent should have a clear, focused purpose
  • Composability: Design agents as composable components
  • Error Handling: Implement robust error handling and recovery
  • Resource Management: Efficiently manage MCP server connections
  • State Isolation: Keep agent state properly isolated between sessions

Performance Optimization

// Optimize agent performance
const performanceConfig = {
  connection_pooling: {
    enabled: true,
    max_connections: 10,
    idle_timeout: 30000
  },
  caching: {
    enabled: true,
    ttl: 300, // 5 minutes
    max_entries: 1000
  },
  batching: {
    enabled: true,
    batch_size: 10,
    max_wait: 100 // milliseconds
  }
};

agent.configure(performanceConfig);
Sponsored
Algolia Inc logo

Algolia Inc

Supporting the MCP ecosystem with cutting-edge tools and services

Try Algolia MCP

Related Categories