Content
# MCP Studio
> A Postman-like backend for testing Model Context Protocol (MCP) servers with AI-powered natural language interactions.
[](https://www.python.org/downloads/)
[](https://fastapi.tiangolo.com/)
[](https://opensource.org/licenses/MIT)
---
## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Quick Start](#quick-start)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage Guide](#usage-guide)
- [Authentication Flow](#authentication-flow)
- [Working with Sessions](#working-with-sessions)
- [Connecting MCP Servers](#connecting-mcp-servers)
- [Using the AI Agent](#using-the-ai-agent)
- [Direct Tool Execution](#direct-tool-execution)
- [API Reference](#api-reference)
- [Architecture](#architecture)
- [Agent Flow](#agent-flow)
- [Project Structure](#project-structure)
- [Data Flow](#data-flow)
- [Customization Guide](#customization-guide)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
---
## Overview
The MCP Testing Platform bridges the gap between complex MCP protocol specifications and practical, user-friendly testing. It enables developers to:
- **Connect** to multiple MCP servers simultaneously
- **Discover** available tools automatically
- **Test** tools using natural language queries
- **Debug** MCP server implementations with detailed responses
### Why Use This?
| Challenge | Solution |
|-----------|----------|
| MCP protocol complexity | Simple REST/WebSocket API |
| Manual tool testing | AI-powered natural language interface |
| Multi-server coordination | Unified session management |
| OAuth authentication flows | Built-in OAuth 2.1 with PKCE support |
---
## Features
### Core Capabilities
| Feature | Description |
|---------|-------------|
| **Multi-Server Support** | Connect to multiple MCP servers in a single session |
| **AI Agent Integration** | GPT-4o/Gemini agents that intelligently select and execute tools |
| **Dual Chat Interfaces** | REST API (sync) and WebSocket (streaming) |
| **OAuth 2.1 Authentication** | Complete OAuth flow with PKCE and Dynamic Client Registration |
| **Tool Discovery & Caching** | Automatic tool discovery with intelligent caching |
| **Session Persistence** | MongoDB-backed persistence with automatic expiration |
| **Credit System** | Built-in usage tracking and billing support |
| **Real-time Streaming** | Live tool execution updates via WebSocket |
### Transport Protocols
- **HTTP POST** - Standard JSON-RPC over HTTP
- **Server-Sent Events (SSE)** - Real-time streaming from MCP servers
---
## Quick Start
Get up and running in 5 minutes:
```bash
# 1. Clone the repository
git clone <repository-url>
cd mcp-templete
# 2. Create virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Set up environment variables
cp .env.example .env
# Edit .env with your API keys (see Configuration section)
# 5. Start services (MongoDB + Redis)
docker-compose up -d
# 6. Run the server
uvicorn app.main:app --reload
# 7. Open API docs
open http://localhost:8000/docs
```
---
## Installation
### Prerequisites
| Requirement | Version | Purpose |
|-------------|---------|---------|
| Python | 3.11+ | Runtime |
| MongoDB | 7.0+ | Session & user data storage |
| Redis | 5.0+ | OAuth state management |
| Docker | 20.10+ | Container runtime (optional) |
### Step-by-Step Installation
#### 1. Clone and Setup Environment
```bash
git clone <repository-url>
cd mcp-templete
# Create virtual environment
python -m venv venv
source venv/bin/activate
```
#### 2. Install Dependencies
```bash
pip install -r requirements.txt
```
#### 3. Configure Environment
```bash
cp .env.example .env
```
Edit `.env` with your configuration (see [Configuration](#configuration)).
#### 4. Start Database Services
**Option A: Docker Compose (Recommended)**
```bash
docker-compose up -d
```
**Option B: Manual Setup**
```bash
# Start MongoDB
docker run -d -p 27017:27017 --name mongodb mongo:7.0
# Start Redis
docker run -d -p 6379:6379 --name redis redis:7
```
#### 5. Run the Server
```bash
# Development (with hot reload)
uvicorn app.main:app --reload
# Production
uvicorn app.main:app --host 0.0.0.0 --port 8000
```
---
## Configuration
### Environment Variables
Create a `.env` file with the following variables:
```bash
# ═══════════════════════════════════════════════════════════════
# AI PROVIDERS (at least one required)
# ═══════════════════════════════════════════════════════════════
OPENAI_API_KEY=sk-... # OpenAI API key for GPT-4o
GEMINI_API_KEY=... # Google Gemini API key
# ═══════════════════════════════════════════════════════════════
# DATABASE
# ═══════════════════════════════════════════════════════════════
MONGODB_URL=mongodb://localhost:27017 # MongoDB connection URL
MONGODB_DATABASE_NAME=mcp_testing # Database name
REDIS_URL=redis://localhost:6379 # Redis connection URL
# ═══════════════════════════════════════════════════════════════
# USER AUTHENTICATION (Google OAuth)
# ═══════════════════════════════════════════════════════════════
GOOGLE_CLIENT_ID=... # From Google Cloud Console
GOOGLE_CLIENT_SECRET=... # From Google Cloud Console
GOOGLE_REDIRECT_URI=http://localhost:8000/api/auth/google/callback
# ═══════════════════════════════════════════════════════════════
# MCP SERVER OAUTH
# ═══════════════════════════════════════════════════════════════
MCP_OAUTH_REDIRECT_URI=http://localhost:8000/api/oauth/callback
# Static OAuth redirect URLs for known MCP servers (optional)
# Comma-separated or JSON array format
OAUTH_REDIRECT_URLS=["https://notion.com/oauth/callback"]
# ═══════════════════════════════════════════════════════════════
# SECURITY
# ═══════════════════════════════════════════════════════════════
JWT_SECRET_KEY=your-secret-key-change-in-production
JWT_ALGORITHM=HS256
JWT_EXPIRATION_HOURS=24
# ═══════════════════════════════════════════════════════════════
# APPLICATION SETTINGS
# ═══════════════════════════════════════════════════════════════
FRONTEND_URL=http://localhost:3000 # Your frontend URL for redirects
SESSION_EXPIRY_HOURS=24 # Session lifetime
INITIAL_CREDITS=10 # Credits for new users
```
### Setting Up Google OAuth
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select existing
3. Navigate to **APIs & Services** → **Credentials**
4. Click **Create Credentials** → **OAuth 2.0 Client ID**
5. Application type: **Web application**
6. Add authorized redirect URI: `http://localhost:8000/api/auth/google/callback`
7. Copy Client ID and Client Secret to `.env`
---
## Usage Guide
### Authentication Flow
```
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Client │────▶│ Login │────▶│ Google │────▶│ Callback │
└──────────┘ │ Endpoint │ │ OAuth │ │ + JWT │
└──────────┘ └──────────┘ └──────────┘
```
**Step 1: Initiate Login**
```bash
curl http://localhost:8000/api/auth/google/login
```
Response:
```json
{
"authorization_url": "https://accounts.google.com/o/oauth2/...",
"state": "abc123..."
}
```
**Step 2: User Authenticates**
- Redirect user to `authorization_url`
- User completes Google OAuth
- Google redirects to callback URL
**Step 3: Use JWT Token**
- The callback returns a JWT token
- Include in all subsequent requests:
```bash
curl -H "Authorization: Bearer <jwt_token>" \
http://localhost:8000/api/auth/me
```
---
### Working with Sessions
Sessions (workspaces) group MCP server connections and conversation history.
**Create a Session**
```bash
curl -X POST http://localhost:8000/api/sessions \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"session_name": "My Weather Project",
"system_prompt": "You are a helpful weather assistant. Always provide temperatures in both Celsius and Fahrenheit."
}'
```
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `session_name` | string | No | Human-readable name for the workspace |
| `system_prompt` | string | No | Default AI behavior instructions for all chats in this session |
Response:
```json
{
"session_id": "550e8400-e29b-41d4-a716-446655440000"
}
```
**List Your Sessions**
```bash
curl http://localhost:8000/api/sessions \
-H "Authorization: Bearer <jwt_token>"
```
Response:
```json
{
"user_id": "user_123",
"sessions": [
{
"session_id": "550e8400-e29b-41d4-a716-446655440000",
"session_name": "My Weather Project",
"created_at": "2024-01-15T10:30:00Z",
"servers": {...}
}
],
"count": 1
}
```
**Get Session Details**
```bash
curl http://localhost:8000/api/sessions/{session_id} \
-H "Authorization: Bearer <jwt_token>"
```
**Update System Prompt**
```bash
curl -X PUT http://localhost:8000/api/sessions/{session_id}/system-prompt \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"system_prompt": "You are a data analyst. Be concise and use bullet points."
}'
```
**Delete a Session**
```bash
curl -X DELETE http://localhost:8000/api/sessions/{session_id} \
-H "Authorization: Bearer <jwt_token>"
```
---
### Connecting MCP Servers
**Add an MCP Server**
```bash
curl -X POST http://localhost:8000/api/sessions/{session_id}/servers \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"name": "weather-server",
"url": "https://mcp-weather.example.com"
}'
```
Response (if no auth required):
```json
{
"server": {
"name": "weather-server",
"url": "https://mcp-weather.example.com",
"state": "connected",
"tools": [
{"name": "get_weather", "description": "Get current weather"}
]
},
"requires_auth": false
}
```
Response (if OAuth required):
```json
{
"server": {...},
"requires_auth": true,
"authorization_url": "https://weather.example.com/oauth/authorize?..."
}
```
**With API Key/Token**
```bash
curl -X POST http://localhost:8000/api/sessions/{session_id}/servers \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"name": "my-server",
"url": "https://mcp.example.com",
"access_token": "your-api-key"
}'
```
**List Connected Servers**
```bash
curl http://localhost:8000/api/sessions/{session_id}/servers \
-H "Authorization: Bearer <jwt_token>"
```
**Remove a Server**
```bash
curl -X DELETE http://localhost:8000/api/sessions/{session_id}/servers/weather-server \
-H "Authorization: Bearer <jwt_token>"
```
---
### Using the AI Agent
The AI agent understands natural language and automatically selects appropriate tools.
#### REST API (Synchronous)
```bash
curl -X POST http://localhost:8000/api/sessions/{session_id}/chat \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"message": "What is the weather in New York?"
}'
```
Response:
```json
{
"response": "The current weather in New York is 72°F with partly cloudy skies.",
"chat_session_id": "chat_abc123",
"credits_remaining": 9
}
```
**Continue a Conversation**
```bash
curl -X POST http://localhost:8000/api/sessions/{session_id}/chat \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"message": "What about tomorrow?",
"chat_session_id": "chat_abc123"
}'
```
**Custom System Prompt**
```bash
curl -X POST http://localhost:8000/api/sessions/{session_id}/chat \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"message": "Analyze the data",
"system_prompt": "You are a data analyst. Be concise and use bullet points."
}'
```
#### WebSocket (Streaming)
```javascript
const token = 'your_jwt_token';
const sessionId = 'your_session_id';
const ws = new WebSocket(
`ws://localhost:8000/ws/sessions/${sessionId}/chat?token=${token}`
);
ws.onopen = () => {
ws.send(JSON.stringify({
type: 'chat',
messages: [
{ role: 'user', content: 'What tools are available?' }
]
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
switch (data.type) {
case 'text_delta':
// Streaming text chunk
process.stdout.write(data.text);
break;
case 'tool_call_start':
console.log(`\n🔧 Calling tool: ${data.tool_name}`);
break;
case 'tool_result':
console.log(`✅ Result: ${JSON.stringify(data.result)}`);
break;
case 'complete':
console.log('\n✨ Response complete');
break;
case 'credits_update':
console.log(`💳 Credits remaining: ${data.credits_remaining}`);
break;
case 'error':
console.error(`❌ Error: ${data.error}`);
break;
}
};
```
**WebSocket Event Types**
| Event | Description | Payload |
|-------|-------------|---------|
| `message_start` | Response begins | - |
| `text_delta` | Text chunk | `{ text: "..." }` |
| `tool_call_start` | Tool selected | `{ tool_name: "..." }` |
| `tool_execution_start` | Tool executing | `{ tool_name: "..." }` |
| `tool_result` | Tool completed | `{ tool_name, result }` |
| `tool_error` | Tool failed | `{ tool_name, error }` |
| `complete` | Response finished | - |
| `credits_update` | Credit deducted | `{ credits_remaining }` |
| `error` | Error occurred | `{ error: "..." }` |
| `pong` | Ping response | - |
---
### Direct Tool Execution
Execute tools directly without AI interpretation:
**List Available Tools**
```bash
curl http://localhost:8000/api/sessions/{session_id}/tools \
-H "Authorization: Bearer <jwt_token>"
```
Response:
```json
{
"tools": [
{
"server_name": "weather-server",
"name": "get_weather",
"description": "Get current weather for a location",
"inputSchema": {
"type": "object",
"properties": {
"location": { "type": "string", "description": "City name" }
},
"required": ["location"]
}
}
]
}
```
**Execute a Tool**
```bash
curl -X POST http://localhost:8000/api/sessions/{session_id}/tools/call \
-H "Authorization: Bearer <jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"server_name": "weather-server",
"tool_name": "get_weather",
"arguments": {
"location": "New York"
}
}'
```
---
## API Reference
### Endpoints Overview
| Method | Endpoint | Description | Auth |
|--------|----------|-------------|------|
| **Authentication** ||||
| `GET` | `/api/auth/google/login` | Initiate Google OAuth | No |
| `GET` | `/api/auth/google/callback` | OAuth callback | No |
| `GET` | `/api/auth/me` | Get current user | Yes |
| **Sessions** ||||
| `GET` | `/api/sessions` | List all sessions | Yes |
| `POST` | `/api/sessions` | Create session (with optional name & system prompt) | Yes |
| `GET` | `/api/sessions/{id}` | Get session details | Yes |
| `DELETE` | `/api/sessions/{id}` | Delete session | Yes |
| `GET` | `/api/sessions/{id}/system-prompt` | Get system prompt | Yes |
| `PUT` | `/api/sessions/{id}/system-prompt` | Update system prompt | Yes |
| `GET` | `/api/sessions/{id}/auth-status` | Check all servers' auth status | Yes |
| **Chat** ||||
| `POST` | `/api/sessions/{id}/chat` | Send chat message | Yes |
| `GET` | `/api/sessions/{id}/chat-sessions` | List all chat sessions | Yes |
| `GET` | `/api/sessions/{id}/chat-sessions/{chat_id}` | Get chat session details | Yes |
| `DELETE` | `/api/sessions/{id}/chat-sessions/{chat_id}` | Delete chat session | Yes |
| `DELETE` | `/api/sessions/{id}/chat/{chat_id}` | Clear chat history (keep session) | Yes |
| **Servers** ||||
| `POST` | `/api/sessions/{id}/servers` | Add MCP server | Yes |
| `GET` | `/api/sessions/{id}/servers` | List servers | Yes |
| `DELETE` | `/api/sessions/{id}/servers/{name}` | Remove server | Yes |
| `PUT` | `/api/sessions/{id}/servers/{name}/token` | Update access token | Yes |
| `PATCH` | `/api/sessions/{id}/servers/{name}/api-key` | Update API key | Yes |
| **Tools** ||||
| `GET` | `/api/sessions/{id}/tools` | List all tools | Yes |
| `POST` | `/api/sessions/{id}/tools/call` | Execute tool directly | Yes |
| **OAuth (MCP Servers)** ||||
| `POST` | `/api/oauth/sessions/{id}/servers/{name}/authorize` | Start OAuth flow | Yes |
| `GET` | `/api/oauth/callback` | OAuth callback | No |
| **WebSocket** ||||
| `WS` | `/ws/sessions/{id}/chat` | Real-time streaming chat | Yes |
| `WS` | `/ws/sessions/{id}/chat/{chat_id}/activity` | Activity stream | Yes |
| **System** ||||
| `GET` | `/` | API info | No |
| `GET` | `/health` | Health check | No |
| `GET` | `/docs` | Swagger UI | No |
### Response Codes
| Code | Description |
|------|-------------|
| `200` | Success |
| `201` | Created |
| `400` | Bad Request |
| `401` | Unauthorized (missing/invalid token) |
| `402` | Payment Required (credits exhausted) |
| `404` | Not Found |
| `500` | Internal Server Error |
---
## Architecture
### Agent Flow
The AI agent is the core of natural language interaction:
```
┌─────────────────────────────────────────────────────────────────┐
│ AGENT FLOW │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ User │───▶│ Agent Service│───▶│ Fetch Tools from │ │
│ │ Message │ │ │ │ All MCP Servers │ │
│ └──────────┘ └──────────────┘ └──────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ Convert to │◀───│ MCP Tool Schemas │ │
│ │ LLM Format │ │ │ │
│ └──────────────┘ └──────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Send to │ │
│ │ OpenAI/ │◀──────────────────────┐ │
│ │ Gemini │ │ │
│ └──────────────┘ │ │
│ │ │ │
│ ▼ │ │
│ ┌──────────────┐ No ┌──────────┴───┐ │
│ │ Tool Calls? │──────────▶│ Return Text │ │
│ └──────────────┘ │ Response │ │
│ │ Yes └──────────────┘ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Execute │ │
│ │ Tools via │ │
│ │ MCP Servers │ │
│ └──────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Process │──────────────┐ │
│ │ Results │ │ │
│ └──────────────┘ │ │
│ │ │ │
│ ▼ │ │
│ ┌──────────────┐ │ │
│ │ More Turns? │──Yes─────────┘ │
│ │ (max: 10) │ │
│ └──────────────┘ │
│ │ No │
│ ▼ │
│ ┌──────────────┐ │
│ │ Final │ │
│ │ Response │ │
│ └──────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
**Key Steps:**
1. **Tool Conversion**: MCP tool schemas are converted to OpenAI/Gemini function format
2. **LLM Decision**: The AI decides which tools to call based on user intent
3. **Tool Execution**: Selected tools are executed against MCP servers
4. **Error Analysis**: Failed executions trigger intelligent error analysis and retry
5. **Response Generation**: Results are formatted into natural language
### Project Structure
```
app/
├── main.py # FastAPI app, routing, CORS, lifecycle
├── config.py # Environment configuration (Pydantic Settings)
│
├── api/ # HTTP & WebSocket endpoints
│ ├── auth.py # Google OAuth login/callback
│ ├── sessions.py # Session CRUD + REST chat
│ ├── servers.py # MCP server management
│ ├── tools.py # Tool listing & direct execution
│ ├── oauth.py # MCP server OAuth flow
│ └── websocket.py # WebSocket streaming chat
│
├── services/ # Core business logic
│ ├── agent_service.py # AI agent (OpenAI/Gemini integration)
│ ├── mcp_client.py # MCP protocol client (HTTP + SSE)
│ ├── mcp_manager.py # Multi-server connection manager
│ ├── oauth_handler.py # OAuth 2.1 with PKCE
│ ├── auth_service.py # User authentication
│ └── credit_service.py # Credit tracking & deduction
│
├── models/ # Pydantic data models
│ ├── session.py # SessionData, MCPServerInfo, MCPServerState
│ ├── mcp.py # JSON-RPC models, MCPTool
│ └── user.py # User model
│
├── utils/ # Utility functions
│ ├── mongodb_client.py # Async MongoDB operations
│ ├── redis_client.py # Redis for OAuth state
│ ├── openai_client.py # OpenAI API wrapper
│ ├── gemini_client.py # Gemini API wrapper
│ ├── activity_store.py # WebSocket activity queue
│ └── domain_extractor.py# URL domain extraction
│
└── middleware/
└── auth.py # JWT authentication middleware
```
### Data Flow
```
┌─────────────────────────────────────────────────────────────────┐
│ DATA FLOW │
└─────────────────────────────────────────────────────────────────┘
┌─────────────┐
│ Client │
│ (Frontend) │
└──────┬──────┘
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ REST API │ │WebSocket │ │ OAuth │
│ Endpoints│ │ Handler │ │ Callback │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
└──────────────┼──────────────┘
│
▼
┌─────────────────────┐
│ Agent Service │
│ (Tool Orchestration│
└──────────┬──────────┘
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ OpenAI │ │ Gemini │ │ MCP │
│ API │ │ API │ │ Manager │
└──────────┘ └──────────┘ └────┬─────┘
│
┌────────────┼────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ MCP │ │ MCP │ │ MCP │
│ Server 1 │ │ Server 2 │ │ Server N │
└──────────┘ └──────────┘ └──────────┘
┌─────────────────────────────────────────────────────────────────┐
│ DATA STORAGE │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ MongoDB │ │ Redis │ │
│ ├──────────────┤ ├──────────────┤ │
│ │ • users │ │ • OAuth │ │
│ │ • sessions │ │ states │ │
│ │ • chat_ │ │ • Session │ │
│ │ sessions │ │ cache │ │
│ │ • credit_ │ │ │ │
│ │ transactions│ │ │ │
│ └──────────────┘ └──────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
### MCP Server States
```
┌─────────────────────────────────────────┐
│ SERVER STATE MACHINE │
└─────────────────────────────────────────┘
┌──────────────┐
│ DISCONNECTED │ ◀─────────────────────────────────┐
└──────┬───────┘ │
│ Add Server │
▼ │
┌──────────────┐ │
│ CONNECTING │───────────────────────────────────┤
└──────┬───────┘ │
│ │
├─────── Success ──────▶ ┌──────────────┐ │
│ │ CONNECTED │───┤
│ └──────────────┘ │
│ │
├─────── OAuth Required ▶┌──────────────┐ │
│ │AUTHENTICATING│───┤
│ └──────────────┘ │
│ │
└─────── Failure ───────▶┌──────────────┐ │
│ ERROR │───┘
└──────────────┘
```
---
## Customization Guide
This codebase is designed as a template you can extract and customize.
### Quick Customization Checklist
| Task | File | Priority |
|------|------|----------|
| Update app name/description | `app/main.py` | High |
| Configure OAuth redirect URLs | `app/config.py` | High |
| Set credit exhaustion message | `app/services/credit_service.py` | High |
| Update CORS origins | `app/main.py` | High |
| Configure initial credits | `.env` (INITIAL_CREDITS) | Medium |
| Replace auth provider | `app/services/auth_service.py` | Optional |
| Replace LLM provider | `app/services/agent_service.py` | Optional |
| Switch database | `app/utils/mongodb_client.py` | Optional |
### Replacing the LLM Provider
To use a different AI provider (e.g., Anthropic Claude):
1. **Install SDK**:
```bash
pip install anthropic
```
2. **Update Agent Service** (`app/services/agent_service.py`):
```python
from anthropic import Anthropic
client = Anthropic(api_key=settings.anthropic_api_key)
# Convert tools to Anthropic format
# Update response parsing
```
3. **Add Config** (`app/config.py`):
```python
anthropic_api_key: str = ""
```
### Customizing the Credit System
**Update Contact Email** (`app/services/credit_service.py`):
```python
def get_credit_exhaustion_message() -> str:
return "Credits exhausted. Contact support@yourcompany.com"
```
**Change Initial Credits** (`.env`):
```bash
INITIAL_CREDITS=50
```
### Adding Custom Endpoints
```python
# app/api/custom.py
from fastapi import APIRouter, Depends
from app.middleware.auth import get_current_user
router = APIRouter(prefix="/api/custom", tags=["custom"])
@router.get("/endpoint")
async def custom_endpoint(user: dict = Depends(get_current_user)):
return {"message": "Hello from custom endpoint"}
# Register in app/main.py
from app.api import custom
app.include_router(custom.router)
```
---
## Troubleshooting
### Common Issues
#### "OAuth redirect URL not being matched"
**Symptom**: Server falls back to dynamic OAuth discovery.
**Solution**:
1. Verify domain extraction matches your server URL
2. Ensure redirect URL includes protocol (`https://...`)
3. Restart server after config changes
#### "Connection refused" to MCP server
**Symptom**: Cannot connect to MCP server.
**Solutions**:
1. Verify the MCP server URL is correct and accessible
2. Check if the server requires authentication
3. Ensure your network allows the connection
#### "Credits exhausted" error
**Symptom**: HTTP 402 response.
**Solution**:
- Contact administrator for credit refill
- Or modify `INITIAL_CREDITS` for new users
#### WebSocket connection fails
**Symptom**: Cannot establish WebSocket connection.
**Solutions**:
1. Verify JWT token is valid
2. Check session ID exists
3. Ensure WebSocket endpoint URL is correct
### Debug Mode
Enable detailed logging:
```python
# app/main.py
import logging
logging.basicConfig(level=logging.DEBUG)
```
### Health Check
```bash
curl http://localhost:8000/health
# Expected: {"status": "healthy"}
```
---
## Contributing
Contributions are welcome! Areas of interest:
- Additional transport protocol support
- Enhanced error handling
- Performance optimizations
- Additional authentication providers
- Frontend integration examples
### Development Setup
```bash
# Clone and setup
git clone <repository-url>
cd mcp-templete
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
# Run with hot reload
uvicorn app.main:app --reload
# Run tests (if available)
pytest
```
---
<div align="center">
**Built with ❤️ for the MCP Community**
[Report Bug](https://github.com/your-repo/issues) · [Request Feature](https://github.com/your-repo/issues)
</div>
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.