Sponsored by Deepsite.site

JS MCP Server

Created By
Positive-Spaces8 months ago
JavaScript MCP Server Component with WASM SDK for easy integration and deployment.
Content

JS MCP Server

JavaScript MCP Server Component with WASM SDK for easy integration and deployment.

Setup

To get started with the JS MCP Server, follow these steps:

git clone https://github.com/justin-echternach/js-mcp-server.git
cd js-mcp-server
npm install -g @bytecodealliance/componentize-js @bytecodealliance/jco
npm install

Build

To build the project and generate the WebAssembly module:

npm run build

This will bundle the JavaScript code using Vite and componentize it into dist/js-mcp-server.wasm.

Customization

You can customize the server by adding or modifying handlers (also referred to as tools). Handlers are registered in the server.js file and are located in the handlers directory. To add a new handler:

  1. Create a new JavaScript file in the handlers directory with your handler implementation.
  2. Import your handler in server.js.
  3. Add your handler to the tools object in the createMcpServer function call, similar to how EchoTool, KgTool, and FetchDogTool are added.

For example, to add a new handler named MyCustomTool:

// In server.js
import { MyCustomTool } from './handlers/index.js';

createMcpServer({
  serverInfo: {
    name: "JavaScript MCP Server",
    version: "1.0.0"
  },
  tools: {
    [EchoTool.name]: EchoTool,
    [KgTool.name]: KgTool,
    [MyCustomTool.name]: MyCustomTool
  },
  handlers: {
    // Custom handlers (optional)
  }
});

Writing Custom Handlers

Handlers (tools) are the core of your server's functionality. Each handler should export:

  • An async handler function that processes requests and returns results.
  • A name (string), description, and schema for input validation and documentation.

Minimal Example

Here's a minimal handler based on FetchDogTool:

// handlers/fetch_dog_tool.js
export async function handleTool(parameters) {
  try {
    // Perform your logic (e.g., HTTP request)
    return { result: 'success!' };
  } catch (error) {
    return { error: error.message };
  }
}

export function getToolName() {
  return 'fetch_dog';
}

export function getToolDescription() {
  return 'Fetches a random dog image from the Dog API';
}

export function getToolSchema() {
  return { type: 'object', properties: {} };
}

export const FetchDogTool = {
  handler: handleTool,
  name: getToolName(),
  description: getToolDescription(),
  schema: getToolSchema()
};

Registering Your Handler

  1. Export it in handlers/index.js:
    import { FetchDogTool } from './fetch_dog_tool.js';
    export { FetchDogTool };
    // ...add to tools map if needed
    
  2. Add it to the tools object in server.js:
    import { FetchDogTool } from './handlers/fetch_dog_tool.js';
    createMcpServer({
      tools: {
        [FetchDogTool.name]: FetchDogTool,
        // ...other tools
      }
    });
    

Best Practices

  • Handlers can be async and return plain objects.
  • Always handle errors gracefully and return a clear error object.
  • Use the schema property to describe expected input.
  • Add meaningful name and description fields for discoverability.

For more advanced features (timeouts, retries, richer error handling), consider extending your handler logic accordingly.


Using the Postgres and HTTP Interfaces

Your MCP server can interact with external services such as HTTP APIs and Postgres databases using robust, developer-friendly abstractions.

Postgres Interface (Async)

You can query a Postgres database using the query function from the comapi:postgres/query@0.1.0 interface. This is useful for knowledge graph or data-backed tools.

Example:

import { query } from "comapi:postgres/query@0.1.0";

export async function handleTool(parameters) {
  const entityFilter = parameters?.entityFilter || "";
  const sqlQuery = `
    SELECT id, name FROM my_table
    WHERE name ILIKE $1
    LIMIT 10
  `;
  const inputValue = `%${entityFilter}%`;
  // PgValue enum/variant: { tag: 'text', val: value }
  const params = [{ tag: 'text', val: inputValue }];
  const result = await query(sqlQuery, params);
  return { rows: result.rows };
}

Best Practices:

  • WIT defined enums/variants must be wrapped as { tag: 'text', val: value } for text inputs.
  • Always validate and sanitize your inputs.
  • Handle errors with try/catch as needed.

HTTP Client Functions

The SDK provides a developer-friendly HTTP client abstraction for making outgoing HTTP requests, wrapping WASI HTTP complexity.

Example:

import { get } from '../sdk/http/index.js';

export async function handleTool(parameters) {
  try {
    // Simple GET request with JSON response
    const response = await get('https://dog.ceo/api/breeds/image/random', { json: true });
    return { image_url: response.message, status: response.status };
  } catch (error) {
    return { error: error.message };
  }
}

Available HTTP methods:

  • get(url, options)
  • post(url, data, options)
  • put(url, data, options)
  • patch(url, data, options)
  • del(url, options) (alias: deleteRequest)
  • head, options, postJson, putJson, patchJson, postForm, putForm
  • You can also create a custom HTTP client via createHttpClient.

Best Practices:

  • Use the json: true option to automatically parse JSON responses.
  • Handle errors with try/catch and return a clear error object.
Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
ChatWiseThe second fastest AI chatbot™
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
Serper MCP ServerA Serper MCP Server
Tavily Mcp
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Playwright McpPlaywright MCP server
DeepChatYour AI Partner on Desktop
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
WindsurfThe new purpose-built IDE to harness magic
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
CursorThe AI Code Editor
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Amap Maps高德地图官方 MCP Server
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.