;
ip_address: string;
user_agent: string;
timestamp: Date;
gdpr_compliant: boolean;
}
```
### Compliance Reports
Generate GDPR compliance reports:
```typescript theme={null}
GET /api/admin/compliance/report
Response:
{
"period": "2025-01",
"deletions": {
"total": 15,
"gdpr_requests": 5,
"user_initiated": 10
},
"exports": {
"total": 45,
"completed": 45,
"failed": 0
},
"data_categories_deleted": [
"personal_data",
"usage_data",
"content_data"
]
}
```
## Testing User Deletion
### Deletion Checklist
* [ ] All projects deleted
* [ ] All profiles deleted
* [ ] All MCP servers deleted
* [ ] All documents deleted
* [ ] All notifications deleted
* [ ] Email tracking deleted
* [ ] Follower relationships removed
* [ ] OAuth accounts removed
* [ ] Sessions terminated
* [ ] Claimed servers handled
* [ ] Avatar files deleted
* [ ] Audit log created
* [ ] Admin notified
### Test Script
```bash theme={null}
# Test user deletion cascade
npm run test:gdpr-deletion
# Verify no orphaned data
SELECT * FROM projects WHERE user_id = 'deleted_user_id';
SELECT * FROM mcp_servers WHERE profile_uuid IN
(SELECT uuid FROM profiles WHERE project_uuid IN
(SELECT uuid FROM projects WHERE user_id = 'deleted_user_id'));
```
## Security Considerations
### Authentication Requirements
* Password verification for deletion
* Email confirmation for sensitive changes
* Session invalidation after deletion
* Rate limiting on deletion requests
### Data Retention
Deleted data is permanently removed and cannot be recovered.
* No soft deletes for user data
* Immediate deletion from database
* File system cleanup for avatars
* Cache invalidation across all services
## Best Practices
Periodically audit user data to ensure compliance
Inform users about data deletion consequences
Encourage users to export data before deletion
Keep detailed logs of all deletions for compliance
Regularly test that all related data is deleted
## Support
For user management assistance:
* **Privacy Policy**: [plugged.in/privacy](https://plugged.in/privacy)
* **Support Email**: [privacy@plugged.in](mailto:privacy@plugged.in)
* **GDPR Requests**: [gdpr@plugged.in](mailto:gdpr@plugged.in)
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
# Configuration Guide
Source: https://docs.plugged.in/quickstart/configuration
Configure Plugged.in for your specific needs
# Configuration Guide
**Using Plugged.in Cloud?** If you're using the hosted version at [plugged.in](https://plugged.in), configuration is already handled for you! Simply sign up and start using the platform. This guide is for self-hosted installations only.
## Cloud vs Self-Hosted
**No configuration needed!**
The cloud version at [plugged.in](https://plugged.in) provides:
* ✅ Automatic updates and maintenance
* ✅ Pre-configured security and optimization
* ✅ Managed database and backups
* ✅ OAuth providers already set up
* ✅ Email delivery configured
* ✅ SSL/TLS certificates included
[Sign up now →](https://plugged.in/register)
**Full control over your instance**
Self-hosting gives you:
* Complete data ownership
* Custom domain and branding
* Private network deployment
* Specific compliance requirements
* Custom integrations
Continue reading for configuration instructions.
## Self-Hosted Configuration
This guide covers the essential configuration steps after installing Plugged.in self-hosted, including database setup, authentication, features, and optimization settings.
### Initial Setup
After installation, follow these steps to configure your Plugged.in instance properly.
### 1. Database Configuration
```bash theme={null}
createdb pluggedin
```
```bash theme={null}
cd pluggedin-app
pnpm db:generate # Generate Drizzle schema
pnpm db:migrate # Run database migrations
```
Test your database connection:
```bash theme={null}
psql $DATABASE_URL -c "SELECT version();"
```
For production environments, always use SSL connections:
```env theme={null}
DATABASE_SSL=true
DATABASE_SSL_REJECT_UNAUTHORIZED=true
```
### 2. Authentication Setup
#### Generate Secret Keys
Generate all required secret keys for secure operation:
```bash theme={null}
# Generate and save these to your .env file
echo "NEXTAUTH_SECRET=$(openssl rand -base64 32)"
echo "NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=$(openssl rand -base64 32)"
echo "UNSUBSCRIBE_TOKEN_SECRET=$(openssl rand -base64 32)"
```
**Important**: Each key must be unique. Never reuse the same key for different purposes.
#### Configure OAuth Providers
1. Go to [GitHub Developer Settings](https://github.com/settings/developers)
2. Create a new OAuth App
3. Set Authorization callback URL: `http://localhost:12005/api/auth/callback/github`
4. Add to `.env`:
```env theme={null}
GITHUB_ID=your_client_id
GITHUB_SECRET=your_client_secret
GITHUB_TOKEN=your_personal_access_token # For API calls
```
1. Go to [Google Cloud Console](https://console.cloud.google.com)
2. Create OAuth 2.0 credentials
3. Add authorized redirect URI: `http://localhost:12005/api/auth/callback/google`
4. Add to `.env`:
```env theme={null}
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
```
### 3. MCP Proxy Configuration
Configure the MCP proxy server connection:
```env theme={null}
# Registry Configuration
REGISTRY_API_URL=http://localhost:3001
REGISTRY_INTERNAL_API_KEY=$(openssl rand -base64 32)
# MCP Proxy Settings
PLUGGEDIN_API_KEY=$(openssl rand -base64 32)
PLUGGEDIN_MCP_URL=http://localhost:3000
```
#### MCP Resource Limits
Control resource usage for MCP servers:
```env theme={null}
# CPU and Memory Limits
MCP_CPU_CORES_MAX=0.5 # 50% of one core
MCP_MEMORY_MAX_MB=512 # Maximum memory per server
# I/O Limits
MCP_IO_READ_MBPS=10 # Max read speed
MCP_IO_WRITE_MBPS=5 # Max write speed
# Timeout Settings
MCP_PROCESS_TIMEOUT_MS=300000 # 5 minutes max runtime
MCP_STARTUP_TIMEOUT_MS=10000 # 10 seconds to start
```
### 4. Email Configuration
```env theme={null}
# Email Server
EMAIL_SERVER_HOST=smtp.gmail.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=your-email@gmail.com
EMAIL_SERVER_PASSWORD=your-app-password
# Email Addresses
EMAIL_FROM=noreply@plugged.in
EMAIL_FROM_NAME=Plugged.in
EMAIL_REPLY_TO=support@plugged.in
```
```env theme={null}
# Welcome Emails
ENABLE_WELCOME_EMAILS=true
WELCOME_EMAIL_DELAY_MINUTES=5
# Follow-up Emails
ENABLE_FOLLOW_UP_EMAILS=true
FOLLOW_UP_2_DAYS=2
FOLLOW_UP_5_DAYS=5
# Email Verification
ENABLE_EMAIL_VERIFICATION=false
```
```env theme={null}
# Admin Email Settings
ADMIN_NOTIFICATION_EMAILS=admin@example.com,team@example.com
ADMIN_NOTIFICATION_SEVERITIES=ALERT,CRITICAL
ADMIN_DAILY_SUMMARY=false
ADMIN_FAILED_LOGIN_THRESHOLD=5
```
### 5. Feature Flags
Enable or disable specific features:
```env theme={null}
# Core Features
ENABLE_RAG=true # Document processing
ENABLE_NOTIFICATIONS=true # Notification system
# Security Features
ENABLE_EMAIL_VERIFICATION=false # Require email verification
```
### 6. AI Model Configuration
Configure API keys for AI model providers:
```env Anthropic theme={null}
ANTHROPIC_API_KEY=sk-ant-api03-...
```
```env OpenAI theme={null}
OPENAI_API_KEY=sk-...
```
```env Google theme={null}
GOOGLE_API_KEY=AIza...
```
### 7. Production Configuration
#### SSL/TLS Setup
For production, configure proper SSL:
```env theme={null}
# Production URLs
NEXTAUTH_URL=https://your-domain.com
NEXT_PUBLIC_APP_URL=https://your-domain.com
# Database SSL
DATABASE_SSL=true
DATABASE_SSL_REJECT_UNAUTHORIZED=true
```
#### Security Headers
Add security headers in your reverse proxy (nginx example):
```nginx theme={null}
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
```
#### Rate Limiting
Configure rate limiting for production:
```env theme={null}
# Rate Limit Configuration
RATE_LIMIT_SERVER_MOD_WINDOW_MS=60000 # 1 minute window
RATE_LIMIT_SERVER_MOD_MAX=10 # Max modifications
RATE_LIMIT_SENSITIVE_WINDOW_MS=3600000 # 1 hour window
RATE_LIMIT_SENSITIVE_MAX=10 # Max sensitive ops
```
## MCP Client Configuration
### Claude Desktop Configuration
Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"pluggedin": {
"command": "node",
"args": ["/path/to/pluggedin-mcp/dist/index.js"],
"env": {
"PLUGGEDIN_API_KEY": "your-api-key",
"PLUGGEDIN_BASE_URL": "https://your-domain.com"
}
}
}
}
```
Edit `%APPDATA%\Claude\claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"pluggedin": {
"command": "node",
"args": ["C:\\path\\to\\pluggedin-mcp\\dist\\index.js"],
"env": {
"PLUGGEDIN_API_KEY": "your-api-key",
"PLUGGEDIN_BASE_URL": "https://your-domain.com"
}
}
}
}
```
Edit `~/.config/Claude/claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"pluggedin": {
"command": "node",
"args": ["/home/user/pluggedin-mcp/dist/index.js"],
"env": {
"PLUGGEDIN_API_KEY": "your-api-key",
"PLUGGEDIN_BASE_URL": "https://your-domain.com"
}
}
}
}
```
### Other MCP Clients
For Cursor, Cline, or other MCP clients, the configuration pattern is similar:
```json theme={null}
{
"command": "node",
"args": ["path/to/pluggedin-mcp/dist/index.js"],
"env": {
"PLUGGEDIN_API_KEY": "your-api-key"
}
}
```
## Advanced Configuration
### Package Management
Configure package storage and caching:
```env theme={null}
# Package Storage
MCP_PACKAGE_STORE_DIR=/var/mcp-packages
MCP_PNPM_STORE_DIR=/var/mcp-packages/pnpm-store
MCP_UV_CACHE_DIR=/var/mcp-packages/uv-cache
# Cache Settings
MCP_PACKAGE_CACHE_DAYS=30
MCP_PREWARM_COMMON_PACKAGES=true
```
### Isolation Configuration
Configure security isolation for MCP servers:
```env theme={null}
# Isolation Type
MCP_ISOLATION_TYPE=bubblewrap # Options: bubblewrap, firejail, none
MCP_ISOLATION_FALLBACK=firejail # Fallback if primary unavailable
MCP_ENABLE_NETWORK_ISOLATION=false # Per-server network namespaces
```
### Custom Admin Users
Define admin users for special privileges:
```env theme={null}
NEXT_PUBLIC_ADMIN_USERS=admin@example.com,team@example.com
ADMIN_MIGRATION_SECRET=$(openssl rand -base64 32)
```
## Validation Checklist
After configuration, verify your setup:
```bash theme={null}
pnpm db:migrate
```
Start the app and try logging in:
```bash theme={null}
pnpm dev
```
```bash theme={null}
curl http://localhost:3000/health
```
Send a test email through the admin panel
## Environment Variables Reference
For a complete list of all environment variables, see the `.env.example` file in the repository or refer to the [Installation Guide](/quickstart/installation#3-configure-environment-variables).
## Troubleshooting
* Verify PostgreSQL is running: `pg_isready`
* Check connection string format
* Ensure database exists: `psql -l`
* Verify user permissions
* Regenerate NEXTAUTH\_SECRET
* Clear browser cookies
* Verify callback URLs match OAuth provider settings
* Check NEXTAUTH\_URL matches your domain
* Verify API keys match between app and proxy
* Check proxy is running: `curl http://localhost:3000/health`
* Review proxy logs for errors
* Ensure ports are not blocked by firewall
* Verify SMTP credentials
* Check app-specific passwords (Gmail)
* Test connection with telnet/openssl
* Review email server logs
## Next Steps
* [Add MCP Servers](/platform/registry)
* [Configure Security Settings](/security/overview)
* [Set Up Deployment](/deployment/ubuntu-setup)
* [API Integration](/api/reference)
# Installation Guide
Source: https://docs.plugged.in/quickstart/installation
Get started with Plugged.in in minutes
# Installation Guide
Get up and running with Plugged.in quickly. Choose between using our hosted platform or self-hosting the application.
**🚀 Recommended**: Use [Plugged.in Cloud](https://plugged.in) for the fastest setup with zero configuration. The cloud version is fully managed, always up-to-date, and includes all features out of the box.
## Quick Start (Cloud Platform - Recommended)
The fastest way to get started is using our hosted platform at [plugged.in](https://plugged.in). No installation required!
Create your account at [plugged.in/register](https://plugged.in/register)
Install the MCP proxy following the instructions in your dashboard
Browse and add servers from the registry or configure your own
Use the generated configuration with Claude, Cursor, or other MCP clients
## Self-Hosting
For organizations that prefer to host their own instance, follow these comprehensive steps.
### Prerequisites
* Node.js 18+ or 20+
* PostgreSQL 15+ (18+ recommended)
* 2GB+ RAM
* 10GB+ storage
* Redis (for caching)
* SMTP server (for emails)
* S3-compatible storage
### Installation Steps
#### 1. Clone the Repositories
```bash Web Application theme={null}
git clone https://github.com/VeriTeknik/pluggedin-app.git
cd pluggedin-app
```
```bash MCP Proxy theme={null}
git clone https://github.com/VeriTeknik/pluggedin-mcp.git
cd pluggedin-mcp
```
#### 2. Install Dependencies
```bash theme={null}
# Web application
cd pluggedin-app
pnpm install
# MCP Proxy
cd ../pluggedin-mcp
npm install
```
```bash theme={null}
# Web application
cd pluggedin-app
npm install
# MCP Proxy
cd ../pluggedin-mcp
npm install
```
#### 3. Configure Environment Variables
Create a `.env` file in the `pluggedin-app` directory based on `.env.example`:
```bash theme={null}
# Database
DATABASE_URL="postgresql://user:password@localhost:5432/pluggedin"
DATABASE_SSL=false # Set to true for production
DATABASE_SSL_REJECT_UNAUTHORIZED=false # Set to false for self-signed certs
# Authentication
NEXTAUTH_URL="http://localhost:12005"
NEXTAUTH_SECRET="your-secret-key-here" # Generate with: openssl rand -base64 32
NEXT_PUBLIC_APP_URL="http://localhost:12005"
# Encryption (REQUIRED for MCP server configs)
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY="" # Generate with: openssl rand -base64 32
# Feature Flags
ENABLE_RAG=true # Enable document processing
ENABLE_NOTIFICATIONS=true # Enable notification system
ENABLE_EMAIL_VERIFICATION=false # Email verification for new users
```
```bash theme={null}
# Email Server (Optional but recommended)
EMAIL_FROM="noreply@plugged.in"
EMAIL_FROM_NAME="Pluggedin"
EMAIL_REPLY_TO="support@plugged.in"
EMAIL_SERVER_HOST="smtp.example.com"
EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER=""
EMAIL_SERVER_PASSWORD=""
# Email Automation
ENABLE_WELCOME_EMAILS=true
ENABLE_FOLLOW_UP_EMAILS=true
WELCOME_EMAIL_DELAY_MINUTES=5
FOLLOW_UP_2_DAYS=2
FOLLOW_UP_5_DAYS=5
# Unsubscribe Security
UNSUBSCRIBE_TOKEN_SECRET="" # Generate with: openssl rand -base64 32
```
```bash theme={null}
# GitHub OAuth (for registry features)
GITHUB_ID=""
GITHUB_SECRET=""
GITHUB_TOKEN="" # For API calls
GITHUB_CLIENT_ID="" # For registry auth
# Google OAuth
GOOGLE_CLIENT_ID=""
GOOGLE_CLIENT_SECRET=""
# Twitter OAuth
TWITTER_CLIENT_ID=""
TWITTER_CLIENT_SECRET=""
```
```bash theme={null}
# AI Model API Keys (Optional)
ANTHROPIC_API_KEY=""
OPENAI_API_KEY=""
GOOGLE_API_KEY=""
# Registry Configuration
REGISTRY_API_URL="http://localhost:3001"
REGISTRY_INTERNAL_API_KEY="your-secure-internal-api-key"
REGISTRY_AUTH_TOKEN="" # JWT for publishing
# RAG Configuration
RAG_API_URL=""
```
```bash theme={null}
# Admin Configuration
ADMIN_NOTIFICATION_EMAILS="" # Comma-separated admin emails
ADMIN_NOTIFICATION_SEVERITIES="ALERT,CRITICAL"
ADMIN_DAILY_SUMMARY=false
ADMIN_FAILED_LOGIN_THRESHOLD=5
ADMIN_MIGRATION_SECRET=""
NEXT_PUBLIC_ADMIN_USERS="" # Admin user emails
# MCP Resource Limits
MCP_CPU_CORES_MAX=0.5 # 50% of one core
MCP_MEMORY_MAX_MB=512
MCP_IO_READ_MBPS=10
MCP_IO_WRITE_MBPS=5
MCP_PROCESS_TIMEOUT_MS=300000 # 5 minutes
MCP_STARTUP_TIMEOUT_MS=10000 # 10 seconds
# Package Management
MCP_PACKAGE_STORE_DIR="/var/mcp-packages"
MCP_PNPM_STORE_DIR="/var/mcp-packages/pnpm-store"
MCP_UV_CACHE_DIR="/var/mcp-packages/uv-cache"
MCP_PACKAGE_CACHE_DAYS=30
MCP_PREWARM_COMMON_PACKAGES=true
# Isolation Configuration
MCP_ISOLATION_TYPE="bubblewrap" # bubblewrap | firejail | none
MCP_ISOLATION_FALLBACK="firejail"
MCP_ENABLE_NETWORK_ISOLATION=false
# Stripe Payments (Optional)
STRIPE_SECRET_KEY=""
STRIPE_WEBHOOK_SECRET=""
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=""
```
**Security Requirements:**
1. **Generate unique secrets** for each key using `openssl rand -base64 32`
2. **Never commit** actual keys to version control
3. **Use different keys** for NEXTAUTH\_SECRET and UNSUBSCRIBE\_TOKEN\_SECRET
4. **Enable SSL** for production database connections
**Quick secret generation commands:**
```bash theme={null}
# Generate all required secrets at once
echo "NEXTAUTH_SECRET=$(openssl rand -base64 32)"
echo "NEXT_SERVER_ACTIONS_ENCRYPTION_KEY=$(openssl rand -base64 32)"
echo "UNSUBSCRIBE_TOKEN_SECRET=$(openssl rand -base64 32)"
echo "REGISTRY_INTERNAL_API_KEY=$(openssl rand -base64 32)"
```
#### 4. Set Up Database
```bash theme={null}
# Create database
createdb pluggedin
# Run migrations
cd pluggedin-app
pnpm db:migrate
# Optional: Run auth migrations
pnpm db:migrate:auth
```
#### 5. Start the Applications
```bash Development theme={null}
# Terminal 1: Web application
cd pluggedin-app
pnpm dev
# Terminal 2: MCP Proxy
cd pluggedin-mcp
npm run dev
```
```bash Production theme={null}
# Build and start web application
cd pluggedin-app
pnpm build
pnpm start
# Build and start MCP proxy
cd pluggedin-mcp
npm run build
npm start
```
The application will be available at:
* Web Interface: `http://localhost:12005`
* MCP Proxy: `http://localhost:3000`
## Docker Installation (Recommended)
**🐳 Docker is the recommended installation method** - it includes PostgreSQL 18, automatic migrations, and optimized configuration out of the box.
**NEW:** Multi-architecture support! Our Docker images now support both AMD64 (Intel/AMD) and ARM64 (Apple Silicon, AWS Graviton) platforms.
### Option 1: Using Pre-built Images from Docker Hub (Fastest)
**Official multi-arch images are available on Docker Hub!** Automatically works on both AMD64 and ARM64 platforms.
```bash theme={null}
# Docker automatically pulls the correct architecture for your platform
docker pull veriteknik/pluggedin:latest
# Or specific version
docker pull veriteknik/pluggedin:v2.16.0
```
```bash theme={null}
# Download production compose file
curl -O https://raw.githubusercontent.com/VeriTeknik/pluggedin-app/main/docker-compose.production.yml
```
```bash theme={null}
# Create .env file
cat > .env <
```bash theme={null}
docker-compose -f docker-compose.production.yml up -d
```
Open [http://localhost:12005](http://localhost:12005) in your browser
**Supported Architectures:**
* ✅ **AMD64 (x86\_64)** - Intel/AMD processors, most cloud platforms
* ✅ **ARM64 (aarch64)** - Apple Silicon (M1/M2/M3), AWS Graviton, Raspberry Pi 4+
### Option 2: Build from Source
```bash theme={null}
git clone https://github.com/VeriTeknik/pluggedin-app.git
cd pluggedin-app
```
```bash theme={null}
cp .env.example .env
# Edit .env with your configuration (see environment variables section above)
```
```bash theme={null}
docker-compose up --build -d
```
Open [http://localhost:12005](http://localhost:12005) in your browser
### What's Included in Docker Setup
* Next.js 15 application
* Node.js 20 runtime
* MCP proxy integration
* Port 12005 exposed
* PostgreSQL 18-alpine
* Automatic migrations
* Health checks
* Persistent storage
* One-time setup (288 MB)
* Drizzle ORM migrations
* Auto-stops after completion
* Database data
* User uploads
* Application logs
* MCP package cache
### Key Features
* ✅ PostgreSQL 18 (latest stable) with automatic migrations
* ✅ Optimized production build with health checks
* ✅ Persistent volumes for data safety
* ✅ Docker-optimized MCP isolation (no sandboxing overhead)
* ✅ Automatic restarts and health monitoring
### Advanced Docker Configuration
For detailed Docker deployment guides including:
* Production setup with Nginx
* Environment variable configuration
* PostgreSQL upgrade paths
* Backup strategies
* Troubleshooting
See the [Docker Deployment Guide](/deployment/docker).
## MCP Client Configuration
After installation, configure your MCP client to use Plugged.in.
### Claude Desktop
Add to your Claude configuration file:
Location: `~/Library/Application Support/Claude/claude_desktop_config.json`
```json theme={null}
{
"mcpServers": {
"pluggedin": {
"command": "node",
"args": ["/path/to/pluggedin-mcp/dist/index.js"],
"env": {
"PLUGGEDIN_API_KEY": "your-api-key"
}
}
}
}
```
Location: `%APPDATA%\Claude\claude_desktop_config.json`
```json theme={null}
{
"mcpServers": {
"pluggedin": {
"command": "node",
"args": ["C:\\path\\to\\pluggedin-mcp\\dist\\index.js"],
"env": {
"PLUGGEDIN_API_KEY": "your-api-key"
}
}
}
}
```
### Other MCP Clients
Most MCP clients support similar configuration. Key points:
* **Command**: `node` or `npx`
* **Script**: Path to `pluggedin-mcp/dist/index.js`
* **API Key**: Your Plugged.in API key
## Verification
Verify your installation is working:
Navigate to `http://localhost:12005` and verify the page loads
```bash theme={null}
cd pluggedin-app
pnpm db:migrate
```
```bash theme={null}
curl http://localhost:3000/health
```
Open your MCP client and verify it connects to Plugged.in
## Troubleshooting
* Verify PostgreSQL is running
* Check DATABASE\_URL format
* Ensure database exists
* Check user permissions
Change the port in `.env`:
```bash theme={null}
# Change web app port
PORT=3001
# Change MCP proxy port
MCP_PORT=3002
```
* Regenerate NEXTAUTH\_SECRET
* Clear browser cookies
* Check NEXTAUTH\_URL matches your domain
* Verify API key is correct
* Check MCP proxy is running
* Review client configuration path
* Check firewall settings
## Next Steps
* [Configure your installation](/quickstart/configuration)
* [Add MCP servers](/platform/registry)
* [Set up document library](/platform/overview)
* [Review security settings](/security/overview)
## Support
Need help? We're here to assist:
* [GitHub Issues](https://github.com/VeriTeknik/pluggedin-app/issues)
* [Community Discussions](https://github.com/orgs/VeriTeknik/discussions)
* API Support: [api-support@plugged.in](mailto:api-support@plugged.in)
* General Support: [support@plugged.in](mailto:support@plugged.in)
# Changelog
Source: https://docs.plugged.in/releases/changelog
Complete history of changes to the Plugged.in platform
# Changelog
All notable changes to the Plugged.in platform are documented here. The project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Latest Releases
**Current Stable**
Collective Best Practices & Intelligent Memory
Agent Architecture & Vector Search
Major Platform Release
Enhanced Security & Performance
## Version 3.1.x Series
### \[3.1.0] - 2026-03-01
Current Version
#### Added
* **Collective Best Practices (CBP)**
* Privacy-preserving pattern aggregation with HMAC-SHA256
* k-anonymity (k>=3) for community patterns
* Success rate tracking and contextual injection
* Feedback loop for quality improvement
* **Concentric Memory Rings**
* Human cognition-inspired memory architecture
* Five ring types: Fresh, Procedures, Practice, Long-term, Shocks
* Intelligent forgetting with configurable decay engine
* Progressive 3-layer retrieval for token efficiency
* **Claude Code Plugin**
* Native MCP integration with zero configuration
* Memory lifecycle hooks with automatic session management
* 9 built-in skills and 2 agents
* CBP post-error suggestions
* **Shared Vector Infrastructure (pgvector)**
* PostgreSQL pgvector extension for native vector search
* HNSW indexing with cosine distance similarity
* 1536-dimension embeddings via OpenAI or Google Gemini
* **Z-Reports (Session Summaries)**
* End-of-session compressed summaries
* Success rate calculation
* Eligible for promotion to long-term memory
* **New MCP Tools**
* `pluggedin_memory_session_start` / `pluggedin_memory_session_end`
* `pluggedin_memory_observe` / `pluggedin_memory_search` / `pluggedin_memory_details`
* `pluggedin_cbp_query` / `pluggedin_cbp_feedback`
#### Security
* 6 rounds of code review hardening
* HMAC-SHA256 privacy for collective patterns
* Advisory lock-based race condition prevention
* Transaction safety for all memory operations
## Version 3.0.x Series
### \[3.0.0] - 2026-02-01
Major Release
#### Added
* **PAP Agent Protocol & Lifecycle Management**
* Comprehensive framework for autonomous agent lifecycle
* Dual-profile architecture: gRPC (PAP-CP) + JSON-RPC (PAP-Hooks)
* Agent state machine with zombie prevention
* DNS-based identity with Ed25519 signatures
* **Model Router (Unified LLM Gateway)**
* Multi-provider routing: OpenAI, Anthropic, Google, xAI, DeepSeek
* OpenAI-compatible API with JWT authentication
* Per-request cost tracking and model aliases
* **Embedded Vector Search (zvec)**
* In-process vector engine with HNSW indexing
* Multi-format document support with automatic chunking
* Semantic natural language queries
* **Agent Templates & Marketplace**
* Docker-based Kubernetes-native deployment
* Template marketplace with ADL configuration
* Integrated health checks and metrics collection
* **Memory Clipboard System**
* Persistent key-value storage with named and indexed access
* Stack operations with TTL expiration
* Source tracking (UI, SDK, MCP)
* **MCP Proxy Enhancements**
* Streamable HTTP transport for remote servers
* OAuth 2.1 with automatic token refresh
* Sandbox isolation with bubblewrap/firejail
* 13 built-in static tools
* **Official SDKs**
* JavaScript/TypeScript SDK (v1.0.1)
* Python SDK (v1.0.1) with sync/async clients
* Go SDK (v1.0.1) with full type safety
#### Changed
* Platform evolution from MCP management to AI Infrastructure Platform
* 50+ database tables with 3000+ line Drizzle ORM schema
* AES-256-GCM encryption for sensitive configuration fields
## Version 2.12.x Series
### \[2.12.0] - 2024-12-21
Current Version
#### Added
* **Redis-Based Rate Limiting**
* Advanced DDoS protection with Redis
* Intelligent in-memory fallback for Redis failures
* Tiered rate limits for different endpoint types
* IP-based tracking without user-agent to prevent bypasses
* **LRU Cache Implementation**
* Memory-efficient caching with automatic eviction
* Configurable TTL via environment variables
* Periodic cleanup of expired entries
* Prevention of memory leaks with size limits
* **Enhanced Security Features**
* Bcrypt cost factor 14 (16,384 iterations)
* Dynamic CSP nonces per request
* Comprehensive security headers (HSTS, X-Frame-Options, etc.)
* Timing attack prevention with fixed delays
* **Dual Storage Display**
* Library shows both file and RAG vector storage
* Real-time storage metrics with cache invalidation
* Vector embedding dimensions and chunk counts
#### Changed
* Replaced dynamic imports with static imports for faster builds
* Optimized database queries for storage calculations
* Improved error handling with proper fallback mechanisms
#### Fixed
* Storage validation bug (usage vs totalUsage)
* Duplicate generateNonce function definitions
* TypeScript errors in AI documents route
* User\_id format mismatch in RAG storage display
#### Security
* Rate limiting prevents brute force attacks
* Enhanced password hashing for rainbow table resistance
* CSP nonces prevent XSS attacks
* Security headers protect against web vulnerabilities
## Version 2.11.x Series
### \[2.11.1] - 2025-01-18
#### Added
* **AI Search in Document Library**
* Semantic search with natural language queries
* Document names displayed instead of cryptic IDs
* Clickable source documents for instant navigation
* 500ms smart debounce for optimal performance
* Comprehensive answers synthesized from multiple documents
* **Document Versioning UI**
* Complete version history timeline
* Visual diff tracking with additions/deletions
* Model attribution badges for each version
* Version comparison and rollback capabilities
* Change summaries and metadata display
* **Performance Optimizations**
* 68% reduction in bundle size
* 60% reduction in memory usage
* Single useReducer pattern replacing 13 state variables
* Dynamic import caching for heavy components
* Comprehensive memoization with React hooks
#### Fixed
* Document IDs showing instead of human-readable names
* Memory leaks in document preview component
* XSS vulnerabilities with proper DOMPurify implementation
* Null safety issues in document ID handling
#### Changed
* Enhanced RAG service to return document metadata
* Improved useKnowledgeBaseSearch hook with documents array
* Updated AiSearchAnswer component for better UX
## Version 2.10.x Series
### \[2.10.3] - 2025-01-28
#### Security
* Additional security patches
* Updated dependencies
* Enhanced input validation
### \[2.10.2] - 2025-01-27
#### Fixed
* Critical security vulnerabilities
* Performance bottlenecks
### \[2.10.1] - 2025-01-27
#### Fixed
* Post-release bug fixes
* UI consistency improvements
### \[2.10.0] - 2025-01-27
Major Release
#### Security Audit & Performance Overhaul
**Key Highlights:**
* Comprehensive security audit addressing ALL GitHub security scanning findings
* Complete encryption system overhaul
* Enhanced Content Security Policy (CSP)
* Performance optimizations across the entire platform
#### Added
* **Security Enhancements**
* New encryption migration system
* Enhanced password reset flow with secure tokens
* Comprehensive input sanitization
* CSRF protection improvements
* **Performance Improvements**
* Optimized database indexes for 10x faster queries
* Reduced JavaScript bundle size by 40%
* Lazy loading for heavy components
* Improved caching strategies
* **UI/UX Updates**
* Simplified Custom Instructions interface
* Better error messaging
* Enhanced loading states
* Improved mobile responsiveness
#### Changed
* Migrated from bcrypt to argon2 for password hashing
* Standardized error handling across all API endpoints
* Updated all dependencies to latest secure versions
* Refactored authentication flow for better security
#### Fixed
* All critical vulnerabilities identified by CodeQL
* Memory leaks in real-time connections
* Race conditions in concurrent operations
* XSS vulnerabilities in user-generated content
## Version 2.9.x Series
### \[2.9.1-security] - 2025-01-27
#### Security
* Emergency security patch
* Fixed authentication bypass vulnerability
### \[2.9.0] - 2025-01-27
#### UUID Tool Prefixing & Collision Resolution
#### Added
* **Automatic UUID Tool Prefixing**
* Prevents tool name collisions between MCP servers
* Automatic UUID prefix generation
* Backward compatibility maintained
* **Slug Generation System**
* Profile-scoped unique server identifiers
* SEO-friendly URLs for shared servers
* Automatic collision handling
#### Changed
* Enhanced server validation logic
* Improved error messages for duplicate servers
* Optimized database queries for slug operations
#### Fixed
* Tool name collision issues
* CORS handling for external MCP servers
* Authentication checks in server operations
## Version 2.8.x Series
### \[2.8.0] - 2025-01-27
Feature Release
#### AI Document Exchange (RAG v2)
**Revolutionary document management with AI integration:**
#### Added
* **AI Document Creation**
* Direct document generation via AI models
* Support for Markdown, JSON, HTML formats
* Model attribution tracking (provider, name, version)
* Automatic content deduplication
* **Document Versioning**
* Complete version history
* Change diff tracking
* Parent-child relationships
* Rollback capabilities
* **Advanced Search**
* Semantic search using PostgreSQL full-text
* Relevance scoring and ranking
* Filter by AI model, date, tags
* Automatic snippet generation
* **Document Preview System**
* Multi-format viewer (PDF, images, text, code)
* Zoom controls (10%-500%)
* Page navigation for PDFs
* Fullscreen mode
* Metadata sidebar
* **MCP Tools**
* `pluggedin_create_document` - AI document creation
* `pluggedin_search_documents` - Semantic search
* `pluggedin_get_document` - Document retrieval
* `pluggedin_update_document` - Document updates
#### Security
* 10MB content size limit
* Rate limiting (10 requests/hour for AI creation)
* Path traversal protection
* Content sanitization for HTML/Markdown
## Version 2.7.x Series
### \[2.7.0] - 2025-01-26
Feature Release
#### Smart Server Wizard & OAuth Integration
#### Added
* **Smart Server Wizard**
* Multi-step guided server creation
* GitHub ownership verification
* Environment variable detection
* Registry submission integration
* Real-time discovery testing
* **OAuth Support**
* Streamable HTTP OAuth for MCP servers
* Session management with PostgreSQL
* Automatic token cleanup
* Support for GitHub, Google, and more
* **Trending Servers**
* Activity-based trending algorithm
* Real-time metrics tracking
* Installation count tracking
* Enhanced discovery experience
#### Changed
* Simplified registry integration
* Improved error handling
* Enhanced search functionality
* Better transport configuration
#### Security
* Comprehensive Zod validation
* XSS vulnerability fixes
* OAuth token security
* Input sanitization improvements
## Version 2.6.x Series
### \[2.6.2] - 2025-01-03
#### Fixed
* "SSEClientTransport already started" errors
* Connection timeout issues
* Retry logic improvements
### \[2.6.1] - 2025-01-03
#### Added
* SSE transport deprecation warnings
* Auto-migration to Streamable HTTP
* Migration UI for bulk conversion
### \[2.6.0] - 2025-01-03
#### Added
* **High-Performance Package Management**
* 10-100x faster npm installs with pnpm
* Python package management with uv
* Content-addressable storage caching
* **CLI-Style Discovery Toast**
* Terminal-style notifications
* Real-time log streaming
* Color-coded output
## Earlier Versions
### \[2.5.0] - 2024-12-15
#### Added
* Collections management system
* Batch server operations
* Enhanced sharing capabilities
### \[2.4.0] - 2024-12-01
#### Added
* User profiles system
* Following/followers functionality
* Activity feed
### \[2.3.0] - 2024-11-15
#### Added
* Internationalization (6 languages)
* Email notification system
* Rate limiting tiers
### \[2.2.0] - 2024-11-01
#### Added
* RAG v1 implementation
* Document upload system
* Vector search capabilities
### \[2.1.0] - 2024-10-15
#### Added
* Social platform features
* Server sharing
* Public profiles
### \[2.0.0] - 2024-10-01
#### Changed
* Complete platform rewrite
* Migration to Next.js 15
* New UI with Shadcn/UI
### \[1.0.0] - 2024-09-01
#### Added
* Initial MCP proxy implementation
* Basic server management
* Authentication system
## Versioning Policy
Plugged.in follows [Semantic Versioning](https://semver.org/):
* **Major versions (X.0.0)**: Breaking changes
* **Minor versions (0.X.0)**: New features, backward compatible
* **Patch versions (0.0.X)**: Bug fixes and security updates
## Support Lifecycle
| Version | Status | Support Until |
| --------------- | ----------- | ------------------ |
| 3.1.x | **Current** | Active development |
| 3.0.x | Supported | September 2026 |
| 2.12.x | Maintenance | June 2026 |
| 2.10.x - 2.11.x | Maintenance | March 2026 |
| \< 2.10.0 | End of Life | - |
## Migration Guides
* [Migrating to v3.1.0](/releases/v3-1-0#migration-notes)
* [Migrating to v3.0.0](/releases/v3-0-0#migration-notes)
* [Migrating to v2.10.0](/releases/v2-10-0#migration)
* [Migrating to v2.8.0](/releases/v2-8-0#migration)
* [Migrating to v2.7.0](/releases/v2-7-0#migration)
## Reporting Issues
Found a bug or have a feature request?
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
* **Security Issues**: Email [security@plugged.in](mailto:security@plugged.in)
* **Feature Requests**: Use GitHub Discussions
# Version 2.10.0 - Security & Performance
Source: https://docs.plugged.in/releases/v2-10-0
Comprehensive security audit and performance optimizations
# Version 2.10.0 Release Notes
Major Security Release
Performance Improvements
Released: January 27, 2025
## Overview
Version 2.10.0 represents a comprehensive security audit and performance overhaul of the Plugged.in platform. This release addresses ALL critical vulnerabilities identified by GitHub's security scanning tools while delivering significant performance improvements.
## Key Highlights
Complete resolution of all CodeQL findings and security vulnerabilities
40% reduction in bundle size and 10x faster database queries
Migration from bcrypt to argon2 with enhanced key management
Simplified Custom Instructions and better error handling
## Security Enhancements
### Vulnerability Fixes
* **SQL Injection Prevention**: Enhanced parameterized queries across all database operations
* **XSS Protection**: Comprehensive input sanitization and output encoding
* **CSRF Mitigation**: Updated token validation and SameSite cookie attributes
* **Path Traversal**: Fixed file access vulnerabilities in document handling
* **Authentication Bypass**: Resolved session validation weaknesses
* **Sensitive Data Exposure**: Removed logging of sensitive information
* **Dependency Vulnerabilities**: Updated all packages with known CVEs
### Encryption System Overhaul
The entire encryption system has been redesigned for better security:
```typescript theme={null}
// Old system (deprecated)
bcrypt.hash(password, 10)
// New system
argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 65536,
timeCost: 3,
parallelism: 4
})
```
**Migration Features:**
* Automatic migration of existing passwords on next login
* Secure token generation for password resets
* Enhanced session management with rolling tokens
* Encrypted storage for API keys and sensitive configuration
### Content Security Policy
Implemented strict CSP headers:
```http theme={null}
Content-Security-Policy:
default-src 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' wss: https:;
```
## Performance Improvements
### Database Optimizations
Database queries are now up to 10x faster with new indexing strategies.
#### New Indexes Added
```sql theme={null}
-- User lookup optimization
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_username ON users(username);
-- Server discovery optimization
CREATE INDEX idx_servers_profile_uuid ON mcp_servers(profile_uuid);
CREATE INDEX idx_shared_servers_is_public ON shared_servers(is_public);
-- Document search optimization
CREATE INDEX idx_docs_project_profile ON docs(project_uuid, profile_uuid);
CREATE INDEX idx_docs_created_at ON docs(created_at DESC);
```
### Bundle Size Reduction
Achieved 40% reduction in JavaScript bundle size:
Implemented dynamic imports for heavy components
Removed unused code and dependencies
Enabled Brotli compression for static assets
Converted images to WebP format with lazy loading
### Memory Management
* Fixed memory leaks in WebSocket connections
* Implemented connection pooling for database
* Added garbage collection hints for large operations
* Optimized React component re-renders
## New Features
### Simplified Custom Instructions UI
The Custom Instructions interface has been completely redesigned:
* **Cleaner Layout**: Removed clutter and improved spacing
* **Better Validation**: Real-time validation with helpful error messages
* **Auto-save**: Changes are automatically saved as you type
* **Templates**: Pre-built instruction templates for common use cases
### Enhanced Error Handling
Standardized error responses across all API endpoints:
```json theme={null}
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input provided",
"details": {
"field": "email",
"issue": "Invalid email format"
}
},
"timestamp": "2025-01-27T12:00:00Z",
"requestId": "req_abc123"
}
```
### Improved Loading States
* Skeleton loaders for better perceived performance
* Progressive content loading
* Optimistic UI updates
* Background refresh indicators
## Breaking Changes
These changes may require updates to your integrations.
1. **API Authentication**: Bearer tokens now require `Bearer` prefix
2. **Password Requirements**: Minimum 12 characters (up from 8)
3. **Session Duration**: Reduced to 7 days (from 30 days)
4. **Rate Limits**: Stricter limits on authentication endpoints
## Migration Guide
### For Users
No action required. The platform will automatically:
* Migrate your password on next login
* Update your session tokens
* Apply new security settings
### For Developers
```javascript theme={null}
// Old
headers: { 'X-API-Key': apiKey }
// New
headers: { 'Authorization': `Bearer ${apiKey}` }
```
```javascript theme={null}
try {
const response = await api.call();
} catch (error) {
if (error.code === 'RATE_LIMITED') {
// Handle rate limiting
}
}
```
```javascript theme={null}
// Minimum 12 characters, 1 uppercase, 1 lowercase, 1 number
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{12,}$/;
```
### For Self-Hosted Instances
Run the migration script:
```bash theme={null}
# Backup your database first
pg_dump pluggedin_prod > backup.sql
# Run migrations
pnpm db:migrate
# Run encryption migration
pnpm migrate:encryption
# Restart the application
systemctl restart pluggedin
```
## Bug Fixes
* Fixed race conditions in concurrent server discovery
* Resolved memory leaks in real-time connections
* Fixed infinite loop in recursive document processing
* Corrected timezone handling in activity logs
* Fixed file upload size validation
* Resolved OAuth state management issues
* Fixed duplicate notification delivery
* Corrected collection sharing permissions
## Technical Details
### Dependencies Updated
Major dependency updates in this release:
| Package | Old Version | New Version |
| ------------------------- | ----------- | -------------- |
| next | 15.0.0 | 15.5.2 |
| @modelcontextprotocol/sdk | 1.13.1 | 1.17.5 |
| postgres | 3.4.0 | 3.4.7 |
| bcrypt | 5.1.0 | - (removed) |
| argon2 | - | 0.31.2 (added) |
### Performance Metrics
Improvements measured in production:
* **Page Load Time**: 2.1s → 1.2s (43% faster)
* **API Response Time**: 150ms → 45ms (70% faster)
* **Database Queries**: 500ms → 50ms (90% faster)
* **Bundle Size**: 2.4MB → 1.4MB (40% smaller)
* **Memory Usage**: 512MB → 320MB (37% reduction)
## Known Issues
* OAuth redirect may fail on Safari with strict privacy settings
* Large document uploads (>50MB) may timeout on slow connections
* Search indexing may lag during high traffic periods
## Future Improvements
Planned for v2.11.0:
* WebAuthn/Passkey support
* Advanced threat detection
* Real-time collaboration features
* Enhanced mobile app
* GraphQL API endpoint
## Support
For help with this release:
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
* **Security Issues**: [security@plugged.in](mailto:security@plugged.in)
## Acknowledgments
Special thanks to:
* The security research community for responsible disclosure
* Our beta testers for performance testing
* Contributors who helped with the security audit
# Version 2.11.1
Source: https://docs.plugged.in/releases/v2-11-1
AI Search enhancements, document versioning UI, and major performance improvements
# Version 2.11.1 Release Notes
Released on January 18, 2025 - This release brings powerful AI search capabilities to the document library, complete document versioning UI, and significant performance improvements.
## 🎯 Highlights
Semantic search with document name display
Full version history with diff visualization
Major performance optimizations
## ✨ AI Search in Document Library
The document library now features a powerful AI-powered search capability that provides intelligent answers based on your documents.
### Key Features
Switch between traditional keyword search and AI-powered semantic search with a single click. The AI search uses advanced natural language processing to understand the intent behind your queries.
```typescript theme={null}
// Toggle between search modes
const [aiSearchEnabled, setAiSearchEnabled] = useState(false);
```
No more cryptic document IDs! The AI search now displays actual document names as clickable buttons, making it easy to identify and access source documents.
**Before**: `099fdd05...`, `3d7c39a7...`
**After**: `Project Requirements.pdf`, `API Documentation.md`
Get instant AI-generated answers with a 500ms debounce for optimal performance. The system intelligently processes your query and returns relevant information from your documents.
Every AI answer includes clear source attribution with clickable document links. Click any source document to instantly open it in the preview modal.
### How It Works
1. **Enable AI Search**: Click the sparkles icon in the library search bar
2. **Type Your Query**: Enter a natural language question
3. **Get Instant Answers**: AI analyzes your documents and provides relevant answers
4. **Explore Sources**: Click on source documents to view the full content
### Technical Implementation
```typescript theme={null}
// Enhanced askKnowledgeBase with document name fetching
export async function askKnowledgeBase(
userId: string,
query: string,
projectUuid?: string
): Promise<{
answer?: string;
documents?: Array<{ id: string; name: string }>;
sources?: string[];
}>
```
## 📚 Document Versioning UI
Complete user interface for document version management with visual diff tracking.
### Version History Features
* Chronological version display
* Expandable version details
* Visual indicators for current version
* Model attribution badges
* Addition/deletion indicators
* Line-by-line diff visualization
* Change summaries
* Modification highlights
* Select two versions to compare
* Side-by-side diff view
* Merge conflict resolution
* Rollback capabilities
### Version Metadata
Each document version includes:
* **Version Number**: Sequential versioning
* **Created By**: AI model attribution (name, provider, version)
* **Timestamp**: Creation time with relative display
* **Change Summary**: Brief description of modifications
* **Content Diff**: Additions, deletions, and modifications
## ⚡ Performance Optimizations
Major performance improvements across the document preview system.
### Optimization Metrics
| Metric | Before | After | Improvement |
| --------------- | -------- | -------------- | ----------------- |
| Bundle Size | 312KB | 100KB | **68% reduction** |
| Memory Usage | 150MB | 60MB | **60% reduction** |
| State Variables | 13 | 1 (useReducer) | **92% reduction** |
| Re-renders | Frequent | Minimal | **Memoized** |
### Technical Improvements
Replaced 13 individual state variables with a single `useReducer` for centralized state management.
```typescript theme={null}
// Before: 13 useState hooks
// After: Single useReducer
const [state, dispatch] = useReducer(documentReducer, initialState);
```
Implemented dynamic import caching to prevent redundant module loading.
```typescript theme={null}
const importCache: Record = {};
const getDynamicImport = async (key: string, importFn: () => Promise) => {
if (!importCache[key]) {
importCache[key] = await importFn();
}
return importCache[key];
};
```
Comprehensive memoization with `useMemo`, `useCallback`, and `React.memo` for optimal rendering performance.
Implemented React.lazy and Suspense for code splitting and on-demand loading of heavy components.
## 🔧 API Enhancements
### Enhanced RAG Query Response
The RAG API now returns structured data with document metadata:
```json theme={null}
{
"results": "Your AI-generated answer...",
"sources": ["doc1.pdf", "doc2.md"],
"document_ids": ["uuid1", "uuid2"],
"documents": [
{ "id": "uuid1", "name": "Project Requirements.pdf" },
{ "id": "uuid2", "name": "API Documentation.md" }
]
}
```
### New Hooks
**`useKnowledgeBaseSearch`**: Complete hook for AI search functionality
```typescript theme={null}
const {
query,
answer,
documents,
sources,
isLoading,
error,
setQuery,
clearAnswer
} = useKnowledgeBaseSearch();
```
## 🐛 Bug Fixes
* Fixed document ID display showing cryptic identifiers instead of names
* Resolved null safety issues in document ID handling
* Fixed memory leaks in document preview component
* Corrected AbortController cleanup in useEffect hooks
* Fixed XSS vulnerabilities with DOMPurify implementation
## 🌍 Internationalization
All new features include complete translations for:
* English (en)
* Turkish (tr)
* Chinese (zh)
* Hindi (hi)
* Japanese (ja)
* Dutch (nl)
## 🔒 Security Improvements
Important security enhancements in this release
* Enhanced input sanitization with DOMPurify
* Proper cleanup of AbortController to prevent memory leaks
* Type safety improvements replacing `any` types
* Content Security Policy (CSP) headers for preview modal
## 📦 Migration Guide
### For Developers
1. **Update Dependencies**
```bash theme={null}
pnpm update
pnpm install
```
2. **Database Migration**
No database migrations required for this release.
3. **Environment Variables**
No new environment variables required.
### For Users
1. **Clear Browser Cache**: Recommended to ensure all performance optimizations take effect
2. **Refresh Library Page**: The new AI search toggle will appear automatically
3. **Re-index Documents**: Optional but recommended for optimal search performance
## 🚀 What's Next
Looking ahead to v2.12.0:
* Multi-language document support
* Advanced version merging capabilities
* Collaborative document editing
* Enhanced AI model selection for document generation
## 📝 Full Changelog
View the complete list of changes in our [GitHub repository](https://github.com/VeriTeknik/pluggedin-app/releases/tag/v2.11.1).
## 🙏 Acknowledgments
Special thanks to all contributors and the community for their feedback and support in making this release possible.
# Version 2.12.0
Source: https://docs.plugged.in/releases/v2-12-0
Enhanced Security & Performance Release
# Version 2.12.0 - Enhanced Security & Performance
Released: December 2024
## 🎯 Overview
Version 2.12.0 focuses on significant security enhancements and performance optimizations, introducing enterprise-grade rate limiting, efficient caching mechanisms, and comprehensive security hardening across the platform.
## 🚀 Key Features
### Redis-Based Rate Limiting with Intelligent Fallback
* **Advanced DDoS Protection**: Implemented Redis-based rate limiting for all API endpoints
* **Intelligent Fallback**: In-memory fallback mechanism ensures rate limiting continues even during Redis failures
* **Tiered Limits**: Different rate limits for authentication (5/15min), API (60/min), and sensitive operations
* **IP-Based Tracking**: Removed user-agent from rate limit keys to prevent bypass attempts
### LRU Cache Implementation
* **Memory-Efficient Caching**: New Least Recently Used (LRU) cache with automatic eviction
* **Configurable TTL**: Cache time-to-live configurable via `RAG_CACHE_TTL_MS` environment variable
* **Automatic Cleanup**: Periodic cleanup of expired entries every minute
* **Prevents Memory Leaks**: Maximum cache size limits with intelligent eviction strategies
### Enhanced Security Features
* **Password Security**: Upgraded to Bcrypt cost factor 14 (16,384 iterations) for stronger password hashing
* **Dynamic CSP Nonces**: Cryptographically secure Content Security Policy nonces generated per request
* **Security Headers**: Comprehensive headers including HSTS, X-Frame-Options, X-Content-Type-Options
* **Timing Attack Prevention**: Fixed delay added to failed authentication attempts
### Dual Storage Display
* **Comprehensive Storage View**: Library page now shows both file storage and RAG vector storage usage
* **Vector Storage Metrics**: Display embedding dimensions, chunk counts, and estimated storage in MB
* **Real-Time Updates**: Cache invalidation on document operations for accurate storage display
### Performance Optimizations
* **Static Imports**: Replaced dynamic imports with static imports for faster build times
* **Build Performance**: Significant reduction in Next.js build times
* **Database Query Optimization**: Improved query patterns for storage calculations
## 🔧 Technical Improvements
### Code Quality
* **Eliminated Duplication**: Created shared utilities (`rag-storage-utils.ts`) for consistent storage calculations
* **Type Safety**: Fixed all TypeScript errors and improved type definitions
* **Error Handling**: Enhanced error handling with proper fallback mechanisms
### Infrastructure
* **Redis Integration**: Full Redis support with connection pooling and retry strategies
* **Environment Variables**: New configuration options for cache TTL and Redis connection
* **Docker Optimization**: Improved container builds with better dependency management
## 🐛 Bug Fixes
* Fixed storage validation bug using wrong property (`usage` vs `totalUsage`)
* Resolved duplicate `generateNonce` function definitions
* Fixed TypeScript errors in AI documents route
* Corrected type assertions in OpenSource component
* Fixed user\_id format mismatch causing 0 bytes display in RAG storage
## 📝 Configuration Changes
### New Environment Variables
```bash theme={null}
# Redis Configuration (Optional)
REDIS_URL=redis://localhost:6379
# Cache Configuration (Optional)
RAG_CACHE_TTL_MS=60000 # Default: 1 minute
```
### Updated Dependencies
* Added `ioredis` for Redis support
* Security dependency updates
## 🔄 Migration Notes
### For Existing Installations
1. **Optional Redis Setup**: Redis is optional but recommended for production
2. **No Database Changes**: No migrations required
3. **Backward Compatible**: All changes are backward compatible
### Upgrade Steps
```bash theme={null}
# Pull latest changes
git pull origin main
# Install new dependencies
pnpm install
# Build application
pnpm build
# Restart services
pnpm start
```
## 🔐 Security Advisory
This release includes important security improvements:
* Rate limiting prevents brute force attacks
* Enhanced password hashing increases resistance to rainbow table attacks
* CSP nonces prevent XSS attacks
* Security headers protect against various web vulnerabilities
We recommend all users upgrade to v2.12.0 for these security benefits.
## 📊 Performance Metrics
* **Build Time**: \~30% faster with static imports
* **Cache Hit Rate**: \~80% for RAG storage queries
* **Memory Usage**: Stable with LRU cache eviction
* **Rate Limiting**: less than 1 ms overhead per request
## 🙏 Acknowledgments
Thanks to all contributors who helped identify and fix security issues, particularly those reported through our security audit process.
## 📚 Documentation
For detailed documentation on new features:
* [Security Overview](https://docs.plugged.in/security/overview)
* [Rate Limiting Configuration](https://docs.plugged.in/api/authentication)
* [Cache Management](https://docs.plugged.in/platform/performance)
## 🚀 What's Next
In the upcoming releases, we plan to:
* Implement distributed caching with Redis Cluster
* Add more granular rate limiting rules
* Enhance monitoring and alerting capabilities
* Continue security hardening efforts
***
For questions or issues, please visit our [GitHub Discussions](https://github.com/orgs/VeriTeknik/discussions) or contact us at [team@plugged.in](mailto:team@plugged.in).
# Version 2.7.0 - Smart Server Wizard
Source: https://docs.plugged.in/releases/v2-7-0
Comprehensive server creation wizard and OAuth integration
# Version 2.7.0 Release Notes
Feature Release
OAuth Support
Released: January 26, 2025
## Overview
Version 2.7.0 introduces the **Smart Server Wizard**, a comprehensive multi-step guide for creating and configuring MCP servers, along with OAuth integration for streamable HTTP servers and a new trending servers discovery feature.
## Key Features
Multi-step guided server creation with registry submission
Streamable HTTP OAuth support for secure authentication
Activity-based trending algorithm for discovery
Automatic ownership verification for claimed servers
## Smart Server Wizard
### Multi-Step Configuration
The new wizard guides users through server setup:
Choose between registry servers, custom servers, or GitHub imports
Set server name, description, and transport type
Automatic detection and configuration of required variables
Real-time validation of server connectivity
Optional submission to the MCP Registry
### GitHub Ownership Verification
Automatically verify ownership of GitHub-based servers:
```typescript theme={null}
// Verification process
1. User claims server from GitHub repo
2. System checks GitHub API for ownership
3. Verified badge applied to server
4. Enhanced trust in registry
```
### Environment Variable Detection
The wizard automatically detects required environment variables:
```json theme={null}
{
"env": {
"OPENAI_API_KEY": {
"required": true,
"description": "OpenAI API key for AI features"
},
"DATABASE_URL": {
"required": false,
"description": "PostgreSQL connection string"
}
}
}
```
## OAuth Integration
### Streamable HTTP OAuth
Support for OAuth authentication in MCP servers:
```typescript theme={null}
// OAuth configuration
{
"transport": {
"type": "streamable",
"oauth": {
"provider": "github",
"clientId": "your-client-id",
"scopes": ["repo", "user"],
"redirectUri": "https://plugged.in/oauth/callback"
}
}
}
```
### Session Management
OAuth sessions are securely managed with automatic cleanup.
**Features:**
* PostgreSQL session storage
* In-memory caching for performance
* Automatic token refresh
* Session expiry handling
* Secure token storage
### Supported Providers
```json theme={null}
{
"provider": "github",
"scopes": ["repo", "user", "gist"]
}
```
```json theme={null}
{
"provider": "google",
"scopes": ["drive.readonly", "sheets"]
}
```
```json theme={null}
{
"provider": "linear",
"scopes": ["read", "write"]
}
```
```json theme={null}
{
"provider": "custom",
"authorizationUrl": "https://example.com/oauth/authorize",
"tokenUrl": "https://example.com/oauth/token"
}
```
## Trending Servers
### Activity-Based Algorithm
Servers trend based on real-time activity:
```typescript theme={null}
// Trending score calculation
score = (installs * 0.4) +
(views * 0.2) +
(shares * 0.3) +
(recency * 0.1)
```
### Metrics Tracking
* Installation count
* View count
* Share count
* Recent activity
* User engagement
### Discovery Interface
The trending section shows:
* Top 10 trending servers
* Activity sparklines
* Installation badges
* Quick install buttons
## Registry Integration
### Enhanced Submission Process
Automatic validation of server configuration
Secure submission with registry tokens
Real-time submission status updates
Detailed error messages with fixes
### Registry Schema Support
Support for new registry schema format:
```json theme={null}
{
"name": "my-server",
"description": "Server description",
"author": "username",
"transport": {
"type": "streamable",
"baseUrl": "https://api.example.com"
},
"tools": ["tool1", "tool2"],
"resources": ["resource1"],
"prompts": ["prompt1"]
}
```
## Security Enhancements
### Input Validation
Comprehensive Zod schemas for all inputs:
```typescript theme={null}
const serverSchema = z.object({
name: z.string().min(3).max(50),
description: z.string().max(500),
transport: z.union([
streamableSchema,
stdioSchema,
sseSchema
]),
env: z.record(z.string(), envVarSchema).optional()
});
```
### XSS Prevention
Removed all instances of `dangerouslySetInnerHTML`:
```typescript theme={null}
// Before (vulnerable)
// After (secure)
{DOMPurify.sanitize(content)}
```
### OAuth Security
* State parameter validation
* PKCE flow support
* Token encryption at rest
* Automatic token cleanup
* Session hijacking prevention
## UI/UX Improvements
### Wizard Interface
Clear progress through wizard steps
Real-time validation with helpful messages
Progress saved automatically
Contextual help for each field
### Connection Handling
Improved StreamingCliToast:
* Better error messages
* Retry logic
* Connection state indicators
* Timeout handling
## Performance Improvements
### Query Optimization
```sql theme={null}
-- New indexes for trending calculation
CREATE INDEX idx_server_metrics_created ON server_metrics(created_at DESC);
CREATE INDEX idx_server_activity ON servers(install_count, view_count);
-- Optimized trending query
SELECT s.*,
(install_count * 0.4 + view_count * 0.2 + share_count * 0.3) as score
FROM servers s
WHERE created_at > NOW() - INTERVAL '7 days'
ORDER BY score DESC
LIMIT 10;
```
### Bundle Size Reduction
* Removed unused dependencies
* Code splitting for wizard components
* Lazy loading for OAuth providers
## Migration Guide
### Database Updates
```bash theme={null}
# Run migrations for new tables
pnpm db:migrate
# New tables added:
# - oauth_sessions
# - server_metrics
# - github_verifications
```
### API Changes
OAuth endpoints added:
```typescript theme={null}
// Initiate OAuth flow
GET /api/oauth/authorize?provider=github
// OAuth callback
GET /api/oauth/callback?code=xxx&state=yyy
// Token refresh
POST /api/oauth/refresh
```
### Environment Variables
New optional variables:
```env theme={null}
# OAuth providers
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret
# Registry
REGISTRY_API_URL=https://registry.plugged.in
REGISTRY_API_TOKEN=your-token
```
## Bug Fixes
* Fixed OAuth state management race conditions
* Resolved registry submission timeout issues
* Fixed server claiming for community servers
* Corrected environment variable validation
* Fixed LLM provider mapping in playground
* Resolved console.log removal syntax errors
* Fixed transport configuration handling
## Known Issues
* OAuth redirect may fail with strict browser settings
* Large environment variable sets may cause UI lag
* Registry submission may timeout for complex servers
## Future Enhancements
Planned for v2.8.0:
* Advanced OAuth scopes management
* Batch server imports
* Server templates
* Enhanced metrics dashboard
* API rate limiting per OAuth app
## Breaking Changes
SSE transport is now deprecated. Migrate to Streamable HTTP.
1. **SSE Deprecation**: SSE servers show migration warnings
2. **Registry Format**: New schema format required
3. **OAuth Required**: Some servers now require OAuth
## Support
For help with this release:
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
* **Wizard Guide**: [Server Creation Guide](/platform/servers)
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
# Version 2.8.0 - AI Document Exchange
Source: https://docs.plugged.in/releases/v2-8-0
Revolutionary document management with AI model attribution
# Version 2.8.0 Release Notes
Feature Release
RAG v2
Released: January 27, 2025
## Overview
Version 2.8.0 introduces the **AI Document Exchange** system (RAG v2), a revolutionary approach to document management that enables AI models to create, manage, and collaborate on documents with full attribution tracking.
## Key Features
Direct document generation by AI models with attribution
Complete version history with change tracking
Advanced search with relevance scoring
Support for Markdown, JSON, HTML, and more
## AI Document Exchange System
### Document Creation API
AI models can now create documents directly through the API:
```bash theme={null}
POST /api/documents/ai
Authorization: Bearer YOUR_API_KEY
{
"title": "MCP Integration Guide",
"content": "# Complete guide to MCP integration...",
"format": "md",
"metadata": {
"model": {
"name": "Claude 3",
"provider": "Anthropic",
"version": "3.0"
},
"context": "User requested comprehensive MCP guide",
"visibility": "workspace"
},
"tags": ["mcp", "integration", "guide"]
}
```
### Model Attribution
Every AI-generated document tracks complete attribution:
```json theme={null}
{
"document_id": "doc_abc123",
"attributions": [
{
"model_name": "Claude 3",
"model_provider": "Anthropic",
"model_version": "3.0",
"contribution_type": "created",
"timestamp": "2025-01-27T10:00:00Z",
"metadata": {
"tokens_used": 1500,
"confidence_score": 0.95
}
},
{
"model_name": "GPT-4",
"model_provider": "OpenAI",
"contribution_type": "reviewed",
"timestamp": "2025-01-27T11:00:00Z"
}
]
}
```
## Document Management Features
### Version Control
All documents now support complete version history with rollback capabilities.
#### Version Tracking
* Automatic version creation on updates
* Parent-child relationships between versions
* Change diff generation
* Rollback to any previous version
#### Version API
```typescript theme={null}
// Get version history
GET /api/documents/{id}/versions
// Create new version
POST /api/documents/{id}/versions
{
"content": "Updated content",
"changeSummary": "Fixed typos and added examples"
}
// Rollback to version
POST /api/documents/{id}/rollback/{versionId}
```
### Advanced Search
PostgreSQL full-text search with relevance scoring:
```typescript theme={null}
POST /api/documents/search
{
"query": "MCP server configuration",
"filters": {
"modelName": "Claude 3",
"modelProvider": "Anthropic",
"dateFrom": "2025-01-01",
"dateTo": "2025-01-31",
"source": "ai_generated",
"tags": ["mcp", "configuration"]
},
"limit": 10,
"offset": 0
}
```
**Search Features:**
* Semantic relevance scoring
* Automatic snippet generation
* Keyword highlighting
* Filter by AI model, date, tags, source
* Pagination with total count
## Document Preview System
### Multi-Format Viewer
The new document preview modal supports:
* Page navigation
* Zoom controls (10%-500%)
* Text selection
* Search within document
* Pan and zoom
* Rotation controls
* Fullscreen mode
* Format support: PNG, JPG, GIF, WebP, SVG
* Syntax highlighting for 20+ languages
* Line numbers
* Code folding
* Copy to clipboard
* Rendered preview
* Table of contents
* Link navigation
* Embedded media
### Preview Controls
```typescript theme={null}
// Preview component usage
setPreviewOpen(false)}
onNavigate={(direction) => navigateDocument(direction)}
fullscreen={true}
/>
```
## MCP Tools Integration
New MCP tools for document operations:
### pluggedin\_create\_document
Create documents from MCP servers:
```json theme={null}
{
"name": "pluggedin_create_document",
"parameters": {
"title": "API Documentation",
"content": "# API Reference...",
"format": "md",
"category": "documentation",
"tags": ["api", "reference"]
}
}
```
### pluggedin\_search\_documents
Search documents semantically:
```json theme={null}
{
"name": "pluggedin_search_documents",
"parameters": {
"query": "authentication flow",
"limit": 5
}
}
```
### pluggedin\_get\_document
Retrieve specific documents:
```json theme={null}
{
"name": "pluggedin_get_document",
"parameters": {
"documentId": "doc_abc123",
"includeContent": true,
"includeVersions": false
}
}
```
### pluggedin\_update\_document
Update existing documents:
```json theme={null}
{
"name": "pluggedin_update_document",
"parameters": {
"documentId": "doc_abc123",
"operation": "append",
"content": "\n## New Section\nAdditional content..."
}
}
```
## Security Enhancements
### Rate Limiting
* AI document creation: 10 requests per hour
* Document search: 60 requests per minute
* Document updates: 30 requests per minute
### Content Security
All AI-generated content is sanitized before storage.
* HTML/Markdown sanitization
* Path traversal protection
* Content size limit: 10MB
* File type validation
* XSS prevention
### Access Control
```typescript theme={null}
// Document visibility levels
enum Visibility {
PRIVATE = 'private', // Only owner
WORKSPACE = 'workspace', // Project members
PUBLIC = 'public' // Everyone
}
```
## Database Schema Updates
### New Tables
#### document\_versions
```sql theme={null}
CREATE TABLE document_versions (
id UUID PRIMARY KEY,
document_id UUID REFERENCES docs(id),
version_number INTEGER,
content TEXT,
content_hash VARCHAR(64),
change_summary TEXT,
created_at TIMESTAMP,
created_by UUID REFERENCES users(id)
);
```
#### document\_model\_attributions
```sql theme={null}
CREATE TABLE document_model_attributions (
id UUID PRIMARY KEY,
document_id UUID REFERENCES docs(id),
model_name VARCHAR(255),
model_provider VARCHAR(255),
model_version VARCHAR(50),
contribution_type VARCHAR(50),
metadata JSONB,
created_at TIMESTAMP
);
```
### Updated docs Table
New fields added:
* `source`: 'upload' | 'ai\_generated' | 'api'
* `ai_metadata`: JSONB for AI-specific data
* `content_hash`: SHA-256 hash for deduplication
* `visibility`: Document visibility level
* `version`: Current version number
* `parent_document_id`: For version relationships
## UI Enhancements
### Library Interface
Filter documents by source (Uploaded, AI Generated, API)
Visual indicators for AI-generated content
Real-time upload and processing progress
Instant document preview in modal
### Upload Progress
Enhanced progress tracking shows:
* Text extraction progress
* Chunking progress
* Embedding generation
* Database insertion
* Estimated time remaining
## Migration Guide
### Database Migration
Run the migration script:
```bash theme={null}
# Run new migrations
pnpm db:migrate
# The migration adds:
# - document_versions table
# - document_model_attributions table
# - New fields to docs table
```
### API Updates
Update your API calls to include model metadata:
```javascript theme={null}
// Old API call
await createDocument({
title: "My Document",
content: "Content here"
});
// New API call with attribution
await createDocument({
title: "My Document",
content: "Content here",
metadata: {
model: {
name: "Claude 3",
provider: "Anthropic",
version: "3.0"
}
}
});
```
## Performance Improvements
* Optimized search queries with new indexes
* Lazy loading for document previews
* Content deduplication reduces storage by 30%
* Streaming support for large documents
## Known Issues
* PDF preview may be slow for documents >100 pages
* Search relevance scoring needs tuning for short queries
* Version diff generation slow for very large documents
## Future Enhancements
Planned for future releases:
* Real-time collaborative editing
* Document templates
* Advanced version merging
* AI-powered document summarization
* Export to multiple formats
## Support
For help with RAG v2 features:
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
* **API Reference**: [API Documentation](/api/reference)
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
# Version 3.0.0
Source: https://docs.plugged.in/releases/v3-0-0
Major Platform Release — Agent Architecture, Embedded Vector Search & Universal MCP Hub
# Version 3.0.0 - Major Platform Release
Released: February 2026
## Overview
Version 3.0.0 is a major milestone that transforms plugged.in from an MCP management platform into a comprehensive AI Infrastructure Platform with autonomous agent lifecycle management, embedded vector search, and universal tool orchestration.
## Key Features
### PAP Agent Protocol & Lifecycle Management
* **Plugged.in Agent Protocol (PAP)**: Comprehensive framework for autonomous agent lifecycle management
* **Dual-Profile Architecture**: gRPC control plane (PAP-CP) + JSON-RPC I/O plane (PAP-Hooks)
* **Agent State Machine**: NEW -> PROVISIONED -> ACTIVE -> DRAINING -> TERMINATED lifecycle
* **Zombie Prevention**: Strict heartbeat/metrics separation prevents control plane saturation
* **DNS-Based Identity**: Verifiable agent identities via `{agent}.{region}.a.plugged.in`
* **Ed25519 Signatures**: All control plane messages cryptographically signed
### Model Router (Unified LLM Gateway)
* **Multi-Provider Routing**: OpenAI, Anthropic, Google, xAI, DeepSeek support
* **OpenAI-Compatible API**: Drop-in replacement for any OpenAI SDK
* **JWT Authentication**: Per-agent token generation with 1-year expiry
* **Cost Tracking**: Per-request cost and latency headers
* **Model Aliases**: `claude` -> `claude-sonnet-4`, `gemini` -> `gemini-2.0-flash`
### Embedded Vector Search (zvec)
* **In-Process Vector Engine**: No external vector database needed
* **HNSW Indexing**: High-recall approximate nearest neighbor search
* **Multi-Format Document Support**: PDF, TXT, Markdown with automatic chunking
* **Semantic Search**: Natural language queries across your knowledge base
### Agent Templates & Marketplace
* **Docker-Based Deployment**: Kubernetes-native agent deployment
* **Template Marketplace**: Browse, install, and configure agent templates
* **ADL Configuration**: Agent Description Language for configurable agents
* **Health Monitoring**: Integrated health checks and metrics collection
### Memory Clipboard System
* **Persistent Key-Value Storage**: Named and indexed access patterns
* **Stack Operations**: Push/pop for sequential processing
* **TTL Expiration**: Automatic cleanup with configurable TTL
* **Source Tracking**: Track whether entries came from UI, SDK, or MCP
### MCP Proxy Enhancements
* **Streamable HTTP Transport**: Modern HTTP streaming for remote MCP servers
* **OAuth 2.1 Integration**: Automatic token refresh with 15-minute pre-expiry rotation
* **Sandbox Isolation**: bubblewrap/firejail for STDIO server sandboxing
* **13 Built-in Static Tools**: Discover, search, clipboard, documents, notifications
### Official SDKs
* **JavaScript/TypeScript SDK** (v1.0.1): Full-featured with TypeScript types
* **Python SDK** (v1.0.1): Sync and async clients with Pydantic models
* **Go SDK** (v1.0.1): Full type safety with Go 1.24+
## Technical Details
* **50+ Database Tables**: Comprehensive schema with 3000+ line Drizzle ORM definition
* **6 Languages**: English, Turkish, Chinese, Hindi, Japanese, Dutch
* **Rate Limiting**: Tiered Redis-backed with in-memory fallback
* **AES-256-GCM Encryption**: For all sensitive configuration fields
## Migration Notes
### From v2.x
1. Pull latest changes and install dependencies
2. Run database migrations: `pnpm db:generate && pnpm db:migrate`
3. Configure new environment variables for agent features (optional)
4. No breaking changes to existing MCP server configurations
### New Environment Variables
```bash theme={null}
# Model Router (required for agents)
MODEL_ROUTER_JWT_SECRET=
# Feature Flags (optional)
ENABLE_RAG=true
ENABLE_NOTIFICATIONS=true
```
### Upgrade Steps
```bash theme={null}
# Pull latest changes
git pull origin main
# Install dependencies
pnpm install
# Generate and apply database migrations
pnpm db:generate
pnpm db:migrate
# Build and restart
pnpm build
pnpm start
```
## What's Next
* Collective Best Practices system (v3.1.0)
* Long-term memory with intelligent forgetting
* Claude Code native plugin
***
For questions or issues, please visit our [GitHub Discussions](https://github.com/orgs/VeriTeknik/discussions) or contact us at [team@plugged.in](mailto:team@plugged.in).
# Version 3.1.0
Source: https://docs.plugged.in/releases/v3-1-0
Collective Best Practices, Intelligent Memory & Claude Code Plugin
# Version 3.1.0 - Collective Best Practices & Intelligent Memory
Released: March 2026
## Overview
Version 3.1.0 introduces the Collective Best Practices (CBP) system, a human cognition-inspired intelligent memory architecture, shared vector infrastructure with pgvector, and a native Claude Code plugin.
## Key Features
### Claude Code Plugin
* **Native MCP Integration**: All plugged.in tools, knowledge base, memory, and notifications available directly in Claude Code
* **Zero Configuration**: Add via `.mcp.json` with just your API key
* **Memory Lifecycle Hooks**: Automatic session management -- start on session begin, Z-reports on end
* **Pre-Compaction Context**: Relevant memories injected before context window compaction
* **9 Built-in Skills**: Memory search, extraction, workflow, status, RAG context, setup, and more
* **2 Agents**: Memory curator for classification, focus assistant for working set management
* **CBP Post-Error Suggestions**: Automatic community pattern suggestions after tool errors
### Collective Best Practices (CBP)
* **Privacy-Preserving Pattern Aggregation**: Learns from all users while protecting individual data
* **HMAC-SHA256 Pattern Hashing**: Patterns normalized and hashed -- never stored in plaintext
* **k-Anonymity (k>=3)**: Patterns only shared when observed by 3+ unique profiles
* **Success Rate Tracking**: Community patterns ranked by effectiveness
* **Contextual Injection**: Relevant CBP patterns automatically suggested during sessions
* **Feedback Loop**: Users can confirm or reject CBP suggestions to improve quality
### Concentric Memory Rings
Human cognition-inspired memory architecture with five ring types:
* **Fresh Memory**: Observation buffer with auto-classification and embedding
* **Procedures**: Repeatable workflows, how-tos, step-by-step guides
* **Practice/Habits**: Successful patterns reinforced through repetition
* **Long-term**: Validated insights requiring success\_score >= 0.7
* **Shocks**: Critical failures that bypass decay -- never forgotten
### Intelligent Forgetting (Decay Engine)
Token economics of forgetting inspired by human memory:
| Stage | Tokens | Time to Next |
| ---------- | ------ | ------------ |
| FULL | \~500 | 7 days |
| COMPRESSED | \~250 | 30 days |
| SUMMARY | \~150 | 90 days |
| ESSENCE | \~50 | 365 days |
| FORGOTTEN | 0 | Deleted |
Exceptions: Shocks never decay, frequently accessed memories decay slower, low-success memories decay faster.
### Shared Vector Infrastructure (pgvector)
* **PostgreSQL pgvector Extension**: Native vector search without external services
* **HNSW Indexing**: High-recall cosine distance similarity search
* **1536-Dimension Embeddings**: Using `text-embedding-3-small` via OpenAI or Google Gemini
* **AI Provider Abstraction**: Automatic routing between OpenAI and Google embedding providers
### Progressive Retrieval (3-Layer)
Token-efficient memory access inspired by claude-mem:
* **Layer 1 (Search)**: Returns `content_essence` or `content_summary` (50-150 tokens each)
* **Layer 2 (Timeline)**: Adds temporal context -- when, which session, related observations
* **Layer 3 (Full Details)**: Returns `content_full` only for selected memories
### Z-Reports (Session Summaries)
End-of-session compressed summaries (inspired by retail Z-reports):
* Summary text with key observations
* Decisions made and tools used
* Success rate calculation (0.0-1.0)
* Z-reports eligible for promotion to long-term memory
### New MCP Tools
| Tool | Description |
| -------------------------------- | -------------------------------------- |
| `pluggedin_memory_session_start` | Start a memory session |
| `pluggedin_memory_session_end` | End session + trigger Z-report |
| `pluggedin_memory_observe` | Record an observation during a session |
| `pluggedin_memory_search` | Search memories (layer 1 progressive) |
| `pluggedin_memory_details` | Get full memory details (layer 3) |
| `pluggedin_cbp_query` | Query collective best practices |
| `pluggedin_cbp_feedback` | Submit feedback on CBP suggestions |
## Database Changes
4 new tables added:
* `memory_sessions` -- Session tracking with Z-reports
* `fresh_memory` -- Observation buffer with vector embeddings
* `memory_ring` -- Unified long-term store for all ring types
* `gut_patterns` -- Collective wisdom (NOT profile-scoped, k-anonymous)
## Migration Notes
### Upgrade Steps
```bash theme={null}
# Pull latest and install
git pull origin main
pnpm install
# Generate and apply migrations
pnpm db:generate
pnpm db:migrate
# The migration automatically enables the pgvector extension
```
### New Environment Variables (Optional)
```bash theme={null}
# Memory Configuration
MEMORY_EMBEDDING_MODEL=text-embedding-3-small
MEMORY_DECAY_CRON_ENABLED=true
MEMORY_ANALYTICS_BATCH_SIZE=50
MEMORY_EMBEDDING_DIMENSION=1536
```
## Security
* 6 rounds of code review hardening (PR #138)
* HMAC-SHA256 privacy for collective patterns
* k-anonymity threshold enforcement
* Advisory lock-based race condition prevention
* Transaction safety for all memory operations
## What's Next
* Full memory UI (Fresh, Long-term, Procedures tabs)
* Advanced analytics dashboard
* Cross-agent memory sharing
* Memory export/import
***
For questions or issues, please visit our [GitHub Discussions](https://github.com/orgs/VeriTeknik/discussions) or contact us at [team@plugged.in](mailto:team@plugged.in).
# Version 3.2.0
Source: https://docs.plugged.in/releases/v3-2-0
Jungian Intelligence Layer — Psychology-Inspired Memory Subsystems
# Version 3.2.0 - Jungian Intelligence Layer
Released: March 2026
## Overview
Version 3.2.0 introduces the **Jungian Intelligence Layer**, four psychology-inspired subsystems that transform raw memory data into meaningful, context-aware intelligence. Built on top of the concentric memory rings (v3.1.0) and Collective Best Practices, this release adds temporal pattern detection, archetype-driven pattern delivery, automatic memory consolidation, and per-profile maturity scoring.
The Jungian Intelligence Layer is named after Carl Jung's analytical psychology. Each subsystem maps to a Jungian concept: **Archetypes** classify patterns, **Synchronicity** discovers meaningful coincidences, **Dreams** consolidate memories, and **Individuation** measures growth toward self-realization.
## Key Features
### 1. Synchronicity Detection
Discovers temporal co-occurrence patterns across anonymized profiles using pure SQL analysis -- no LLM calls required. Three analysis types operate on the `temporal_events` table:
* **Co-occurrence**: Tools that are frequently used together within a 5-minute window
* **Failure Correlation**: Tools that tend to fail at specific times (day-of-week and hour-of-day clustering)
* **Emergent Workflows**: Three-tool sequential patterns that recur across 3+ profiles
Patterns that pass the k-anonymity threshold (k >= 3 unique profiles) are stored in `gut_patterns` with `pattern_type='synchronicity'` and embedded for vector search.
**Privacy**: Only `profile_hash` (HMAC-SHA256) is stored in temporal events -- raw UUIDs never touch the table. Events are retained for 90 days by default.
### 2. Archetype-Driven Pattern Delivery
Wraps the existing CBP injection engine with Jungian archetype filtering. Each pattern is classified into one of four archetypes:
| Archetype | Label | Pattern Types | When Dominant |
| ------------- | ----------------- | ---------------------------------------------------------------------- | --------------------------- |
| **Shadow** | Shadow Warning | `anti_pattern`, `security_warning`, `gotcha` | Error/failure contexts |
| **Sage** | Sage Advice | `best_practice`, `error_solution`, `performance_tip`, `migration_note` | Default (knowledge sharing) |
| **Hero** | Hero Path | `workflow`, `tool_sequence`, `migration_note` | Workflow/tool contexts |
| **Trickster** | Trickster Insight | `gotcha`, `compatibility`, `error_recovery` | 2+ consecutive failures |
Archetype selection is **fully deterministic** -- context fields (outcome, observation type, consecutive failures) are mapped to weights without any LLM call. Patterns are then sorted by `archetypeWeight * confidence * similarity` and capped at 2 per archetype.
### 3. Dream Processing (Memory Consolidation)
Discovers clusters of semantically similar memories and consolidates them into single unified memories via LLM, reducing token consumption while preserving all key insights.
**Three-phase pipeline:**
1. **Cluster Discovery** (no LLM): Uses vector embeddings and Union-Find to identify connected components of memories with cosine similarity >= 0.75
2. **LLM Consolidation**: Each cluster is fed to a compression-tuned LLM that merges redundant content into one coherent memory (max 300 output tokens)
3. **Transactional Storage**: New consolidated memory, dream record, and source cluster marking all happen in a single database transaction
Source memories are **not deleted** -- they continue to decay naturally through the existing decay engine. Dream processing is integrated into the decay cron; no separate job is needed.
### 4. Individuation Scoring
Per-profile maturity scoring with four components (each 0-25, total 0-100), calculated via pure SQL with in-memory caching:
| Component | What It Measures | Max |
| --------------------------- | ------------------------------------------------------------------- | --- |
| **Memory Depth** | Ring diversity + decay survival + shock recovery | 25 |
| **Learning Velocity** | Weekly observation rate + classification confidence + reinforcement | 25 |
| **Collective Contribution** | CBP patterns promoted + pattern diversity + feedback given | 25 |
| **Self-Awareness** | Memory search usage + memory engagement + dream consolidation count | 25 |
**Five maturity levels:**
| Level | Score Range | Description |
| ------------ | ----------- | ---------------------------- |
| Nascent | 0-20 | Just getting started |
| Developing | 21-40 | Building initial patterns |
| Established | 41-60 | Consistent memory usage |
| Mature | 61-80 | Deep, diverse knowledge base |
| Individuated | 81-100 | Full self-realization |
Daily snapshots are saved automatically at session start for trend tracking. Weekly trends are calculated as `accelerating`, `stable`, or `decelerating` by comparing recent vs. older snapshot averages.
## Ecosystem Updates
### New Database Tables
| Table | Purpose |
| ------------------------- | -------------------------------------------------------- |
| `temporal_events` | Anonymized tool usage events for synchronicity detection |
| `dream_consolidations` | Records of cluster-to-memory consolidations |
| `individuation_snapshots` | Daily per-profile individuation score snapshots |
### New API Endpoints
| Endpoint | Method | Description |
| ------------------------------------- | ------ | --------------------------------------------------------------- |
| `/api/memory/temporal-events` | POST | Batch write temporal events |
| `/api/memory/temporal-events/cleanup` | POST | Cleanup events older than retention period |
| `/api/memory/sync/detect` | POST | Trigger synchronicity detection |
| `/api/memory/sync/patterns` | GET | Retrieve detected synchronicity patterns |
| `/api/memory/dream/process` | POST | Trigger dream processing for current profile |
| `/api/memory/dream/history` | GET | Get dream consolidation history |
| `/api/memory/archetype/inject` | POST | Archetype-enhanced pattern search |
| `/api/memory/individuation` | GET | Get individuation score (with optional `?history=true&days=30`) |
### New SDK Methods
Available in all three official SDKs (JavaScript, Python, Go):
| Method | Description |
| ----------------------------------------------- | -------------------------------------------------- |
| `searchWithContext(query, toolName?, outcome?)` | Archetype-aware memory search |
| `getIndividuationScore()` | Get current individuation score and maturity level |
| `getIndividuationHistory(days?)` | Get score history for trend visualization |
| `getSynchronicityPatterns()` | Retrieve detected synchronicity patterns |
| `getDreamHistory()` | Get dream consolidation history |
### New MCP Tools
| Tool | Description |
| -------------------------------------- | ----------------------------------------------------------------- |
| `pluggedin_memory_search_with_context` | Search memories with archetype-aware context (tool name, outcome) |
| `pluggedin_memory_individuation` | Get individuation score with maturity level and improvement tips |
## Environment Variables
All new settings have sensible defaults and are optional:
```bash theme={null}
# Synchronicity Detector
SYNC_RETENTION_DAYS=90
SYNC_COOCCURRENCE_WINDOW_DAYS=30
SYNC_COOCCURRENCE_GAP_MINUTES=5
SYNC_FAILURE_WINDOW_DAYS=90
SYNC_WORKFLOW_WINDOW_DAYS=30
SYNC_WORKFLOW_GAP_MINUTES=15
SYNC_MIN_EVENTS_THRESHOLD=10
SYNC_CRON_ENABLED=true
# Dream Processing
DREAM_ENABLED=true
DREAM_MIN_CLUSTER_SIZE=3
DREAM_SIMILARITY_THRESHOLD=0.75
DREAM_MAX_CLUSTERS_PER_RUN=10
DREAM_CONSOLIDATION_MAX_INPUT_TOKENS=1500
DREAM_COOLDOWN_DAYS=7
# Archetype Router
ARCHETYPE_ENABLED=true
ARCHETYPE_MAX_PATTERNS_PER_TYPE=2
ARCHETYPE_SHADOW_BOOST=1.2
ARCHETYPE_SAGE_BOOST=1.1
# Individuation Metrics
INDIVIDUATION_ENABLED=true
INDIVIDUATION_CACHE_TTL_MINUTES=60
INDIVIDUATION_HISTORY_DAYS=90
```
## Migration Notes
### Upgrade Steps
```bash theme={null}
# Pull latest and install
git pull origin main
pnpm install
# Generate and apply migrations
pnpm db:generate
pnpm db:migrate
# No additional setup required -- all features are enabled by default
```
### Breaking Changes
None. All new features are additive and backward compatible. The existing memory API, MCP tools, and injection engine continue to work unchanged. Archetype routing enriches existing patterns without altering their underlying data.
## Security
* **Temporal events** store only `profile_hash` (HMAC-SHA256), never raw UUIDs
* **Synchronicity patterns** enforce k-anonymity (k >= 3) before surfacing
* **Advisory locks** prevent concurrent synchronicity detection or dream processing runs
* **Dream consolidation prompt** includes explicit anti-injection instructions
* **Individuation scores** are profile-scoped and cached in-memory (not shared)
## What's Next
* Jungian Intelligence UI dashboard with archetype visualizations
* Cross-agent synchronicity detection
* Dream processing analytics and token savings reports
* Individuation leaderboards (opt-in, anonymized)
***
For questions or issues, please visit our [GitHub Discussions](https://github.com/orgs/VeriTeknik/discussions) or contact us at [team@plugged.in](mailto:team@plugged.in).
# Go SDK
Source: https://docs.plugged.in/sdks/go
Official Go SDK for the Plugged.in Library API with context support
# Go SDK
[](https://pkg.go.dev/github.com/veriteknik/pluggedinkit-go)
[](https://opensource.org/licenses/MIT)
The official Go SDK for interacting with Plugged.in's Library API. Features context-aware operations, comprehensive error handling, and full type safety.
View on pkg.go.dev
Source code and examples
## Installation
```bash theme={null}
go get github.com/veriteknik/pluggedinkit-go
```
### Requirements
* Go 1.18 or higher
* No external dependencies beyond the standard library
## Quick Start
```go theme={null}
package main
import (
"context"
"fmt"
"log"
pluggedin "github.com/veriteknik/pluggedinkit-go"
)
func main() {
// Initialize client
client := pluggedin.NewClient("your-api-key")
// For local development:
// client := pluggedin.NewClientWithOptions("your-api-key", "http://localhost:12005", nil)
ctx := context.Background()
// List documents
docs, err := client.Documents.List(ctx, &pluggedin.DocumentFilters{
Source: pluggedin.SourceAll,
Limit: 10,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d documents\n", docs.Total)
// Search documents
results, err := client.Documents.Search(ctx, "machine learning", nil, 10, 0)
if err != nil {
log.Fatal(err)
}
for _, result := range results.Results {
fmt.Printf("%s - Relevance: %.2f\n", result.Title, result.RelevanceScore)
}
// Query RAG
answer, err := client.RAG.AskQuestion(ctx, "What are the main features?")
if err != nil {
log.Fatal(err)
}
fmt.Println(answer)
}
```
## Authentication
Get your API key from your [Plugged.in Profile](https://plugged.in/profile/settings):
```go theme={null}
import (
"os"
pluggedin "github.com/veriteknik/pluggedinkit-go"
)
// Using environment variables (recommended)
client := pluggedin.NewClient(os.Getenv("PLUGGEDIN_API_KEY"))
// With custom configuration
import (
"net/http"
"time"
)
httpClient := &http.Client{
Timeout: 120 * time.Second,
}
client := pluggedin.NewClientWithOptions(
os.Getenv("PLUGGEDIN_API_KEY"),
os.Getenv("PLUGGEDIN_BASE_URL"),
httpClient,
)
// Update API key at runtime
client.SetAPIKey("new-api-key")
// Change base URL
client.SetBaseURL("http://localhost:12005")
```
## Core Features
### Document Management
#### List Documents
```go theme={null}
filters := &pluggedin.DocumentFilters{
Source: pluggedin.SourceAIGenerated,
Tags: []string{"report", "analysis"},
Category: pluggedin.CategoryDocumentation,
Sort: pluggedin.SortDateDesc,
Limit: 20,
Offset: 0,
ModelProvider: "anthropic",
}
// Time filters
from := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
to := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)
filters.DateFrom = &from
filters.DateTo = &to
response, err := client.Documents.List(ctx, filters)
if err != nil {
log.Fatal(err)
}
for _, doc := range response.Documents {
fmt.Printf("%s (%d bytes)\n", doc.Title, doc.FileSize)
fmt.Printf(" Created: %s\n", doc.CreatedAt)
fmt.Printf(" Tags: %v\n", doc.Tags)
}
```
#### Get Document
```go theme={null}
// Get document metadata only
doc, err := client.Documents.Get(ctx, "document-id", false, false)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Title: %s\n", doc.Title)
fmt.Printf("Version: %d\n", doc.Version)
// Get document with content and version history
docWithContent, err := client.Documents.Get(ctx, "document-id", true, true)
if err != nil {
log.Fatal(err)
}
fmt.Println(docWithContent.Content)
// Check last access time
if docWithContent.LastAccessAt != nil {
fmt.Printf("Last accessed: %s\n", *docWithContent.LastAccessAt)
}
```
#### Search Documents
```go theme={null}
filters := map[string]interface{}{
"modelProvider": "anthropic",
"dateFrom": "2024-01-01T00:00:00Z",
"tags": "finance,q4",
}
results, err := client.Documents.Search(ctx, "quarterly report", filters, 10, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found %d results for query: %s\n", results.Total, results.Query)
for _, result := range results.Results {
fmt.Printf("\n%s\n", result.Title)
fmt.Printf(" Document ID: %s\n", result.DocumentID)
fmt.Printf(" Relevance: %.2f\n", result.RelevanceScore)
fmt.Printf(" Snippet: %s\n", result.Snippet)
fmt.Printf(" Tags: %v\n", result.Tags)
}
```
#### Create AI-Generated Document
```go theme={null}
request := &pluggedin.CreateDocumentRequest{
Title: "API Integration Guide",
Content: "# API Integration Guide\n\n## Introduction\n\n...",
Metadata: map[string]interface{}{
"format": "md",
"category": "documentation",
"tags": []string{"api", "guide"},
"model": map[string]string{
"name": "claude-3-opus",
"provider": "anthropic",
"version": "20240229",
},
"prompt": "Create an API integration guide",
"visibility": "workspace",
},
}
doc, err := client.Documents.Create(ctx, request)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created document: %s\n", doc.ID)
fmt.Printf("Version: %d\n", doc.Version)
```
#### Update Document
```go theme={null}
request := &pluggedin.UpdateDocumentRequest{
Operation: pluggedin.OpAppend,
Content: "\n\n## New Section\n\nAdditional content here.",
Metadata: map[string]interface{}{
"changeSummary": "Added implementation details section",
"model": map[string]string{
"name": "gpt-4",
"provider": "openai",
"version": "0613",
},
},
}
response, err := client.Documents.Update(ctx, "document-id", request)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Updated to version %d\n", response.Version)
fmt.Printf("Updated at: %s\n", response.UpdatedAt)
```
#### Delete Document
```go theme={null}
err := client.Documents.Delete(ctx, "document-id")
if err != nil {
log.Fatal(err)
}
fmt.Println("Document deleted successfully")
```
### RAG Operations
#### Simple Query
```go theme={null}
// Basic question answering
answer, err := client.RAG.AskQuestion(ctx, "What are the deployment procedures?")
if err != nil {
log.Fatal(err)
}
fmt.Println("Answer:", answer)
// Check availability
status, err := client.RAG.CheckAvailability(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("RAG Available: %v\n", status["available"])
// Get storage statistics
stats, err := client.RAG.GetStorageStats(ctx, "user-id-from-dashboard")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Documents: %d\n", stats.DocumentsCount)
fmt.Printf("Estimated storage: %.2f MB\n", stats.EstimatedStorageMB)
```
#### Query with Sources
```go theme={null}
result, err := client.RAG.QueryWithSources(
ctx,
"Explain the authentication flow",
"",
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Answer: %s\n", result.Answer)
fmt.Println("\nSources:")
for index, source := range result.Sources {
var documentID string
if index < len(result.DocumentIDs) {
documentID = result.DocumentIDs[index]
}
fmt.Printf("- %s (%s)\n", source, documentID)
}
```
#### Find Relevant Documents
```go theme={null}
documents, err := client.RAG.FindRelevantDocuments(
ctx,
"user authentication",
"",
5, // Top 5 documents
)
if err != nil {
log.Fatal(err)
}
for _, doc := range documents {
fmt.Printf("- %s (%s)\n", doc.Source, doc.DocumentID)
}
```
### File Uploads
> **Important:** The Go SDK no longer exposes binary upload helpers. All previous
> upload functions now return descriptive errors so legacy code fails fast.
> Continue using `DocumentsService.Create` for AI-generated content and the
> Plugged.in web interface (or forthcoming ingestion tools) for binary files.
## Error Handling
The SDK provides typed error structs for comprehensive error handling:
```go theme={null}
doc, err := client.Documents.Get(ctx, "invalid-id", false, false)
if err != nil {
switch e := err.(type) {
case *pluggedin.AuthenticationError:
fmt.Println("Invalid API key - please check your credentials")
// Refresh API key logic
case *pluggedin.RateLimitError:
fmt.Printf("Rate limited. Retry after %d seconds\n", e.RetryAfter)
// Implement retry with backoff
time.Sleep(time.Duration(e.RetryAfter) * time.Second)
case *pluggedin.NotFoundError:
fmt.Printf("Document not found: %s\n", e.ID)
// Handle missing document
case *pluggedin.ValidationError:
fmt.Printf("Validation error on field '%s': %s\n", e.Field, e.Message)
// Fix validation issues
case *pluggedin.APIError:
fmt.Printf("API error (%d): %s\n", e.StatusCode, e.Message)
if e.Details != nil {
fmt.Printf("Details: %v\n", e.Details)
}
default:
fmt.Printf("Unexpected error: %v\n", err)
}
}
```
## PAP Agents
The SDK provides full support for managing PAP (Plugged.in Agent Protocol) agents:
### Creating Agents
```go theme={null}
result, err := client.Agents.Create(ctx, pluggedinkit.CreateAgentRequest{
Name: "my-agent",
Description: stringPtr("My autonomous PAP agent"),
Resources: &pluggedinkit.ResourceRequirements{
CPURequest: stringPtr("100m"),
MemoryRequest: stringPtr("256Mi"),
CPULimit: stringPtr("1000m"),
MemoryLimit: stringPtr("1Gi"),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Agent created: %s\n", result.Agent.UUID)
fmt.Printf("DNS: %s\n", result.Agent.DNSName) // my-agent.is.plugged.in
func stringPtr(s string) *string { return &s }
```
### Listing and Managing Agents
```go theme={null}
// List all agents
agents, err := client.Agents.List(ctx)
// Get agent details
details, err := client.Agents.Get(ctx, agentID)
fmt.Println(details.RecentHeartbeats)
fmt.Println(details.RecentMetrics)
fmt.Println(details.LifecycleEvents)
// Export agent data
exportData, err := client.Agents.Export(ctx, agentID, true, 1000)
// Delete agent
deleteResp, err := client.Agents.Delete(ctx, agentID)
```
### Heartbeats and Metrics
> **CRITICAL**: Heartbeats contain ONLY liveness data. Resource telemetry goes in metrics (separate channel). This separation is PAP's zombie prevention superpower.
```go theme={null}
// Send heartbeat (liveness only)
_, err = client.Agents.Heartbeat(ctx, agentID, "IDLE", 330.0)
// Send metrics (resource telemetry)
customMetrics := map[string]interface{}{
"queue_depth": 3,
"cache_hit_rate": 0.85,
}
_, err = client.Agents.Metrics(ctx, agentID, 12.5, 128, 45, customMetrics)
```
### Concurrent Agent Operations
```go theme={null}
func monitorAgents(client *pluggedinkit.Client, agentIDs []string) {
ctx := context.Background()
var wg sync.WaitGroup
for _, agentID := range agentIDs {
wg.Add(1)
go func(id string) {
defer wg.Done()
// Send heartbeat and metrics concurrently
errChan := make(chan error, 2)
go func() {
_, err := client.Agents.Heartbeat(ctx, id, "IDLE", 330.0)
errChan <- err
}()
go func() {
_, err := client.Agents.Metrics(ctx, id, 10.0, 100, 20, nil)
errChan <- err
}()
// Wait for both to complete
for i := 0; i < 2; i++ {
if err := <-errChan; err != nil {
log.Printf("Error for agent %s: %v", id, err)
}
}
}(agentID)
}
wg.Wait()
}
```
### Agent States
Agents follow the PAP lifecycle state machine:
```
NEW → PROVISIONED → ACTIVE ↔ DRAINING → TERMINATED
↓ (error)
KILLED
```
```go theme={null}
// Poll until agent is active
for {
details, err := client.Agents.Get(ctx, agentID)
if err != nil {
return err
}
if details.Agent.State == "ACTIVE" {
fmt.Println("Agent is ready!")
break
}
time.Sleep(5 * time.Second)
}
```
See [PAP Agents Documentation](/agents/overview) for complete details on the Plugged.in Agent Protocol.
## Context and Cancellation
All SDK methods accept a context for cancellation and timeout control:
```go theme={null}
// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
docs, err := client.Documents.List(ctx, nil)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("Request timed out")
}
}
// With cancellation
ctx, cancel := context.WithCancel(context.Background())
// Cancel from another goroutine
go func() {
time.Sleep(5 * time.Second)
cancel()
}()
// This will be cancelled after 5 seconds
answer, err := client.RAG.AskQuestion(ctx, "Long running query")
if err != nil {
if errors.Is(err, context.Canceled) {
fmt.Println("Request was cancelled")
}
}
```
## Concurrent Operations
Leverage Go's concurrency for parallel operations:
```go theme={null}
func fetchDocumentsConcurrently(client *pluggedin.Client) {
ctx := context.Background()
documentIDs := []string{"doc1", "doc2", "doc3", "doc4", "doc5"}
type result struct {
doc *pluggedin.Document
err error
}
results := make(chan result, len(documentIDs))
// Fetch documents concurrently
for _, id := range documentIDs {
go func(docID string) {
doc, err := client.Documents.Get(ctx, docID, true, false)
results <- result{doc, err}
}(id)
}
// Collect results
for i := 0; i < len(documentIDs); i++ {
r := <-results
if r.err != nil {
fmt.Printf("Error fetching document: %v\n", r.err)
} else {
fmt.Printf("Fetched: %s\n", r.doc.Title)
}
}
}
```
## Testing
### Unit Testing with Interfaces
```go theme={null}
// Define interface for testing
type DocumentService interface {
List(ctx context.Context, filters *DocumentFilters) (*ListDocumentsResponse, error)
Get(ctx context.Context, id string, includeContent, includeVersions bool) (*Document, error)
}
// Test function
func TestDocumentList(t *testing.T) {
// Mock implementation
mockService := &MockDocumentService{
ListFunc: func(ctx context.Context, filters *DocumentFilters) (*ListDocumentsResponse, error) {
return &ListDocumentsResponse{
Documents: []Document{{Title: "Test Doc"}},
Total: 1,
}, nil
},
}
// Test
response, err := mockService.List(context.Background(), nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if response.Total != 1 {
t.Errorf("expected 1 document, got %d", response.Total)
}
}
```
### Integration Testing
```go theme={null}
func TestDocumentLifecycle(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
client := pluggedin.NewClient(os.Getenv("PLUGGEDIN_API_KEY"))
ctx := context.Background()
// Create document
doc, err := client.Documents.Create(ctx, &CreateDocumentRequest{
Title: "Test Document",
Content: "Test content",
Metadata: map[string]interface{}{
"tags": []string{"test"},
},
})
if err != nil {
t.Fatalf("failed to create document: %v", err)
}
// Cleanup
defer func() {
_ = client.Documents.Delete(ctx, doc.ID)
}()
// Update document
updateResp, err := client.Documents.Update(ctx, doc.ID, &UpdateDocumentRequest{
Operation: OpAppend,
Content: "\nUpdated content",
})
if err != nil {
t.Fatalf("failed to update document: %v", err)
}
if updateResp.Version <= doc.Version {
t.Errorf("expected version to increase, got %d", updateResp.Version)
}
}
```
### Benchmarking
```go theme={null}
func BenchmarkDocumentSearch(b *testing.B) {
client := pluggedin.NewClient(os.Getenv("PLUGGEDIN_API_KEY"))
ctx := context.Background()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := client.Documents.Search(ctx, "test query", nil, 10, 0)
if err != nil {
b.Fatalf("search failed: %v", err)
}
}
}
```
## Advanced Configuration
### Custom HTTP Transport
```go theme={null}
import (
"net/http"
"net/url"
"time"
)
// Custom transport with proxy
proxyURL, _ := url.Parse("http://proxy.example.com:8080")
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
}
httpClient := &http.Client{
Transport: transport,
Timeout: 2 * time.Minute,
}
client := pluggedin.NewClientWithOptions(
"your-api-key",
"https://plugged.in",
httpClient,
)
```
### Environment Variables
```go theme={null}
// Load from environment
type Config struct {
APIKey string
BaseURL string
Timeout time.Duration
}
func LoadConfig() *Config {
timeout, _ := time.ParseDuration(os.Getenv("PLUGGEDIN_TIMEOUT"))
if timeout == 0 {
timeout = 60 * time.Second
}
return &Config{
APIKey: os.Getenv("PLUGGEDIN_API_KEY"),
BaseURL: os.Getenv("PLUGGEDIN_BASE_URL"),
Timeout: timeout,
}
}
// Use configuration
config := LoadConfig()
httpClient := &http.Client{Timeout: config.Timeout}
client := pluggedin.NewClientWithOptions(config.APIKey, config.BaseURL, httpClient)
```
## Rate Limiting
The SDK handles rate limiting automatically:
* **API Endpoints**: 60 requests per minute
* **Document Search**: 10 requests per hour for AI documents
* **RAG Queries**: Subject to plan limits
```go theme={null}
// Implement retry with exponential backoff
func retryWithBackoff(ctx context.Context, fn func() error) error {
maxRetries := 5
baseDelay := 1 * time.Second
for i := 0; i < maxRetries; i++ {
err := fn()
if err == nil {
return nil
}
// Check if it's a rate limit error
if rateLimitErr, ok := err.(*pluggedin.RateLimitError); ok {
delay := time.Duration(rateLimitErr.RetryAfter) * time.Second
fmt.Printf("Rate limited, waiting %v\n", delay)
time.Sleep(delay)
continue
}
// Exponential backoff for other errors
delay := baseDelay * time.Duration(1<
View on NPM Registry
Source code and examples
## Installation
```bash theme={null}
npm install pluggedinkit-js
```
```bash theme={null}
yarn add pluggedinkit-js
```
```bash theme={null}
pnpm add pluggedinkit-js
```
## Quick Start
```typescript theme={null}
import { PluggedInClient } from 'pluggedinkit-js';
// Initialize the client
const client = new PluggedInClient({
apiKey: 'your-api-key',
// baseUrl defaults to https://plugged.in
});
// List documents
const documents = await client.documents.list({
limit: 10,
source: 'all'
});
// Search documents
const results = await client.documents.search('machine learning', {
tags: ['ai', 'ml']
});
// Query RAG
const ragResponse = await client.rag.query('What are the latest updates?');
console.log(ragResponse.answer);
console.log('Matched documents:', ragResponse.documentIds);
```
## Authentication
Get your API key from your [Plugged.in Profile](https://plugged.in/profile/settings) and configure the client:
```typescript theme={null}
const client = new PluggedInClient({
apiKey: process.env.PLUGGEDIN_API_KEY,
baseUrl: process.env.PLUGGEDIN_BASE_URL || 'https://plugged.in',
timeout: 60000, // 60 seconds
maxRetries: 5,
debug: true // Enable debug logging
});
// Update API key at runtime
client.setApiKey('new-api-key');
```
## Core Features
### Document Management
#### List Documents
```typescript theme={null}
import { DocumentFilters, DocumentSource, SortOrder } from 'pluggedinkit-js';
const filters: DocumentFilters = {
source: 'ai_generated',
tags: ['report', 'analysis'],
sort: 'date_desc',
limit: 20,
offset: 0,
category: 'documentation',
dateFrom: '2024-01-01T00:00:00Z',
modelProvider: 'anthropic'
};
const response = await client.documents.list(filters);
console.log(`Found ${response.total} documents`);
response.documents.forEach(doc => {
console.log(`- ${doc.title} (${doc.fileSize} bytes)`);
});
```
#### Get Document
```typescript theme={null}
// Get metadata only
const doc = await client.documents.get('document-id');
// Get document with content and version history
const fullDoc = await client.documents.get('document-id', {
includeContent: true,
includeVersions: true
});
console.log(fullDoc.content);
console.log(`Version: ${fullDoc.version}`);
```
#### Search Documents
```typescript theme={null}
const searchResults = await client.documents.search('quarterly report', {
modelProvider: 'anthropic',
dateFrom: '2024-01-01T00:00:00Z',
tags: ['finance', 'q4']
}, 10, 0);
searchResults.results.forEach(result => {
console.log(`${result.title}`);
console.log(` Relevance: ${result.relevanceScore}`);
console.log(` Snippet: ${result.snippet}`);
});
```
#### Create AI-Generated Document
```typescript theme={null}
const newDoc = await client.documents.create(
'API Integration Guide',
'# API Integration Guide\n\n## Introduction\n\n...',
{
format: 'md',
category: 'documentation',
tags: ['api', 'integration', 'guide'],
model: {
name: 'claude-3-opus',
provider: 'anthropic',
version: '20240229'
},
prompt: 'Create a comprehensive API integration guide',
context: 'User requested comprehensive API documentation',
updateReason: 'Initial creation',
changesFromPrompt: 'Created new guide as requested',
changeSummary: 'New comprehensive API integration guide',
conversationContext: [
{ role: 'user', content: 'Create an API guide' },
{ role: 'assistant', content: "I'll create a comprehensive guide..." }
],
sourceDocuments: ['doc-123', 'doc-456'],
visibility: 'workspace',
sessionId: 'session-789',
generationParams: {
temperature: 0.7,
maxTokens: 4000,
topP: 0.9
},
// Dynamic fields - add any custom metadata
customField: 'Any custom value',
projectMetadata: {
team: 'engineering',
version: '1.0.0'
}
}
);
console.log(`Created document: ${newDoc.id}`);
// Access all metadata including custom fields
console.log('All metadata:', newDoc.aiMetadata);
```
#### Update Document
```typescript theme={null}
const updateResult = await client.documents.update('document-id', {
operation: 'append',
content: '\n\n## New Section\n\nAdditional content here.',
metadata: {
changeSummary: 'Added implementation details section',
model: {
name: 'gpt-4',
provider: 'openai',
version: '0613'
},
updateReason: 'Added new section on authentication',
changesFromPrompt: 'User requested additional auth details',
prompt: 'Add a section about OAuth 2.0 authentication',
lastUpdatedBy: {
name: 'gpt-4',
provider: 'openai',
version: '0613'
},
lastUpdateTimestamp: '2024-01-15T10:30:00Z',
conversationContext: [
{ role: 'user', content: 'Add OAuth 2.0 section' },
{ role: 'assistant', content: 'Adding authentication details...' }
],
// Custom metadata fields
customUpdateMetadata: {
reviewedBy: 'security-team',
complianceCheck: 'passed'
}
}
});
console.log(`Document updated to version ${updateResult.version}`);
```
### RAG Operations
#### Simple Query
```typescript theme={null}
const rag = await client.rag.query('What are our deployment procedures?');
console.log(rag.answer);
```
#### Query with Sources
```typescript theme={null}
const { answer, sources } = await client.rag.queryWithSources(
'Explain the authentication flow'
);
console.log('Answer:', answer);
console.log('Sources:');
sources.forEach(source => {
console.log(`- ${source.name} (${source.id})`);
});
```
#### Find Relevant Documents
```typescript theme={null}
const matches = await client.rag.findRelevantDocuments(
'user authentication',
undefined,
5 // Top 5 documents
);
matches.forEach(match => {
console.log(`- ${match.name} (${match.id})`);
});
// Storage statistics (requires your Plugged.in user id)
const stats = await client.rag.getStorageStats('user-id-from-dashboard');
console.log(`Indexed documents: ${stats.documentsCount}`);
```
### File Uploads
> **Important:** Direct file uploads are no longer exposed via the public API.
> The `client.uploads` helpers now throw descriptive errors so existing code
> fails fast. Use the Plugged.in web interface or the forthcoming ingestion
> workflow for binary files. AI-generated content can still be created with
> `client.documents.create` or `client.uploads.uploadDocument`.
## Error Handling
The SDK provides typed error classes for better error handling:
```typescript theme={null}
import {
PluggedInError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError
} from 'pluggedinkit-js';
try {
const doc = await client.documents.get('invalid-id');
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key - please check your credentials');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
// Implement retry logic
} else if (error instanceof NotFoundError) {
console.error('Document not found');
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.details);
} else if (error instanceof PluggedInError) {
console.error(`API error: ${error.message}`);
}
}
```
## TypeScript Support
The SDK is written in TypeScript and provides comprehensive type definitions:
```typescript theme={null}
import type {
Document,
DocumentFilters,
DocumentSource,
DocumentVisibility,
DocumentCategory,
RagResponse,
UploadMetadata,
ModelInfo,
UpdateOperation
} from 'pluggedinkit-js';
// All types are fully documented with JSDoc comments
const filters: DocumentFilters = {
source: 'ai_generated',
tags: ['important'],
sort: 'date_desc',
limit: 10
};
// TypeScript will provide autocompletion and type checking
const doc: Document = await client.documents.get('id');
console.log(doc.title); // Type-safe property access
```
## Advanced Configuration
### Environment Variables
```bash theme={null}
# .env
PLUGGEDIN_API_KEY=your-api-key
PLUGGEDIN_BASE_URL=https://plugged.in
```
```typescript theme={null}
const client = new PluggedInClient({
apiKey: process.env.PLUGGEDIN_API_KEY!,
baseUrl: process.env.PLUGGEDIN_BASE_URL
});
```
### Custom HTTP Client
```typescript theme={null}
const client = new PluggedInClient({
apiKey: 'your-api-key',
baseUrl: 'https://plugged.in',
timeout: 120000, // 2 minutes
maxRetries: 10,
debug: process.env.NODE_ENV === 'development',
headers: {
'X-Custom-Header': 'value'
}
});
```
## PAP Agents
The SDK provides full support for managing PAP (Plugged.in Agent Protocol) agents:
### Creating Agents
```typescript theme={null}
const result = await client.agents.create({
name: 'my-agent',
description: 'My autonomous PAP agent',
resources: {
cpu_request: '100m',
memory_request: '256Mi',
cpu_limit: '1000m',
memory_limit: '1Gi'
}
});
console.log(`Agent created: ${result.agent.uuid}`);
console.log(`DNS: ${result.agent.dns_name}`); // my-agent.is.plugged.in
```
### Listing and Managing Agents
```typescript theme={null}
// List all agents
const agents = await client.agents.list();
// Get agent details
const details = await client.agents.get(agentId);
console.log(details.recentHeartbeats);
console.log(details.recentMetrics);
console.log(details.lifecycleEvents);
// Export agent data
const exportData = await client.agents.export(agentId, {
include_telemetry: true,
telemetry_limit: 1000
});
// Delete agent
await client.agents.delete(agentId);
```
### Heartbeats and Metrics
**CRITICAL**: Heartbeats contain ONLY liveness data. Resource telemetry goes in metrics (separate channel). This separation is PAP's zombie prevention superpower.
```typescript theme={null}
// Send heartbeat (liveness only)
await client.agents.heartbeat(agentId, {
mode: 'IDLE', // or 'EMERGENCY', 'SLEEP'
uptime_seconds: process.uptime()
});
// Send metrics (resource telemetry)
await client.agents.metrics(agentId, {
cpu_percent: 12.5,
memory_mb: 128,
requests_handled: 45,
custom_metrics: {
queue_depth: 3,
cache_hit_rate: 0.85
}
});
```
### Agent States
Agents follow the PAP lifecycle state machine:
```
NEW → PROVISIONED → ACTIVE ↔ DRAINING → TERMINATED
↓ (error)
KILLED
```
```typescript theme={null}
// Poll until agent is active
while (true) {
const details = await client.agents.get(agentId);
if (details.agent.state === 'ACTIVE') {
console.log('Agent is ready!');
break;
}
await new Promise(resolve => setTimeout(resolve, 5000));
}
```
See [PAP Agents Documentation](/agents/overview) for complete details on the Plugged.in Agent Protocol.
## Rate Limiting
The SDK automatically handles rate limiting with exponential backoff:
* **API Endpoints**: 60 requests per minute
* **Document Search**: 10 requests per hour for AI document creation
* **RAG Queries**: Subject to plan limits
## Browser Support
The SDK works in both Node.js and browser environments:
```html theme={null}
```
## Examples
Complete working examples are available in the [GitHub repository](https://github.com/VeriTeknik/pluggedinkit-js/tree/main/examples):
* [Basic Usage](https://github.com/VeriTeknik/pluggedinkit-js/blob/main/examples/basic.ts)
* [Document Management](https://github.com/VeriTeknik/pluggedinkit-js/blob/main/examples/documents.ts)
* [RAG Queries](https://github.com/VeriTeknik/pluggedinkit-js/blob/main/examples/rag.ts)
* [File Upload (deprecated)](https://github.com/VeriTeknik/pluggedinkit-js/blob/main/examples/upload.ts)
* [Error Handling](https://github.com/VeriTeknik/pluggedinkit-js/blob/main/examples/errors.ts)
* [Browser Usage](https://github.com/VeriTeknik/pluggedinkit-js/blob/main/examples/browser.html)
## API Reference
### Client Options
| Option | Type | Default | Description |
| ------------ | ------- | -------------------- | ------------------------------- |
| `apiKey` | string | required | Your Plugged.in API key |
| `baseUrl` | string | `https://plugged.in` | API base URL |
| `timeout` | number | `60000` | Request timeout in milliseconds |
| `maxRetries` | number | `5` | Maximum retry attempts |
| `debug` | boolean | `false` | Enable debug logging |
### Document Methods
| Method | Description |
| --------------------------------------- | ------------------------------------ |
| `list(filters)` | List documents with optional filters |
| `get(id, options)` | Get a specific document |
| `search(query, filters, limit, offset)` | Search documents |
| `create(title, content, metadata)` | Create a new document |
| `update(id, request)` | Update an existing document |
| `delete(id)` | Delete a document |
### RAG Methods
| Method | Description |
| -------------------------------------- | ------------------------------------------------------------ |
| `query(question)` | Returns `RagResponse` with answer, sources, and document IDs |
| `queryWithSources(question)` | Returns answer plus structured source metadata |
| `findRelevantDocuments(query, limit?)` | Returns matched document references |
| `getStorageStats(userId)` | Fetch aggregated storage metrics for the authenticated user |
| `checkAvailability()` | Lightweight availability check |
### Upload Methods
All binary upload helpers now throw descriptive errors because the public API no longer exposes direct upload endpoints. Use the web interface or upcoming ingestion pipeline for file uploads.
### Clipboard Methods
| Method | Description |
| ----------------- | -------------------------------- |
| `list()` | List all clipboard entries |
| `get(filters)` | Get entry by name or index |
| `getByName(name)` | Get entry by name |
| `getByIndex(idx)` | Get entry by stack index |
| `set(request)` | Create or update named entry |
| `push(request)` | Push value to indexed stack |
| `pop()` | Pop and remove most recent entry |
| `delete(request)` | Delete specific entry |
| `clearAll()` | Delete all entries |
### Agent Methods
| Method | Description |
| -------------------------- | ------------------------------------------------------------- |
| `list()` | List all PAP agents for the active profile |
| `create(request)` | Create and deploy a new agent |
| `get(agentId)` | Get detailed agent information including telemetry |
| `delete(agentId)` | Terminate and delete an agent |
| `export(agentId, options)` | Export complete agent data including telemetry history |
| `heartbeat(agentId, data)` | Submit heartbeat (liveness only - zombie prevention) |
| `metrics(agentId, data)` | Submit metrics (resource telemetry - separate from heartbeat) |
See [PAP Agents API Reference](/agents/api-reference) for complete endpoint documentation.
## Clipboard (Memory) Service
The Clipboard service provides persistent key-value storage for MCP tools and AI agents.
### Named Access
```typescript theme={null}
// Set a named entry
await client.clipboard.set({
name: 'user_preferences',
value: JSON.stringify({ theme: 'dark', lang: 'en' }),
contentType: 'application/json',
encoding: 'utf-8',
visibility: 'private',
ttlSeconds: 86400 // 24 hours
});
// Get by name
const entry = await client.clipboard.getByName('user_preferences');
console.log('Preferences:', JSON.parse(entry.value));
// Delete by name
await client.clipboard.delete({ name: 'user_preferences' });
```
### Indexed (Stack) Access
```typescript theme={null}
// Push to stack
await client.clipboard.push({
value: 'Step 1 result',
contentType: 'text/plain'
});
await client.clipboard.push({
value: 'Step 2 result',
contentType: 'text/plain'
});
// Get by index (0 = most recent)
const latest = await client.clipboard.getByIndex(0);
console.log('Latest:', latest.value); // "Step 2 result"
// Pop removes and returns the most recent
const popped = await client.clipboard.pop();
console.log('Popped:', popped.value); // "Step 2 result"
```
### List All Entries
```typescript theme={null}
const entries = await client.clipboard.list();
for (const entry of entries) {
console.log(`${entry.name || `idx:${entry.idx}`}: ${entry.value}`);
console.log(` Expires: ${entry.expiresAt}`);
}
```
### TypeScript Types
```typescript theme={null}
import type {
ClipboardEntry,
ClipboardSetRequest,
ClipboardPushRequest,
ClipboardGetFilters,
ClipboardDeleteRequest,
ClipboardSource,
ClipboardEncoding,
ClipboardVisibility
} from 'pluggedinkit-js';
import { DEFAULT_CLIPBOARD_SOURCE } from 'pluggedinkit-js';
// All types are fully documented
const request: ClipboardSetRequest = {
name: 'cache_key',
value: 'cached data',
contentType: 'text/plain',
encoding: 'utf-8', // 'utf-8' | 'base64' | 'hex'
visibility: 'private', // 'private' | 'workspace' | 'public'
ttlSeconds: 3600
};
// ClipboardSource tracks where entries originate
type ClipboardSource = 'ui' | 'sdk' | 'mcp';
// The SDK automatically sets source to 'sdk' for all entries you create.
// DEFAULT_CLIPBOARD_SOURCE is 'ui' for backward compatibility with older entries.
```
## Support
* **NPM Package**: [https://www.npmjs.com/package/pluggedinkit-js](https://www.npmjs.com/package/pluggedinkit-js)
* **GitHub Issues**: [Report bugs and request features](https://github.com/VeriTeknik/pluggedinkit-js/issues)
* **Documentation**: [https://docs.plugged.in](https://docs.plugged.in)
* **Discord**: [Join our community](https://discord.gg/pluggedin)
# Python SDK
Source: https://docs.plugged.in/sdks/python
Official Python SDK for the Plugged.in Library API with sync and async support
# Python SDK
[](https://pypi.org/project/pluggedinkit/)
[](https://pypi.org/project/pluggedinkit/)
[](https://opensource.org/licenses/MIT)
The official Python SDK for interacting with Plugged.in's Library API. Features both synchronous and asynchronous clients with comprehensive type hints using Pydantic models.
View on PyPI Registry
Source code and examples
## Installation
```bash theme={null}
pip install pluggedinkit
```
### Requirements
* Python 3.8 or higher
* httpx for HTTP client
* pydantic for data validation
* typing-extensions for Python \< 3.11
## Quick Start
### Synchronous Client
```python theme={null}
from pluggedinkit import PluggedInClient
# Initialize the client
client = PluggedInClient(
api_key="your-api-key",
# base_url defaults to https://plugged.in
)
# List documents
documents = client.documents.list()
print(f"Found {documents.total} documents")
# Search documents
results = client.documents.search("machine learning")
for result in results.results:
print(f"{result.title} - Relevance: {result.relevance_score}")
# Query knowledge base
answer = client.rag.ask_question("What are the main features?")
print(answer)
```
### Asynchronous Client
```python theme={null}
import asyncio
from pluggedinkit import AsyncPluggedInClient
async def main():
# Initialize async client
async with AsyncPluggedInClient(api_key="your-api-key") as client:
# List documents
documents = await client.documents.list()
print(f"Found {documents.total} documents")
# Query RAG
answer = await client.rag.ask_question("What's new in the project?")
print(answer)
asyncio.run(main())
```
## Authentication
Get your API key from your [Plugged.in Profile](https://plugged.in/profile/settings):
```python theme={null}
import os
from pluggedinkit import PluggedInClient
# Using environment variables (recommended)
client = PluggedInClient(
api_key=os.environ["PLUGGEDIN_API_KEY"],
base_url=os.environ.get("PLUGGEDIN_BASE_URL", "https://plugged.in"),
timeout=60.0, # 60 seconds
max_retries=5,
debug=True # Enable debug logging
)
# Update API key at runtime
client.set_api_key("new-api-key")
```
## Core Features
### Document Management
#### List Documents
```python theme={null}
from pluggedinkit.types import DocumentFilters, DocumentSource
filters = DocumentFilters(
source=DocumentSource.AI_GENERATED,
tags=["report", "analysis"],
category="documentation",
date_from="2024-01-01T00:00:00Z",
date_to="2024-12-31T23:59:59Z",
model_provider="anthropic",
sort="date_desc",
limit=20,
offset=0
)
response = client.documents.list(filters)
for doc in response.documents:
print(f"{doc.title} ({doc.file_size} bytes)")
print(f" Created: {doc.created_at}")
print(f" Tags: {', '.join(doc.tags)}")
```
#### Get Document
```python theme={null}
# Get document metadata only
doc = client.documents.get("document-id")
print(f"Title: {doc.title}")
print(f"Version: {doc.version}")
# Get document with content and version history
doc_with_content = client.documents.get(
"document-id",
include_content=True,
include_versions=True
)
print(doc_with_content.content)
# Access version history
for version in doc_with_content.versions:
print(f"Version {version.number}: {version.created_at}")
```
#### Search Documents
```python theme={null}
from pluggedinkit.types import SearchFilters
filters = SearchFilters(
model_provider="anthropic",
date_from="2024-01-01T00:00:00Z",
tags=["finance", "q4"]
)
results = client.documents.search(
"quarterly report",
filters=filters,
limit=10,
offset=0
)
for result in results.results:
print(f"{result.title}")
print(f" Relevance: {result.relevance_score:.2f}")
print(f" Snippet: {result.snippet}")
print(f" Tags: {', '.join(result.tags)}")
```
#### Create AI-Generated Document
```python theme={null}
metadata = {
"format": "md",
"category": "documentation",
"tags": ["api", "guide"],
"model": {
"name": "claude-3-opus",
"provider": "anthropic",
"version": "20240229"
},
"prompt": "Create a comprehensive API integration guide",
"context": "User requested comprehensive API documentation",
"updateReason": "Initial creation",
"changesFromPrompt": "Created new guide as requested",
"changeSummary": "New comprehensive API integration guide",
"conversationContext": [
{"role": "user", "content": "Create an API guide"},
{"role": "assistant", "content": "I'll create a comprehensive guide..."}
],
"sourceDocuments": ["doc-123", "doc-456"],
"visibility": "workspace",
"sessionId": "session-789",
"generationParams": {
"temperature": 0.7,
"maxTokens": 4000,
"topP": 0.9
},
# Dynamic fields - add any custom metadata
"customField": "Any custom value",
"projectMetadata": {
"team": "engineering",
"version": "1.0.0"
}
}
doc = client.documents.create(
title="API Integration Guide",
content="# API Integration Guide\n\n## Introduction\n\n...",
metadata=metadata
)
print(f"Created document: {doc.id}")
print(f"Version: {doc.version}")
# Access all metadata including custom fields
print(f"All metadata: {doc.ai_metadata.__dict__}")
```
#### Update Document
```python theme={null}
from pluggedinkit.types import UpdateDocumentRequest, UpdateOperation
request = UpdateDocumentRequest(
operation=UpdateOperation.APPEND,
content="\n\n## New Section\n\nAdditional content here.",
metadata={
"changeSummary": "Added implementation details",
"model": {
"name": "gpt-4",
"provider": "openai",
"version": "0613"
},
"updateReason": "Added new section on authentication",
"changesFromPrompt": "User requested additional auth details",
"prompt": "Add a section about OAuth 2.0 authentication",
"lastUpdatedBy": {
"name": "gpt-4",
"provider": "openai",
"version": "0613"
},
"lastUpdateTimestamp": "2024-01-15T10:30:00Z",
"conversationContext": [
{"role": "user", "content": "Add OAuth 2.0 section"},
{"role": "assistant", "content": "Adding authentication details..."}
],
# Custom metadata fields
"customUpdateMetadata": {
"reviewedBy": "security-team",
"complianceCheck": "passed"
}
}
)
response = client.documents.update("document-id", request)
print(f"Updated to version {response.version}")
print(f"Updated at: {response.updated_at}")
```
### RAG Operations
#### Simple Query
```python theme={null}
# Basic question answering
answer = client.rag.ask_question("What are the deployment procedures?")
print(answer)
# Get storage statistics
stats = client.rag.get_storage_stats(user_id="user-id-from-dashboard")
print(f"Documents: {stats.documents_count}")
print(f"Estimated storage: {stats.estimated_storage_mb} MB")
```
#### Query with Sources
```python theme={null}
result = client.rag.query_with_sources("Explain the authentication flow")
print(f"Answer: {result['answer']}")
print("\nSources:")
for source in result["sources"]:
print(f"- {source.name} ({source.id})")
```
#### Find Relevant Documents
```python theme={null}
documents = client.rag.find_relevant_documents(
"user authentication",
limit=5 # Top 5 documents
)
for doc in documents:
print(f"- {doc.name} ({doc.id})")
```
### File Uploads
> **Important:** Direct file uploads are no longer available via the public API.
> The `client.uploads` helpers now raise descriptive errors so legacy code fails
> fast. Use the Plugged.in web interface or upcoming ingestion pipeline for
> binary assets. AI-generated documents remain available through
> `client.documents.create` and `client.uploads.upload_document`.
## Async Operations
### Concurrent Operations
```python theme={null}
import asyncio
from pluggedinkit import AsyncPluggedInClient
async def document_operations():
async with AsyncPluggedInClient(api_key="your-key") as client:
# Concurrent document searches
search_tasks = [
client.documents.search("api"),
client.documents.search("guide"),
client.documents.search("tutorial")
]
results = await asyncio.gather(*search_tasks)
for result in results:
print(f"Found {result.total} matches")
```
### Async RAG Queries
```python theme={null}
async def rag_operations():
async with AsyncPluggedInClient(api_key="your-key") as client:
# Multiple queries concurrently
questions = [
"What is the authentication process?",
"How do I deploy the application?",
"What are the API rate limits?"
]
tasks = [client.rag.ask_question(q) for q in questions]
answers = await asyncio.gather(*tasks)
for q, a in zip(questions, answers):
print(f"Q: {q}")
print(f"A: {a}\n")
asyncio.run(rag_operations())
```
## Error Handling
The SDK provides typed exceptions for better error handling:
```python theme={null}
from pluggedinkit import (
PluggedInError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError
)
try:
doc = client.documents.get("invalid-id")
except AuthenticationError as e:
print("Invalid API key - please check your credentials")
# Refresh API key logic
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
# Implement exponential backoff
time.sleep(e.retry_after)
except NotFoundError as e:
print(f"Document not found: {e.resource_id}")
except ValidationError as e:
print(f"Validation error: {e.details}")
# Fix validation issues
except PluggedInError as e:
print(f"API error: {e}")
# Generic error handling
```
## PAP Agents
The SDK provides full support for managing PAP (Plugged.in Agent Protocol) agents:
### Creating Agents
```python theme={null}
result = client.agents.create({
'name': 'my-agent',
'description': 'My autonomous PAP agent',
'resources': {
'cpu_request': '100m',
'memory_request': '256Mi',
'cpu_limit': '1000m',
'memory_limit': '1Gi'
}
})
print(f"Agent created: {result['agent']['uuid']}")
print(f"DNS: {result['agent']['dns_name']}") # my-agent.is.plugged.in
```
### Listing and Managing Agents
```python theme={null}
# List all agents
agents = client.agents.list()
# Get agent details
details = client.agents.get(agent_id)
print(details['recentHeartbeats'])
print(details['recentMetrics'])
print(details['lifecycleEvents'])
# Export agent data
export_data = client.agents.export(
agent_id,
include_telemetry=True,
telemetry_limit=1000
)
# Delete agent
client.agents.delete(agent_id)
```
### Heartbeats and Metrics
> **CRITICAL**: Heartbeats contain ONLY liveness data. Resource telemetry goes in metrics (separate channel). This separation is PAP's zombie prevention superpower.
```python theme={null}
# Send heartbeat (liveness only)
client.agents.heartbeat(
agent_id,
mode='IDLE', # or 'EMERGENCY', 'SLEEP'
uptime_seconds=time.process_time()
)
# Send metrics (resource telemetry)
client.agents.metrics(
agent_id,
cpu_percent=12.5,
memory_mb=128,
requests_handled=45,
custom_metrics={
'queue_depth': 3,
'cache_hit_rate': 0.85
}
)
```
### Async Agent Operations
```python theme={null}
from pluggedinkit import AsyncPluggedInClient
async with AsyncPluggedInClient(api_key="your-key") as client:
# Create agent
result = await client.agents.create({
'name': 'async-agent',
'description': 'Async PAP agent'
})
# Send heartbeat and metrics concurrently
await asyncio.gather(
client.agents.heartbeat(agent_id, mode='IDLE', uptime_seconds=330),
client.agents.metrics(agent_id, cpu_percent=10, memory_mb=100, requests_handled=20)
)
```
### Agent States
Agents follow the PAP lifecycle state machine:
```
NEW → PROVISIONED → ACTIVE ↔ DRAINING → TERMINATED
↓ (error)
KILLED
```
```python theme={null}
# Poll until agent is active
import time
while True:
details = client.agents.get(agent_id)
if details['agent']['state'] == 'ACTIVE':
print('Agent is ready!')
break
time.sleep(5)
```
See [PAP Agents Documentation](/agents/overview) for complete details on the Plugged.in Agent Protocol.
## Type Safety with Pydantic
The SDK uses Pydantic models for comprehensive type safety:
```python theme={null}
from pluggedinkit.types import (
Document,
DocumentFilters,
DocumentSource,
DocumentVisibility,
DocumentCategory,
UpdateOperation,
ModelInfo
)
# All types are validated
filters = DocumentFilters(
source=DocumentSource.AI_GENERATED,
limit=10 # Validated: must be > 0 and <= 100
)
# IDE autocomplete and type checking
doc: Document = client.documents.get("id")
print(doc.title) # Type-safe attribute access
# Pydantic validation
try:
invalid_filters = DocumentFilters(
limit=-1 # Will raise ValidationError
)
except ValidationError as e:
print(f"Validation failed: {e}")
```
## Advanced Configuration
### Custom HTTP Client
```python theme={null}
import httpx
from pluggedinkit import PluggedInClient
# Custom httpx client with proxy
http_client = httpx.Client(
proxies="http://proxy.example.com:8080",
verify=False, # Disable SSL verification (not recommended)
timeout=httpx.Timeout(30.0)
)
client = PluggedInClient(
api_key="your-api-key",
base_url="https://plugged.in",
http_client=http_client
)
```
### Retry Configuration
```python theme={null}
client = PluggedInClient(
api_key="your-api-key",
max_retries=10,
retry_delay=1.0, # Initial delay in seconds
retry_backoff=2.0 # Exponential backoff factor
)
```
### Logging Configuration
```python theme={null}
import logging
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
client = PluggedInClient(
api_key="your-api-key",
debug=True
)
# SDK will log requests, responses, and errors
```
## Environment Variables
Store your API key securely using environment variables:
```bash theme={null}
# .env file
PLUGGEDIN_API_KEY=your-api-key
PLUGGEDIN_BASE_URL=https://plugged.in
```
```python theme={null}
import os
from dotenv import load_dotenv
from pluggedinkit import PluggedInClient
load_dotenv()
client = PluggedInClient(
api_key=os.environ["PLUGGEDIN_API_KEY"],
base_url=os.environ.get("PLUGGEDIN_BASE_URL")
)
```
## Rate Limiting
The SDK automatically handles rate limiting with exponential backoff:
* **API Endpoints**: 60 requests per minute
* **Document Search**: 10 requests per hour for AI documents
* **RAG Queries**: Subject to plan limits
```python theme={null}
# The SDK will automatically retry with backoff
for i in range(100):
try:
doc = client.documents.get(f"doc-{i}")
except RateLimitError as e:
print(f"Rate limited, waiting {e.retry_after} seconds")
time.sleep(e.retry_after)
```
## Testing
### Unit Testing with Mock
```python theme={null}
import unittest
from unittest.mock import Mock, patch
from pluggedinkit import PluggedInClient
class TestDocuments(unittest.TestCase):
def setUp(self):
self.client = PluggedInClient(api_key="test-key")
@patch('pluggedinkit.client.httpx.Client')
def test_list_documents(self, mock_http):
# Mock response
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {
"documents": [],
"total": 0
}
mock_http.return_value.request.return_value = mock_response
# Test
result = self.client.documents.list()
self.assertEqual(result.total, 0)
```
### Integration Testing
```python theme={null}
import pytest
from pluggedinkit import PluggedInClient
@pytest.fixture
def client():
return PluggedInClient(api_key="test-api-key")
def test_document_lifecycle(client):
# Create document
doc = client.documents.create(
"Test Document",
"Test content",
{"tags": ["test"]}
)
assert doc.id is not None
# Update document
update_result = client.documents.update(
doc.id,
UpdateDocumentRequest(
operation=UpdateOperation.APPEND,
content="\nUpdated content"
)
)
assert update_result.version > doc.version
# Delete document
client.documents.delete(doc.id)
```
## Examples
Complete working examples are available in the [GitHub repository](https://github.com/VeriTeknik/pluggedinkit-python/tree/main/examples):
* [Basic Usage](https://github.com/VeriTeknik/pluggedinkit-python/blob/main/examples/basic.py)
* [Document Management](https://github.com/VeriTeknik/pluggedinkit-python/blob/main/examples/documents.py)
* [RAG Queries](https://github.com/VeriTeknik/pluggedinkit-python/blob/main/examples/rag.py)
* [File Upload (deprecated)](https://github.com/VeriTeknik/pluggedinkit-python/blob/main/examples/upload.py)
* [Async Operations](https://github.com/VeriTeknik/pluggedinkit-python/blob/main/examples/async_example.py)
* [Error Handling](https://github.com/VeriTeknik/pluggedinkit-python/blob/main/examples/errors.py)
## API Reference
### Client Classes
| Class | Description |
| ---------------------- | ----------------------- |
| `PluggedInClient` | Synchronous API client |
| `AsyncPluggedInClient` | Asynchronous API client |
### Configuration Options
| Parameter | Type | Default | Description |
| ------------- | ----- | -------------------- | -------------------------- |
| `api_key` | str | required | Your Plugged.in API key |
| `base_url` | str | `https://plugged.in` | API base URL |
| `timeout` | float | `60.0` | Request timeout in seconds |
| `max_retries` | int | `5` | Maximum retry attempts |
| `debug` | bool | `False` | Enable debug logging |
### Document Methods
| Method | Description |
| -------------------------------------------- | ------------------------------------ |
| `list(filters)` | List documents with optional filters |
| `get(id, include_content, include_versions)` | Get a specific document |
| `search(query, filters, limit, offset)` | Search documents semantically |
| `create(title, content, metadata)` | Create a new document |
| `update(id, request)` | Update an existing document |
| `delete(id)` | Delete a document |
### RAG Methods
| Method | Description |
| --------------------------------------- | ---------------------------------------------- |
| `query(query)` | Returns `RagResponse` with answer and metadata |
| `ask_question(query)` | Simple RAG query (answer text only) |
| `query_with_sources(query)` | Query with structured source metadata |
| `find_relevant_documents(query, limit)` | Find relevant documents |
| `check_availability()` | Check RAG service availability |
| `get_storage_stats(user_id)` | Get storage statistics |
### Upload Methods
Upload helpers now raise descriptive errors because binary ingestion is no longer available via the public API.
### Clipboard Methods
| Method | Description |
| ------------------- | -------------------------------- |
| `list()` | List all clipboard entries |
| `get(name, idx)` | Get entry by name or index |
| `set(...)` | Create or update named entry |
| `push(...)` | Push value to indexed stack |
| `pop()` | Pop and remove most recent entry |
| `delete(name, idx)` | Delete specific entry |
| `clear_all()` | Delete all entries |
## Clipboard (Memory) Service
The Clipboard service provides persistent key-value storage for MCP tools and AI agents. Both sync and async clients are supported.
### Named Access (Sync)
```python theme={null}
# Set a named entry
entry = client.clipboard.set(
name="user_preferences",
value='{"theme": "dark", "lang": "en"}',
content_type="application/json",
encoding="utf-8",
visibility="private",
ttl_seconds=86400 # 24 hours
)
print(f"Created entry: {entry.uuid}")
# Get by name
entry = client.clipboard.get(name="user_preferences")
print(f"Value: {entry.value}")
# Delete by name
deleted = client.clipboard.delete(name="user_preferences")
print(f"Deleted: {deleted}")
```
### Named Access (Async)
```python theme={null}
import asyncio
from pluggedinkit import AsyncPluggedInClient
async def clipboard_operations():
async with AsyncPluggedInClient(api_key="your-key") as client:
# Set entry
entry = await client.clipboard.set(
name="session_data",
value="session info",
content_type="text/plain"
)
# Get entry
entry = await client.clipboard.get(name="session_data")
print(f"Session: {entry.value}")
asyncio.run(clipboard_operations())
```
### Indexed (Stack) Access
```python theme={null}
# Push to stack
client.clipboard.push(
value="Step 1 result",
content_type="text/plain"
)
client.clipboard.push(
value="Step 2 result",
content_type="text/plain"
)
# Get by index (0 = most recent)
latest = client.clipboard.get(idx=0)
print(f"Latest: {latest.value}") # "Step 2 result"
# Pop removes and returns the most recent
popped = client.clipboard.pop()
print(f"Popped: {popped.value}") # "Step 2 result"
```
### List All Entries
```python theme={null}
entries = client.clipboard.list()
for entry in entries:
name_or_idx = entry.name or f"idx:{entry.idx}"
print(f"{name_or_idx}: {entry.value}")
if entry.expires_at:
print(f" Expires: {entry.expires_at}")
```
### Pydantic Models
```python theme={null}
from pluggedinkit.types import (
ClipboardEntry,
ClipboardSetRequest,
ClipboardPushRequest,
ClipboardEncoding,
ClipboardVisibility,
ClipboardSource,
DEFAULT_CLIPBOARD_SOURCE
)
# All types are Pydantic models with validation
request = ClipboardSetRequest(
name="cache_key",
value="cached data",
content_type="text/plain",
encoding=ClipboardEncoding.UTF8,
visibility=ClipboardVisibility.PRIVATE,
ttl_seconds=3600
)
# ClipboardSource tracks where entries originate
class ClipboardSource(str, Enum):
UI = "ui" # Created via web interface
SDK = "sdk" # Created via SDK (automatically set)
MCP = "mcp" # Created via MCP tools
# The SDK automatically sets source to ClipboardSource.SDK for all entries.
# DEFAULT_CLIPBOARD_SOURCE is ClipboardSource.UI for backward compatibility.
```
## Support
* **PyPI Package**: [https://pypi.org/project/pluggedinkit/](https://pypi.org/project/pluggedinkit/)
* **GitHub Issues**: [Report bugs and request features](https://github.com/VeriTeknik/pluggedinkit-python/issues)
* **Documentation**: [https://docs.plugged.in](https://docs.plugged.in)
* **Discord**: [Join our community](https://discord.gg/pluggedin)
# OAuth 2.1 Security
Source: https://docs.plugged.in/security/oauth-2.1
OAuth 2.1 security best practices and implementation details
# OAuth 2.1 Security Implementation
Plugged.in implements **OAuth 2.1** security best practices to ensure the highest level of security for MCP server authentication. This document outlines the security measures in place.
## OAuth 2.1 Overview
OAuth 2.1 is the next evolution of the OAuth 2.0 framework, consolidating security best practices from various OAuth extensions and eliminating insecure patterns.
**Key Difference**: OAuth 2.1 is **NOT** a separate specification, but rather a consolidation of OAuth 2.0 + security best practices (PKCE, token rotation, etc.)
***
## Implemented Security Features
### 1. PKCE (Proof Key for Code Exchange)
**RFC 7636 - Mandatory for all OAuth flows**
* Authorization code interception attacks
* Code injection attacks
* Man-in-the-middle attacks
* S256 challenge method (SHA-256)
* 256-bit code verifier entropy
* Automatic verification on callback
**How it works:**
```typescript theme={null}
// 1. Generate code verifier (256 bits of entropy)
const codeVerifier = crypto.randomBytes(32).toString('base64url');
// 2. Generate code challenge (SHA-256 hash)
const codeChallenge = crypto
.createHash('sha256')
.update(codeVerifier)
.digest('base64url');
// 3. Send challenge in authorization request
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
// 4. Send verifier in token exchange
tokenParams.set('code_verifier', codeVerifier);
```
***
### 2. State Parameter Integrity Binding
**OAuth 2.1 Best Practice - Prevents PKCE state tampering**
**Attack Prevented**: Attackers cannot modify stored PKCE state parameters (server UUID, user ID, code verifier) to steal tokens or hijack flows.
**Implementation:**
```typescript theme={null}
// Generate HMAC-SHA256 integrity hash
const integrityHash = crypto
.createHmac('sha256', secret)
.update(`${state}|${serverUuid}|${userId}|${codeVerifier}`)
.digest('hex');
// Store with PKCE state
await db.insert(oauthPkceStatesTable).values({
state,
server_uuid: serverUuid,
user_id: userId,
code_verifier: codeVerifier,
integrity_hash: integrityHash, // ✅ OAuth 2.1 enhancement
expires_at: new Date(Date.now() + 5 * 60 * 1000),
});
// Verify on callback (timing-safe comparison)
if (!verifyIntegrityHash(pkceState)) {
// Revoke and reject - tampering detected
}
```
**Files:**
* `lib/oauth/integrity.ts` - HMAC generation and verification
* `app/actions/trigger-mcp-oauth.ts` - Hash creation
* `app/api/oauth/callback/route.ts` - Hash verification
***
### 3. Reduced PKCE Expiration (5 Minutes)
**OAuth 2.1 Recommendation - Reduced attack window**
OAuth 2.1 recommends shorter PKCE state expiration to minimize the window for:
* Replay attacks
* Code interception attempts
* State prediction attacks
**Previous**: 10 minutes (OAuth 2.0 typical)
**Current**: 5 minutes (OAuth 2.1 recommended)
```typescript theme={null}
// Updated expiration
expires_at: new Date(Date.now() + 5 * 60 * 1000) // 5 minutes
```
**Files:**
* `db/schema.ts` - Schema documentation
* `app/actions/trigger-mcp-oauth.ts:447` - State creation
* `app/api/oauth/callback/route.ts:166` - Expiration check
***
### 4. Refresh Token Rotation
**OAuth 2.1 Best Practice - Prevents token reuse attacks**
Each refresh token can only be used **once**. After use, it's immediately invalidated.
If a refresh token is reused, **all tokens are revoked** as a security measure.
**Implementation Flow:**
```mermaid theme={null}
graph TD
A[Token Refresh Request] --> B{Check refresh_token_used_at}
B -->|Already Used| C[SECURITY ALERT: Revoke ALL Tokens]
B -->|Not Used| D[Mark as Used Immediately]
D --> E[Exchange with OAuth Server]
E --> F[Receive New Tokens]
F --> G[Store New Tokens + Clear used_at Flag]
G --> H[Success]
C --> I[Force Re-Authentication]
```
**Code:**
```typescript theme={null}
// 1. Check for token reuse (security measure)
if (tokenRecord.refresh_token_used_at) {
console.error('[OAuth Security] Refresh token reuse detected!');
// Revoke ALL tokens as security measure
await db.delete(mcpServerOAuthTokensTable)
.where(eq(mcpServerOAuthTokensTable.server_uuid, serverUuid));
return false;
}
// 2. Mark token as used BEFORE exchange
await db.update(mcpServerOAuthTokensTable)
.set({ refresh_token_used_at: new Date() })
.where(eq(mcpServerOAuthTokensTable.server_uuid, serverUuid));
// 3. Exchange for new tokens
const newTokens = await exchangeRefreshToken(refreshToken);
// 4. Store new tokens with cleared used_at flag
await db.update(mcpServerOAuthTokensTable)
.set({
access_token_encrypted: encrypt(newTokens.access_token),
refresh_token_encrypted: encrypt(newTokens.refresh_token),
refresh_token_used_at: null, // ✅ Fresh token, not used
updated_at: new Date(),
})
.where(eq(mcpServerOAuthTokensTable.server_uuid, serverUuid));
```
**Database Schema:**
```sql theme={null}
ALTER TABLE mcp_server_oauth_tokens
ADD COLUMN refresh_token_used_at TIMESTAMPTZ;
```
**Files:**
* `db/schema.ts:1940` - Schema definition
* `lib/oauth/token-refresh-service.ts:97-104` - Reuse detection
* `lib/oauth/token-refresh-service.ts:128-139` - Mark as used
* `lib/oauth/token-refresh-service.ts:179-190` - Store new tokens
***
### 5. HTTP Basic Authentication for Client Credentials
**RFC 6749 Section 2.3.1 - Prevents credential logging**
**Security Issue**: Sending `client_secret` in URL-encoded body causes it to be logged in:
* Proxy access logs
* WAF logs
* Server access logs
* Load balancer logs
**Secure Method:**
```typescript theme={null}
// ✅ CORRECT: HTTP Basic Auth (RFC 6749 Section 2.3.1)
const credentials = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
headers['Authorization'] = `Basic ${credentials}`;
// Body contains ONLY refresh_token
const tokenParams = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
// NO client_secret here!
});
```
**Files:**
* `lib/oauth/token-refresh-service.ts:134-140` - Token refresh
* `app/api/oauth/callback/route.ts` - Token exchange
***
## Security Enhancements Summary
| Feature | Standard | Plugged.in Implementation | Security Benefit |
| -------------------- | --------------- | ------------------------------ | --------------------------- |
| **PKCE** | RFC 7636 | ✅ S256 method, 256-bit entropy | Prevents code interception |
| **State Integrity** | OAuth 2.1 BP | ✅ HMAC-SHA256 binding | Prevents state tampering |
| **PKCE Expiration** | OAuth 2.1 BP | ✅ 5 minutes (vs 10) | Reduced attack window |
| **Token Rotation** | OAuth 2.1 BP | ✅ Single-use + reuse detection | Prevents token replay |
| **Client Auth** | RFC 6749 §2.3.1 | ✅ HTTP Basic Auth | Prevents credential logging |
| **User Binding** | OWASP | ✅ PKCE state → user\_id FK | Prevents flow hijacking |
| **Server Ownership** | Custom | ✅ Multi-level validation | Prevents token substitution |
| **Rate Limiting** | OWASP | ✅ 10 req/15min on callback | Prevents brute force |
***
## Attack Scenarios Prevented
### Before OAuth 2.1 Implementation
❌ **Authorization Code Injection**
→ Attacker could hijack victim's OAuth flow
❌ **Token Reuse Attacks**
→ Stolen refresh tokens could be used indefinitely
❌ **State Parameter Tampering**
→ Attacker could modify PKCE state to steal tokens
❌ **Credential Logging**
→ Client secrets exposed in access logs
❌ **Extended Attack Window**
→ 10-minute PKCE expiration too long
### After OAuth 2.1 Implementation
✅ **All OAuth flows bound to authenticated user**
✅ **Refresh tokens are single-use only**
✅ **HMAC integrity verification prevents tampering**
✅ **Client secrets never logged (HTTP Basic Auth)**
✅ **5-minute PKCE expiration reduces risk**
✅ **Automatic token revocation on reuse**
✅ **Server ownership validation**
✅ **Rate limiting on OAuth endpoints**
***
## Multi-Instance & Production Requirements
### Redis Rate Limiting (CRITICAL)
**Multi-Instance Deployments**: Redis is **REQUIRED** for distributed rate limiting when running multiple application instances. In-memory rate limiting is NOT SAFE for horizontal scaling.
**Why Redis is Required:**
* Rate limits are enforced **per instance** with in-memory storage
* Attackers can bypass rate limits by distributing requests across instances
* OAuth callback rate limits become ineffective
* Token refresh rate limits become ineffective
**Setup:**
```bash theme={null}
# Install Redis client
npm install redis
# Configure Redis URL
export REDIS_URL="redis://redis-host:6379"
# Production with authentication
export REDIS_URL="redis://user:password@redis-host:6379"
```
**Verification:**
The application will log on startup:
```
✅ [RateLimit] Using Redis backend for distributed rate limiting
```
If you see this warning in production:
```
⚠️ [RateLimit] WARNING: Using in-memory rate limiting in production!
⚠️ [RateLimit] This is NOT SAFE for multi-instance deployments.
```
**Action required**: Configure `REDIS_URL` immediately.
### Performance Optimizations
#### OAuth Config Caching
OAuth configurations are cached for **5 minutes** to reduce database load:
```typescript theme={null}
// Automatic - no configuration needed
// Each instance maintains its own LRU cache (max 500 entries)
// Cache invalidates on config updates
```
**Impact:** Significantly reduces database queries for frequently refreshed tokens.
#### Server Ownership Validation
Optimized from 3 sequential queries to 1 JOIN query:
```sql theme={null}
-- Before: N+1 problem (3 round-trips)
SELECT profile_uuid FROM mcp_servers WHERE uuid = $1;
SELECT project_uuid FROM profiles WHERE uuid = $2;
SELECT user_id FROM projects WHERE uuid = $3;
-- After: Single JOIN query
SELECT projects.user_id
FROM mcp_servers
INNER JOIN profiles ON mcp_servers.profile_uuid = profiles.uuid
INNER JOIN projects ON profiles.project_uuid = projects.uuid
WHERE mcp_servers.uuid = $1;
```
**Impact:** 60-70% latency improvement for token refresh operations.
#### Request Timeouts
All OAuth API calls now have 10-second timeouts:
```typescript theme={null}
await fetch(oauthConfig.token_endpoint, {
method: 'POST',
headers,
body: tokenParams,
signal: AbortSignal.timeout(10000), // NEW: Prevents hanging requests
});
```
**Impact:** Prevents resource exhaustion from unresponsive OAuth providers.
### IPv6 Support
Metrics endpoint now supports **IPv6 CIDR validation**:
```bash theme={null}
# IPv4 (existing)
METRICS_ALLOWED_IPS="127.0.0.1,::1,172.17.0.0/16"
# IPv6 (NEW)
METRICS_ALLOWED_IPS="127.0.0.1,::1,2001:db8::/32"
# IPv4-mapped IPv6
METRICS_ALLOWED_IPS="127.0.0.1,::1,::ffff:192.0.2.0/24"
```
### Production Security Checklist
**Rate Limiting:**
* [ ] Redis configured with `REDIS_URL`
* [ ] Verify Redis connection on startup
* [ ] No rate limit warnings in production logs
**Metrics Security:**
* [ ] `METRICS_ALLOWED_IPS` restricted to Prometheus IP only
* [ ] Default `10.0.0.0/8` removed (16.7M IPs)
* [ ] IPv6 ranges validated if applicable
**OAuth Configuration:**
* [ ] All instances share same `NEXTAUTH_SECRET`
* [ ] All instances connect to same database
* [ ] OAuth config caching verified (check logs)
**Performance:**
* [ ] Database connection pooling configured
* [ ] Server ownership queries optimized (JOIN)
* [ ] Request timeouts enabled (10s)
### Multi-Instance Deployment
For complete multi-instance deployment guide, see:
Production-ready horizontal scaling with Redis, load balancing, and high availability
***
## Migration Notes
### Database Changes
Two migrations were applied to support OAuth 2.1:
**Migration 0071: State Integrity Hash**
```sql theme={null}
ALTER TABLE oauth_pkce_states
ADD COLUMN integrity_hash TEXT NOT NULL;
```
**Migration 0072: Refresh Token Rotation**
```sql theme={null}
ALTER TABLE mcp_server_oauth_tokens
ADD COLUMN refresh_token_used_at TIMESTAMPTZ;
```
### Backward Compatibility
✅ **Fully Backward Compatible**
* Existing OAuth flows continue to work
* New security features apply to all new flows
* No breaking changes to API
* Automatic migration on application upgrade
***
## Environment Variables
### Required
```bash .env theme={null}
# Use existing NEXTAUTH_SECRET or set dedicated OAuth secret
NEXTAUTH_SECRET=
# Or use dedicated OAuth integrity secret
OAUTH_INTEGRITY_SECRET=
```
### Recommended
```bash .env theme={null}
# Enable automatic PKCE cleanup
CRON_SECRET=
# Production deployment flag
CLOUD_DEPLOY=true
```
***
## Monitoring & Observability
### Structured Logging with Loki
Plugged.in uses **structured JSON logging** with Loki for comprehensive OAuth security monitoring. All security events are automatically logged with full context for analysis.
See [Observability Documentation](/observability/overview) for complete setup guide
### Security Events Logged
All OAuth operations emit structured JSON logs to Loki:
```json Normal OAuth Flow theme={null}
{
"level": 30,
"time": 1699564800000,
"service_name": "pluggedin-app",
"event": "oauth_flow_success",
"provider": "github-mcp-server",
"duration_ms": 3500,
"hasRefreshToken": true,
"msg": "OAuth flow completed successfully"
}
```
```json Token Refresh Success theme={null}
{
"level": 30,
"event": "token_refresh_success",
"serverUuid": "server-uuid-123",
"duration_ms": 850,
"hasNewRefreshToken": true,
"msg": "Token rotation complete"
}
```
```json CRITICAL: Token Reuse Detected theme={null}
{
"level": 60,
"event": "oauth_refresh_token_reuse_detected",
"severity": "critical",
"userId": "user-id-123",
"serverUuid": "server-uuid-456",
"tokenUsedAt": "2024-01-15T10:29:45Z",
"currentAttempt": "2024-01-15T10:30:00Z",
"msg": "Refresh token reuse detected - revoking all tokens"
}
```
```json CRITICAL: Code Injection Attempt theme={null}
{
"level": 60,
"event": "oauth_code_injection_attempt",
"severity": "critical",
"attackerUserId": "attacker-id",
"victimUserId": "victim-id",
"state": "[REDACTED]",
"serverUuid": "server-uuid",
"msg": "Authorization code injection attack detected"
}
```
```json HIGH: Integrity Violation theme={null}
{
"level": 50,
"event": "oauth_integrity_violation",
"severity": "high",
"violationType": "hash_mismatch",
"state": "[REDACTED]",
"expectedHash": "abc123...",
"actualHash": "def456...",
"msg": "PKCE state integrity check failed"
}
```
### LogQL Security Queries
**Critical Security Events (Last Hour):**
```logql theme={null}
{service_name="pluggedin-app"}
| json
| severity="critical"
| event =~ "(token_reuse|code_injection)"
```
**All Integrity Violations:**
```logql theme={null}
{service_name="pluggedin-app"}
| json
| event="oauth_integrity_violation"
| line_format "{{.violationType}}: {{.msg}}"
```
**Token Refresh Failures:**
```logql theme={null}
{service_name="pluggedin-app"}
| json
| event="token_refresh_failure"
| line_format "{{.reason}}: {{.err.message}}"
```
**OAuth Flow Success Rate:**
```logql theme={null}
(
sum(count_over_time({service_name="pluggedin-app"} | json | event="oauth_flow_success" [5m]))
/
sum(count_over_time({service_name="pluggedin-app"} | json | event =~ "oauth_flow_(success|failure)" [5m]))
) * 100
```
### Prometheus Metrics
17 OAuth-specific metrics for real-time monitoring:
`oauth_flows_total{status="success"}` / `oauth_flows_total`
**SLO**: > 95%
`oauth_token_refresh_total{status="reuse_detected"}`
**Alert**: > 0 (Critical)
`oauth_code_injection_attempts_total`
**Alert**: > 0 (Critical)
`oauth_integrity_violations_total`
**Alert**: > 0 (High)
**PromQL Alert Queries:**
```promql theme={null}
# P0: Token reuse detected
increase(oauth_token_refresh_total{status="reuse_detected"}[5m]) > 0
# P0: Code injection attempt
increase(oauth_code_injection_attempts_total[5m]) > 0
# P1: OAuth flow success rate below 95%
(
sum(rate(oauth_flows_total{status="success"}[5m]))
/ sum(rate(oauth_flows_total[5m]))
) < 0.95
# P1: Token refresh p95 duration > 2s
histogram_quantile(0.95,
sum(rate(oauth_token_refresh_duration_seconds_bucket[5m])) by (le)
) > 2
```
### Grafana Dashboards
Pre-built dashboards available in `/observability/dashboards`:
* Success rates
* Operations/min
* Active tokens
* Error trends
* Security events timeline
* Attack heatmap
* Top attackers
* Violation breakdown
* Latency percentiles (p50, p95, p99)
* Throughput by provider
* Slow operations
* Discovery performance
### Critical Alerts Configuration
Configure these alerts in Grafana:
```yaml theme={null}
groups:
- name: oauth_critical
rules:
# P0 Alerts - Page immediately
- alert: OAuthTokenReuseDetected
expr: increase(oauth_token_refresh_total{status="reuse_detected"}[5m]) > 0
labels:
severity: critical
priority: P0
annotations:
summary: "OAuth token reuse attack detected"
description: "Potential replay attack - tokens revoked"
- alert: OAuthCodeInjectionAttempt
expr: increase(oauth_code_injection_attempts_total[5m]) > 0
labels:
severity: critical
priority: P0
annotations:
summary: "OAuth code injection attempt"
description: "Authorization code injection attack in progress"
# P1 Alerts - Notify team
- alert: OAuthFlowSuccessRateLow
expr: |
(sum(rate(oauth_flows_total{status="success"}[5m]))
/ sum(rate(oauth_flows_total[5m]))) < 0.95
for: 5m
labels:
severity: high
priority: P1
annotations:
summary: "OAuth flow success rate below 95%"
- alert: OAuthIntegrityViolations
expr: increase(oauth_integrity_violations_total[15m]) > 5
labels:
severity: high
priority: P1
annotations:
summary: "Multiple OAuth integrity violations detected"
```
### Metrics to Monitor
**SLO**: > 95%
**Metric**: `oauth_flows_total{status="success"}` / `oauth_flows_total`
**Alert if**: \< 95% for 5 minutes
**SLO**: > 99%
**Metric**: `oauth_token_refresh_total{status="success"}` / `oauth_token_refresh_total`
**Alert if**: \< 99% for 5 minutes
**Expected**: 0
**Metric**: `oauth_token_refresh_total{status="reuse_detected"}`
**Alert if**: > 0 (IMMEDIATE - Critical)
**Expected**: 0
**Metric**: `oauth_code_injection_attempts_total`
**Alert if**: > 0 (IMMEDIATE - Critical)
**Expected**: \~0
**Metric**: `oauth_integrity_violations_total`
**Alert if**: > 5 per 15 minutes (High)
**SLO**: \< 2 seconds
**Metric**: `histogram_quantile(0.95, oauth_token_refresh_duration_seconds_bucket)`
**Alert if**: > 2s for 5 minutes
### Incident Response Playbooks
**Severity**: Critical - Immediate action required
**Indicators**:
* `oauth_refresh_token_reuse_detected` event in logs
* `oauth_token_refresh_total{status="reuse_detected"}` > 0
**Automatic Actions**:
* ✅ All tokens for server immediately revoked
* ✅ User forced to re-authenticate
* ✅ Security event logged with full context
**Manual Response**:
1. Check logs for `serverUuid` and `userId`
2. Review user's recent OAuth activity
3. Check for concurrent requests (race condition vs. attack)
4. If attack: Block user IP, audit account
5. If race condition: Review application logs, check for retry logic issues
**Loki Query**:
```logql theme={null}
{service_name="pluggedin-app"}
| json
| event="oauth_refresh_token_reuse_detected"
| line_format "User: {{.userId}}, Server: {{.serverUuid}}, Used: {{.tokenUsedAt}}"
```
**Severity**: Critical - Immediate action required
**Indicators**:
* `oauth_code_injection_attempt` event in logs
* `oauth_code_injection_attempts_total` > 0
**Automatic Actions**:
* ✅ Authorization code rejected
* ✅ Security event logged with attacker/victim details
**Manual Response**:
1. Identify attacker from logs: `attackerUserId`
2. Identify victim: `victimUserId`
3. Block attacker account immediately
4. Notify victim user of attempted account compromise
5. Audit all OAuth flows for both users in last 24h
6. Check for pattern of attacks (same IP, same target servers)
**Loki Query**:
```logql theme={null}
{service_name="pluggedin-app"}
| json
| event="oauth_code_injection_attempt"
| line_format "Attacker: {{.attackerUserId}}, Victim: {{.victimUserId}}"
```
**Severity**: High - Investigate within 1 hour
**Indicators**:
* `oauth_integrity_violation` events in logs
* `oauth_integrity_violations_total` increasing
**Possible Causes**:
* State tampering attempt
* Database corruption
* Application bug (HMAC calculation mismatch)
**Manual Response**:
1. Check `violationType`: hash\_mismatch, state\_reuse, user\_mismatch
2. Review affected `serverUuid` and `userId`
3. If single occurrence: Likely user error or network issue
4. If multiple from same user: Possible attack or client issue
5. If widespread: Check for application deployment issues
**Loki Query**:
```logql theme={null}
{service_name="pluggedin-app"}
| json
| event="oauth_integrity_violation"
| line_format "[{{.violationType}}] {{.msg}}"
```
**Severity**: High - Investigate within 1 hour
**Indicators**:
* OAuth success rate \< 95%
* Increased error rates in dashboards
**Possible Causes**:
* OAuth server downtime
* Network issues
* Configuration changes
* High user error rate (expired states, etc.)
**Manual Response**:
1. Check recent deployments
2. Review error distribution by type
3. Check OAuth server status
4. Review network connectivity
5. Check for expired PKCE states (>5 minutes)
**PromQL Query**:
```promql theme={null}
topk(10, sum by (event) (
rate(oauth_flows_total{status="failure"}[5m])
))
```
### Sensitive Data Redaction
All sensitive OAuth data is automatically redacted in logs:
**Redacted Fields** (never logged in plaintext):
* `access_token`
* `refresh_token`
* `code_verifier`
* `client_secret`
* `authorization_code`
Example redacted log:
```json theme={null}
{
"event": "token_refresh_success",
"access_token": "[REDACTED]",
"refresh_token": "[REDACTED]",
"serverUuid": "visible-server-id",
"msg": "Token successfully refreshed"
}
```
***
## Testing OAuth 2.1 Compliance
### Test State Integrity
```bash theme={null}
# Should fail - tampering detected
curl "https://app.plugged.in/api/oauth/callback?code=valid&state=tampered" \
-H "Cookie: session_token"
# Expected: oauth_error=integrity_violation
```
### Test Refresh Token Reuse
```bash theme={null}
# 1. Valid refresh
curl -X POST /api/refresh-token -d "server_uuid=..."
# 2. Attempt reuse (should revoke all tokens)
curl -X POST /api/refresh-token -d "server_uuid=..."
# Expected: All tokens revoked, forced re-auth
```
### Test PKCE Expiration
```bash theme={null}
# Wait 6 minutes after initiating OAuth
curl "https://app.plugged.in/api/oauth/callback?code=valid&state=expired"
# Expected: oauth_error=state_expired
```
***
## References
PKCE - Proof Key for Code Exchange
OAuth 2.0 Authorization Framework
OAuth 2.1 Specification (Draft)
OAuth 2.0 Security Best Practices
***
## Summary
Plugged.in implements **industry-leading OAuth 2.1 security** with:
✅ **5 Core Security Enhancements** beyond OAuth 2.0
✅ **8 Attack Scenarios** prevented
✅ **Zero Breaking Changes** for existing integrations
✅ **Comprehensive Monitoring** and alerting
✅ **Full RFC Compliance** with OAuth 2.1 draft
Your MCP server authentication is **enterprise-grade secure**.
# Security Overview
Source: https://docs.plugged.in/security/overview
Comprehensive security features and best practices for Plugged.in
# Security Documentation
Plugged.in implements comprehensive security measures to protect your data and prevent various attack vectors. This document outlines our security features and best practices.
## Security Features
### 1. URL Validation and SSRF Prevention
The application implements comprehensive URL validation to prevent Server-Side Request Forgery (SSRF) attacks.
* Only allows requests to explicitly trusted domains
* Prevents requests to arbitrary external services
* Configurable per environment
**Blocks all private IPv4 ranges (RFC 1918):**
* 10.0.0.0/8
* 172.16.0.0/12
* 192.168.0.0/16
* 169.254.0.0/16 (link-local)
* 127.0.0.0/8 (loopback)
**Blocks IPv6 private/local addresses:**
* ::1 (loopback)
* fe80::/10 (link-local)
* fc00::/7 (unique local)
* ff00::/8 (multicast)
### 2. Protocol Enforcement
* Only allows HTTP and HTTPS protocols
* Blocks potentially dangerous protocols: `file://`, `ftp://`, `javascript:`, `data:`
### 3. Credential Protection
* Prevents URLs with embedded credentials (username:password@)
* Protects against credential leakage
* Automatic credential stripping in shared configurations
### 4. Special Character Protection
* Blocks null bytes in URLs
* Prevents directory traversal attempts
* Path normalization and validation
## Usage Guidelines
### For External APIs
```typescript theme={null}
import { validateExternalUrl } from '@/lib/url-validator';
// Validate before making request
const url = validateExternalUrl('https://api.github.com/repos/owner/repo');
const response = await fetch(url.toString());
```
### For Internal Registry APIs
```typescript theme={null}
import { validateInternalUrl } from '@/lib/url-validator';
// More restrictive validation for internal services
// Allows: registry.plugged.in, staging.plugged.in and their api subdomains
const url = validateInternalUrl('https://registry.plugged.in/v0/servers');
const response = await fetch(url.toString());
```
### For Development with Localhost
```typescript theme={null}
// Localhost is automatically allowed in development (NODE_ENV=development)
const url = validateExternalUrl('http://localhost:8000');
// Or explicitly enable localhost in any environment
const url = validateExternalUrl('http://localhost:8000', {
allowLocalhost: true
});
```
## Security Assumptions
### Trust Boundary
The allowed domains list defines our trust boundary. Only add domains that are:
* Under our control (registry.plugged.in, staging.plugged.in)
* Well-known, trusted third-party services (GitHub, npm, etc.)
* Required for application functionality
### Environment-based Security
* Strict domain allowlisting
* No localhost access
* Enhanced monitoring
* Localhost automatically allowed
* Relaxed restrictions for testing
* Debug logging enabled
* Staging domains always allowed
* Production-like security
* Testing environment
### Defense in Depth
URL validation is one layer of defense. Additional layers include:
* Rate limiting on API endpoints
* Authentication and authorization checks
* Input validation at multiple levels
* Output encoding to prevent XSS
### Fail Secure
When validation fails, the request is blocked. No fallback or bypass mechanisms.
## Testing
Comprehensive test coverage is provided in `tests/security/url-validator.test.ts`:
* SSRF prevention tests
* IPv4 and IPv6 validation
* Domain allowlisting
* Credential blocking
* Protocol validation
* Edge cases and attack vectors
Run security tests:
```bash theme={null}
pnpm test tests/security/url-validator.test.ts
```
## Monitoring and Logging
Consider implementing:
1. **Security Telemetry**: Log blocked requests for security monitoring
2. **Rate Limiting**: Limit validation failures per IP to prevent abuse
3. **Alerting**: Alert on unusual patterns of blocked requests
## Updating Allowed Domains
To add a new allowed domain:
Review the domain's trustworthiness and necessity
Add to `ALLOWED_DOMAINS` in `lib/url-validator.ts`
Document the reason for addition in code comments
Update tests to cover the new domain
Determine if it should be in `validateInternalUrl` allowed list
## Known Limitations
1. **DNS Rebinding**: URL validation happens before the request. DNS rebinding attacks that occur after validation are not prevented by this layer.
2. **Redirect Following**: The validator only checks the initial URL. Server-side redirects need additional handling.
3. **Time-of-Check vs Time-of-Use**: Domain resolution can change between validation and request execution.
## Incident Response
If a security issue is discovered:
1. Block the affected domain/IP immediately
2. Review logs for exploitation attempts
3. Update validation rules
4. Deploy fix with urgency
5. Document in security changelog
## Regular Security Reviews
* Review allowed domains quarterly
* Update blocked IP ranges as new private ranges are allocated
* Monitor for new SSRF techniques and update defenses
* Keep dependencies updated for security patches
## Additional Security Features
### Collective Best Practices Privacy (v3.1.0+)
Plugged.in's Collective Best Practices (CBP) system aggregates anonymized patterns from the community. All data undergoes a **three-stage anonymization pipeline** before entering the collective pool:
1. **Regex PII Removal**: Strips emails, API keys, UUIDs, file paths, IPs, JWTs, connection strings, and bearer tokens
2. **LLM Generalization**: AI removes usernames, project names, company names, and domain-specific details while preserving technical insights
3. **Post-Processing Re-Scan**: LLM output is re-scanned to catch any PII that leaked through generalization
Additional privacy guarantees:
* **HMAC-SHA256 Profile Hashing**: Profile identities are keyed-hashed — raw UUIDs never stored in the collective pool
* **k-Anonymity (k≥3)**: Patterns only become visible when 3+ independent profiles contribute the same insight
* **No Reverse Mapping**: It is impossible to trace a collective pattern back to any individual user
For full details on the anonymization pipeline, see [Data Anonymization & Collective Knowledge](/security/data-anonymization).
### End-to-End Encryption (v2.2.0+)
* All sensitive MCP server configuration data encrypted at rest
* AES-256-GCM encryption
* Per-profile encryption keys
* Automatic encryption/decryption
### Rate Limiting
* Auth endpoints: 5 requests per 15 minutes
* API endpoints: 60 requests per minute
* Public endpoints: 100 requests per minute
* AI document creation: 10 requests per hour
### Input Validation
* Zod validation schemas for all server actions
* Sanitization of HTML/Markdown content
* Path traversal protection
* Content length validation
### MCP Protocol Security
The MCP Proxy implements comprehensive protocol security measures:
* **Protocol Version Validation**: Only supported MCP protocol versions accepted (2024-11-05)
* **Header Validation**: Strict header format enforcement with Title-Case standardization
* **Authentication Isolation**: Lazy auth - discovery operations work without credentials
* **Error Code Sanitization**: Standardized JSON-RPC 2.0 error codes prevent information leakage
* **CORS Configuration**: Secure CORS headers with proper origin and header restrictions
* **Session Management**: Secure session handling with optional stateless mode
For detailed MCP security implementation, see [MCP Protocol Compliance](/mcp-proxy/protocol-compliance).
## Contact
For security concerns or vulnerability reports, please contact:
* Email: [security@plugged.in](mailto:security@plugged.in)
* GitHub Security Advisories: [Report a vulnerability](https://github.com/VeriTeknik/pluggedin-app/security/advisories/new)
# MCP Server Sandboxing
Source: https://docs.plugged.in/security/sandboxing
Comprehensive guide to sandboxing and isolation for MCP servers
# MCP Server Sandboxing
Plugged.in implements robust sandboxing for all STDIO MCP servers to ensure security and resource isolation. This guide covers the sandboxing architecture, configuration, and best practices.
## Overview
Sandboxing is enabled by default for all STDIO MCP servers. Never disable sandboxing in production environments unless absolutely necessary.
Sandboxing provides:
* **Process Isolation**: Each MCP server runs in its own isolated environment
* **Filesystem Protection**: Restricted access to system files and directories
* **Resource Limits**: CPU, memory, and I/O constraints
* **Network Control**: Optional network isolation for untrusted servers
* **Privilege Dropping**: Servers run with minimal privileges
## Sandboxing Technologies
### Bubblewrap (Primary)
Bubblewrap is the preferred sandboxing technology due to its lightweight nature and user-namespace support.
**Features:**
* User namespace isolation (no root required)
* Bind mount control for selective file access
* Network namespace support
* Resource limits via cgroups
* Minimal performance overhead
**Installation:**
```bash theme={null}
# Ubuntu/Debian
sudo apt-get install -y bubblewrap
# RHEL/CentOS/Fedora
sudo dnf install -y bubblewrap
# Verify installation
bwrap --version
```
### Firejail (Fallback)
Firejail provides SUID-based sandboxing with extensive security profiles.
**Features:**
* Extensive security profiles
* AppArmor/SELinux integration
* X11 sandboxing support
* Network filtering capabilities
* Comprehensive logging
**Installation:**
```bash theme={null}
# Ubuntu/Debian
sudo apt-get install -y firejail
# RHEL/CentOS/Fedora
sudo dnf install -y firejail
# Verify installation
firejail --version
```
### FUSE Requirements
Some applications require FUSE (Filesystem in Userspace) support:
```bash theme={null}
# Install FUSE3
sudo apt-get install -y fuse3 libfuse3-3
# Enable FUSE for containers
sudo modprobe fuse
# Verify FUSE is available
fusermount3 --version
```
## Configuration
### Environment Variables
Configure sandboxing behavior through environment variables:
```env theme={null}
# Sandboxing Type
MCP_ISOLATION_TYPE=bubblewrap # Options: bubblewrap | firejail | none
MCP_ISOLATION_FALLBACK=firejail # Fallback if primary not available
# Network Isolation
MCP_ENABLE_NETWORK_ISOLATION=false # Set to true for strict isolation
# Resource Limits
MCP_CPU_CORES_MAX=0.5 # Maximum CPU cores (0.5 = 50% of one core)
MCP_MEMORY_MAX_MB=512 # Maximum memory in MB
MCP_IO_READ_MBPS=10 # I/O read limit in MB/s
MCP_IO_WRITE_MBPS=5 # I/O write limit in MB/s
MCP_PROCESS_TIMEOUT_MS=300000 # Process timeout in milliseconds
MCP_STARTUP_TIMEOUT_MS=10000 # Startup timeout in milliseconds
# Package Storage
MCP_PACKAGE_STORE_DIR=/var/mcp-packages
MCP_PNPM_STORE_DIR=/var/mcp-packages/pnpm-store
MCP_UV_CACHE_DIR=/var/mcp-packages/uv-cache
```
### Sandboxing Modes
**Default and recommended mode**
```typescript theme={null}
// Bubblewrap configuration
{
isolation: {
type: "bubblewrap",
config: {
unshareAll: true, // Unshare all namespaces
shareNet: true, // Allow network (configurable)
dieWithParent: true, // Terminate on parent exit
newSession: true, // New session for process
uid: 1000, // Run as non-root user
gid: 1000, // Run as non-root group
hostname: "mcp-sandbox", // Isolated hostname
capDrop: ["ALL"], // Drop all capabilities
capAdd: ["CAP_NET_BIND_SERVICE"] // Add specific capabilities
}
}
}
```
**Fallback mode with SUID-based isolation**
```typescript theme={null}
// Firejail configuration
{
isolation: {
type: "firejail",
config: {
private: "/tmp/mcp-workspace", // Private workspace
noroot: true, // No root access
net: "none", // Network isolation
nodbus: true, // No D-Bus access
nogroups: true, // No supplementary groups
nonewprivs: true, // No new privileges
seccomp: true, // Seccomp filtering
capsDropAll: true, // Drop all capabilities
quiet: true // Suppress firejail output
}
}
}
```
**NOT recommended for production**
```env theme={null}
MCP_ISOLATION_TYPE=none
```
Disabling sandboxing exposes your system to potential security risks. Only use for debugging in isolated environments.
## Implementation Details
### Filesystem Isolation
The sandboxing system creates isolated filesystem views:
```typescript theme={null}
// Bubblewrap filesystem bindings
const filesystemBindings = [
// Read-only system directories
{ source: "/usr", target: "/usr", readonly: true },
{ source: "/lib", target: "/lib", readonly: true },
{ source: "/lib64", target: "/lib64", readonly: true },
// Writable workspace
{ source: "/tmp/mcp-workspace", target: "/workspace", readonly: false },
// Package manager directories
{ source: MCP_PACKAGE_STORE_DIR, target: MCP_PACKAGE_STORE_DIR, readonly: false },
// Optional: User home (restricted)
{ source: "~/.config", target: "~/.config", readonly: true }
];
```
### Resource Limits
Resource constraints applied to sandboxed processes:
```typescript theme={null}
// Resource limit configuration
const resourceLimits = {
cpu: {
cores: 0.5, // 50% of one CPU core
nice: 10 // Lower priority
},
memory: {
max: 512 * 1024 * 1024, // 512 MB
swap: 0 // No swap usage
},
io: {
readBandwidth: 10 * 1024 * 1024, // 10 MB/s read
writeBandwidth: 5 * 1024 * 1024, // 5 MB/s write
maxOpenFiles: 1024 // File descriptor limit
},
process: {
maxProcesses: 32, // Process limit
timeout: 300000 // 5 minute timeout
}
};
```
### Network Isolation
Control network access for sandboxed servers:
```env theme={null}
MCP_ENABLE_NETWORK_ISOLATION=false
```
* Servers can access external networks
* Suitable for API-based MCP servers
* Docker socket access allowed
```env theme={null}
MCP_ENABLE_NETWORK_ISOLATION=true
```
* No network access
* Loopback interface only
* Suitable for compute-only servers
```typescript theme={null}
// Advanced network configuration
{
network: {
isolation: "partial",
allowedHosts: ["api.example.com"],
allowedPorts: [443, 8080],
denyLocal: true
}
}
```
## Security Considerations
### Privilege Escalation Prevention
1. **Drop All Capabilities**: Remove all Linux capabilities by default
2. **No New Privileges**: Prevent privilege escalation via setuid
3. **User Namespace**: Run in unprivileged user namespace
4. **Seccomp Filtering**: Restrict system calls
### Directory Traversal Protection
```typescript theme={null}
// Path validation for sandbox
function validateSandboxPath(path: string): boolean {
const normalized = path.normalize(path);
const resolved = path.resolve(path);
// Prevent directory traversal
if (normalized.includes('..')) return false;
// Ensure path is within allowed directories
const allowedPaths = [
'/tmp/mcp-workspace',
MCP_PACKAGE_STORE_DIR
];
return allowedPaths.some(allowed =>
resolved.startsWith(allowed)
);
}
```
### OAuth and Authentication
Special handling for OAuth-enabled MCP servers:
```typescript theme={null}
// OAuth directory isolation
if (server.requiresOAuth) {
const oauthDir = path.join(
MCP_PACKAGE_STORE_DIR,
'servers',
server.uuid,
'oauth'
);
// Bind OAuth directory for token storage
filesystemBindings.push({
source: oauthDir,
target: oauthDir,
readonly: false
});
}
```
## Troubleshooting
### Common Issues
**Error:** "bwrap: command not found"
**Solution:**
```bash theme={null}
# Install bubblewrap
sudo apt-get update
sudo apt-get install -y bubblewrap
# Or use firejail as fallback
sudo apt-get install -y firejail
export MCP_ISOLATION_TYPE=firejail
```
**Error:** "Permission denied: /var/mcp-packages"
**Solution:**
```bash theme={null}
# Fix ownership and permissions
sudo mkdir -p /var/mcp-packages
sudo chown -R $USER:$USER /var/mcp-packages
sudo chmod -R 755 /var/mcp-packages
```
**Error:** "fusermount: fuse device not found"
**Solution:**
```bash theme={null}
# Install and enable FUSE
sudo apt-get install -y fuse3
sudo modprobe fuse
# For Docker containers
docker run --cap-add SYS_ADMIN --device /dev/fuse
```
**Error:** "Cannot connect to API endpoint"
**Solution:**
```bash theme={null}
# Disable network isolation for API servers
export MCP_ENABLE_NETWORK_ISOLATION=false
# Or allow specific servers to bypass
server.applySandboxing = false # Use with caution
```
### Debug Mode
Enable debug logging for sandboxing:
```bash theme={null}
# Enable sandbox debugging
export DEBUG=mcp:sandbox
export MCP_SANDBOX_VERBOSE=true
# View sandbox configuration
cat /proc/[PID]/status | grep Cap
cat /proc/[PID]/cgroup
```
### Testing Sandboxing
Verify sandboxing is working:
```bash theme={null}
# Test with bubblewrap
bwrap \
--unshare-all \
--share-net \
--die-with-parent \
--ro-bind /usr /usr \
--ro-bind /lib /lib \
--ro-bind /lib64 /lib64 \
--tmpfs /tmp \
--proc /proc \
--dev /dev \
-- /bin/sh -c "echo 'Sandbox works!'"
# Test with firejail
firejail \
--quiet \
--private=/tmp/test \
--noroot \
--net=none \
-- /bin/sh -c "echo 'Firejail works!'"
```
## Best Practices
Never disable sandboxing in production. If a server requires it, investigate alternatives.
Grant minimal permissions required for functionality.
Keep sandboxing tools updated for latest security fixes.
Track CPU, memory, and I/O usage to tune limits.
Test MCP servers in sandbox before production deployment.
If sandboxing must be disabled, document the reason and compensating controls.
## Performance Impact
Sandboxing overhead is minimal:
| Metric | No Sandbox | Bubblewrap | Firejail |
| --------------- | ---------- | ------------ | ------------ |
| Startup Time | 100ms | 120ms (+20%) | 150ms (+50%) |
| Memory Overhead | 0 MB | 2-4 MB | 5-10 MB |
| CPU Overhead | 0% | \< 1% | 1-2% |
| I/O Overhead | 0% | \< 1% | 2-3% |
## Platform-Specific Notes
### Docker Containers
For Docker deployments:
```dockerfile theme={null}
# Install sandboxing tools in container
RUN apt-get update && apt-get install -y \
bubblewrap \
firejail \
fuse3
# Enable required capabilities
docker run \
--cap-add SYS_ADMIN \
--cap-add NET_ADMIN \
--security-opt apparmor=unconfined \
--device /dev/fuse \
pluggedin:latest
```
### Kubernetes
For Kubernetes deployments:
```yaml theme={null}
securityContext:
capabilities:
add:
- SYS_ADMIN
- NET_ADMIN
privileged: false
runAsNonRoot: true
runAsUser: 1000
```
## Support
For sandboxing assistance:
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
* **Security Issues**: [security@plugged.in](mailto:security@plugged.in)
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
# URL Validation & Security
Source: https://docs.plugged.in/security/url-validation
Comprehensive guide to URL validation and SSRF prevention
# URL Validation & Security
Plugged.in implements multiple layers of URL validation to prevent Server-Side Request Forgery (SSRF) attacks and ensure secure connections to MCP servers.
## Overview
Proper URL validation is critical for preventing SSRF attacks that could expose internal resources.
URL validation occurs at multiple levels:
1. **Input Validation**: Syntax and format checking
2. **Domain Allowlisting**: Approved domains only
3. **IP Range Blocking**: Prevent internal network access
4. **Protocol Validation**: HTTPS enforcement
5. **Port Restrictions**: Limited to safe ports
## Validation Layers
### 1. Input Validation
All URLs are validated using strict patterns:
```typescript theme={null}
// URL validation schema using Zod
const urlSchema = z.string()
.url("Invalid URL format")
.regex(/^https?:\/\//, "URL must start with http:// or https://")
.refine(url => {
try {
const parsed = new URL(url);
return parsed.hostname !== 'localhost' &&
!parsed.hostname.startsWith('127.') &&
!parsed.hostname.startsWith('192.168.') &&
!parsed.hostname.startsWith('10.') &&
!parsed.hostname.startsWith('172.');
} catch {
return false;
}
}, "URL points to restricted network");
```
### 2. Domain Allowlisting
Only pre-approved domains are allowed for MCP server connections in production.
```typescript theme={null}
const ALLOWED_DOMAINS = [
'github.com',
'api.github.com',
'registry.plugged.in',
'api.anthropic.com',
'api.openai.com',
'*.vercel.app', // Wildcard support
'*.netlify.app'
];
function isDomainAllowed(url: string): boolean {
const { hostname } = new URL(url);
return ALLOWED_DOMAINS.some(allowed => {
if (allowed.startsWith('*.')) {
const suffix = allowed.slice(2);
return hostname.endsWith(suffix);
}
return hostname === allowed;
});
}
```
### 3. IP Range Blocking
Prevent access to internal networks:
```typescript theme={null}
const BLOCKED_IP_RANGES = [
'127.0.0.0/8', // Loopback
'10.0.0.0/8', // Private network
'172.16.0.0/12', // Private network
'192.168.0.0/16', // Private network
'169.254.0.0/16', // Link-local
'fc00::/7', // IPv6 private
'::1/128' // IPv6 loopback
];
async function isIPAllowed(hostname: string): Promise {
const addresses = await dns.resolve4(hostname);
for (const address of addresses) {
if (isInBlockedRange(address, BLOCKED_IP_RANGES)) {
return false;
}
}
return true;
}
```
### 4. Protocol Validation
Enforce secure protocols:
```typescript theme={null}
const ALLOWED_PROTOCOLS = ['https:', 'wss:'];
const DEVELOPMENT_PROTOCOLS = ['http:', 'ws:'];
function isProtocolAllowed(url: string): boolean {
const { protocol } = new URL(url);
if (process.env.NODE_ENV === 'development') {
return [...ALLOWED_PROTOCOLS, ...DEVELOPMENT_PROTOCOLS]
.includes(protocol);
}
return ALLOWED_PROTOCOLS.includes(protocol);
}
```
### 5. Port Restrictions
Limit connections to safe ports:
```typescript theme={null}
const ALLOWED_PORTS = [
80, // HTTP
443, // HTTPS
3000, // Common dev port
8080, // Alternative HTTP
8443 // Alternative HTTPS
];
function isPortAllowed(url: string): boolean {
const { port, protocol } = new URL(url);
// Default ports
if (!port) {
return protocol === 'https:' || protocol === 'http:';
}
return ALLOWED_PORTS.includes(parseInt(port));
}
```
## Implementation
### Complete Validation Function
```typescript theme={null}
export async function validateMCPServerURL(
url: string,
options: ValidationOptions = {}
): Promise {
const {
allowLocalhost = false,
allowPrivateNetworks = false,
customAllowedDomains = [],
strict = true
} = options;
try {
// 1. Parse URL
const parsed = new URL(url);
// 2. Protocol check
if (!isProtocolAllowed(parsed.href)) {
return {
valid: false,
error: 'Protocol not allowed'
};
}
// 3. Port check
if (!isPortAllowed(parsed.href)) {
return {
valid: false,
error: 'Port not allowed'
};
}
// 4. Domain allowlist check (production only)
if (strict && !isDomainAllowed(parsed.href)) {
return {
valid: false,
error: 'Domain not in allowlist'
};
}
// 5. IP range check
if (!allowPrivateNetworks) {
const ipAllowed = await isIPAllowed(parsed.hostname);
if (!ipAllowed) {
return {
valid: false,
error: 'IP address in blocked range'
};
}
}
// 6. Additional security checks
if (hasPathTraversal(parsed.pathname)) {
return {
valid: false,
error: 'Path traversal detected'
};
}
return {
valid: true,
sanitized: sanitizeURL(parsed)
};
} catch (error) {
return {
valid: false,
error: 'Invalid URL format'
};
}
}
```
### URL Sanitization
Clean and normalize URLs:
```typescript theme={null}
function sanitizeURL(parsed: URL): string {
// Remove credentials
parsed.username = '';
parsed.password = '';
// Remove fragment
parsed.hash = '';
// Normalize path
parsed.pathname = parsed.pathname
.replace(/\/+/g, '/') // Multiple slashes
.replace(/\.\./g, '') // Path traversal
.replace(/^\/~/, '/'); // Home directory
// Remove dangerous query parameters
const params = new URLSearchParams(parsed.search);
const dangerous = ['redirect', 'callback', 'return_to'];
dangerous.forEach(param => params.delete(param));
parsed.search = params.toString();
return parsed.toString();
}
```
## Security Headers
### Content Security Policy
Prevent XSS and data injection:
```typescript theme={null}
const CSP_DIRECTIVES = {
'default-src': ["'self'"],
'script-src': ["'self'", "'unsafe-inline'"],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", "data:", "https:"],
'connect-src': [
"'self'",
"https://api.github.com",
"https://registry.plugged.in",
"wss://plugged.in"
],
'frame-ancestors': ["'none'"],
'form-action': ["'self'"],
'base-uri': ["'self'"]
};
```
### Additional Security Headers
```typescript theme={null}
app.use((req, res, next) => {
// Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');
// Prevent MIME sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');
// Enable XSS protection
res.setHeader('X-XSS-Protection', '1; mode=block');
// Referrer policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// Permissions policy
res.setHeader('Permissions-Policy',
'geolocation=(), microphone=(), camera=()');
next();
});
```
## SSRF Prevention
### Request Interception
Intercept and validate all outgoing requests:
```typescript theme={null}
import { Agent } from 'https';
const secureAgent = new Agent({
lookup: (hostname, options, callback) => {
// Custom DNS resolution with validation
dns.resolve4(hostname, (err, addresses) => {
if (err) return callback(err);
// Check each resolved IP
for (const address of addresses) {
if (isInBlockedRange(address)) {
return callback(new Error('Blocked IP range'));
}
}
callback(null, addresses[0], 4);
});
}
});
// Use secure agent for all requests
const response = await fetch(url, {
agent: secureAgent
});
```
### Timeout Protection
Prevent hanging connections:
```typescript theme={null}
const TIMEOUT_MS = 30000; // 30 seconds
async function safeRequest(url: string): Promise {
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, TIMEOUT_MS);
try {
const response = await fetch(url, {
signal: controller.signal,
agent: secureAgent
});
return response;
} finally {
clearTimeout(timeout);
}
}
```
## Testing URL Validation
### Unit Tests
```typescript theme={null}
describe('URL Validation', () => {
it('should reject localhost URLs', async () => {
const result = await validateMCPServerURL('http://localhost:3000');
expect(result.valid).toBe(false);
expect(result.error).toContain('restricted network');
});
it('should reject private IPs', async () => {
const result = await validateMCPServerURL('http://192.168.1.1');
expect(result.valid).toBe(false);
expect(result.error).toContain('blocked range');
});
it('should allow approved domains', async () => {
const result = await validateMCPServerURL('https://api.github.com');
expect(result.valid).toBe(true);
});
it('should sanitize URLs', async () => {
const result = await validateMCPServerURL(
'https://user:pass@example.com/../path?redirect=evil'
);
expect(result.sanitized).toBe('https://example.com/path');
});
});
```
### Security Testing
Test SSRF prevention:
```bash theme={null}
# Test localhost bypass attempts
curl -X POST /api/servers \
-d '{"url": "http://0.0.0.0:8080"}'
# Test DNS rebinding
curl -X POST /api/servers \
-d '{"url": "http://evil.rebind.network"}'
# Test URL encoding bypass
curl -X POST /api/servers \
-d '{"url": "http://127.0.0.1%2f"}'
# Test redirect bypass
curl -X POST /api/servers \
-d '{"url": "https://trusted.com/redirect?to=http://localhost"}'
```
## Configuration
### Environment Variables
```env theme={null}
# URL Validation
ALLOWED_DOMAINS=github.com,api.anthropic.com
BLOCK_PRIVATE_NETWORKS=true
ENFORCE_HTTPS=true
MAX_REDIRECT_COUNT=5
# Timeouts
REQUEST_TIMEOUT_MS=30000
DNS_TIMEOUT_MS=5000
# Security
ENABLE_CSP=true
ENABLE_HSTS=true
```
### Runtime Configuration
```typescript theme={null}
interface SecurityConfig {
url: {
validation: {
enabled: boolean;
strict: boolean;
allowLocalhost: boolean;
allowPrivateNetworks: boolean;
customAllowedDomains: string[];
blockedPorts: number[];
maxRedirects: number;
};
sanitization: {
enabled: boolean;
removeCredentials: boolean;
removeFragment: boolean;
normalizeProtocol: boolean;
};
};
headers: {
csp: boolean;
hsts: boolean;
frameOptions: string;
contentTypeOptions: boolean;
};
}
```
## Best Practices
Never trust user-provided URLs. Always validate before use.
Explicitly allow known-good domains rather than blocking bad ones.
Re-validate URLs after following redirects.
Log all validation failures for security monitoring.
Periodically review and update validation rules.
Use multiple layers of validation, don't rely on a single check.
## Troubleshooting
### Common Issues
| Issue | Cause | Solution |
| ------------------ | ----------------------- | ------------------------- |
| Valid URL rejected | Domain not in allowlist | Add to ALLOWED\_DOMAINS |
| Timeout errors | DNS resolution slow | Increase DNS\_TIMEOUT\_MS |
| False positives | Overly strict rules | Adjust validation options |
| Bypass attempts | Inadequate validation | Add additional checks |
## Support
For security-related questions:
* **Security Issues**: [security@plugged.in](mailto:security@plugged.in)
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
# Setup Guide
Source: https://docs.plugged.in/setup-guide
Connect your MCP clients to Plugged.in and share resources across all your AI tools.
# Plugged.in Setup Guide
**Why Connect to Plugged.in?** By connecting Plugged.in to your MCP clients, you'll get a unified layer where you can:
Create a document on LM Studio and instantly access or update it with Claude Code, ChatGPT, or any other connected client.
Create tasks in one client and mark them as completed from any other client - perfect for workflow continuity.
Configure your MCP servers once in Plugged.in and use the same tools across Claude Desktop, Cursor, LM Studio, ChatGPT, and more - without reconfiguring each client.
**Multiple Connection Methods:** Choose the approach that works best for your workflow - from simple npx commands to Docker deployments to local development setups.
## Who should follow this guide
* Developers connecting Claude Desktop, Cline, Cursor, LM Studio, ChatGPT, or any MCP-compatible tool to Plugged.in
* Teams who want to share knowledge, tools, and tasks across different AI clients
* Anyone who wants to avoid reconfiguring MCP servers for each AI platform
## Prerequisites
* Node.js 20 LTS or newer (for npx/pnpm methods)
* A Plugged.in account with API key access
* Your favorite MCP client (Claude Desktop, Cursor, LM Studio, etc.)
## 1. Create an API key
1. Sign in at [https://plugged.in](https://plugged.in)
2. Open **Settings -> API Keys**
3. Create a key with MCP access scope
4. Copy the value (keys start with `pg_in_`). Store it securely.
## 2. Connect your MCP client
Most users can connect without any installation - just use npx! The proxy package downloads automatically when needed.
Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"command": "npx",
"args": [
"-y",
"@pluggedin/pluggedin-mcp-proxy@latest"
],
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
**Alternative (global install):**
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"command": "pluggedin-mcp-proxy",
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
Restart Claude Desktop after saving.
Edit `%APPDATA%\Claude\claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"command": "npx",
"args": [
"-y",
"@pluggedin/pluggedin-mcp-proxy@latest"
],
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
Restart Claude Desktop to apply changes.
**Configuration:**
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"command": "npx",
"args": [
"-y",
"@pluggedin/pluggedin-mcp-proxy@latest"
],
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
**Setup:** Add this configuration to your Cursor/VS Code MCP settings and restart the editor.
**Configuration:**
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"command": "npx",
"args": [
"-y",
"@pluggedin/pluggedin-mcp-proxy@latest"
],
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
**Setup:** Add this configuration to LM Studio's MCP settings in the desktop app.
**Start proxy as HTTP service:**
```bash theme={null}
PLUGGEDIN_API_KEY=pg_in_your_key \
npx @pluggedin/pluggedin-mcp-proxy@latest \
--transport streamable-http --port 12006 --require-api-auth
```
**ChatGPT configuration:**
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"url": "http://localhost:12006/mcp",
"headers": {
"Authorization": "Bearer pg_in_your_key"
}
}
}
}
```
The **official Plugged.in plugin** provides the best Claude Code experience — device authorization, persistent memory, lifecycle hooks, and 9 built-in skills.
**Install from the marketplace:**
```bash theme={null}
/plugin marketplace add VeriTeknik/pluggedin-plugin
/plugin install pluggedin@VeriTeknik-pluggedin-plugin
```
**Set up with device authorization:**
```bash theme={null}
/pluggedin:setup
```
This opens your browser for a one-click authorization flow (similar to `gh auth login`):
1. A verification code is displayed in your terminal
2. Your browser opens to the Plugged.in authorization page
3. Verify the codes match, select a Hub, and click **Authorize**
4. Your API key is automatically saved to `.claude/settings.local.json`
5. Restart Claude Code, then run `/pluggedin:status` to verify
No manual key copying needed.
If you prefer a lightweight setup without the full plugin, connect directly via the MCP proxy:
```bash theme={null}
claude mcp add -e PLUGGEDIN_API_KEY=pg_in_your_key PluggedIn -- npx -y @pluggedin/pluggedin-mcp-proxy@latest
```
This registers the MCP server and injects the API key. If you prefer manual configuration, add the full MCP server block to `.claude/settings.local.json`:
```json theme={null}
{
"mcpServers": {
"PluggedIn": {
"command": "npx",
"args": ["-y", "@pluggedin/pluggedin-mcp-proxy@latest"],
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
The direct proxy gives you MCP tools only. The official plugin adds memory sessions, lifecycle hooks, agents, and skills on top.
## 3. Install the proxy (if needed)
**Most users can skip this step!** npx, pnpm dlx, and Docker work without installation. Only install globally if you prefer it for long-lived desktop integrations.
```bash theme={null}
# macOS/Linux
PLUGGEDIN_API_KEY=pg_in_your_key \
npx -y @pluggedin/pluggedin-mcp-proxy@latest
# Windows PowerShell
$env:PLUGGEDIN_API_KEY = "pg_in_your_key"
npx -y @pluggedin/pluggedin-mcp-proxy@latest
```
Downloads and runs the proxy on demand.
```bash theme={null}
npm install -g @pluggedin/pluggedin-mcp-proxy
PLUGGEDIN_API_KEY=pg_in_your_key pluggedin-mcp-proxy
```
Best for long-lived desktop integrations.
```bash theme={null}
PLUGGEDIN_API_KEY=pg_in_your_key \
pnpm dlx -y @pluggedin/pluggedin-mcp-proxy@latest
```
Keeps the package in pnpm's store for reuse.
```bash theme={null}
docker run --rm -it \
-e PLUGGEDIN_API_KEY=pg_in_your_key \
-e PLUGGEDIN_API_BASE_URL=https://plugged.in \
ghcr.io/veriteknik/pluggedin-mcp:latest \
--transport streamable-http --port 12006 --require-api-auth
```
Perfect for server deployments and HTTP mode.
## 3. Configure environment variables
Set these before launching the proxy (most are optional with sensible defaults).
| Variable | Required | Default | Purpose |
| ------------------------------- | -------- | -------------------- | --------------------------------------------------------------------------------- |
| `PLUGGEDIN_API_KEY` | Required | Required | Authenticates the proxy with your Plugged.in workspace. |
| `PLUGGEDIN_API_BASE_URL` | Optional | `https://plugged.in` | Change only if you self-host the Plugged.in app. |
| `PLUGGEDIN_UUID_TOOL_PREFIXING` | Optional | `true` | Disable (`false`) if your client cannot handle prefixed tool names. |
| `PLUGGEDIN_DEBUG` | Optional | `false` | Set to `true` to log verbose diagnostics (Streamable HTTP mode prints to stdout). |
**Environment Setup:** On Windows CMD use `set VAR=value`, on PowerShell use `$env:VAR='value'`, on macOS/Linux use `export VAR=value`.
## 4. Verify with MCP Inspector
Run a quick end-to-end check:
```bash theme={null}
PLUGGEDIN_API_KEY=pg_in_your_key \
npx @modelcontextprotocol/inspector npx:-y:@pluggedin/pluggedin-mcp-proxy@latest
```
Inside the Inspector:
1. Choose **List tools** - you should see static tools like `pluggedin_setup` plus any servers you configured in Plugged.in.
2. Call `pluggedin_discover_tools` - this refreshes server metadata if you just added a new integration.
3. Try `pluggedin_search_documents` or `pluggedin_ask_knowledge_base` to confirm knowledge-base access.
## 5. Add MCP servers from the UI
Once your client is connected, you'll want to add some MCP servers to see the cross-client sharing in action:
Visit [https://plugged.in/search](https://plugged.in/search) to explore 1,500+ available MCP servers
Start with these community favorites to see cross-client sharing:
* **GitHub Tools** - Create issues in Claude Desktop, check status in Cursor
* **Database Tools** - Query data in LM Studio, analyze results in ChatGPT
* **File System** - Search files in VS Code, read contents in Claude Code
* **Web Search** - Research in one client, summarize findings in another
For each server you add:
* Choose your preferred transport (STDIO, SSE, or HTTP)
* Configure environment variables if needed
* Set command arguments for STDIO servers
* Test the connection before saving
After adding servers in the UI:
* Use `pluggedin_discover_tools` in any connected client to refresh
* You should see your new servers' tools in ALL connected clients
* Test cross-client workflow: create content in one client, access it from another
**Cross-Client Benefits:** Once configured in Plugged.in, your servers work across ALL connected clients. Configure once, use everywhere!
## 6. Local development setup (optional)
For contributors or advanced users who want to run the MCP proxy locally:
```bash theme={null}
git clone https://github.com/VeriTeknik/pluggedin-mcp.git
cd pluggedin-mcp
npm install
```
```bash theme={null}
cp .env.example .env.local
# Edit .env.local and add your API key:
# PLUGGEDIN_API_KEY=pg_in_your_key
# PLUGGEDIN_API_BASE_URL=https://plugged.in
```
```bash theme={null}
npm run build
npm run inspector # Test with MCP Inspector
```
```json theme={null}
{
"mcpServers": {
"PluggedInMCP": {
"command": "node",
"args": ["/path/to/pluggedin-mcp/dist/index.js"],
"env": {
"PLUGGEDIN_API_KEY": "pg_in_your_key"
}
}
}
}
```
## Built-in static tools
| Tool | Requires API key? | Purpose |
| ---------------------------------------------------------------------------------------------------------------------------------- | ----------------- | ---------------------------------------------------------- |
| `pluggedin_setup` | No | Walks through onboarding topics without hitting the API. |
| `pluggedin_discover_tools` | Partial | Refreshes server metadata; full results need an API key. |
| `pluggedin_ask_knowledge_base` | Yes | Answers questions from your Plugged.in knowledge base. |
| `pluggedin_search_documents`, `pluggedin_get_document`, `pluggedin_update_document` | Yes | Work with knowledge-base documents. |
| `pluggedin_send_notification`, `pluggedin_list_notifications`, `pluggedin_mark_notification_done`, `pluggedin_delete_notification` | Yes | Manage Plugged.in notifications programmatically. |
| `pluggedin_create_document`, `pluggedin_list_documents` | Yes | Create and browse AI-authored documents in your workspace. |
## Troubleshooting
* **Blank tool list** - Confirm `PLUGGEDIN_API_KEY` is set and your Plugged.in workspace has active MCP servers.
* **401 Unauthorized (HTTP mode)** - Your client must pass `Authorization: Bearer pg_in...` when `--require-api-auth` is set.
* **Prefixed tool names look odd** - Set `PLUGGEDIN_UUID_TOOL_PREFIXING=false` if your client duplicates prefixes.
* **Tools not appearing** - Run `pluggedin_discover_tools` in your client after adding servers in the UI.
* **Cross-client sharing not working** - Ensure all clients use the same Plugged.in workspace and API key.
* **Connection issues** - Check that your API key is valid and has MCP access permissions.
* **Package installation issues** - Use `npx -y @pluggedin/pluggedin-mcp-proxy@latest` with the `-y` flag to auto-approve.
* **Still stuck?** Collect logs with `PLUGGEDIN_DEBUG=true` and contact [api-support@plugged.in](mailto:api-support@plugged.in).
# Email Testing Guide
Source: https://docs.plugged.in/testing/email-testing
Test email functionality using Mailtrap and other services
# Email Testing
This guide explains how to test email functionality in Plugged.in using [Mailtrap](https://mailtrap.io) for development and staging environments.
## Quick Setup with Mailtrap
Sign up for a free account at [Mailtrap.io](https://mailtrap.io)
Navigate to **Inboxes** → Select inbox → **SMTP Settings** → Choose **Nodemailer**
```env theme={null}
EMAIL_SERVER_HOST=sandbox.smtp.mailtrap.io
EMAIL_SERVER_PORT=2525
EMAIL_SERVER_USER=your-mailtrap-username
EMAIL_SERVER_PASSWORD=your-mailtrap-password
EMAIL_FROM=noreply@plugged.in
EMAIL_FROM_NAME=Plugged.in
```
```bash theme={null}
curl -X POST http://localhost:12005/api/auth/test-email \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer your-admin-secret' \
-d '{"email": "test@example.com"}'
```
## Email Templates
Plugged.in includes responsive HTML email templates for various notifications:
Sent when users register to verify their email address
Sent when users request a password reset
Activity alerts and system notifications
Onboarding email for new users
## Development Setup
### 1. Install Dependencies
Ensure email dependencies are installed:
```bash theme={null}
pnpm install nodemailer @types/nodemailer
```
### 2. Configure Mailtrap
1. Log into [Mailtrap Dashboard](https://mailtrap.io)
2. Navigate to **Inboxes**
3. Click on your inbox
4. Copy SMTP credentials
5. Select **Nodemailer** integration
```bash theme={null}
# Get API token from Mailtrap settings
curl -X GET "https://mailtrap.io/api/v1/inboxes" \
-H "Api-Token: your-api-token"
```
### 3. Environment Configuration
Create or update `.env.local`:
```env theme={null}
# Mailtrap Settings
EMAIL_SERVER_HOST=sandbox.smtp.mailtrap.io
EMAIL_SERVER_PORT=2525
EMAIL_SERVER_USER=your-username
EMAIL_SERVER_PASSWORD=your-password
# Email Configuration
EMAIL_FROM=noreply@plugged.in
EMAIL_FROM_NAME=Plugged.in
ENABLE_EMAIL_VERIFICATION=true
# Admin Secret for Testing
ADMIN_SECRET=your-secret-key
```
### 4. Test Email Functionality
#### Using Application Forms
* **Password Reset**: Visit `/forgot-password`
* **User Registration**: Visit `/register`
* **Email Verification**: Complete registration flow
#### Using Test Endpoint
```bash theme={null}
# Test email delivery
curl -X POST http://localhost:12005/api/auth/test-email \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer your-admin-secret' \
-d '{
"email": "test@example.com",
"subject": "Test Email",
"template": "verification"
}'
```
## Email Template Customization
### Template Structure
All email templates follow this structure:
```html theme={null}
```
### Customizing Templates
Edit email templates in `lib/email.ts`:
```typescript theme={null}
// lib/email.ts
export const emailTemplates = {
verification: (token: string) => ({
subject: 'Verify your email',
html: generateTemplate({
title: 'Email Verification',
content: `Click below to verify your email`,
buttonText: 'Verify Email',
buttonUrl: `${process.env.NEXTAUTH_URL}/verify?token=${token}`
})
}),
passwordReset: (token: string) => ({
subject: 'Reset your password',
html: generateTemplate({
title: 'Password Reset',
content: `Click below to reset your password`,
buttonText: 'Reset Password',
buttonUrl: `${process.env.NEXTAUTH_URL}/reset-password?token=${token}`
})
})
};
```
### Logo Customization
Logos are embedded as base64 to ensure display even when images are blocked.
Replace the logo:
```typescript theme={null}
// Convert logo to base64
const logoBase64 = fs.readFileSync('logo.png').toString('base64');
// Update in lib/email.ts
const DEFAULT_LOGO_BASE64 = `data:image/png;base64,${logoBase64}`;
```
**Logo Guidelines:**
* Maximum size: 30KB (to avoid email size issues)
* Recommended dimensions: 200x50px
* Format: PNG with transparency or JPEG
* Optimize before converting to base64
## Testing Strategies
### Unit Testing
```typescript theme={null}
// tests/email.test.ts
import { sendEmail } from '@/lib/email';
import { vi, describe, it, expect } from 'vitest';
describe('Email Service', () => {
it('should send verification email', async () => {
const mockTransport = {
sendMail: vi.fn().mockResolvedValue({ messageId: '123' })
};
const result = await sendEmail({
to: 'test@example.com',
subject: 'Test',
html: 'Test
'
});
expect(mockTransport.sendMail).toHaveBeenCalled();
expect(result.messageId).toBe('123');
});
});
```
### Integration Testing
```typescript theme={null}
// tests/email.integration.test.ts
describe('Email Integration', () => {
it('should deliver to Mailtrap', async () => {
const response = await fetch('/api/auth/test-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.ADMIN_SECRET}`
},
body: JSON.stringify({
email: 'integration@test.com'
})
});
expect(response.status).toBe(200);
// Verify in Mailtrap API
const mailtrapMessages = await checkMailtrap();
expect(mailtrapMessages).toContainEmail('integration@test.com');
});
});
```
## Production Email Services
### Supported Providers
```env theme={null}
EMAIL_SERVER_HOST=smtp.sendgrid.net
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=apikey
EMAIL_SERVER_PASSWORD=your-sendgrid-api-key
```
```env theme={null}
EMAIL_SERVER_HOST=email-smtp.us-east-1.amazonaws.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=your-smtp-username
EMAIL_SERVER_PASSWORD=your-smtp-password
```
```env theme={null}
EMAIL_SERVER_HOST=smtp.mailgun.org
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=postmaster@your-domain.mailgun.org
EMAIL_SERVER_PASSWORD=your-mailgun-password
```
```env theme={null}
EMAIL_SERVER_HOST=smtp.gmail.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=your-email@gmail.com
EMAIL_SERVER_PASSWORD=your-app-password
```
### Production Checklist
* [ ] Replace Mailtrap with production email service
* [ ] Configure SPF, DKIM, and DMARC records
* [ ] Set up email bounce handling
* [ ] Implement rate limiting for email sending
* [ ] Add email analytics tracking
* [ ] Configure unsubscribe links
* [ ] Test email deliverability
* [ ] Monitor email reputation
* [ ] Remove or secure test endpoints
* [ ] Update logo to production version
## Email Debugging
### Common Issues
**Solutions:**
* Verify Mailtrap credentials in `.env`
* Check console for error messages
* Ensure `EMAIL_SERVER_PORT` is 2525 (not 25 or 587)
* Test connection with telnet: `telnet sandbox.smtp.mailtrap.io 2525`
**Solutions:**
* Check firewall settings
* Verify network allows outbound SMTP
* Try alternative ports (2525, 587, 465)
* Use secure connection: `EMAIL_SERVER_SECURE=true`
**Solutions:**
* Regenerate Mailtrap credentials
* Ensure no extra spaces in credentials
* Check for special characters that need escaping
* Verify account is active and not suspended
**Solutions:**
* Use base64 embedded images
* Keep image size under 30KB
* Test in multiple email clients
* Provide alt text for accessibility
### Debug Mode
Enable detailed logging:
```typescript theme={null}
// lib/email.ts
import { createTransport } from 'nodemailer';
const transporter = createTransport({
host: process.env.EMAIL_SERVER_HOST,
port: Number(process.env.EMAIL_SERVER_PORT),
auth: {
user: process.env.EMAIL_SERVER_USER,
pass: process.env.EMAIL_SERVER_PASSWORD,
},
debug: true, // Enable debug output
logger: true // Log to console
});
```
### Testing Tools
Safe email testing sandbox
[mailtrap.io](https://mailtrap.io)
Spam score analysis
[mail-tester.com](https://www.mail-tester.com)
Email client preview testing
[litmus.com](https://litmus.com)
Comprehensive email testing
[emailonacid.com](https://www.emailonacid.com)
## API Reference
### Test Email Endpoint
```typescript theme={null}
POST /api/auth/test-email
Authorization: Bearer {admin-secret}
{
"email": "recipient@example.com",
"subject": "Custom Subject",
"template": "verification" | "passwordReset" | "notification"
}
Response:
{
"success": true,
"messageId": "abc123",
"preview": "https://mailtrap.io/inboxes/123/messages/456"
}
```
### Email Service Methods
```typescript theme={null}
// Send email
await sendEmail({
to: string | string[],
subject: string,
html: string,
text?: string,
attachments?: Array<{
filename: string,
content: Buffer
}>
});
// Send templated email
await sendTemplatedEmail({
to: string,
template: 'verification' | 'passwordReset',
data: {
token: string,
userName?: string,
expiresIn?: string
}
});
```
## Support
For email testing assistance:
* **Documentation**: [docs.plugged.in](https://docs.plugged.in)
* **Mailtrap Support**: [help.mailtrap.io](https://help.mailtrap.io)
* **GitHub Issues**: [Report issues](https://github.com/VeriTeknik/pluggedin-app/issues)
# Troubleshooting Guide
Source: https://docs.plugged.in/troubleshooting
Common issues and solutions for the Plugged.in platform
# Troubleshooting Guide
This guide covers common issues and their solutions for the Plugged.in platform. Use this as a reference when encountering problems.
## Quick Diagnostics
### Health Check Commands
```bash theme={null}
# Check if services are running
systemctl status pluggedin-app pluggedin-mcp
# Check logs for errors
journalctl -u pluggedin-app -f
tail -f /var/log/pluggedin/app.log
# Test database connectivity
pnpm db:check
# Verify MCP proxy health
curl http://localhost:12005/health
```
### Common Status Codes
* **200**: Success
* **400**: Bad Request - Check your parameters
* **401**: Unauthorized - Check API key
* **403**: Forbidden - Insufficient permissions
* **404**: Not Found - Check endpoint URL
* **429**: Rate Limited - Too many requests
* **500**: Server Error - Check server logs
## MCP Server Issues
### "Session not found" Errors
**Symptoms:**
* MCP tools return "Session not found"
* Server appears offline in web interface
**Solutions:**
1. **Check MCP Proxy Status**
```bash theme={null}
# Verify proxy is running
systemctl status pluggedin-mcp
# Check proxy logs
journalctl -u pluggedin-mcp -n 50
```
2. **Restart MCP Proxy**
```bash theme={null}
# Restart the proxy service
systemctl restart pluggedin-mcp
# Or manually restart
cd pluggedin-mcp && pnpm start
```
3. **Clear Browser Cache**
```bash theme={null}
# Hard refresh in browser
Ctrl+Shift+R (Linux/Windows)
Cmd+Shift+R (Mac)
```
### Tool Name Collisions
**Symptoms:**
* Tools from different servers have same names
* Some tools not appearing in client
**Solutions:**
1. **Enable UUID Prefixing** (v2.9.0+)
```bash theme={null}
# Check if UUID prefixing is enabled
grep UUID_PREFIX pluggedin-app/.env
# Enable if not set
echo "UUID_PREFIX_ENABLED=true" >> pluggedin-app/.env
```
2. **Manual Server Restart**
```bash theme={null}
# Restart app to apply changes
pm2 restart pluggedin-app
```
### Sandboxing Issues
**Symptoms:**
* STDIO servers fail to start
* Permission denied errors
* Sandbox-related failures
**Solutions:**
1. **Check Sandbox Configuration**
```bash theme={null}
# Verify sandbox settings
grep MCP_ISOLATION pluggedin-app/.env
# Required settings
echo "MCP_ISOLATION_TYPE=bubblewrap" >> pluggedin-app/.env
echo "MCP_ISOLATION_FALLBACK=firejail" >> pluggedin-app/.env
```
2. **Install Dependencies**
```bash theme={null}
# Ubuntu/Debian
sudo apt-get install bubblewrap firejail fuse3
# CentOS/RHEL
sudo yum install bubblewrap firejail fuse3
# Arch Linux
sudo pacman -S bubblewrap firejail fuse3
```
3. **Test Sandbox**
```bash theme={null}
# Test bubblewrap
bwrap --ro-bind / / --proc /proc --dev /dev --tmpfs /tmp echo "Sandbox works"
# Test firejail
firejail --version
```
## Database Issues
### Connection Failures
**Symptoms:**
* "Connection refused" errors
* Database timeout issues
* Migration failures
**Solutions:**
1. **Check Database Status**
```bash theme={null}
# PostgreSQL status
systemctl status postgresql
# Test connection
psql -h localhost -U pluggedin_user pluggedin_db
```
2. **Verify Connection String**
```bash theme={null}
# Check environment variables
grep DATABASE_URL pluggedin-app/.env
# Test connection string
psql "$DATABASE_URL" -c "SELECT 1"
```
3. **Common Fixes**
```bash theme={null}
# Restart PostgreSQL
systemctl restart postgresql
# Check available connections
psql -c "SELECT count(*) FROM pg_stat_activity WHERE datname = 'pluggedin_db'"
```
### Migration Issues
**Symptoms:**
* Migration command fails
* Schema inconsistencies
* Data corruption
**Solutions:**
1. **Safe Migration Process**
```bash theme={null}
# Always backup first
pg_dump pluggedin_db > backup_$(date +%Y%m%d_%H%M%S).sql
# Run migration in transaction
pnpm db:migrate
# Verify migration
pnpm db:verify
```
2. **Rollback Migration**
```bash theme={null}
# Rollback last migration
pnpm db:migrate:down
# Restore from backup if needed
psql pluggedin_db < backup_file.sql
```
## Authentication Issues
### API Key Problems
**Symptoms:**
* 401 Unauthorized errors
* API requests failing
* Cannot access protected endpoints
**Solutions:**
1. **Verify API Key**
```bash theme={null}
# Check if key exists
grep PLUGGEDIN_API_KEY pluggedin-app/.env
# Test API key
curl -H "Authorization: Bearer $PLUGGEDIN_API_KEY" \
https://plugged.in/api/profile
```
2. **Generate New Key**
```bash theme={null}
# Generate new API key
openssl rand -hex 32
# Update environment
echo "PLUGGEDIN_API_KEY=new_key_here" >> pluggedin-app/.env
```
### OAuth Issues
**Symptoms:**
* Cannot authenticate with GitHub/Linear
* OAuth callbacks failing
* Token refresh issues
**Solutions:**
1. **Check OAuth Configuration**
```bash theme={null}
# Verify OAuth settings
grep GITHUB_CLIENT_ID pluggedin-app/.env
grep LINEAR_CLIENT_ID pluggedin-app/.env
# Check OAuth URLs
grep NEXTAUTH_URL pluggedin-app/.env
```
2. **Clear OAuth Sessions**
```bash theme={null}
# Clear corrupted sessions
pnpm db:query "DELETE FROM oauth_sessions WHERE expires_at < NOW()"
```
## Performance Issues
### Slow Response Times
**Symptoms:**
* API calls taking >5 seconds
* Web interface slow to load
* High memory usage
**Solutions:**
1. **Check Resource Usage**
```bash theme={null}
# Memory usage
free -h
# Disk usage
df -h
# Top processes
top -p $(pgrep -f pluggedin)
```
2. **Database Optimization**
```bash theme={null}
# Analyze query performance
pnpm db:analyze
# Rebuild indexes
pnpm db:reindex
```
3. **Cache Issues**
```bash theme={null}
# Clear application cache
rm -rf pluggedin-app/.next/cache
# Clear Redis cache (if using)
redis-cli FLUSHALL
```
### High Memory Usage
**Symptoms:**
* Out of memory errors
* System becoming unresponsive
* Frequent OOM killer events
**Solutions:**
1. **Memory Optimization**
```bash theme={null}
# Check for memory leaks
pm2 monit
# Set memory limits
pm2 start pluggedin-app --max-memory-restart 1G
```
2. **Garbage Collection**
```bash theme={null}
# Force garbage collection
curl http://localhost:12005/admin/gc
# Monitor GC stats
curl http://localhost:12005/admin/stats
```
## File Upload Issues
### Upload Failures
**Symptoms:**
* File uploads timing out
* "File too large" errors
* Upload progress stuck
**Solutions:**
1. **Check File Size Limits**
```bash theme={null}
# Current limits
grep MAX_FILE_SIZE pluggedin-app/.env
# Increase if needed
echo "MAX_FILE_SIZE=10485760" >> pluggedin-app/.env # 10MB
```
2. **Storage Space**
```bash theme={null}
# Check available space
df -h uploads/
# Clean old uploads if needed
find uploads/ -type f -mtime +30 -delete
```
### Document Processing Issues
**Symptoms:**
* Documents not appearing in search
* RAG processing failures
* Vector search not working
**Solutions:**
1. **Check RAG Service**
```bash theme={null}
# RAG service status
systemctl status pluggedin-rag
# Test RAG processing
pnpm rag:test
```
2. **Rebuild Search Index**
```bash theme={null}
# Rebuild vector index
pnpm rag:rebuild
# Test search functionality
pnpm rag:search "test query"
```
## Network Issues
### SSRF Protection Blocks
**Symptoms:**
* Legitimate requests blocked
* "SSRF attempt detected" errors
* Cannot access internal resources
**Solutions:**
1. **Check URL Validation**
```bash theme={null}
# Review blocked URLs
tail -f /var/log/pluggedin/security.log | grep SSRF
# Whitelist safe domains
echo "ALLOWED_DOMAINS=github.com,linear.app" >> pluggedin-app/.env
```
2. **Debug Mode**
```bash theme={null}
# Enable debug logging
echo "DEBUG=pluggedin:*" >> pluggedin-app/.env
# Check validation logs
journalctl -u pluggedin-app -f | grep -i validation
```
### Rate Limiting Issues
**Symptoms:**
* 429 Too Many Requests
* API calls being throttled
* Cannot perform bulk operations
**Solutions:**
1. **Check Rate Limits**
```bash theme={null}
# Current limits
grep RATE_LIMIT pluggedin-app/.env
# Adjust if needed
echo "RATE_LIMIT_API=120" >> pluggedin-app/.env # per minute
```
2. **Redis Issues** (if using Redis)
```bash theme={null}
# Check Redis status
redis-cli ping
# Clear rate limit cache
redis-cli --scan --pattern "ratelimit:*" | xargs redis-cli DEL
```
## Docker Issues
### Container Issues
**Symptoms:**
* Containers failing to start
* Port conflicts
* Volume mount issues
**Solutions:**
1. **Check Docker Logs**
```bash theme={null}
# View container logs
docker logs pluggedin-app
# Check resource usage
docker stats pluggedin-app pluggedin-mcp
```
2. **Common Fixes**
```bash theme={null}
# Clean up containers
docker system prune -f
# Restart containers
docker-compose restart
# Check port availability
netstat -tlnp | grep :12005
```
## Security Issues
### Encryption Issues
**Symptoms:**
* Cannot decrypt sensitive data
* "Invalid key" errors
* Data corruption
**Solutions:**
1. **Check Encryption Keys**
```bash theme={null}
# Verify encryption key exists
grep ENCRYPTION_KEY pluggedin-app/.env
# Generate new key if needed
openssl rand -base64 32
```
2. **Migration Issues**
```bash theme={null}
# Check encryption migration status
pnpm db:query "SELECT COUNT(*) FROM servers WHERE command_encrypted IS NULL"
# Run encryption migration
pnpm migrate:encryption
```
### XSS Protection Issues
**Symptoms:**
* Content not displaying properly
* Scripts being blocked
* HTML content sanitized incorrectly
**Solutions:**
1. **Check CSP Settings**
```bash theme={null}
# Review Content Security Policy
grep CSP_HEADER pluggedin-app/.env
# Adjust CSP if needed
echo "CSP_HEADER=default-src 'self'; script-src 'self' 'unsafe-inline'" >> pluggedin-app/.env
```
## Getting Help
### Log Collection
When reporting issues, include:
1. **System Information**
```bash theme={null}
uname -a
node --version
npm --version
docker --version
```
2. **Application Logs**
```bash theme={null}
# Last 100 lines of app logs
tail -n 100 /var/log/pluggedin/app.log
# MCP proxy logs
tail -n 100 /var/log/pluggedin/mcp.log
# Database logs
tail -n 100 /var/log/postgresql/postgresql.log
```
3. **Configuration (without secrets)**
```bash theme={null}
# Environment variables (redacted)
env | grep -v SECRET | grep -v KEY | grep -v TOKEN
```
### Support Channels
* **GitHub Issues**: [Bug Reports](https://github.com/VeriTeknik/pluggedin-app/issues)
* **Discussions**: [Community Help](https://github.com/orgs/VeriTeknik/discussions)
* **Email**: [support@plugged.in](mailto:support@plugged.in)
* **Emergency**: [security@plugged.in](mailto:security@plugged.in)
### Emergency Procedures
For critical production issues:
1. **Immediate Actions**
* Check system resources (CPU, memory, disk)
* Look for obvious errors in logs
* Test basic functionality
2. **Quick Fixes**
* Restart services: `systemctl restart pluggedin-*`
* Clear caches: `rm -rf pluggedin-app/.next/cache`
* Check database connectivity
3. **Escalation**
* Contact support with collected logs
* Provide steps to reproduce
* Include system specifications
## Prevention
### Monitoring Setup
```bash theme={null}
# Set up log monitoring
journalctl -u pluggedin-app -f > /var/log/pluggedin/app.log &
journalctl -u pluggedin-mcp -f > /var/log/pluggedin/mcp.log &
# Set up alerting
# Monitor for common error patterns
grep -f error-patterns /var/log/pluggedin/*.log | \
while read line; do
echo "Error detected: $line" | mail -s "Plugged.in Error" admin@your-domain.com
done
```
### Regular Maintenance
```bash theme={null}
# Daily health checks
pnpm health:check
# Weekly cleanup
find uploads/ -type f -mtime +30 -delete
pnpm db:cleanup
# Monthly optimization
pnpm db:optimize
pnpm cache:clean
```
This troubleshooting guide covers the most common issues. For additional help, consult the [community discussions](https://github.com/orgs/VeriTeknik/discussions) or [contact support](mailto:support@plugged.in).
# API Integration
Source: https://docs.plugged.in/tutorials/api-integration
Complete guide to integrating with the Plugged.in API for MCP server management and automation
# API Integration Tutorial
Learn how to integrate Plugged.in's powerful API into your applications for programmatic MCP server management, automation, and custom workflows.
## Overview
The Plugged.in API provides comprehensive access to all platform features, enabling you to:
* Manage MCP servers programmatically
* Automate server discovery and installation
* Build custom integrations and workflows
* Access RAG knowledge bases
* Handle notifications and monitoring
## Authentication
### API Key Generation
Go to **Settings** → **API Keys** in your Plugged.in dashboard
Click "Create API Key" and provide a descriptive name
Copy the generated key immediately - it won't be shown again
Store the API key in environment variables or a secure vault
### Using Your API Key
Include the API key in the `Authorization` header:
```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://plugged.in/api/servers
```
Or in JavaScript:
```javascript theme={null}
const response = await fetch('https://plugged.in/api/servers', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
}
});
```
## Core API Endpoints
### MCP Servers
#### List All Servers
```bash theme={null}
GET /api/servers
```
**Response:**
```json theme={null}
{
"servers": [
{
"uuid": "server-uuid",
"name": "My MCP Server",
"type": "STDIO",
"config": {...},
"status": "connected"
}
]
}
```
#### Create Server
```bash theme={null}
POST /api/servers
```
**Request Body:**
```json theme={null}
{
"name": "New Server",
"type": "STDIO",
"config": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-memory"]
}
}
```
#### Update Server
```bash theme={null}
PUT /api/servers/{uuid}
```
**Request Body:**
```json theme={null}
{
"name": "Updated Name",
"config": {
"command": "node",
"args": ["server.js"]
}
}
```
#### Delete Server
```bash theme={null}
DELETE /api/servers/{uuid}
```
### Server Discovery
#### Search Registry
```bash theme={null}
GET /api/registry/search?q=weather
```
**Response:**
```json theme={null}
{
"results": [
{
"name": "weather-server",
"description": "Get weather information",
"author": "username",
"stars": 42,
"installs": 1337
}
]
}
```
#### Install from Registry
```bash theme={null}
POST /api/registry/install
```
**Request Body:**
```json theme={null}
{
"server_name": "weather-server",
"profile_uuid": "profile-uuid"
}
```
### Tools and Resources
#### List Server Tools
```bash theme={null}
GET /api/servers/{uuid}/tools
```
**Response:**
```json theme={null}
{
"tools": [
{
"name": "get_weather",
"description": "Get current weather",
"inputSchema": {...}
}
]
}
```
#### Execute Tool
```bash theme={null}
POST /api/servers/{uuid}/tools/{tool_name}/execute
```
**Request Body:**
```json theme={null}
{
"parameters": {
"location": "New York"
}
}
```
## Advanced Integration Patterns
### Webhook Integration
Set up webhooks for real-time notifications:
```javascript theme={null}
// Register webhook
const webhook = await fetch('https://plugged.in/api/webhooks', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: 'https://your-app.com/webhook',
events: ['server.connected', 'server.error', 'tool.executed']
})
});
```
### Batch Operations
Process multiple operations efficiently:
```javascript theme={null}
// Batch create servers
const batchCreate = await fetch('https://plugged.in/api/batch', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
operations: [
{
method: 'POST',
path: '/servers',
body: { name: 'Server 1', type: 'STDIO', config: {...} }
},
{
method: 'POST',
path: '/servers',
body: { name: 'Server 2', type: 'SSE', config: {...} }
}
]
})
});
```
### Streaming Responses
Handle streaming responses for real-time data:
```javascript theme={null}
// SSE connection for live updates
const eventSource = new EventSource(
'https://plugged.in/api/servers/events?token=YOUR_API_KEY'
);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Server event:', data);
};
eventSource.addEventListener('tool.executed', (event) => {
const result = JSON.parse(event.data);
console.log('Tool result:', result);
});
```
## SDK Examples
### JavaScript/TypeScript
```typescript theme={null}
import { PluggedinClient } from '@pluggedin/sdk';
const client = new PluggedinClient({
apiKey: process.env.PLUGGEDIN_API_KEY
});
// List servers
const servers = await client.servers.list();
// Create server
const newServer = await client.servers.create({
name: 'My Server',
type: 'STDIO',
config: {
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-memory']
}
});
// Execute tool
const result = await client.servers.executeTool(
'server-uuid',
'get_weather',
{ location: 'London' }
);
```
### Python
```python theme={null}
from pluggedin import PluggedinClient
client = PluggedinClient(api_key="YOUR_API_KEY")
# List servers
servers = client.servers.list()
# Create server
new_server = client.servers.create(
name="My Server",
type="STDIO",
config={
"command": "python",
"args": ["server.py"]
}
)
# Execute tool
result = client.servers.execute_tool(
server_uuid="server-uuid",
tool_name="get_weather",
parameters={"location": "Paris"}
)
```
### Go
```go theme={null}
package main
import (
"github.com/pluggedin/go-sdk"
)
func main() {
client := pluggedin.NewClient("YOUR_API_KEY")
// List servers
servers, err := client.Servers.List()
if err != nil {
log.Fatal(err)
}
// Create server
server, err := client.Servers.Create(&pluggedin.ServerConfig{
Name: "My Server",
Type: "STDIO",
Config: map[string]interface{}{
"command": "go",
"args": []string{"run", "server.go"},
},
})
// Execute tool
result, err := client.Servers.ExecuteTool(
"server-uuid",
"get_weather",
map[string]interface{}{"location": "Tokyo"},
)
}
```
## Rate Limiting and Quotas
API rate limits are enforced to ensure fair usage and platform stability.
### Rate Limits by Tier
| Tier | Requests/Hour | Burst Limit | Concurrent Connections |
| ---------- | ------------- | ----------- | ---------------------- |
| Free | 100 | 10 | 2 |
| Pro | 1,000 | 50 | 10 |
| Business | 10,000 | 200 | 50 |
| Enterprise | Custom | Custom | Custom |
### Handling Rate Limits
The API returns rate limit information in response headers:
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 950
X-RateLimit-Reset: 1640995200
```
Implement exponential backoff for rate limit errors:
```javascript theme={null}
async function apiCallWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || Math.pow(2, i);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
continue;
}
return response;
}
throw new Error('Max retries exceeded');
}
```
## Error Handling
### Common Error Codes
| Code | Description | Resolution |
| ---- | --------------------- | ----------------------------------- |
| 400 | Bad Request | Check request format and parameters |
| 401 | Unauthorized | Verify API key is valid |
| 403 | Forbidden | Check permissions for resource |
| 404 | Not Found | Verify resource exists |
| 429 | Too Many Requests | Implement rate limiting |
| 500 | Internal Server Error | Contact support if persists |
### Error Response Format
```json theme={null}
{
"error": {
"code": "INVALID_PARAMETER",
"message": "The 'name' field is required",
"details": {
"field": "name",
"value": null
}
}
}
```
### Error Handling Example
```javascript theme={null}
try {
const response = await fetch('https://plugged.in/api/servers', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(serverConfig)
});
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
console.error('Invalid request:', error.message);
break;
case 401:
console.error('Authentication failed');
break;
case 429:
console.error('Rate limited, retry after:', response.headers.get('Retry-After'));
break;
default:
console.error('API error:', error);
}
}
const data = await response.json();
return data;
} catch (err) {
console.error('Network error:', err);
}
```
## Testing Your Integration
### Using the API Playground
Test API endpoints directly in the browser:
1. Visit [https://plugged.in/api/playground](https://plugged.in/api/playground)
2. Enter your API key
3. Select an endpoint
4. Configure parameters
5. Execute and view response
### Postman Collection
Import our Postman collection for easy testing:
```json theme={null}
{
"info": {
"name": "Plugged.in API",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{api_key}}"
}
]
}
}
```
### Mock Server
Use our mock server for development:
```bash theme={null}
# Install mock server
npm install -g @pluggedin/mock-server
# Run mock server
pluggedin-mock --port 3000
# Point your API calls to localhost
API_BASE_URL=http://localhost:3000
```
## Best Practices
* Never expose API keys in client-side code
* Use environment variables for key storage
* Rotate keys regularly
* Implement IP whitelisting for production
* Use HTTPS for all API calls
* Cache frequently accessed data
* Use pagination for large datasets
* Implement connection pooling
* Batch operations when possible
* Use webhooks instead of polling
* Implement retry logic with exponential backoff
* Handle network timeouts gracefully
* Log all API interactions
* Monitor API usage and errors
* Set up alerts for failures
* Use versioned API endpoints
* Test with mock data first
* Implement comprehensive error handling
* Document your integration
* Keep SDKs updated
## Example Applications
### Monitoring Dashboard
Build a real-time monitoring dashboard:
```javascript theme={null}
// Real-time server status monitoring
class ServerMonitor {
constructor(apiKey) {
this.apiKey = apiKey;
this.servers = new Map();
}
async start() {
// Initial load
const servers = await this.fetchServers();
servers.forEach(s => this.servers.set(s.uuid, s));
// Subscribe to updates
this.subscribeToUpdates();
// Periodic health checks
setInterval(() => this.healthCheck(), 30000);
}
subscribeToUpdates() {
const eventSource = new EventSource(
`https://plugged.in/api/events?token=${this.apiKey}`
);
eventSource.onmessage = (event) => {
const update = JSON.parse(event.data);
this.handleUpdate(update);
};
}
async healthCheck() {
for (const [uuid, server] of this.servers) {
const health = await this.checkServerHealth(uuid);
this.updateServerStatus(uuid, health);
}
}
}
```
### Automation Workflow
Create an automation workflow:
```javascript theme={null}
// Automated server provisioning
class ServerProvisioner {
async provisionForUser(userId, template) {
// Create project
const project = await this.createProject(userId);
// Install servers from template
for (const serverConfig of template.servers) {
await this.installServer(project.uuid, serverConfig);
}
// Configure integrations
await this.setupIntegrations(project.uuid, template.integrations);
// Send notification
await this.notifyUser(userId, project);
return project;
}
}
```
## Next Steps
Learn to build knowledge bases with RAG
Set up team workspaces and collaboration
## Additional Resources
* [API Reference Documentation](/api/reference)
* [Authentication Guide](/api/authentication)
* [Platform Overview](/platform/overview)
* [Support & Community](https://github.com/orgs/VeriTeknik/discussions)
# Building Custom MCP Servers
Source: https://docs.plugged.in/tutorials/custom-mcp-server
Learn how to build, test, and deploy your own custom MCP servers for Plugged.in
# Building Custom MCP Servers
Learn how to create your own Model Context Protocol (MCP) servers to extend AI capabilities with custom tools, resources, and integrations.
## Overview
MCP servers are the building blocks that enable AI assistants to interact with external systems. By building custom MCP servers, you can:
* Integrate proprietary systems and APIs
* Create specialized tools for your domain
* Expose custom data sources
* Build workflow automations
* Extend AI capabilities for your specific needs
## MCP Server Architecture
### Core Components
Every MCP server consists of three main components:
Handles communication between the client and server (STDIO, SSE, HTTP)
Implements the MCP specification for message exchange
Your custom logic for tools, resources, and prompts
### Transport Types
| Transport | Use Case | Pros | Cons |
| --------- | ----------------- | ------------------ | --------------------- |
| **STDIO** | Local processes | Simple, secure | Single client only |
| **SSE** | Web-based servers | Real-time updates | One-way communication |
| **HTTP** | REST APIs | Scalable, standard | Higher latency |
## Getting Started
### Prerequisites
* Node.js 18+ or Python 3.8+
* Git for version control
* Text editor or IDE
Install the MCP SDK for your language:
```bash theme={null}
# Node.js
npm install @modelcontextprotocol/sdk
# Python
pip install mcp
```
Create an account to test and deploy your server
## Building Your First Server
### Node.js Example
Let's build a simple weather MCP server:
```javascript theme={null}
// weather-server.js
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import axios from 'axios';
class WeatherServer {
constructor() {
this.server = new Server(
{
name: 'weather-server',
version: '1.0.0',
},
{
capabilities: {
tools: {},
},
}
);
this.setupHandlers();
}
setupHandlers() {
// List available tools
this.server.setRequestHandler('tools/list', async () => ({
tools: [
{
name: 'get_weather',
description: 'Get current weather for a location',
inputSchema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name or coordinates',
},
units: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
default: 'celsius',
},
},
required: ['location'],
},
},
],
}));
// Handle tool execution
this.server.setRequestHandler('tools/call', async (request) => {
const { name, arguments: args } = request.params;
if (name === 'get_weather') {
return this.getWeather(args);
}
throw new Error(`Unknown tool: ${name}`);
});
}
async getWeather(args) {
const { location, units = 'celsius' } = args;
// Call weather API (replace with your API)
const response = await axios.get(`https://api.weather.com/current`, {
params: {
q: location,
units: units === 'celsius' ? 'metric' : 'imperial',
},
});
return {
content: [
{
type: 'text',
text: `Current weather in ${location}: ${response.data.temp}° with ${response.data.description}`,
},
],
};
}
async run() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error('Weather MCP server running');
}
}
// Start the server
const server = new WeatherServer();
server.run().catch(console.error);
```
### Python Example
The same server in Python:
```python theme={null}
# weather_server.py
import asyncio
import json
from mcp.server.models import InitializationOptions
from mcp.server import NotificationOptions, Server
from mcp.server.stdio import stdio_server
import mcp.types as types
import httpx
server = Server("weather-server")
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
"""List available tools."""
return [
types.Tool(
name="get_weather",
description="Get current weather for a location",
inputSchema={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name or coordinates",
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius",
},
},
"required": ["location"],
},
)
]
@server.call_tool()
async def handle_call_tool(
name: str, arguments: dict | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
"""Handle tool execution."""
if name == "get_weather":
return await get_weather(arguments or {})
raise ValueError(f"Unknown tool: {name}")
async def get_weather(args: dict):
"""Fetch weather data."""
location = args.get("location")
units = args.get("units", "celsius")
# Call weather API
async with httpx.AsyncClient() as client:
response = await client.get(
"https://api.weather.com/current",
params={
"q": location,
"units": "metric" if units == "celsius" else "imperial"
}
)
data = response.json()
return [
types.TextContent(
type="text",
text=f"Current weather in {location}: {data['temp']}° with {data['description']}"
)
]
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="weather-server",
server_version="1.0.0",
capabilities=server.get_capabilities(
notification_options=NotificationOptions(),
experimental_capabilities={},
),
),
)
if __name__ == "__main__":
asyncio.run(main())
```
## Advanced Features
### Resources
Expose data sources that AI can read:
```javascript theme={null}
// Add resource support
server.setRequestHandler('resources/list', async () => ({
resources: [
{
uri: 'weather://forecast/weekly',
name: 'Weekly Forecast',
description: 'Get 7-day weather forecast',
mimeType: 'application/json',
},
],
}));
server.setRequestHandler('resources/read', async (request) => {
const { uri } = request.params;
if (uri === 'weather://forecast/weekly') {
const forecast = await getWeeklyForecast();
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify(forecast),
},
],
};
}
});
```
### Prompts
Provide reusable prompt templates:
```javascript theme={null}
server.setRequestHandler('prompts/list', async () => ({
prompts: [
{
name: 'weather_report',
description: 'Generate a detailed weather report',
arguments: [
{
name: 'location',
description: 'Location for the report',
required: true,
},
],
},
],
}));
server.setRequestHandler('prompts/get', async (request) => {
const { name, arguments: args } = request.params;
if (name === 'weather_report') {
return {
description: 'Weather Report Template',
messages: [
{
role: 'user',
content: {
type: 'text',
text: `Generate a detailed weather report for ${args.location} including current conditions, forecast, and recommendations.`,
},
},
],
};
}
});
```
### Notifications
Send real-time updates to clients:
```javascript theme={null}
// Send notifications for severe weather
async function checkSevereWeather() {
const alerts = await getWeatherAlerts();
if (alerts.length > 0) {
await server.sendNotification('notifications/resources/updated', {
uri: 'weather://alerts/current',
});
}
}
// Run periodic checks
setInterval(checkSevereWeather, 60000);
```
## Testing Your Server
### Local Testing
Test your server locally using the MCP Inspector:
```bash theme={null}
# Install MCP Inspector
npm install -g @modelcontextprotocol/inspector
# Run your server with the inspector
mcp-inspector node weather-server.js
```
### Unit Testing
Write tests for your server logic:
```javascript theme={null}
// weather-server.test.js
import { describe, it, expect } from 'vitest';
import { WeatherServer } from './weather-server.js';
describe('WeatherServer', () => {
it('should list available tools', async () => {
const server = new WeatherServer();
const response = await server.handleListTools();
expect(response.tools).toHaveLength(1);
expect(response.tools[0].name).toBe('get_weather');
});
it('should fetch weather data', async () => {
const server = new WeatherServer();
const result = await server.getWeather({
location: 'London',
units: 'celsius',
});
expect(result.content[0].text).toContain('London');
});
});
```
### Integration Testing
Test with Plugged.in platform:
```bash theme={null}
# Configure your server in config
cat > mcp-test-config.json << EOF
{
"mcpServers": {
"weather-test": {
"command": "node",
"args": ["./weather-server.js"]
}
}
}
EOF
# Test with Plugged.in CLI
npx @pluggedin/cli test mcp-test-config.json
```
## Packaging and Distribution
### Package Structure
Organize your MCP server project:
```
weather-mcp-server/
├── package.json
├── README.md
├── LICENSE
├── src/
│ ├── index.js
│ ├── handlers/
│ │ ├── tools.js
│ │ ├── resources.js
│ │ └── prompts.js
│ └── utils/
│ └── weather-api.js
├── test/
│ └── server.test.js
└── examples/
└── config.json
```
### Package.json Configuration
```json theme={null}
{
"name": "@yourorg/weather-mcp-server",
"version": "1.0.0",
"description": "MCP server for weather information",
"main": "src/index.js",
"type": "module",
"bin": {
"weather-mcp": "./src/index.js"
},
"scripts": {
"start": "node src/index.js",
"test": "vitest",
"lint": "eslint src"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0",
"axios": "^1.6.0"
},
"keywords": ["mcp", "weather", "ai", "assistant"],
"author": "Your Name",
"license": "MIT"
}
```
### Publishing to npm
```bash theme={null}
# Build and test
npm run test
npm run lint
# Login to npm
npm login
# Publish
npm publish --access public
```
## Deployment Options
### Docker Deployment
Create a Dockerfile for containerized deployment:
```dockerfile theme={null}
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY src ./src
EXPOSE 3000
CMD ["node", "src/index.js"]
```
### Systemd Service
Deploy as a system service:
```ini theme={null}
[Unit]
Description=Weather MCP Server
After=network.target
[Service]
Type=simple
User=mcp-user
WorkingDirectory=/opt/weather-mcp-server
ExecStart=/usr/bin/node src/index.js
Restart=always
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
```
### Cloud Deployment
Deploy to cloud platforms:
```json theme={null}
{
"functions": {
"api/mcp.js": {
"runtime": "nodejs20.x"
}
}
}
```
```yaml theme={null}
functions:
weather-mcp:
handler: src/lambda.handler
runtime: nodejs20.x
environment:
API_KEY: ${env:WEATHER_API_KEY}
```
```yaml theme={null}
runtime: nodejs20
service: weather-mcp
handlers:
- url: /.*
script: auto
```
## Publishing to Plugged.in Registry
### Prepare for Registry
1. **Documentation**: Write comprehensive README
2. **Examples**: Provide configuration examples
3. **Testing**: Ensure all tests pass
4. **Licensing**: Choose appropriate license
### Submit to Registry
```bash theme={null}
# Install Plugged.in CLI
npm install -g @pluggedin/cli
# Login
pluggedin login
# Submit server
pluggedin submit \
--name "weather-server" \
--repo "https://github.com/yourorg/weather-mcp-server" \
--description "Get real-time weather information" \
--category "utilities"
```
## Best Practices
* Always validate input parameters
* Return meaningful error messages
* Implement retry logic for external APIs
* Log errors for debugging
* Cache frequently accessed data
* Implement rate limiting
* Use connection pooling
* Optimize response sizes
* Never expose API keys in code
* Validate and sanitize all inputs
* Use HTTPS for external requests
* Implement authentication if needed
* Document all tools and parameters
* Provide usage examples
* Include troubleshooting guide
* Maintain changelog
## Common Patterns
### Database Integration
```javascript theme={null}
import { createPool } from 'mysql2/promise';
class DatabaseMCPServer {
constructor() {
this.pool = createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
});
}
async queryDatabase(sql, params) {
const [rows] = await this.pool.execute(sql, params);
return rows;
}
}
```
### API Gateway
```javascript theme={null}
class APIGatewayServer {
constructor() {
this.endpoints = new Map();
this.registerEndpoints();
}
registerEndpoints() {
this.endpoints.set('users', 'https://api.example.com/users');
this.endpoints.set('posts', 'https://api.example.com/posts');
}
async callAPI(endpoint, method, data) {
const url = this.endpoints.get(endpoint);
const response = await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
return response.json();
}
}
```
## Troubleshooting
### Common Issues
| Issue | Solution |
| --------------------- | ------------------------------------------- |
| Server not responding | Check transport configuration and logs |
| Tools not appearing | Verify tool schema and registration |
| Authentication errors | Confirm API keys and credentials |
| Performance issues | Implement caching and rate limiting |
| Connection timeouts | Increase timeout values and add retry logic |
## Next Steps
Deploy Plugged.in with your custom servers
Learn about the MCP proxy architecture
## Additional Resources
* [MCP Specification](https://modelcontextprotocol.io/specification)
* [SDK Documentation](https://github.com/modelcontextprotocol/sdk)
* [Example Servers](https://github.com/modelcontextprotocol/servers)
* [Community Support](https://github.com/orgs/VeriTeknik/discussions)
# RAG Knowledge Base
Source: https://docs.plugged.in/tutorials/rag-knowledge-base
Learn how to build and manage a knowledge base with RAG (Retrieval-Augmented Generation) in Plugged.in
# RAG Knowledge Base Tutorial
Build a powerful knowledge base using Retrieval-Augmented Generation (RAG) to enhance your AI interactions with contextual information.
## Overview
The RAG (Retrieval-Augmented Generation) system in Plugged.in allows you to create project-specific knowledge bases that can be queried by AI models through MCP servers. This enables AI assistants to access your documentation, notes, and other text content to provide more accurate and contextual responses.
### Key Features
Upload and organize documents in multiple formats (PDF, DOCX, TXT, Markdown)
Advanced vector-based search for finding relevant information quickly
Complete data isolation between projects for security and privacy
Seamless integration with MCP servers for AI-powered queries
## Prerequisites
Before setting up your RAG knowledge base, ensure you have:
An active account with at least one project created
A valid API key for authentication (available in Settings → API Keys)
Text-based documents you want to include in your knowledge base
## Step 1: Enable RAG Features
First, ensure RAG features are enabled for your project:
1. Navigate to **Settings** → **Project Settings**
2. Enable the "RAG Features" toggle
3. Save your settings
RAG features may require additional permissions or a specific subscription tier. Contact support if you don't see this option.
## Step 2: Upload Documents
### Using the Web Interface
1. Go to **Library** in the sidebar
2. Click **Upload Documents**
3. Select your files (supported formats: PDF, DOCX, TXT, MD)
4. Add optional metadata:
* Title
* Description
* Tags
* Category
### Using the API
```bash theme={null}
curl -X POST https://plugged.in/api/documents \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: multipart/form-data" \
-F "file=@document.pdf" \
-F "metadata={\"title\":\"My Document\",\"tags\":[\"tutorial\",\"rag\"]}"
```
### Supported File Types
| Format | Extensions | Max Size |
| -------------- | ----------- | -------- |
| PDF | .pdf | 10 MB |
| Microsoft Word | .docx, .doc | 10 MB |
| Text | .txt | 5 MB |
| Markdown | .md, .mdx | 5 MB |
| HTML | .html, .htm | 5 MB |
## Step 3: Configure MCP Server
Add the Plugged.in RAG MCP server to your configuration:
```json theme={null}
{
"mcpServers": {
"pluggedin-rag": {
"command": "npx",
"args": ["-y", "@pluggedin/pluggedin-mcp-proxy"],
"env": {
"PLUGGEDIN_API_KEY": "YOUR_API_KEY"
}
}
}
}
```
## Step 4: Query Your Knowledge Base
Once configured, the RAG system provides several tools for querying:
### Available Tools
#### `pluggedin_rag_query`
Search and retrieve relevant information from your knowledge base.
**Parameters:**
* `query` (required): Your search query
* `max_results` (optional): Maximum number of results (default: 5)
* `threshold` (optional): Relevance threshold 0-1 (default: 0.7)
**Example:**
```json theme={null}
{
"tool": "pluggedin_rag_query",
"parameters": {
"query": "How to configure authentication?",
"max_results": 3
}
}
```
## Step 5: Managing Your Knowledge Base
### Update Documents
Documents can be updated through the web interface or API:
```bash theme={null}
curl -X PUT https://plugged.in/api/documents/{document_id} \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "Updated Title",
"content": "Updated content...",
"metadata": {"version": "2.0"}
}'
```
### Delete Documents
Remove documents when they're no longer needed:
```bash theme={null}
curl -X DELETE https://plugged.in/api/documents/{document_id} \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Search Documents
Search your knowledge base programmatically:
```bash theme={null}
curl -X POST https://plugged.in/api/documents/search \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "authentication setup",
"limit": 10,
"filters": {
"tags": ["security", "auth"]
}
}'
```
## AI Search in Document Library (New in v2.11.1)
The Document Library now features an integrated AI search that provides intelligent answers directly in the web interface.
### Key Improvements
No more cryptic IDs - see actual document names
Click any source document to open it instantly
500ms debounce for optimal performance
Natural language queries with context awareness
### Using AI Search in the Library
Open the Document Library from the sidebar
Click the sparkles icon (✨) in the search bar to toggle AI mode
Enter a natural language query like "How do I configure authentication?"
The AI provides a comprehensive answer with source documents displayed as clickable buttons
Click any document name to open it in the preview modal
### Example Queries
| Query Type | Example | What It Returns |
| ------------------- | -------------------------------- | ------------------------------------------ |
| **How-to** | "How do I set up OAuth?" | Step-by-step guide from your docs |
| **Conceptual** | "What is the architecture?" | Overview synthesized from multiple sources |
| **Troubleshooting** | "Why is authentication failing?" | Potential causes and solutions |
| **Reference** | "List all API endpoints" | Comprehensive endpoint documentation |
### AI Search Response Structure
```typescript theme={null}
interface AiSearchResponse {
answer: string; // AI-generated comprehensive answer
documents: Array<{ // Source documents with names
id: string; // Document UUID
name: string; // Human-readable name (e.g., "API Guide.pdf")
}>;
sources: string[]; // Relevant excerpts from documents
confidence: number; // Answer confidence score (0-1)
}
```
### Performance Optimizations
The AI search system includes several performance enhancements:
* **Smart Debouncing**: 500ms delay prevents excessive API calls while typing
* **Result Caching**: Recent queries are cached for instant retrieval
* **Progressive Loading**: Results stream in as they become available
* **Optimized Rendering**: Virtual scrolling for large result sets
## Best Practices
* Use clear, descriptive titles that appear in AI search results
* Apply consistent tagging taxonomy
* Group related documents by category
* Keep documents focused on single topics
* Use plain text when possible for better indexing
* Break large documents into smaller, focused pieces
* Include relevant keywords naturally
* Update outdated information regularly
* Use specific, descriptive queries
* Include context in your questions
* Experiment with different phrasings
* Adjust relevance thresholds as needed
* Ask complete questions for better context
* Use natural language, not keywords
* Reference specific topics or technologies
* Try rephrasing if results aren't satisfactory
* Never upload sensitive credentials
* Use project isolation for different clients
* Regularly audit document access logs
* Remove obsolete documents promptly
## Advanced Features
### AI-Generated Documents
Plugged.in supports AI-generated documents with full attribution tracking:
```bash theme={null}
curl -X POST https://plugged.in/api/documents/ai \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "API Documentation",
"content": "# API Overview\n\n...",
"metadata": {
"model": {
"name": "Claude 3.5 Sonnet",
"provider": "Anthropic",
"version": "3.5"
}
}
}'
```
### Document Versioning (New in v2.11.1)
Track changes and maintain complete history for all documents:
Every document now includes a comprehensive version history interface:
* **Timeline View**: Visual representation of all versions
* **Diff Visualization**: See what changed between versions
* **Model Attribution**: Track which AI model made each change
* **Change Summary**: Brief description of modifications
Compare any two versions side-by-side:
```typescript theme={null}
// Version metadata structure
interface DocumentVersion {
version_number: number;
created_by_model: {
name: string;
provider: string;
version?: string;
};
content_diff: {
additions: number;
deletions: number;
changes: Array<{
type: 'addition' | 'deletion' | 'modification';
content: string;
}>;
};
change_summary: string;
created_at: Date;
}
```
Programmatically manage document versions:
```bash theme={null}
# Get version history
curl -X GET https://plugged.in/api/documents/{id}/versions \
-H "Authorization: Bearer YOUR_API_KEY"
# Compare two versions
curl -X GET https://plugged.in/api/documents/{id}/compare?v1=1&v2=2 \
-H "Authorization: Bearer YOUR_API_KEY"
# Rollback to previous version
curl -X POST https://plugged.in/api/documents/{id}/rollback \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"version": 3}'
```
### Vector Search Configuration
Customize vector search behavior:
```json theme={null}
{
"search_config": {
"embedding_model": "text-embedding-ada-002",
"similarity_metric": "cosine",
"reranking": true,
"hybrid_search": true
}
}
```
### Bulk Operations
Import multiple documents at once:
```bash theme={null}
curl -X POST https://plugged.in/api/documents/bulk \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"documents": [
{"title": "Doc 1", "content": "..."},
{"title": "Doc 2", "content": "..."}
]
}'
```
## Troubleshooting
Common issues and their solutions:
### Documents Not Appearing in Search
1. **Check indexing status**: Documents may take 1-2 minutes to index
2. **Verify file format**: Ensure documents are in supported formats
3. **Check file size**: Files over 10MB are rejected
4. **Review content**: Very short documents may not index well
### Low Relevance Scores
* Improve document quality with more descriptive content
* Use specific keywords that match likely queries
* Break complex topics into focused documents
* Consider adjusting the similarity threshold
### API Rate Limits
RAG operations have the following limits:
* Document uploads: 100 per hour
* Search queries: 1000 per hour
* AI document creation: 10 per hour
## Example Use Cases
### Customer Support Knowledge Base
Build a comprehensive support knowledge base:
1. Upload product documentation
2. Add FAQ documents
3. Include troubleshooting guides
4. Configure MCP server for support agents
5. Query for instant answers during customer interactions
### Development Documentation
Create a technical knowledge base for your team:
1. Upload API documentation
2. Add architecture diagrams (as text descriptions)
3. Include coding standards and best practices
4. Enable for development MCP servers
5. Query during code reviews and planning
### Research Repository
Organize research materials:
1. Upload research papers and notes
2. Tag by topic and date
3. Add summaries and key findings
4. Configure for research assistants
5. Query for literature reviews and citations
## Next Steps
Learn how to integrate RAG with your applications
Share knowledge bases with your team
## Additional Resources
* [RAG API Reference](/api/reference#rag)
* [Security Best Practices](/security/overview)
* [Platform Overview](/platform/overview)
* [MCP Proxy Documentation](/mcp-proxy/overview)
# Self-Hosting Guide
Source: https://docs.plugged.in/tutorials/self-hosting
Complete guide to deploying Plugged.in on your own infrastructure
# Self-Hosting Plugged.in
Deploy Plugged.in on your own infrastructure for complete control over your MCP server management platform.
## Overview
Self-hosting Plugged.in gives you:
* **Complete Data Control**: All data stays on your infrastructure
* **Custom Configuration**: Tailor the platform to your needs
* **Network Isolation**: Run in air-gapped environments
* **Compliance**: Meet specific regulatory requirements
* **Cost Control**: Optimize for your usage patterns
## System Requirements
### Minimum Requirements
| Component | Specification |
| --------- | -------------------------- |
| CPU | 2 cores |
| RAM | 4 GB |
| Storage | 20 GB SSD |
| OS | Ubuntu 20.04+ / Debian 11+ |
| Database | PostgreSQL 15+ |
| Node.js | 20.x LTS |
### Recommended Production Setup
| Component | Specification |
| ------------- | -------------------- |
| CPU | 4+ cores |
| RAM | 8+ GB |
| Storage | 100 GB SSD |
| Load Balancer | Nginx/HAProxy |
| Cache | Redis 7+ |
| Monitoring | Prometheus + Grafana |
## Deployment Options
### Docker Deployment (Recommended)
The easiest way to deploy Plugged.in is using Docker:
```bash theme={null}
git clone https://github.com/VeriTeknik/pluggedin-app.git
cd pluggedin-app
```
```bash theme={null}
cp .env.example .env
# Edit .env with your configuration
nano .env
```
```bash theme={null}
# Production deployment
docker-compose -f docker-compose.production.yml up -d
# Check status
docker-compose ps
```
```bash theme={null}
docker-compose exec pluggedin-app pnpm db:migrate
```
#### Docker Compose Configuration
```yaml theme={null}
version: '3.8'
services:
pluggedin-app:
image: veriteknik/pluggedin:latest
container_name: pluggedin-app
restart: always
ports:
- '3000:3000'
volumes:
- mcp-cache:/app/.cache
- app-uploads:/app/uploads
environment:
- NODE_ENV=production
- DATABASE_URL=postgresql://user:pass@postgres:5432/pluggedin
- NEXTAUTH_URL=https://your-domain.com
- NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
- PLUGGEDIN_API_KEY=${PLUGGEDIN_API_KEY}
# Sandboxing configuration
- MCP_ISOLATION_TYPE=bubblewrap
- MCP_ISOLATION_FALLBACK=firejail
- MCP_ENABLE_NETWORK_ISOLATION=false
depends_on:
- postgres
- redis
networks:
- pluggedin-network
postgres:
image: postgres:16-alpine
container_name: pluggedin-postgres
restart: always
environment:
POSTGRES_DB: pluggedin
POSTGRES_USER: pluggedin
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- pluggedin-network
redis:
image: redis:7-alpine
container_name: pluggedin-redis
restart: always
volumes:
- redis-data:/data
command: redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru
networks:
- pluggedin-network
nginx:
image: nginx:alpine
container_name: pluggedin-nginx
restart: always
ports:
- '80:80'
- '443:443'
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
- ./nginx/ssl:/etc/nginx/ssl:ro
depends_on:
- pluggedin-app
networks:
- pluggedin-network
volumes:
postgres-data:
redis-data:
mcp-cache:
app-uploads:
networks:
pluggedin-network:
driver: bridge
```
### Manual Installation
For more control, install manually:
```bash theme={null}
# Update system
sudo apt update && sudo apt upgrade -y
# Install Node.js 20
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# Install PostgreSQL
sudo apt install -y postgresql postgresql-contrib
# Install Redis
sudo apt install -y redis-server
# Install pnpm
npm install -g pnpm
# Install sandboxing tools
sudo apt install -y bubblewrap firejail
```
```bash theme={null}
# Create database and user
sudo -u postgres psql << EOF
CREATE USER pluggedin WITH PASSWORD 'your-secure-password';
CREATE DATABASE pluggedin OWNER pluggedin;
GRANT ALL PRIVILEGES ON DATABASE pluggedin TO pluggedin;
EOF
```
```bash theme={null}
# Clone repository
git clone https://github.com/VeriTeknik/pluggedin-app.git
cd pluggedin-app
# Install dependencies
pnpm install
# Configure environment
cp .env.example .env
nano .env
```
```bash theme={null}
# Build application
pnpm build
# Run database migrations
pnpm db:migrate
# Start production server
NODE_ENV=production pnpm start
```
### Kubernetes Deployment
Deploy to Kubernetes for scalability:
```yaml theme={null}
# pluggedin-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: pluggedin-app
spec:
replicas: 3
selector:
matchLabels:
app: pluggedin
template:
metadata:
labels:
app: pluggedin
spec:
containers:
- name: pluggedin
image: veriteknik/pluggedin:latest
ports:
- containerPort: 3000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: pluggedin-secret
key: database-url
- name: NEXTAUTH_SECRET
valueFrom:
secretKeyRef:
name: pluggedin-secret
key: nextauth-secret
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "2Gi"
cpu: "2000m"
---
apiVersion: v1
kind: Service
metadata:
name: pluggedin-service
spec:
selector:
app: pluggedin
ports:
- port: 80
targetPort: 3000
type: LoadBalancer
```
Apply the configuration:
```bash theme={null}
kubectl apply -f pluggedin-deployment.yaml
kubectl apply -f pluggedin-service.yaml
kubectl apply -f pluggedin-ingress.yaml
```
## Configuration
### Environment Variables
Never commit `.env` files to version control. Use secrets management for production.
#### Required Variables
```bash theme={null}
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/pluggedin
# Authentication
NEXTAUTH_URL=https://your-domain.com
NEXTAUTH_SECRET=generate-with-openssl-rand-base64-32
# API
PLUGGEDIN_API_KEY=your-secure-api-key
# MCP Proxy
MCP_PROXY_BASE_URL=http://localhost:3001
```
#### Optional Variables
```bash theme={null}
# Redis (for sessions and caching)
REDIS_URL=redis://localhost:6379
# Email (for notifications)
EMAIL_SERVER_HOST=smtp.gmail.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=your-email@gmail.com
EMAIL_SERVER_PASSWORD=your-app-password
EMAIL_FROM=noreply@your-domain.com
# OAuth Providers
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
# RAG Features
ENABLE_RAG=true
RAG_API_URL=http://localhost:8000
# Monitoring
SENTRY_DSN=your-sentry-dsn
PROMETHEUS_PORT=9090
```
### Nginx Configuration
Configure Nginx as reverse proxy:
```nginx theme={null}
server {
listen 80;
server_name your-domain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name your-domain.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
client_max_body_size 10M;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api {
proxy_pass http://localhost:3000/api;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
}
```
### Systemd Service
Create a systemd service for automatic startup:
```ini theme={null}
# /etc/systemd/system/pluggedin.service
[Unit]
Description=Plugged.in MCP Platform
After=network.target postgresql.service redis.service
[Service]
Type=simple
User=pluggedin
Group=pluggedin
WorkingDirectory=/opt/pluggedin
ExecStart=/usr/bin/node .next/standalone/server.js
Restart=always
RestartSec=10
# Environment
Environment="NODE_ENV=production"
Environment="PORT=3000"
EnvironmentFile=/opt/pluggedin/.env
# Security
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/pluggedin/uploads /opt/pluggedin/.cache
[Install]
WantedBy=multi-user.target
```
Enable and start the service:
```bash theme={null}
sudo systemctl enable pluggedin
sudo systemctl start pluggedin
sudo systemctl status pluggedin
```
## Security Hardening
### SSL/TLS Configuration
Generate SSL certificates:
```bash theme={null}
# Using Let's Encrypt
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
# Or generate self-signed for testing
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout /etc/ssl/private/pluggedin.key \
-out /etc/ssl/certs/pluggedin.crt
```
### Firewall Configuration
```bash theme={null}
# Allow only necessary ports
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```
### Database Security
```sql theme={null}
-- Restrict database access
REVOKE ALL ON DATABASE pluggedin FROM PUBLIC;
GRANT CONNECT ON DATABASE pluggedin TO pluggedin;
GRANT USAGE ON SCHEMA public TO pluggedin;
GRANT CREATE ON SCHEMA public TO pluggedin;
-- Enable SSL for database connections
ALTER SYSTEM SET ssl = on;
```
### Application Security
* Enforce strong passwords
* Enable 2FA for admin accounts
* Configure session timeouts
* Use secure session cookies
* Implement rate limiting
* Use API key rotation
* Enable CORS restrictions
* Log all API access
* Use VPN for admin access
* Implement IP whitelisting
* Enable DDoS protection
* Monitor network traffic
* Encrypt data at rest
* Backup encryption keys
* Regular security audits
* Implement data retention policies
## Monitoring and Maintenance
### Health Checks
Set up health monitoring endpoints:
```javascript theme={null}
// pages/api/health.js
export default function handler(req, res) {
// Check database
const dbHealthy = await checkDatabase();
// Check Redis
const redisHealthy = await checkRedis();
// Check disk space
const diskHealthy = await checkDiskSpace();
if (dbHealthy && redisHealthy && diskHealthy) {
res.status(200).json({ status: 'healthy' });
} else {
res.status(503).json({
status: 'unhealthy',
checks: { db: dbHealthy, redis: redisHealthy, disk: diskHealthy }
});
}
}
```
### Prometheus Metrics
Export metrics for monitoring:
```yaml theme={null}
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'pluggedin'
static_configs:
- targets: ['localhost:3000']
metrics_path: '/api/metrics'
```
### Backup Strategy
Implement regular backups:
```bash theme={null}
#!/bin/bash
# backup.sh
# Variables
BACKUP_DIR="/backup/pluggedin"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="pluggedin"
# Create backup directory
mkdir -p $BACKUP_DIR
# Backup database
pg_dump -h localhost -U pluggedin -d $DB_NAME | gzip > $BACKUP_DIR/db_$DATE.sql.gz
# Backup uploads
tar -czf $BACKUP_DIR/uploads_$DATE.tar.gz /opt/pluggedin/uploads
# Backup configuration
tar -czf $BACKUP_DIR/config_$DATE.tar.gz /opt/pluggedin/.env /opt/pluggedin/config
# Remove old backups (keep 30 days)
find $BACKUP_DIR -type f -mtime +30 -delete
# Upload to S3 (optional)
aws s3 sync $BACKUP_DIR s3://your-backup-bucket/pluggedin/
```
Add to crontab:
```bash theme={null}
# Run backup daily at 2 AM
0 2 * * * /opt/pluggedin/scripts/backup.sh
```
### Log Management
Configure centralized logging:
```javascript theme={null}
// lib/logger.js
import pino from 'pino';
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
transport: {
targets: [
{
target: 'pino-pretty',
options: { destination: 1 } // stdout
},
{
target: 'pino/file',
options: { destination: '/var/log/pluggedin/app.log' }
},
{
target: '@logtail/pino',
options: { sourceToken: process.env.LOGTAIL_TOKEN }
}
]
}
});
export default logger;
```
## Scaling Strategies
### Horizontal Scaling
Deploy multiple instances behind a load balancer:
```nginx theme={null}
upstream pluggedin_backend {
least_conn;
server app1.internal:3000;
server app2.internal:3000;
server app3.internal:3000;
keepalive 32;
}
server {
location / {
proxy_pass http://pluggedin_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
```
### Database Scaling
Implement read replicas:
```javascript theme={null}
// db/config.js
const writeDb = new Pool({
connectionString: process.env.DATABASE_URL
});
const readDb = new Pool({
connectionString: process.env.DATABASE_READ_URL
});
export { writeDb, readDb };
```
### Caching Strategy
Implement multi-level caching:
```javascript theme={null}
// lib/cache.js
import Redis from 'ioredis';
import LRU from 'lru-cache';
// L1: In-memory cache
const memCache = new LRU({
max: 500,
ttl: 1000 * 60 * 5 // 5 minutes
});
// L2: Redis cache
const redis = new Redis(process.env.REDIS_URL);
export async function getCached(key, fetcher) {
// Check L1
if (memCache.has(key)) {
return memCache.get(key);
}
// Check L2
const cached = await redis.get(key);
if (cached) {
const value = JSON.parse(cached);
memCache.set(key, value);
return value;
}
// Fetch and cache
const value = await fetcher();
memCache.set(key, value);
await redis.setex(key, 3600, JSON.stringify(value));
return value;
}
```
## Troubleshooting
### Common Issues
| Issue | Solution |
| -------------------------- | ---------------------------------------------------- |
| Database connection errors | Check PostgreSQL status and credentials |
| High memory usage | Adjust Node.js heap size with `--max-old-space-size` |
| Slow performance | Enable Redis caching and optimize database queries |
| SSL errors | Verify certificate paths and permissions |
| MCP server failures | Check sandboxing configuration and permissions |
### Debug Mode
Enable debug logging:
```bash theme={null}
# Set debug environment variables
export DEBUG=pluggedin:*
export LOG_LEVEL=debug
export NODE_ENV=development
# Start with debugging
node --inspect=0.0.0.0:9229 .next/standalone/server.js
```
### Performance Tuning
Optimize Node.js settings:
```bash theme={null}
# Increase memory limit
node --max-old-space-size=4096 server.js
# Enable cluster mode
pm2 start server.js -i max
# Optimize garbage collection
node --optimize-for-size --max-old-space-size=2048 server.js
```
## Migration from Cloud
### Export Data
Export data from cloud instance:
```bash theme={null}
# Export from cloud
pg_dump $CLOUD_DATABASE_URL > cloud-backup.sql
# Export files
rsync -avz cloud-server:/uploads/ ./uploads/
```
### Import to Self-Hosted
```bash theme={null}
# Import database
psql $LOCAL_DATABASE_URL < cloud-backup.sql
# Copy files
cp -r ./uploads/* /opt/pluggedin/uploads/
# Update configurations
pnpm db:migrate
```
## Support and Resources
Detailed Docker deployment guide
Ubuntu-specific configuration
## Additional Resources
* [System Requirements](/platform/overview#requirements)
* [Security Best Practices](/security/overview)
* [API Documentation](/api/reference)
* [Community Support](https://github.com/orgs/VeriTeknik/discussions)
* [Enterprise Support](mailto:api-support@plugged.in)
# Team Collaboration
Source: https://docs.plugged.in/tutorials/team-collaboration
Set up team workspaces, manage permissions, and collaborate effectively with your team in Plugged.in
# Team Collaboration Tutorial
Learn how to set up team workspaces, manage permissions, and collaborate effectively with your team using Plugged.in's collaboration features.
## Overview
Plugged.in provides comprehensive team collaboration features that enable organizations to:
* Create shared workspaces for teams
* Manage user roles and permissions
* Share MCP servers and collections
* Collaborate on knowledge bases
* Track team activity and usage
## Setting Up Your Team
### Create an Organization
Go to **Settings** → **Organization** in your dashboard
Click "Create Organization" and enter your organization details:
* Organization name
* Description
* Website (optional)
* Logo (optional)
Set up organization preferences:
* Default language
* Time zone
* Notification preferences
Add team members by email invitation
### Organization Roles
Plugged.in supports multiple organization roles with different permission levels:
| Role | Description | Permissions |
| ---------- | ------------------ | ---------------------------------------- |
| **Owner** | Organization owner | Full access to all features and settings |
| **Admin** | Administrator | Manage users, projects, and settings |
| **Member** | Team member | Create and manage own projects |
| **Viewer** | Read-only access | View shared resources only |
## Project Collaboration
### Creating Team Projects
Projects in Plugged.in can be shared across your team:
```javascript theme={null}
// Create a team project via API
const project = await fetch('https://plugged.in/api/projects', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Team Project',
organization_id: 'org-uuid',
visibility: 'organization', // or 'public', 'private'
members: [
{ user_id: 'user1', role: 'admin' },
{ user_id: 'user2', role: 'member' }
]
})
});
```
### Project Roles and Permissions
Each project can have custom role assignments:
* Full control over project settings
* Can delete the project
* Manage all team members
* Access all resources
* Manage project settings
* Add/remove team members
* Create and modify resources
* Cannot delete project
* Create and manage MCP servers
* Upload documents to knowledge base
* Use shared resources
* Cannot modify project settings
* View project resources
* Use shared MCP servers
* Read knowledge base
* Cannot make changes
## Sharing MCP Servers
### Share Within Organization
Make your MCP servers available to your team:
1. Navigate to **MCP Servers**
2. Select the server to share
3. Click **Share** → **Organization**
4. Configure sharing settings:
* **Visibility**: Organization-wide or specific teams
* **Permissions**: Use only, or allow modifications
* **Notes**: Add usage instructions
### Collection Sharing
Group related servers into collections for easier sharing:
```json theme={null}
{
"collection": {
"name": "Development Tools",
"description": "Essential development MCP servers",
"servers": [
"github-server-uuid",
"database-server-uuid",
"testing-server-uuid"
],
"visibility": "organization",
"permissions": {
"install": ["member", "admin"],
"modify": ["admin"]
}
}
}
```
### Best Practices for Server Sharing
Never share servers containing sensitive credentials directly. Use environment variables or secure vaults.
#### Secure Credential Management
```json theme={null}
{
"server_config": {
"name": "Database Server",
"type": "STDIO",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${SECRET_DATABASE_URL}"
}
}
}
```
Team members provide their own credentials when installing.
## Knowledge Base Collaboration
### Shared Knowledge Bases
Create team knowledge bases for collective documentation:
1. **Create Knowledge Base**
```bash theme={null}
POST /api/knowledge-bases
{
"name": "Team Documentation",
"project_id": "project-uuid",
"visibility": "organization",
"contributors": ["user1", "user2"]
}
```
2. **Set Permissions**
* **Editors**: Can add, modify, and delete documents
* **Contributors**: Can add and modify own documents
* **Readers**: Read-only access
3. **Version Control**
All changes are tracked with attribution:
```json theme={null}
{
"document_id": "doc-uuid",
"version": 3,
"changes": [
{
"version": 1,
"author": "user1",
"timestamp": "2024-01-15T10:00:00Z",
"summary": "Initial version"
},
{
"version": 2,
"author": "user2",
"timestamp": "2024-01-16T14:30:00Z",
"summary": "Added API examples"
}
]
}
```
### Document Collaboration Features
Multiple users can work on documents simultaneously with conflict resolution
Add inline comments and discussions on specific document sections
Full version history with diff viewing and rollback capabilities
Submit documents for review and approval before publishing
## Team Activity Monitoring
### Activity Dashboard
Monitor team activity through the dashboard:
```javascript theme={null}
// Fetch team activity
const activity = await fetch('https://plugged.in/api/organizations/activity', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
// Response
{
"activities": [
{
"user": "alice@company.com",
"action": "created_server",
"resource": "GitHub Integration",
"timestamp": "2024-01-20T10:30:00Z"
},
{
"user": "bob@company.com",
"action": "shared_collection",
"resource": "Dev Tools Collection",
"timestamp": "2024-01-20T09:15:00Z"
}
]
}
```
### Usage Analytics
Track team usage and resource consumption:
| Metric | Description | API Endpoint |
| --------------- | -------------------------- | ------------------------ |
| Active Users | Daily/monthly active users | `/api/analytics/users` |
| Server Usage | Most used MCP servers | `/api/analytics/servers` |
| API Calls | API usage by user/project | `/api/analytics/api` |
| Storage | Knowledge base storage | `/api/analytics/storage` |
| Tool Executions | MCP tool usage stats | `/api/analytics/tools` |
## Communication and Notifications
### Team Notifications
Set up team-wide notifications:
```javascript theme={null}
// Configure team notifications
const config = {
organization_id: 'org-uuid',
notifications: {
server_errors: {
enabled: true,
channels: ['email', 'in_app'],
recipients: ['admins']
},
new_shares: {
enabled: true,
channels: ['in_app'],
recipients: ['all']
},
usage_alerts: {
enabled: true,
threshold: 90, // percentage
channels: ['email'],
recipients: ['owner', 'admins']
}
}
};
```
### Integration with Communication Tools
Connect Plugged.in with your team's communication tools:
```bash theme={null}
POST /api/integrations/slack
{
"webhook_url": "https://hooks.slack.com/services/...",
"channel": "#mcp-updates",
"events": [
"server.created",
"server.shared",
"collection.published"
]
}
```
```bash theme={null}
POST /api/integrations/teams
{
"webhook_url": "https://outlook.office.com/webhook/...",
"events": [
"server.error",
"usage.limit_reached"
]
}
```
```bash theme={null}
POST /api/integrations/discord
{
"webhook_url": "https://discord.com/api/webhooks/...",
"events": ["all"]
}
```
## Access Control Best Practices
### Principle of Least Privilege
Grant users only the permissions they need:
```javascript theme={null}
// Role-based access control
const permissions = {
developer: [
'servers.create',
'servers.read',
'servers.execute',
'knowledge.read'
],
analyst: [
'servers.read',
'servers.execute',
'knowledge.read',
'knowledge.write'
],
admin: [
'servers.*',
'knowledge.*',
'users.manage',
'settings.modify'
]
};
```
### Audit Logging
Enable comprehensive audit logging:
```javascript theme={null}
// Query audit logs
const auditLogs = await fetch('https://plugged.in/api/audit-logs', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
params: {
start_date: '2024-01-01',
end_date: '2024-01-31',
user: 'user-uuid',
action: 'server.delete'
}
});
```
## Workflow Automation
### Automated Onboarding
Set up automated workflows for new team members:
```javascript theme={null}
class TeamOnboarding {
async onboardMember(email, role) {
// 1. Send invitation
const invitation = await this.inviteUser(email, role);
// 2. Create default project
const project = await this.createProject({
name: `${email} Workspace`,
template: 'starter'
});
// 3. Install default servers
await this.installDefaultServers(project.uuid);
// 4. Share team collections
await this.shareTeamCollections(project.uuid);
// 5. Add to team channels
await this.addToChannels(email);
// 6. Send welcome email
await this.sendWelcomeEmail(email, {
project_uuid: project.uuid,
getting_started_url: 'https://plugged.in/getting-started'
});
return { invitation, project };
}
}
```
### Approval Workflows
Implement approval processes for sensitive operations:
```javascript theme={null}
// Request approval for production server
const approvalRequest = await fetch('https://plugged.in/api/approvals', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'server_deployment',
resource: {
server_uuid: 'prod-server-uuid',
environment: 'production'
},
approvers: ['admin1', 'admin2'],
required_approvals: 2,
deadline: '2024-01-25T00:00:00Z'
})
});
```
## Troubleshooting Common Issues
### Permission Conflicts
**Issue**: User cannot access shared resources
**Solution**:
1. Verify user is part of the organization
2. Check project membership and role
3. Confirm resource sharing settings
4. Review organization-wide permissions
### Sync Issues
**Issue**: Changes not reflecting for team members
**Solution**:
```bash theme={null}
# Force sync via API
POST /api/sync/force
{
"organization_id": "org-uuid",
"resources": ["servers", "collections", "knowledge_bases"]
}
```
### Notification Delivery
**Issue**: Team members not receiving notifications
**Solution**:
1. Check notification preferences in user settings
2. Verify email addresses are confirmed
3. Review organization notification settings
4. Check spam/junk folders for email notifications
## Best Practices Summary
Key practices for effective team collaboration:
1. **Clear Role Definition**: Define roles and responsibilities clearly
2. **Regular Audits**: Review permissions and access regularly
3. **Documentation**: Maintain comprehensive team documentation
4. **Communication**: Set up appropriate notification channels
5. **Security**: Use secure credential management practices
6. **Training**: Provide onboarding and training for team members
7. **Monitoring**: Track usage and activity for optimization
## Next Steps
Learn to build custom MCP servers for your team
Deploy Plugged.in on your own infrastructure
## Additional Resources
* [Organization Management](/platform/user-management)
* [Security Best Practices](/security/overview)
* [API Documentation](/api/reference)
* [Support Community](https://github.com/orgs/VeriTeknik/discussions)