rest2mcp
v0.0.1
Published
Convert REST API endpoints into Model Context Protocol (MCP) tools for agentic AI systems. Supports HTTP/stdio transports, URL templating, body templating, and automatic parameter validation.
Maintainers
Readme
REST-to-MCP SDK
Convert any REST API endpoint into Model Context Protocol (MCP) tools for AI agents.
⚠️ Preview Release: This is a preview release (v0.1.0) for early adopters and testing. Upon v1.0.0 release, a rest2mcp API key will be required for production usage. Current preview versions are free to use.
Installation
npm install rest2mcpQuick Start
import { MCPServer } from "rest2mcp";
// Initialize the MCP server
const rest2mcp = new MCPServer();
// Configure tools for your REST API endpoints
rest2mcp.tool({
name: "get_weather",
description: "Get current weather for a city",
restUrl: "https://api.openweathermap.org/data/2.5/weather",
method: "GET",
parameters: {
q: {
type: "string",
description: "City name",
},
appid: {
type: "string",
description: "OpenWeatherMap API key",
},
units: {
type: "string",
description: "Temperature units",
enum: ["metric", "imperial", "kelvin"],
default: "metric",
},
},
});
// Start the MCP server with HTTP transport
rest2mcp.start({
name: "rest-api-mcp-server",
http: {
port: 3000,
host: "localhost",
},
});Core Concepts
Tools
Tools are REST API endpoints exposed as MCP-compatible functions that AI agents can call:
rest2mcp.tool({
name: "unique_tool_name", // Tool identifier
description: "What this tool does", // Human-readable description
restUrl: "https://api.example.com/endpoint", // Target API
method: "GET", // HTTP method (optional, defaults to GET)
parameters: {
/* parameter schema */
}, // Input validation
headers: {
/* custom headers */
}, // Authentication, etc.
body: "{ /* request body */ }", // For POST/PUT requests
});Server Configuration
// HTTP transport (recommended for web agents)
rest2mcp.start({
name: "my-api-server",
http: {
port: 3000, // HTTP port
host: "localhost" // Host (optional)
}
});
// Stdio transport (for CLI integration)
rest2mcp.start({
name: "my-api-server"
// No http config = stdio transport
});
```ipt/JavaScript SDK for REST-to-MCP
> **Primary Language Implementation** | [← Back to Main Documentation](../README.md)
Convert any REST API endpoint into Model Context Protocol (MCP) tools using TypeScript/JavaScript. This SDK provides type-safe, production-ready tools for integrating REST APIs with AI agents and MCP-compatible systems.
> **⚠️ Preview Release**: This is a preview release (v0.x.x) for early adopters and testing. Upon v1.0.0 release, a rest2mcp API key will be required for production usage. Current preview versions are free to use.
## � Quick Start
<details>
<summary><strong>📦 Installation & Setup</strong></summary>
### Prerequisites
- **Node.js**: 18.0.0 or higher
- **Package Manager**: npm, yarn, or pnpm
- **TypeScript**: 5.0+ (for TypeScript projects)
### Installation
```bash
# Using npm
npm install rest2mcp
# Using yarn
yarn add rest2mcp
# Using pnpm
pnpm add rest2mcpTypeScript Configuration
If you're using TypeScript, ensure your tsconfig.json includes:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"skipLibCheck": true
}
}MCPServer Class
The main server class for creating and managing MCP tools.
import { MCPServer } from "rest2mcp";
class MCPServer {
constructor(options: ServerOptions);
// Tool management
registerTool(tool: ToolOptions): void;
getTool(name: string): ToolOptions | undefined;
// Server lifecycle
start(): Promise<void>; // Auto-detect transport
startHttpServer(port?: number): Promise<void>; // HTTP transport
startStdioTransport(): Promise<void>; // Stdio transport
}Type Definitions
interface ServerOptions {
name: string; // Server name (displayed in MCP clients)
version: string; // Server version
port?: number; // HTTP port (default: 3000)
}
interface ToolOptions {
name: string; // Unique tool identifier
description: string; // Human-readable description
restUrl: string; // API endpoint URL (supports {{param}} placeholders)
method?: string; // HTTP method (default: "GET")
parameters?: Record<string, JsonSchemaProperty>; // Parameter definitions
headers?: Record<string, string>; // Custom HTTP headers
body?: string; // Request body with Handlebars templating
}
interface JsonSchemaProperty {
type: "string" | "number" | "boolean" | "object" | "array";
description?: string;
enum?: any[];
default?: any;
items?: JsonSchemaProperty; // For array types
properties?: Record<string, JsonSchemaProperty>; // For object types
required?: string[]; // Required properties for objects
}Examples
Weather API
rest2mcp.tool({
name: "get_weather",
description: "Get current weather data",
restUrl: "https://api.openweathermap.org/data/2.5/weather",
parameters: {
q: { type: "string", description: "City name" },
appid: { type: "string", description: "OpenWeatherMap API key" },
units: {
type: "string",
enum: ["metric", "imperial", "kelvin"],
default: "metric",
},
},
});Pokemon API with Path Parameters
rest2mcp.tool({
name: "get_pokemon",
description: "Get Pokemon information by name or ID",
restUrl: "https://pokeapi.co/api/v2/pokemon/{pokemon}",
method: "GET",
parameters: {
pokemon: {
type: "string",
description: "Pokemon name or ID (e.g., 'pikachu', '25')",
},
},
});GraphQL with Body Templates
rest2mcp.tool({
name: "graphql_query",
description: "Execute a GraphQL query with variables",
restUrl: "https://countries.trevorblades.com/",
method: "POST",
body: `{
"query": "query GetCountry($code: ID!) { country(code: $code) { name capital emoji currency languages { name } } }",
"variables": { "code": "{{countryCode}}" }
}`,
parameters: {
countryCode: {
type: "string",
description: "Country code (e.g., 'US', 'BR', 'JP')",
},
},
});POST API for Creating Resources
rest2mcp.tool({
name: "create_user",
description: "Create a new user",
restUrl: "https://jsonplaceholder.typicode.com/users",
method: "POST",
parameters: {
name: {
type: "string",
description: "User's full name",
},
email: {
type: "string",
description: "User's email address",
},
phone: {
type: "string",
description: "User's phone number",
},
},
});Transport Options
HTTP Transport (Recommended)
Best for web-based AI agents and development:
const rest2mcp = new MCPServer();
// Add your tools...
rest2mcp.tool({...});
// Start with HTTP transport
rest2mcp.start({
name: "My API Server",
http: {
port: 3000,
host: "localhost" // Optional, defaults to localhost
}
});
// Server available at http://localhost:3000Stdio Transport
For command-line applications and desktop AI assistants:
const rest2mcp = new MCPServer();
// Add your tools...
rest2mcp.tool({...});
// Start with stdio transport (no http config)
rest2mcp.start({
name: "My API Server"
// No http = stdio transport automatically
});
// Communicates via stdin/stdoutParameter Schema
Define input validation using JSON Schema:
parameters: {
// String with constraints
email: {
type: "string",
description: "User email address",
pattern: "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
},
// Number with limits
age: {
type: "number",
description: "User age",
minimum: 0,
maximum: 120
},
// Enum values
status: {
type: "string",
enum: ["active", "inactive", "pending"],
default: "active"
},
// Object with properties
address: {
type: "object",
properties: {
street: { type: "string" },
city: { type: "string" },
zipCode: { type: "string" }
},
required: ["street", "city"]
},
// Array of items
tags: {
type: "array",
items: { type: "string" },
maxItems: 10
}
}Advanced Features
Handlebars Templating
The SDK uses Handlebars for powerful templating in URLs and request bodies:
URL Path Parameters
rest2mcp.tool({
name: "get_repo_issues",
description: "Get GitHub repository issues",
restUrl:
"https://api.github.com/repos/{{owner}}/{{repo}}/issues/{{number}}",
parameters: {
owner: { type: "string", description: "Repository owner" },
repo: { type: "string", description: "Repository name" },
number: { type: "number", description: "Issue number" },
},
});Complex Body Templates
rest2mcp.tool({
name: "create_issue",
description: "Create a GitHub issue with arrays and conditionals",
restUrl: "https://api.github.com/repos/{{owner}}/{{repo}}/issues",
method: "POST",
body: `{
"title": "{{title}}",
"body": "{{description}}",
"assignees": [{{#each assignees}}"{{this}}"{{#unless @last}},{{/unless}}{{/each}}],
"labels": [{{#each labels}}"{{this}}"{{#unless @last}},{{/unless}}{{/each}}],
"milestone": {{#if milestone}}{{milestone}}{{else}}null{{/if}}
}`,
parameters: {
owner: { type: "string", description: "Repository owner" },
repo: { type: "string", description: "Repository name" },
title: { type: "string", description: "Issue title" },
description: { type: "string", description: "Issue description" },
assignees: {
type: "array",
items: { type: "string" },
description: "Array of usernames to assign",
},
labels: {
type: "array",
items: { type: "string" },
description: "Array of label names",
},
milestone: {
type: "number",
description: "Milestone number (optional)",
},
},
});Handlebars Helpers
Built-in helpers for dynamic templates:
{{#each array}}...{{/each}}- Loop through arrays{{#if condition}}...{{/if}}- Conditional rendering{{#unless condition}}...{{/unless}}- Inverse conditionals{{@index}},@first,@last- Loop metadata{{{raw}}}- Unescaped output (use carefully!)
Custom Headers
Add authentication and custom headers:
headers: {
"Authorization": "Bearer {{token}}",
"X-API-Key": "your-api-key",
"Content-Type": "application/json",
"User-Agent": "MyApp/1.0.0"
}Testing Your Server
With MCP Inspector
# Start your server
node your-server.js
# In another terminal, start MCP Inspector
npx @modelcontextprotocol/inspector
# Connect to your server at http://localhost:3000
# Test tools interactively in the web interfaceWith curl
# Check server health
curl http://localhost:3000/health
# List available tools
curl -X POST http://localhost:3000/ \
-H "Content-Type: application/json" \
-d '{"method": "tools/list"}'
# Execute a tool
curl -X POST http://localhost:3000/ \
-H "Content-Type: application/json" \
-d '{
"method": "tools/call",
"params": {
"name": "get_weather",
"arguments": {"q": "London", "appid": "your-key"}
}
}'Error Handling
The SDK automatically handles:
- HTTP errors: Non-2xx responses are converted to error messages
- Network timeouts: Failed requests are reported with details
- Parameter validation: Invalid inputs are rejected before API calls
- JSON parsing: Response parsing errors are handled gracefully
TypeScript Support
Full TypeScript support with type definitions:
import { MCPServer } from "rest2mcp";
const rest2mcp = new MCPServer();
// Type-safe tool configuration
rest2mcp.tool({
name: "weather",
description: "Weather data",
restUrl: "https://api.weather.com/v1/current.json",
parameters: {
q: { type: "string", description: "City name" },
key: { type: "string", description: "API key" },
},
});
// Type-safe server configuration
rest2mcp.start({
name: "Typed Server",
http: {
port: 3000,
host: "localhost",
},
});Requirements
- Node.js 18.0.0 or higher
- TypeScript 5.0+ (for TypeScript projects)
Support
- Issues: GitHub Issues
- Documentation: Full Documentation
- MCP Protocol: Model Context Protocol
