npm package: @qantuslab/mcp-sdk
Description: QantusLab SDK for MCP monitoring, security, and analytics
Author: QantusLab
Latest version: 0.1.3

# @qantuslab/mcp-sdk

QantusLab SDK for MCP (Model Context Protocol) monitoring, security, and analytics.

**Monitor every AI tool call. Secure your MCP traffic. Gain visibility.**

## Features

- **Automatic Monitoring** - All MCP requests are logged to your QantusLab dashboard
- **Security Inspection** - PII detection, injection prevention, and DLP rules
- **Analytics** - Usage metrics, latency tracking, and security insights
- **Zero Config** - Works with any MCP server without code changes
- **Type Safe** - Full TypeScript support with comprehensive types

## Installation

```bash
npm install @qantuslab/mcp-sdk
# or
yarn add @qantuslab/mcp-sdk
# or
pnpm add @qantuslab/mcp-sdk
```

## Quick Start

### As an MCP Client

Connect to any MCP server through QantusLab Hub:

```typescript
import { QantusLabClient } from '@qantuslab/mcp-sdk';

// Initialize client
const client = new QantusLabClient({
  apiKey: process.env.QANTUSLAB_API_KEY,
});

// Connect to an MCP server
const github = await client.connect('npx -y @modelcontextprotocol/server-github');

// Use like a normal MCP client
const tools = await github.listTools();
const result = await github.callTool('list_repos', { owner: 'anthropic' });

// All requests are automatically:
// ✓ Logged to QantusLab dashboard
// ✓ Inspected for security issues
// ✓ Tracked for analytics
```

### As an MCP Server

Wrap your existing MCP server to add monitoring:

```typescript
import { QantusLabServer } from '@qantuslab/mcp-sdk';
import { Server } from '@modelcontextprotocol/sdk/server';

// Your existing server
const server = new Server({ name: 'my-server', version: '1.0.0' });

// Wrap with QantusLab monitoring
const monitored = new QantusLabServer(server, {
  apiKey: process.env.QANTUSLAB_API_KEY,
  serverName: 'my-server',
});

// All incoming requests are now monitored
```

## Configuration

### Environment Variables

The SDK automatically reads these environment variables:

| Variable | Description | Default |
|----------|-------------|---------|
| `QANTUSLAB_API_KEY` | Your QantusLab API key | Required |
| `QANTUSLAB_HUB_URL` | QantusLab Hub URL | `https://api.qantuslab.com` |
| `QANTUSLAB_DEBUG` | Enable debug logging | `false` |
| `QANTUSLAB_TIMEOUT` | Request timeout (ms) | `30000` |
| `QANTUSLAB_RETRIES` | Max retry attempts | `3` |
| `QANTUSLAB_FALLBACK_ENABLED` | Enable direct fallback | `false` |

### Programmatic Configuration

```typescript
const client = new QantusLabClient({
  // Required
  apiKey: 'your-api-key',

  // Optional
  hubUrl: 'https://api.qantuslab.com',
  timeout: 30000,
  retries: 3,
  fallbackEnabled: false,
  debug: false,

  // Middleware hooks
  middleware: {
    onRequest: (request) => {
      console.log('Sending:', request.method);
      return request;
    },
    onResponse: (response) => {
      console.log('Received:', response.result);
      return response;
    },
    onError: (error, request) => {
      console.error('Error:', error.message);
    },
  },
});
```

## API Reference

### QantusLabClient

Main client for connecting to MCP servers.

```typescript
const client = new QantusLabClient(config);

// Connect to a server
const connection = await client.connect(upstream, options);

// Disconnect
client.disconnect(upstream);
client.disconnectAll();

// Get active sessions
const sessions = client.getSessions();

// Check hub health
const healthy = await client.checkHubHealth();
```

### MCPConnection

Represents a connected MCP server.

```typescript
const connection = await client.connect('npx server-command');

// List tools
const tools = await connection.listTools();

// Call a tool
const result = await connection.callTool('tool-name', { arg: 'value' });

// List resources
const resources = await connection.listResources();

// Read a resource
const content = await connection.readResource('resource://uri');

// List prompts
const prompts = await connection.listPrompts();

// Get a prompt
const prompt = await connection.getPrompt('prompt-name', { arg: 'value' });

// Raw request
const response = await connection.request('custom/method', { params: {} });

// Get server info
const info = connection.getServerInfo();
```

### QantusLabServer

Wrapper for adding monitoring to MCP servers.

```typescript
const monitored = new QantusLabServer(server, {
  apiKey: 'your-api-key',
  serverName: 'my-server',
  hubUrl: 'https://api.qantuslab.com',
  debug: false,
  asyncReporting: true,
});

// Add hooks
monitored.beforeRequest((request) => {
  console.log('Before:', request.method);
});

monitored.afterResponse((request, response) => {
  console.log('After:', request.method);
});

// Wrap a handler
const wrapped = monitored.wrapHandler(originalHandler);
```

## Error Handling

The SDK throws `QantusLabError` for all errors:

```typescript
import { QantusLabError, QantusLabErrorCode } from '@qantuslab/mcp-sdk';

try {
  await client.connect('server-command');
} catch (error) {
  if (error instanceof QantusLabError) {
    switch (error.code) {
      case QantusLabErrorCode.MISSING_API_KEY:
        console.error('API key required');
        break;
      case QantusLabErrorCode.HUB_UNREACHABLE:
        console.error('Cannot reach QantusLab Hub');
        break;
      case QantusLabErrorCode.REQUEST_BLOCKED:
        console.error('Request blocked by security policy');
        break;
      default:
        console.error('Error:', error.message);
    }
  }
}
```

## Using with AI Clients

### Claude Desktop

Add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@qantuslab/mcp-proxy", "--upstream", "npx -y @modelcontextprotocol/server-github"],
      "env": {
        "QANTUSLAB_API_KEY": "your-api-key"
      }
    }
  }
}
```

### Cursor IDE

Add to `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@qantuslab/mcp-proxy", "--upstream", "npx -y @modelcontextprotocol/server-github"],
      "env": {
        "QANTUSLAB_API_KEY": "your-api-key"
      }
    }
  }
}
```

### VS Code

Add to `.vscode/mcp.json`:

```json
{
  "mcp.servers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@qantuslab/mcp-proxy", "--upstream", "npx -y @modelcontextprotocol/server-github"],
      "env": {
        "QANTUSLAB_API_KEY": "your-api-key"
      }
    }
  }
}
```

## TypeScript Types

The SDK exports comprehensive TypeScript types:

```typescript
import type {
  QantusLabConfig,
  MCPRequest,
  MCPResponse,
  MCPTool,
  MCPResource,
  MCPPrompt,
  ToolCallResult,
  ServerInfo,
} from '@qantuslab/mcp-sdk';
```

## Related Packages

- `@qantuslab/mcp-proxy` - CLI tool for proxying MCP traffic
- `qantuslab-mcp` - Python SDK (coming soon)

## Support

- Documentation: [https://qantuslab.com/docs](https://qantuslab.com/docs)
- Issues: [https://github.com/qantuslab/mcp-sdk/issues](https://github.com/qantuslab/mcp-sdk/issues)
- Email: hello@qantuslab.com

## License

MIT