@olbrain/generic-api-mcp
Version:
Generic MCP server for wrapping any REST API with configuration-driven approach
345 lines (269 loc) • 7.96 kB
Markdown
# Generic API MCP Server
A generic MCP (Model Context Protocol) server that can wrap **any REST API** with a configuration-driven approach. Configure your API endpoints via environment variables and instantly expose them as MCP tools.
## Features
- ✅ **Universal API Support** - Works with any REST API (OpenAPI, custom APIs, etc.)
- ✅ **Multiple Auth Methods** - Bearer, API Key, Basic Auth, OAuth 2.0
- ✅ **Configuration-Driven** - No code changes needed, just environment variables
- ✅ **MCP Protocol Compliant** - Full JSON-RPC 2.0 implementation
- ✅ **Production Ready** - Used by Alchemist AI for private API integrations
## Installation
```bash
npx -y @alchemist/generic-api-mcp
```
## Quick Start
### 1. Set Environment Variables
```bash
# Required
export API_BASE_URL="https://api.example.com"
export API_ENDPOINTS_CONFIG="$(echo '[
{
"name": "get_users",
"method": "GET",
"path": "/users",
"description": "Get list of users",
"parameters": [
{"name": "limit", "type": "number", "required": false}
]
}
]' | base64)"
# Optional (for authentication)
export API_AUTH_TYPE="bearer"
export BEARER_TOKEN="your-api-token"
```
### 2. Run the Server
```bash
npx -y @alchemist/generic-api-mcp
```
The server will start and listen for MCP protocol requests on stdin/stdout.
## Configuration
### Required Environment Variables
| Variable | Description | Example |
|----------|-------------|---------|
| `API_BASE_URL` | Base URL of your API | `https://api.example.com` |
| `API_ENDPOINTS_CONFIG` | Base64-encoded JSON array of endpoint configurations | See below |
### Optional Environment Variables (Authentication)
| Variable | Description | Auth Type |
|----------|-------------|-----------|
| `API_AUTH_TYPE` | Authentication type: `none`, `bearer`, `api_key`, `basic`, `oauth` | All |
| `BEARER_TOKEN` | Bearer token for authentication | bearer |
| `API_KEY` | API key value | api_key |
| `API_KEY_HEADER` | Header name for API key (default: `X-API-Key`) | api_key |
| `USERNAME` | Username for basic auth | basic |
| `PASSWORD` | Password for basic auth | basic |
| `CLIENT_ID` | OAuth client ID | oauth |
| `CLIENT_SECRET` | OAuth client secret | oauth |
| `ACCESS_TOKEN` | Pre-obtained OAuth access token | oauth |
## Endpoint Configuration Schema
The `API_ENDPOINTS_CONFIG` must be a base64-encoded JSON array with this structure:
```json
[
{
"name": "tool_name",
"method": "GET|POST|PUT|DELETE|PATCH",
"path": "/api/endpoint",
"description": "Tool description",
"parameters": [
{
"name": "param_name",
"type": "string|number|boolean",
"description": "Parameter description",
"required": true|false,
"in": "query|body"
}
]
}
]
```
### Encoding Endpoints Config
```bash
# Using echo and base64
export API_ENDPOINTS_CONFIG="$(echo '[...]' | base64)"
# Using Python
python3 -c "import json, base64; print(base64.b64encode(json.dumps([...]).encode()).decode())"
# Using Node.js
node -e "console.log(Buffer.from(JSON.stringify([...])).toString('base64'))"
```
## Examples
### Example 1: Public API (No Auth)
```bash
export API_BASE_URL="https://jsonplaceholder.typicode.com"
export API_AUTH_TYPE="none"
export API_ENDPOINTS_CONFIG="$(echo '[
{
"name": "get_posts",
"method": "GET",
"path": "/posts",
"description": "Get all posts",
"parameters": [
{"name": "userId", "type": "number", "required": false}
]
},
{
"name": "create_post",
"method": "POST",
"path": "/posts",
"description": "Create a new post",
"parameters": [
{"name": "title", "type": "string", "required": true, "in": "body"},
{"name": "body", "type": "string", "required": true, "in": "body"},
{"name": "userId", "type": "number", "required": true, "in": "body"}
]
}
]' | base64)"
npx -y @alchemist/generic-api-mcp
```
### Example 2: Bearer Token Auth
```bash
export API_BASE_URL="https://api.github.com"
export API_AUTH_TYPE="bearer"
export BEARER_TOKEN="ghp_your_github_token"
export API_ENDPOINTS_CONFIG="$(echo '[
{
"name": "get_user",
"method": "GET",
"path": "/user",
"description": "Get authenticated user info"
},
{
"name": "list_repos",
"method": "GET",
"path": "/user/repos",
"description": "List user repositories"
}
]' | base64)"
npx -y @alchemist/generic-api-mcp
```
### Example 3: API Key Auth
```bash
export API_BASE_URL="https://api.openweathermap.org/data/2.5"
export API_AUTH_TYPE="api_key"
export API_KEY="your_openweather_api_key"
export API_KEY_HEADER="appid" # Custom header name
export API_ENDPOINTS_CONFIG="$(echo '[
{
"name": "get_weather",
"method": "GET",
"path": "/weather",
"description": "Get current weather",
"parameters": [
{"name": "q", "type": "string", "description": "City name", "required": true}
]
}
]' | base64)"
npx -y @alchemist/generic-api-mcp
```
### Example 4: Basic Auth
```bash
export API_BASE_URL="https://api.example.com"
export API_AUTH_TYPE="basic"
export USERNAME="your_username"
export PASSWORD="your_password"
export API_ENDPOINTS_CONFIG="$(echo '[...]' | base64)"
npx -y @alchemist/generic-api-mcp
```
## MCP Protocol
The server implements the full MCP (Model Context Protocol) specification:
### Supported Methods
- `initialize` - Initialize MCP session
- `tools/list` - List available tools
- `tools/call` - Execute a tool (API request)
### Request Format
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "get_users",
"arguments": {
"limit": 10
}
}
}
```
### Response Format
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [{
"type": "text",
"text": "{...API response...}"
}]
}
}
```
## Testing Locally
Create a test script to verify your configuration:
```bash
# test_local.sh
export API_BASE_URL="https://jsonplaceholder.typicode.com"
export API_AUTH_TYPE="none"
export API_ENDPOINTS_CONFIG="$(echo '[
{
"name": "get_posts",
"method": "GET",
"path": "/posts",
"parameters": [{"name": "userId", "type": "number"}]
}
]' | base64)"
# Send test request
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | npx -y @alchemist/generic-api-mcp
```
## Use Cases
- **Private API Integration** - Wrap your internal APIs for AI agents
- **Third-Party API Wrappers** - Quick MCP servers for external APIs
- **Prototyping** - Test API integrations without writing code
- **Custom Workflows** - Build agent tools from any REST API
## Requirements
- Node.js 16+ (for npx)
- Python 3.8+ (installed automatically via postinstall)
- `httpx` Python package (installed automatically)
## Troubleshooting
### Missing Environment Variables
```
Error: Missing required environment variables: API_BASE_URL, API_ENDPOINTS_CONFIG
```
**Solution**: Set all required environment variables before running
### Invalid Base64 Encoding
```
Failed to decode API_ENDPOINTS_CONFIG
```
**Solution**: Ensure your endpoints config is properly base64-encoded
### Authentication Errors
```
HTTP error: 401
```
**Solution**: Check your auth credentials and auth type configuration
### Module Not Found
```
ModuleNotFoundError: No module named 'httpx'
```
**Solution**: Manually install dependencies:
```bash
pip3 install -r requirements.txt
```
## Development
```bash
# Clone repository
git clone https://github.com/alchemist-ai/alchemist.git
cd packages/integrations/generic-api-mcp
# Install dependencies
npm install
pip3 install -r requirements.txt
# Run tests
npm test
# Run locally
./index.js
```
## License
MIT
## Contributing
Contributions welcome! Please open an issue or pull request.
## Support
For issues and questions:
- GitHub Issues: https://github.com/alchemist-ai/alchemist/issues
- Documentation: https://docs.alchemist.ai
---
Built with ❤️ by [Alchemist AI](https://alchemist.ai)