GitBook MCP Proxy
by forrestmid
README.md
# GitBook MCP Proxy
> OAuth-style authentication proxy for GitBook MCP with custom JWT authentication and secure credential storage.
[](https://opensource.org/licenses/MIT)
[](https://nodejs.org)
A local proxy server that enables AI assistants (Cursor, Claude Desktop, etc.) to access your GitBook documentation via MCP (Model Context Protocol) with custom JWT authentication from your backend.
## Features
✨ **Dual Transport Support** - HTTP server mode or stdio transport for MCP
✨ **Auto Port Selection** - Automatically finds available port if default is in use
✨ **MCP-Compliant Credential Storage** - Encrypted at rest using AES-256-GCM
✨ **Platform-Specific Application Support** - Follows MCP ecosystem standards
✨ **OAuth-Style Authentication** - Secure browser-based authorization flow
✨ **Token Persistence** - Survives restarts with encrypted storage
✨ **Auto-Open Browser** - Automatically opens authorization URL
✨ **Automatic Redirect Following** - Handles HTTP 3xx redirects
✨ **Multi-Method Authentication** - Sends JWT as query param and cookie
✨ **LaunchDarkly Integration** - Forwards feature flags for adaptive content
✨ **Detailed Logging** - Request tracing, auth context, security info
## How It Works
```
┌─────────────────────────────────────────────────────────┐
│ 1. Start proxy → generates session ID │
│ 2. Browser opens → authenticate with your backend │
│ 3. Backend generates JWT → redirects to localhost │
│ 4. Proxy encrypts & stores credentials (MCP compliant) │
│ 5. AI makes MCP request → proxy adds JWT + forwards │
│ 6. GitBook validates JWT → returns documentation │
└─────────────────────────────────────────────────────────┘
```
## Prerequisites
- Node.js 16+
- A backend that can generate GitBook JWT tokens
- GitBook space with custom authentication enabled
## Installation
```bash
npm install
```
## Configuration
Create a `.env` file (or set environment variables):
```bash
# Required: Your authentication backend URL
BACKEND_AUTH_URL=https://your-backend.com
# Required: Your GitBook MCP endpoint
GITBOOK_MCP_URL=https://your-docs.gitbook.io/~gitbook/mcp
# Optional: Proxy port (default: 3333)
MCP_PROXY_PORT=3333
```
See `.env.example` for a template.
## Backend Requirements
Your backend must implement an authorization endpoint that:
1. **Authenticates the user** (via session cookie or other method)
2. **Generates a GitBook JWT token** with claims like:
```json
{
"iat": 1738478400,
"exp": 1739083200,
"user_context_id": "user-123",
"organization_context_id": "org-456"
}
```
3. **Redirects to callback** with token and optional LaunchDarkly cookie:
```
http://localhost:3333/callback?token=JWT&expires=UNIX_TIMESTAMP&ld_cookie={...}
```
Query parameters received from proxy:
- `session` - Unique session ID for logging
- `callback` - Localhost callback URL (must validate this is localhost!)
Example authorization endpoint:
```php
public function gitbookMcpAuthorize() {
// 1. Check authentication
if (!authenticated()) {
redirectToLogin();
}
// 2. Validate callback is localhost
$callback = $_GET['callback'];
if (!isLocalhost($callback)) {
halt(400, "Callback must be localhost");
}
// 3. Generate JWT
$jwt = generateGitbookJWT($user, $org);
$expires = time() + 604800; // 1 week
// 4. Get LaunchDarkly flags (optional)
$ldFlags = getLaunchDarklyFlags($user);
// 5. Redirect to callback
redirect($callback . "?token=$jwt&expires=$expires&ld_cookie=" . urlencode($ldFlags));
}
```
## Transport Modes
The proxy supports two transport modes. GitBook's MCP server uses HTTP with Server-Sent Events (SSE) transport, which both modes now support.
### HTTP Transport (Default)
HTTP transport runs a local HTTP server that MCP clients can connect to.
```bash
npm start
# or
node index.js
```
The proxy will automatically find an available port starting from 3333. If port 3333 is in use, it will try 3334, 3335, etc.
Configuration for HTTP mode:
```json
{
"mcpServers": {
"your-gitbook": {
"url": "http://localhost:3333"
}
}
}
```
### Stdio Transport
Stdio transport uses stdin/stdout for JSON-RPC communication. This is the native MCP protocol.
```bash
node index.js --stdio
```
#### Stdio Configuration Options
There are two ways to configure environment variables for stdio mode:
**Option 1: Using env field in config (Recommended)**
Pass environment variables directly in the MCP configuration:
```json
{
"mcpServers": {
"your-gitbook": {
"command": "node",
"args": ["/path/to/gitbook-mcp-proxy/index.js", "--stdio"],
"env": {
"BACKEND_AUTH_URL": "https://your-backend.com",
"GITBOOK_MCP_URL": "https://your-docs.gitbook.io/~gitbook/mcp",
"MCP_PROXY_PORT": "3333"
}
}
}
}
```
**Option 2: Using a shell wrapper script**
A wrapper script `start-proxy.sh` is included:
```bash
#!/bin/bash
export BACKEND_AUTH_URL="${BACKEND_AUTH_URL:-https://your-backend.com}"
export GITBOOK_MCP_URL="${GITBOOK_MCP_URL:-https://your-docs.gitbook.io/~gitbook/mcp}"
export MCP_PROXY_PORT="${MCP_PROXY_PORT:-3333}"
exec node "$SCRIPT_DIR/index.js" --stdio
```
Edit the script with your values, then configure:
```json
{
"mcpServers": {
"your-gitbook": {
"command": "/path/to/gitbook-mcp-proxy/start-proxy.sh"
}
}
}
```
#### Stdio Mode Behavior
In stdio mode, the proxy acts as a JSON-RPC to HTTP/SSE bridge:
1. **Receives JSON-RPC** from stdin (MCP protocol)
2. **Forwards to GitBook** via HTTP POST with JWT authentication
3. **Parses SSE response** from GitBook (extracts JSON from `data:` lines)
4. **Returns JSON-RPC** to stdout
Technical details:
- JSON-RPC messages are read from stdin (one per line)
- JSON-RPC responses are written to stdout (one per line)
- Automatically parses Server-Sent Events (SSE) format from GitBook
- All logs and diagnostics go to stderr (keeps stdout clean)
- A temporary HTTP server starts only for OAuth callbacks
- No port conflicts since there's no permanent HTTP server
- Same authentication and credential storage as HTTP mode
**Note:** Stdio mode works for most MCP operations but may have limitations with streaming operations since it converts persistent SSE connections into discrete request/response cycles.
## Usage
### 1. Start the Proxy
```bash
npm start
```
You'll see output with an authorization URL:
```
========================================
GitBook MCP Proxy
========================================
✓ Proxy server running
• Local endpoint: http://localhost:3333
• Target: https://your-docs.gitbook.io/~gitbook/mcp
🔐 AUTHORIZATION REQUIRED:
https://your-backend.com/api/gitbook/mcp-authorize?session=abc123...
Opening browser automatically...
```
### 2. Authorize in Browser
- Browser opens automatically (or copy the URL)
- Log into your backend if needed
- Backend generates JWT and redirects back
- Proxy encrypts and saves credentials
- You'll see "Authorization Successful"
### 3. Configure Your AI Assistant
#### Cursor
Open Cursor settings: `⌘ + Shift + P` → "MCP: Configure"
```json
{
"mcpServers": {
"your-gitbook": {
"url": "http://localhost:3333"
}
}
}
```
#### Claude Desktop
Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
```json
{
"mcpServers": {
"your-gitbook": {
"url": "http://localhost:3333"
}
}
}
```
### 4. Use It!
Ask your AI assistant questions like:
- "What does the documentation say about feature flags?"
- "Search the docs for authentication examples"
- "Show me the API reference"
## Credential Storage (MCP Spec)
Following the Model Context Protocol specification for secure credential storage:
### Storage Locations (Platform-Specific)
- **macOS**: `~/Library/Application Support/gitbook-mcp-proxy/credentials.json`
- **Linux**: `~/.config/gitbook-mcp-proxy/credentials.json`
- **Windows**: `%APPDATA%/gitbook-mcp-proxy/credentials.json`
### Encryption
- **Algorithm**: AES-256-GCM (authenticated encryption)
- **Key Storage**: Machine-specific key in `.key` file
- **Permissions**: 0600 (owner read/write only)
- **Tamper Detection**: GCM auth tag ensures integrity
### Security Properties
- ✅ Credentials encrypted at rest
- ✅ Machine-specific encryption key
- ✅ Automatic cleanup of expired tokens
- ✅ Platform-specific Application Support directories
- ✅ Restrictive file permissions
## Security
✅ **MCP-compliant credential storage** - Follows Model Context Protocol security spec
✅ **Encrypted at rest** - AES-256-GCM authenticated encryption
✅ **No credentials in env vars** - OAuth-style browser authorization
✅ **Localhost callbacks only** - Backend must validate callback URL
✅ **Token expiration** - Tokens expire automatically
✅ **HTTPS only** - All GitBook communication over HTTPS
✅ **JWT signature verification** - GitBook validates token cryptographically
✅ **Restrictive file permissions** - 0600 on all credential files
## API Endpoints
| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/callback` | GET | OAuth callback (receives token from backend) |
| `/health` | GET | Health check and authentication status |
| `/*` | * | MCP proxy (forwards all other requests to GitBook) |
### Health Check
```bash
curl http://localhost:3333/health
```
Response:
```json
{
"status": "ok",
"authenticated": true,
"expires": "2026-02-10T12:00:00.000Z"
}
```
## Troubleshooting
### "BACKEND_AUTH_URL not set"
Set the `BACKEND_AUTH_URL` environment variable to your authentication backend.
### Authorization Timeout
The proxy waits 30 seconds for authorization. Complete the browser flow within that time, or the MCP request will timeout.
### Token Expired
Tokens expire based on your backend's configuration (typically 1 week). When expired:
1. Browser will auto-open to re-authorize
2. Or manually open the authorization URL shown in console
### Port Already in Use
The proxy automatically finds an available port starting from 3333. If port 3333 is in use, it will try 3334, 3335, etc.
You can also:
```bash
# Set a specific preferred port
export MCP_PROXY_PORT=3334
npm start
# Or use stdio mode (no permanent HTTP server)
node index.js --stdio
```
### Corrupted Credentials
If credentials become corrupted, the proxy will automatically delete them and prompt for re-authorization.
## Environment Variables
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `BACKEND_AUTH_URL` | Yes | `https://your-backend.com` | Your authentication backend URL |
| `GITBOOK_MCP_URL` | Yes | `https://your-docs.gitbook.io/~gitbook/mcp` | Your GitBook MCP endpoint |
| `MCP_PROXY_PORT` | No | `3333` | Local proxy port |
## Development
```bash
# Install dependencies
npm install
# Run in development
npm start
# Run health check
npm run health
```
## Architecture
The proxy acts as a bridge between AI assistants and GitBook:
1. **Authentication Layer**: OAuth-style browser flow with your backend
2. **Credential Storage**: MCP-compliant encrypted storage
3. **Request Forwarding**: Adds JWT authentication to GitBook requests
4. **Cookie Management**: Forwards JWT + LaunchDarkly feature flags
5. **Redirect Handling**: Automatically follows HTTP 3xx redirects
## Related Resources
- [Model Context Protocol Specification](https://modelcontextprotocol.io/specification)
- [GitBook MCP Documentation](https://gitbook.com/docs/publishing-documentation/mcp-servers-for-published-docs)
- [GitBook Custom Authentication](https://gitbook.com/docs/publishing-documentation/authenticated-access/setting-up-a-custom-backend)
## License
MIT License - see [LICENSE](LICENSE) file for details
## Contributing
Contributions welcome! Please open an issue or PR.
## Author
Created by Forrest Middleton
## Support
If you encounter issues:
1. Check the [Troubleshooting](#troubleshooting) section
2. Review logs in the console
3. Open an issue on GitHubThis server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo recent community issues