Skip to content

MCP Server Examples

This page provides complete, working examples of MCP servers you can deploy on Universal API. All examples follow the enhanced description format for better AI agent understanding.

Basic Echo Server

A minimal server with simple tools demonstrating the enhanced description format:

javascript
/**
 * Echo MCP Server
 * 
 * A simple demonstration server for testing MCP connectivity.
 * 
 * ## Connection Example (Cline):
 * {
 *   "echo-server": {
 *     "type": "streamableHttp",
 *     "url": "https://api.universalapi.co/mcp/YOUR_SERVER_ID"
 *   }
 * }
 */
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
const { z } = require("zod");

function createMcpServer() {
  const mcpServer = new McpServer({
    name: "echo-server",
    version: "1.0.0",
    description: `Echo Server for testing MCP connectivity.

## Quick Start
1. Use echo to test basic connectivity
2. Use reverse for text transformation`
  });

  mcpServer.registerTool("echo", {
    title: "Echo",
    description: `Echo back the provided message.

Use this tool to test MCP server connectivity.

Example response:
    "Echo: Hello, world!"

Notes:
    - Returns the exact message prefixed with "Echo: "
    - Useful for testing connectivity

Args:
    message: The message to echo back (required)
        Example: "Hello, world!"

Returns:
    The message prefixed with "Echo: "`,
    inputSchema: {
      message: z.string().describe("Message to echo back")
    }
  }, async ({ message }) => ({
    content: [{ type: "text", text: `Echo: ${message}` }]
  }));

  mcpServer.registerTool("reverse", {
    title: "Reverse",
    description: `Reverse the characters in a string.

Use this tool to reverse text.

Example:
    Input: "Hello"
    Output: "Reversed: olleH"

Args:
    text: The text to reverse (required)
        Example: "Hello"

Returns:
    The reversed text prefixed with "Reversed: "`,
    inputSchema: {
      text: z.string().describe("Text to reverse")
    }
  }, async ({ text }) => ({
    content: [{ type: "text", text: `Reversed: ${text.split("").reverse().join("")}` }]
  }));

  return mcpServer;
}

module.exports = { createMcpServer };

Multi-Tool Server

A server with multiple utility tools:

javascript
/**
 * Utility Tools MCP Server
 * 
 * Provides common utility functions like time, calculator, and random numbers.
 */
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
const { z } = require("zod");

function createMcpServer() {
  const mcpServer = new McpServer({
    name: "utility-tools",
    version: "1.0.0",
    description: `Utility Tools MCP Server

Provides common utility functions for AI agents.

## Available Tools
- get_time: Get current date/time
- calculate: Basic arithmetic
- random: Generate random numbers`
  });

  mcpServer.registerTool("get_time", {
    title: "Get Current Time",
    description: `Get the current date and time.

Use this tool when you need to know the current time.

Example response:
    {
        "iso": "2026-01-22T21:30:00.000Z",
        "local": "1/22/2026, 2:30:00 PM",
        "timestamp": 1769142600000
    }

Args:
    timezone: IANA timezone name (optional)
        Default: System timezone
        Example: "America/New_York"

Returns:
    JSON object with iso, local, and timestamp fields`,
    inputSchema: {
      timezone: z.string().optional().describe("Timezone (e.g., 'America/New_York')")
    }
  }, async ({ timezone }) => {
    const now = new Date();
    const options = timezone ? { timeZone: timezone } : {};
    return {
      content: [{
        type: "text",
        text: JSON.stringify({
          iso: now.toISOString(),
          local: now.toLocaleString("en-US", options),
          timestamp: now.getTime()
        }, null, 2)
      }]
    };
  });

  mcpServer.registerTool("calculate", {
    title: "Calculator",
    description: `Perform basic arithmetic operations.

Use this tool for mathematical calculations.

Example:
    a: 10, b: 5, operation: "add"
    Result: "10 add 5 = 15"

Notes:
    - Division by zero returns an error

Args:
    a: First number (required)
    b: Second number (required)
    operation: Operation to perform (required)
        Options: "add", "subtract", "multiply", "divide"

Returns:
    Formatted calculation result`,
    inputSchema: {
      a: z.number().describe("First number"),
      b: z.number().describe("Second number"),
      operation: z.enum(["add", "subtract", "multiply", "divide"]).describe("Operation")
    }
  }, async ({ a, b, operation }) => {
    let result;
    switch (operation) {
      case "add": result = a + b; break;
      case "subtract": result = a - b; break;
      case "multiply": result = a * b; break;
      case "divide":
        if (b === 0) return { content: [{ type: "text", text: "Error: Division by zero" }] };
        result = a / b;
        break;
    }
    return { content: [{ type: "text", text: `${a} ${operation} ${b} = ${result}` }] };
  });

  mcpServer.registerTool("random", {
    title: "Random Number",
    description: `Generate a random integer within a range.

Use this tool when you need a random number.

Example:
    min: 1, max: 100
    Result: "Random number between 1 and 100: 42"

Args:
    min: Minimum value (optional)
        Default: 0
    max: Maximum value (optional)
        Default: 100

Returns:
    Random integer between min and max (inclusive)`,
    inputSchema: {
      min: z.number().default(0).describe("Minimum value (default: 0)"),
      max: z.number().default(100).describe("Maximum value (default: 100)")
    }
  }, async ({ min = 0, max = 100 }) => {
    const result = Math.floor(Math.random() * (max - min + 1)) + min;
    return { content: [{ type: "text", text: `Random number between ${min} and ${max}: ${result}` }] };
  });

  return mcpServer;
}

module.exports = { createMcpServer };

API Wrapper Server

A server that wraps external API calls:

javascript
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
const { z } = require("zod");
const https = require("https");

// Helper function for HTTPS requests
function httpsRequest(options, postData = null) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let data = "";
      res.on("data", chunk => data += chunk);
      res.on("end", () => {
        try {
          resolve({ status: res.statusCode, data: JSON.parse(data) });
        } catch {
          resolve({ status: res.statusCode, data: { raw: data } });
        }
      });
    });
    req.on("error", reject);
    if (postData) req.write(postData);
    req.end();
  });
}

function createMcpServer() {
  const mcpServer = new McpServer({
    name: "api-wrapper",
    version: "1.0.0"
  });

  // Wrap Universal API action list
  mcpServer.registerTool("list_actions", {
    title: "List Universal API Actions",
    description: "Lists available actions in the Universal API catalog",
    inputSchema: {
      visibility: z.enum(["all", "public", "private"]).optional()
        .describe("Filter by visibility")
    }
  }, async ({ visibility }) => {
    const path = visibility ? `/action/list?visibility=${visibility}` : "/action/list";
    const result = await httpsRequest({
      hostname: "api.universalapi.co",
      path,
      method: "GET",
      port: 443
    });
    return {
      content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
    };
  });

  // JSONPlaceholder example
  mcpServer.registerTool("get_posts", {
    title: "Get Posts",
    description: "Fetches posts from JSONPlaceholder API",
    inputSchema: {
      userId: z.number().optional().describe("Filter by user ID"),
      limit: z.number().default(5).describe("Number of posts to return")
    }
  }, async ({ userId, limit }) => {
    let path = "/posts";
    if (userId) path += `?userId=${userId}`;

    const result = await httpsRequest({
      hostname: "jsonplaceholder.typicode.com",
      path,
      method: "GET",
      port: 443
    });

    const posts = result.data.slice(0, limit);
    return {
      content: [{ type: "text", text: JSON.stringify(posts, null, 2) }]
    };
  });

  return mcpServer;
}

module.exports = { createMcpServer };

Resources and Prompts Server

A server demonstrating MCP resources and prompts:

javascript
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
const { z } = require("zod");

function createMcpServer() {
  const mcpServer = new McpServer({
    name: "full-features",
    version: "1.0.0"
  });

  // Register a tool
  mcpServer.registerTool("greet", {
    title: "Greet",
    description: "Generates a greeting message",
    inputSchema: {
      name: z.string().describe("Name to greet"),
      style: z.enum(["formal", "casual", "enthusiastic"]).default("casual")
    }
  }, async ({ name, style }) => {
    let greeting;
    switch (style) {
      case "formal": greeting = `Good day, ${name}. How may I assist you?`; break;
      case "casual": greeting = `Hey ${name}! What's up?`; break;
      case "enthusiastic": greeting = `WOW! ${name}! SO GREAT to see you!!!`; break;
    }
    return { content: [{ type: "text", text: greeting }] };
  });

  // Register a resource
  mcpServer.registerResource("config://settings", {
    name: "Server Settings",
    description: "Current server configuration",
    mimeType: "application/json"
  }, async () => ({
    contents: [{
      uri: "config://settings",
      mimeType: "application/json",
      text: JSON.stringify({
        version: "1.0.0",
        features: ["tools", "resources", "prompts"],
        limits: { maxRequests: 100 }
      }, null, 2)
    }]
  }));

  // Register a prompt
  mcpServer.registerPrompt("summarize", {
    name: "Summarize Text",
    description: "A prompt template for summarizing text",
    arguments: [
      { name: "text", description: "Text to summarize", required: true },
      { name: "length", description: "Desired summary length", required: false }
    ]
  }, async ({ text, length = "brief" }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `Please provide a ${length} summary of the following text:\n\n${text}`
      }
    }]
  }));

  return mcpServer;
}

module.exports = { createMcpServer };

Universal API Actions Wrapper

A server that exposes Universal API actions as MCP tools:

javascript
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
const { z } = require("zod");
const https = require("https");

const API_HOST = "api.universalapi.co";

async function apiRequest(path, method = "GET", body = null) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: API_HOST,
      path,
      method,
      port: 443,
      headers: { "Content-Type": "application/json" }
    };

    const req = https.request(options, (res) => {
      let data = "";
      res.on("data", chunk => data += chunk);
      res.on("end", () => {
        try { resolve(JSON.parse(data)); }
        catch { resolve({ raw: data }); }
      });
    });
    req.on("error", reject);
    if (body) req.write(JSON.stringify(body));
    req.end();
  });
}

function createMcpServer() {
  const mcpServer = new McpServer({
    name: "universalapi-mcp-server",
    version: "1.0.0"
  });

  mcpServer.registerTool("list_actions", {
    title: "List Actions",
    description: "List available actions in the Universal API catalog",
    inputSchema: {
      visibility: z.enum(["all", "public", "private"]).optional()
    }
  }, async ({ visibility }) => {
    const params = visibility ? `?visibility=${visibility}` : "";
    const result = await apiRequest(`/action/list${params}`);
    return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
  });

  mcpServer.registerTool("get_action", {
    title: "Get Action",
    description: "Get details of a specific action by ID",
    inputSchema: {
      actionId: z.string().describe("The action ID")
    }
  }, async ({ actionId }) => {
    const result = await apiRequest(`/action/info/${actionId}`);
    return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
  });

  mcpServer.registerTool("execute_action", {
    title: "Execute Action",
    description: "Execute a Universal API action",
    inputSchema: {
      actionId: z.string().describe("The action ID to execute"),
      params: z.record(z.any()).optional().describe("Parameters to pass to the action")
    }
  }, async ({ actionId, params }) => {
    const queryString = params
      ? "?" + Object.entries(params).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&")
      : "";
    const result = await apiRequest(`/action/${actionId}${queryString}`);
    return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
  });

  return mcpServer;
}

module.exports = { createMcpServer };

Using These Examples

  1. Go to universalapi.co/mcp-servers
  2. Click "Create MCP Server"
  3. Choose "Write Code" mode
  4. Paste one of the examples above
  5. Fill in name and description
  6. Click "Create"
  7. Copy the endpoint URL
  8. Add to your Claude configuration

Next Steps

Universal API - The agentic entry point to the universe of APIs