What is MCP?
The Model Context Protocol (MCP) is an open standard that allows AI models to securely interact with external tools, data sources, and services. LLM Gateway implements MCP to enable:- File system access: Read and write local files
- Database queries: Connect to SQL/NoSQL databases
- API integrations: Call external REST/GraphQL APIs
- Custom tools: Execute any function or service
- Real-time data: Access live information sources
MCP is supported by Claude Code, Cursor, Windsurf, and other AI development tools.
Architecture
LLM Gateway provides an MCP server that:- Exposes tools for LLM operations (chat, list-models, generate-image)
- Authenticates using your API keys
- Routes requests through the gateway
- Returns responses in MCP format
Authentication
LLM Gateway’s MCP server supports OAuth 2.0 authentication for seamless integration with AI tools.OAuth Flow
The server implements:- Authorization endpoint:
/oauth/authorize - Token endpoint:
/oauth/token - Registration endpoint:
/oauth/register - Metadata:
/.well-known/oauth-authorization-server
Supported Grant Types
- Client Credentials
Registering a Client
Before using OAuth, register your client:For MCP, the
client_id and client_secret are both your LLM Gateway API key.MCP Endpoints
Server Endpoint
GET: Establish SSE connection or get server infoPOST: Send JSON-RPC requestsDELETE: Terminate session
Server Information
Get server metadata:SSE Connection (Streamable Transport)
Establish a persistent connection for real-time updates:- Session ID in
mcp-session-idheader - Endpoint URL via SSE event
- Messages as they’re processed
Available Tools
The MCP server exposes these tools:1. chat
Generate text responses using any LLM. Use for: Text generation, conversations, analysis, coding, etc.| Parameter | Type | Required | Description |
|---|---|---|---|
model | string | Yes | Model ID (e.g., “gpt-4o”) |
messages | array | Yes | Conversation history |
temperature | number | No | Randomness (0.0-2.0) |
max_tokens | number | No | Max response length |
2. list-models
List all available LLM models with capabilities and pricing.| Parameter | Type | Description |
|---|---|---|
family | string | Filter by provider (“openai”, “anthropic”, etc.) |
limit | number | Max models to return (default: 20) |
include_deactivated | boolean | Include inactive models |
exclude_deprecated | boolean | Exclude deprecated models |
3. generate-image
Create images from text descriptions. Use for: Image generation, artwork, diagrams, etc.| Parameter | Type | Description |
|---|---|---|
prompt | string | Image description |
model | string | Image model (default: “qwen-image-plus”) |
size | string | Image dimensions (e.g., “1024x1024”) |
n | number | Number of images (1-4) |
4. generate-nano-banana
Generate images using Gemini 3 Pro Image Preview with file saving.| Parameter | Type | Description |
|---|---|---|
prompt | string | Image description |
aspect_ratio | string | ”1:1”, “16:9”, “4:3”, or “5:4” |
filename | string | Optional filename (saved to UPLOAD_DIR) |
Set
UPLOAD_DIR environment variable to enable file saving.5. list-image-models
List all available image generation models.imageGenerations: true capability.
Client Setup
Claude Code
Configure Claude Code to use LLM Gateway’s MCP server:Install Claude Code
Follow the official installation guide at anthropic.ai/claude-code.
Add MCP Server
Edit your Claude Code config file:macOS/Linux:
~/.claude/mcp-servers.jsonWindows: %APPDATA%\Claude\mcp-servers.jsonCursor
Add LLM Gateway as an MCP server in Cursor:Add Server
Click Add Server and enter:
- Name: LLM Gateway
- URL:
https://api.llmgateway.io/mcp - Auth: OAuth 2.0
- API Key: Your LLM Gateway API key
Custom Client
Build your own MCP client:Session Management
MCP connections use sessions to maintain state:Creating a Session
- Send
GETrequest withAccept: text/event-stream - Receive
mcp-session-idheader - Use session ID for subsequent requests
Using Sessions
Include session ID in POST requests:Terminating Sessions
Security Considerations
Session Ownership
Sessions are tied to API keys:- Each session belongs to one API key
- Attempts to use a session with a different key are rejected
- This prevents session hijacking
Redirect URI Validation
For OAuth flows:- Redirect URIs must be registered during client registration
- Loopback addresses (localhost, 127.0.0.1) are allowed per RFC 8252
- HTTPS required for non-loopback URIs
- Prevents authorization code interception
Error Handling
MCP uses JSON-RPC error codes:| Code | Message | Description |
|---|---|---|
| -32700 | Parse error | Invalid JSON |
| -32600 | Invalid Request | Malformed request |
| -32601 | Method not found | Unknown method |
| -32602 | Invalid params | Invalid parameters |
| -32603 | Internal error | Server error |
| -32001 | Unauthorized | Authentication failed |
Best Practices
Connection Management
Connection Management
- Reuse SSE connections when possible
- Implement reconnection logic with exponential backoff
- Close sessions when done to free resources
- Monitor connection health with ping requests
Error Handling
Error Handling
- Handle all JSON-RPC error codes
- Retry transient errors (500, 503)
- Don’t retry auth errors (401, 403)
- Log errors for debugging
- Provide user-friendly error messages
Performance
Performance
- Batch requests when possible
- Cache model lists locally
- Stream responses for better UX
- Use appropriate timeouts
- Monitor latency and throughput
Security
Security
- Store API keys securely (env vars, secrets manager)
- Validate all inputs before sending
- Implement rate limiting
- Monitor for unusual activity
- Rotate keys periodically
Troubleshooting
Connection Refused
Connection Refused
Possible causes:
- Invalid API key
- Network issues
- Firewall blocking requests
- Verify API key is correct
- Check network connectivity
- Ensure firewall allows HTTPS
Session Ownership Error
Session Ownership Error
Error: “Session belongs to a different API key”Cause: Trying to use a session ID with a different API keySolution: Create a new session or use the correct API key
OAuth Redirect Mismatch
OAuth Redirect Mismatch
Error: “Invalid redirect_uri”Cause: Redirect URI not registered for clientSolution: Register the redirect URI via
/oauth/registerTool Not Found
Tool Not Found
Error: “Method not found: tools/call”Cause: Incorrect JSON-RPC request formatSolution: Ensure proper request structure (see examples above)
Next Steps
AI Tools Setup
Configure Claude Code, Cursor, and Windsurf.
API Reference
Explore the complete API documentation.
Playground
Test MCP tools in the interactive playground.
Projects
Manage API keys and project settings.