> ## Documentation Index
> Fetch the complete documentation index at: https://docs.plugged.in/llms.txt
> Use this file to discover all available pages before exploring further.

# 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

<Steps>
  <Step title="Navigate to API Keys">
    Go to **Settings** → **API Keys** in your Plugged.in dashboard
  </Step>

  <Step title="Create New Key">
    Click "Create API Key" and provide a descriptive name
  </Step>

  <Step title="Copy Key">
    Copy the generated key immediately - it won't be shown again
  </Step>

  <Step title="Store Securely">
    Store the API key in environment variables or a secure vault
  </Step>
</Steps>

### 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

<Warning>
  API rate limits are enforced to ensure fair usage and platform stability.
</Warning>

### 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

<AccordionGroup>
  <Accordion title="Security">
    * 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
  </Accordion>

  <Accordion title="Performance">
    * Cache frequently accessed data
    * Use pagination for large datasets
    * Implement connection pooling
    * Batch operations when possible
    * Use webhooks instead of polling
  </Accordion>

  <Accordion title="Reliability">
    * Implement retry logic with exponential backoff
    * Handle network timeouts gracefully
    * Log all API interactions
    * Monitor API usage and errors
    * Set up alerts for failures
  </Accordion>

  <Accordion title="Development">
    * Use versioned API endpoints
    * Test with mock data first
    * Implement comprehensive error handling
    * Document your integration
    * Keep SDKs updated
  </Accordion>
</AccordionGroup>

## 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

<CardGroup cols={2}>
  <Card title="RAG Knowledge Base" icon="database" href="/tutorials/rag-knowledge-base">
    Learn to build knowledge bases with RAG
  </Card>

  <Card title="Team Collaboration" icon="users" href="/tutorials/team-collaboration">
    Set up team workspaces and collaboration
  </Card>
</CardGroup>

## Additional Resources

* [API Reference Documentation](/api/reference)
* [Authentication Guide](/api/authentication)
* [Platform Overview](/platform/overview)
* [Support & Community](https://github.com/orgs/VeriTeknik/discussions)
