- JS MCP Server
JS MCP Server
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:
- Create a new JavaScript file in the
handlersdirectory with your handler implementation. - Import your handler in
server.js. - Add your handler to the
toolsobject in thecreateMcpServerfunction call, similar to howEchoTool,KgTool, andFetchDogToolare 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
- Export it in
handlers/index.js:import { FetchDogTool } from './fetch_dog_tool.js'; export { FetchDogTool }; // ...add to tools map if needed - Add it to the
toolsobject inserver.js:import { FetchDogTool } from './handlers/fetch_dog_tool.js'; createMcpServer({ tools: { [FetchDogTool.name]: FetchDogTool, // ...other tools } });
Best Practices
- Handlers can be
asyncand return plain objects. - Always handle errors gracefully and return a clear error object.
- Use the
schemaproperty to describe expected input. - Add meaningful
nameanddescriptionfields 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: trueoption to automatically parse JSON responses. - Handle errors with
try/catchand return a clear error object.