v0.1.6·Technical Reference
Custom MCPs
Build your own Model Context Protocol servers

Custom MCPs

Create custom MCP servers to expose your tools and data to AI agents.

MCP Server Basics

Server Structure

import { MCPServer } from '@ui-lab/mcp';

const server = new MCPServer({
  name: 'my-tool-server',
  version: '1.0.0',
  tools: [...]
});

server.start();

Tool Definition

Define a tool that agents can use:

{
  name: 'query_database',
  description: 'Query the application database',
  parameters: {
    type: 'object',
    properties: {
      query: {
        type: 'string',
        description: 'SQL query to execute'
      }
    },
    required: ['query']
  },
  handler: async (params) => {
    return await executeQuery(params.query);
  }
}

Creating a Simple MCP Server

Step 1: Define Your Tools

List what functionality you want to expose:

const tools = [
  {
    name: 'send_email',
    description: 'Send an email to a recipient'
  },
  {
    name: 'get_user_data',
    description: 'Retrieve user information'
  },
  {
    name: 'create_task',
    description: 'Create a new task in the system'
  }
];

Step 2: Implement Tool Handlers

const handlers = {
  async send_email({ to, subject, body }) {
    return await emailService.send(to, subject, body);
  },

  async get_user_data({ userId }) {
    return await db.users.findById(userId);
  },

  async create_task({ title, description }) {
    return await taskService.create(title, description);
  }
};

Step 3: Create and Start Server

const server = new MCPServer({
  name: 'app-integration',
  version: '1.0.0',
  tools: tools.map(tool => ({
    ...tool,
    handler: handlers[tool.name]
  }))
});

await server.start({ port: 8000 });

Advanced Features

Streaming Responses

Return large results progressively:

async function* streamLargeDataset(params) {
  for (let page = 0; page < totalPages; page++) {
    const data = await fetchPage(page);
    yield data;
  }
}

Resource Management

Handle expensive operations efficiently:

{
  name: 'analyze_document',
  description: 'Analyze a large document',
  timeout: 30000,
  maxConcurrent: 1,
  handler: async (params) => {
    // Implementation
  }
}

Error Handling

Robust error handling:

async function toolHandler(params) {
  try {
    return await performOperation(params);
  } catch (error) {
    if (error.type === 'NOT_FOUND') {
      throw new MCPError('Resource not found', 404);
    }
    throw new MCPError('Internal error', 500);
  }
}

Authentication

Secure your MCP server:

const server = new MCPServer({
  authentication: {
    type: 'bearer-token',
    validators: [validateToken]
  },
  tools: [...]
});

Testing Your MCP

Unit Tests

Test individual tools:

describe('send_email tool', () => {
  it('should send email to recipient', async () => {
    const result = await handlers.send_email({
      to: 'test@example.com',
      subject: 'Test',
      body: 'Hello'
    });
    expect(result.success).toBe(true);
  });
});

Integration Tests

Test MCP server end-to-end:

const client = new MCPClient('http://localhost:8000');
const tools = await client.getTools();
const result = await client.callTool('send_email', {...});

Deployment

Docker Deployment

Containerize your MCP server:

FROM node:18
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 8000
CMD ["npm", "start"]

Environment Configuration

Use environment variables:

DATABASE_URL=postgresql://...
API_KEY=your-api-key
LOG_LEVEL=debug

Monitoring

Track server health:

  • Request/response times
  • Error rates
  • Tool usage statistics
  • Resource consumption

Best Practices

  • Clear Naming: Use descriptive tool names
  • Documentation: Provide detailed descriptions
  • Error Messages: Return helpful error information
  • Validation: Validate all inputs
  • Logging: Log all operations
  • Rate Limiting: Prevent abuse
  • Versioning: Version your API
  • Testing: Comprehensive test coverage

Next Steps

Explore Integrations to connect your MCP server with other services, or check the API Reference for complete API documentation.

© 2025 UI Lab • Built for humans and machines