v0.1.6·Technical Reference
Integrations
Integrate agents and MCPs with external services

Integrations

Connect your agents and MCPs with external services and platforms.

Common Integration Patterns

API Integration

Connect to external APIs:

const apiClient = new APIClient({
  baseURL: 'https://api.example.com',
  auth: { type: 'bearer', token: process.env.API_KEY }
});

const tool = {
  name: 'fetch_user_data',
  handler: async (params) => {
    return await apiClient.get(`/users/${params.userId}`);
  }
};

Database Integration

Access databases safely:

const dbClient = new DatabaseClient({
  connectionString: process.env.DATABASE_URL
});

const tool = {
  name: 'query_records',
  handler: async (params) => {
    return await dbClient.query(
      'SELECT * FROM records WHERE id = $1',
      [params.recordId]
    );
  }
};

Message Queue Integration

Async task processing:

const queue = new MessageQueue({
  url: process.env.QUEUE_URL
});

const tool = {
  name: 'schedule_job',
  handler: async (params) => {
    return await queue.enqueue('process_data', params);
  }
};

Third-Party Service Integration

Email Services

Send emails through providers:

const emailTool = {
  name: 'send_email',
  handler: async ({ to, subject, body }) => {
    return await sendgridClient.send({
      to,
      from: 'noreply@app.com',
      subject,
      html: body
    });
  }
};

Analytics Services

Track user events:

const analyticsTool = {
  name: 'track_event',
  handler: async ({ eventName, properties }) => {
    return await mixpanelClient.track(eventName, properties);
  }
};

Payment Processing

Handle payments:

const paymentTool = {
  name: 'process_payment',
  handler: async ({ amount, currency, customerId }) => {
    return await stripeClient.paymentIntents.create({
      amount: amount * 100,
      currency,
      customer: customerId
    });
  }
};

Document Storage

Access cloud storage:

const storageTool = {
  name: 'upload_document',
  handler: async ({ filename, content }) => {
    return await s3Client.putObject({
      Bucket: 'documents',
      Key: filename,
      Body: content
    });
  }
};

Authentication Methods

API Keys

Simple key-based authentication:

const client = new APIClient({
  headers: {
    'X-API-Key': process.env.API_KEY
  }
});

OAuth 2.0

Token-based delegation:

const oauth = new OAuth2Client({
  clientId: process.env.OAUTH_CLIENT_ID,
  clientSecret: process.env.OAUTH_CLIENT_SECRET,
  redirectUri: 'http://localhost:3000/callback'
});

const token = await oauth.getAccessToken(code);

mTLS

Mutual TLS certificates:

const client = new APIClient({
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem'),
  ca: fs.readFileSync('ca.pem')
});

Error Handling in Integrations

Retry Logic

Handle transient failures:

async function callWithRetry(fn, maxAttempts = 3) {
  for (let i = 0; i < maxAttempts; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxAttempts - 1) throw error;
      await delay(Math.pow(2, i) * 1000); // Exponential backoff
    }
  }
}

Fallback Strategies

Provide alternatives:

const tool = {
  name: 'get_data',
  handler: async (params) => {
    try {
      return await primaryService.getData(params);
    } catch (error) {
      // Fallback to cached data
      return await cache.get(params.key);
    }
  }
};

Circuit Breaker

Prevent cascading failures:

const circuitBreaker = new CircuitBreaker({
  failureThreshold: 5,
  timeout: 60000
});

const tool = {
  handler: async (params) => {
    return await circuitBreaker.call(() =>
      externalService.call(params)
    );
  }
};

Rate Limiting

Token Bucket

Smooth rate limiting:

const limiter = new TokenBucket({
  capacity: 100,
  refillRate: 10 // per second
});

const tool = {
  handler: async (params) => {
    await limiter.consume();
    return await service.call(params);
  }
};

Leaky Bucket

Even distribution:

const queue = new LeakyBucket({
  capacity: 50,
  leakRate: 5 // per second
});

queue.add(request);

Data Synchronization

Event-Driven Sync

React to external changes:

externalService.on('data-updated', async (data) => {
  await localCache.update(data);
});

Polling

Regular synchronization:

setInterval(async () => {
  const remoteData = await externalService.fetchLatest();
  const localData = await localCache.getLatest();

  if (remoteData.version > localData.version) {
    await localCache.update(remoteData);
  }
}, 60000);

Testing Integrations

Mock External Services

const mockClient = {
  send: jest.fn().mockResolvedValue({ success: true })
};

const tool = { handler: async (params) => mockClient.send(params) };

Integration Tests

Test with real or test services:

describe('Email integration', () => {
  it('should send email via service', async () => {
    const result = await emailTool.handler({
      to: 'test@example.com',
      subject: 'Test'
    });
    expect(result.messageId).toBeDefined();
  });
});

Next Steps

See API Reference for complete API documentation and supported integrations.

© 2025 UI Lab • Built for humans and machines