cprime-registry-sdk
v1.0.4
Published
SDK for interacting with MCP Registry service
Readme
MCP Registry SDK
A TypeScript SDK for interacting with ContextBridge, an automated MCP (Model Context Protocol) server deployment platform. This SDK provides a clean, type-safe interface for managing MCP servers, monitoring build pipelines, configuring environments, and deploying containerized MCP server instances.
About ContextBridge
ContextBridge transforms GitHub repositories into production-ready, containerized MCP servers with zero configuration required. The platform automatically handles the entire deployment pipeline—from repository cloning and environment detection to Docker image building and production deployment.
Key Features
- Zero-Configuration Deployment: Provide a GitHub repository URL, and ContextBridge handles everything
- Automated Build Pipeline: 6-stage build process with real-time status tracking
- Multi-Strategy Dockerfile Generation: AI-powered and template-based approaches ensure compatibility
- Isolated Multi-tenant Instances: Secure, per-user containerized environments with custom configurations
- HTTP/SSE Endpoints: Custom supergateway wrapper transforms stdio-based MCP servers into HTTP services
- JWT Authentication: Scope-based permissions for fine-grained access control
Installation
npm install cprime-registry-sdkQuick Start
import { MCPRegistryService } from 'cprime-registry-sdk';
import { EventEmitter } from 'events';
// Initialize the service
const service = new MCPRegistryService(
'https://registry.example.com', // ContextBridge registry URL
new EventEmitter(), // Event emitter for error handling
'your-app-token', // Application token
'/v1', // API version
);
// Get all available MCP servers
const servers = await service.getServers('[email protected]');
console.log(servers.data.servers);Constructor Parameters
The MCPRegistryService constructor accepts the following parameters:
url(string, required): The base URL of the ContextBridge registry serviceeventEmitter(EventEmitter, optional): Event emitter instance for error handling. Defaults to a new EventEmitter if not providedappToken(string, required): Application token for authentication. This token is exchanged for user-specific JWT tokensversion(string, required): API version path (e.g., '/v1')
Authentication
The SDK implements automatic JWT token management with refresh capabilities. When you call any method, the SDK:
- Checks if a valid JWT token exists for the user
- Automatically requests a new token using the app token if needed
- Refreshes expired tokens automatically
- Handles token refresh failures gracefully
Manual Token Management
// Request a JWT token manually
const tokenData = await service.requestRegistryJwtToken(
'[email protected]',
'your-app-token',
['registry.list', 'registry.add'], // Required scopes
);
// Refresh an existing token
const newToken = await service.refreshRegistryJwtToken(
'[email protected]',
tokenData.refresh_token,
);
// Check authentication status
const isAuth = service.isAuthenticated('[email protected]');
// Clear authentication state
service.clearUserAuthState('[email protected]');Available Scopes
The SDK automatically requests appropriate scopes based on the operations you perform. Available scopes include:
registry.list- List serversregistry.add- Add new serversregistry.run- Start server instancesregistry.stop- Stop server instancesregistry.delete- Delete serversregistry.state- Manage server statelogs.get- Retrieve logslogs.export- Export logs as CSVsettings.get,settings.create,settings.update,settings.delete- Manage user settingsdeployer.logs- Access build pipeline logs
API Reference
Server Management
Get All Servers
Retrieve all MCP servers available to a user, including their status, tools, and running instances.
const result = await service.getServers('[email protected]');
// Returns: { status, message, data: { servers: [...] } }Each server includes:
- Server metadata (name, description, version, status)
- Available tools with schemas
- Running instances with URLs
- Instance status and creation timestamps
Add a New MCP Server
Add a GitHub repository to ContextBridge. This triggers the automated build pipeline.
const result = await service.addMcpServer(
'[email protected]',
'https://github.com/user/mcp-server.git',
);
// Returns: { status, message, data: { git_url, user_email, app_name, status }, error }This operation initiates the 6-stage build pipeline:
- Repository cloning
- Config processing (AI-powered environment variable extraction)
- Dockerfile generation (multi-strategy approach)
- Image building with security validation
- Server registration
- Cleanup
Start a Server Instance
Start an isolated container instance of an MCP server with custom environment configuration.
const result = await service.startMcpServer(
'[email protected]',
'image-id-123', // Image ID from getServers()
{
env: {
API_KEY: 'your-api-key',
DEBUG: 'true',
},
},
);
// Returns: { status, message, data: { url, stdout, stderr } }
// The 'url' is the HTTP/SSE endpoint for MCP communicationEach instance is isolated per user/organization and receives a unique endpoint URL.
Stop a Server Instance
Stop a running server instance.
const result = await service.stopMcpServer('[email protected]', 'image-id-123');
// Returns: { status, message, data: { service_name, stopped } }Delete a Server
Permanently delete an MCP server and its associated Docker image.
const result = await service.deleteMcpServer(
'[email protected]',
'image-id-123',
);
// Returns: { status, message, data: { image_id, deleted } }Set Server State
Enable or disable a server (controls availability without deletion).
await service.setMCPServerState(
'[email protected]',
'image-id-123',
'enabled', // or 'disabled'
);Build Pipeline Management
Get Pipeline Status
Monitor the progress of the automated build pipeline for a repository.
const pipeline = await service.getPipelineStatus(
'[email protected]',
'https://github.com/user/mcp-server.git',
);
// Returns: { error, data: { pipeline_id, git_url, server_name, pipeline_status, stage_results } }The pipeline status includes:
- Overall pipeline status
- Individual stage results (cloning, config processing, Dockerfile generation, building, registration, cleanup)
- Stage timestamps and output data
- Success/failure status for each stage
Example response:
{
data: {
pipeline_id: "pipeline-123",
git_url: "https://github.com/user/mcp-server.git",
server_name: "mcp-server",
pipeline_status: "completed", // or "in_progress", "failed"
stage_results: [
{
stage: "repository_cloning",
status: "completed",
success: true,
started_at: "2024-01-01T10:00:00Z",
completed_at: "2024-01-01T10:00:05Z",
output_data: { ... }
},
// ... more stages
]
}
}User Settings Management
User settings allow you to store and manage environment variable configurations for MCP servers, enabling quick instance deployment with pre-configured environments.
Get User Settings
Retrieve saved environment configurations for a specific repository.
const settings = await service.getUserSettings(
'[email protected]',
'https://github.com/user/mcp-server.git',
);
// Returns: { status, data: { _id, user_email, git_url, envs, created_at, updated_at } }Create User Settings
Save environment variable configurations for a repository.
const settings = await service.createUserSettings(
'[email protected]',
'https://github.com/user/mcp-server.git',
{
API_KEY: 'your-api-key',
DEBUG: 'true',
CUSTOM_VAR: 'value',
},
);
// Returns: { status, message, data: { _id, user_email, git_url, envs } }Update User Settings
Update existing environment configurations.
await service.updateUserSettings(
'[email protected]',
'https://github.com/user/mcp-server.git',
{
API_KEY: 'new-api-key',
DEBUG: 'false',
},
);Delete User Settings
Remove saved configurations.
await service.deleteUserSettings('[email protected]', 'config-id-123');Logs Management
Get Server Logs
Retrieve logs for a specific user, with filtering and pagination options.
const logs = await service.getMcpServerLogs(
'[email protected]',
'user-id-123',
'desc', // Sort order: 'asc' or 'desc'
'all', // Log type: 'system', 'rpc', or 'all'
0, // Skip (pagination offset)
50, // Limit (number of logs)
new Date('2024-01-01'), // Start date (optional)
new Date('2024-01-31'), // End date (optional)
);
// Returns: { logs: [...], total: number }Export Logs as CSV
Export logs in CSV format for analysis.
const csvContent = await service.getMcpServerLogsCsvFile(
'[email protected]',
'user-id-123',
'desc',
'all',
new Date('2024-01-01'),
new Date('2024-01-31'),
);
// Returns: CSV string contentRemote Server Management
Add Remote MCP Server
Add a remote MCP server that's not managed by ContextBridge (external servers).
await service.addRemoteMcpServer(
'[email protected]',
'remote-server-name',
'https://remote-server.example.com',
'sse', // Transport type: 'sse', 'stdio', etc.
'Description of the server', // Optional
{ customParam: 'value' }, // Optional params
'https://homepage.com', // Optional homepage
'Vendor Name', // Optional vendor
'1.0.0', // Optional version
'https://github.com/...', // Optional git URL
);Instance Configuration
Get Instance Configuration
Retrieve the MCP server configuration for a specific instance.
const config = await service.getInstanceConfig('instance-id-123');
// Returns: { status, data: { mcpServers: {...} } }Authentication & Token Management
Create App Token
Create a new application token with specific scopes.
const result = await service.createAppToken(
'[email protected]',
'your-token',
'organization-name',
['registry.list', 'registry.add'],
'Token description', // Optional
);
// Returns: { status, message, data: { app_token } }Get Available Scopes
Retrieve all available permission scopes.
const scopes = await service.getAvailableScopes();
// Returns: { status, data: string[] }Health Check
Check if the registry service is available.
const health = await service.healthCheck();
// Returns: { status, message? }Complete Workflow Example
Here's a complete example showing the typical workflow from adding a server to running an instance:
import { MCPRegistryService } from 'cprime-registry-sdk';
import { EventEmitter } from 'events';
const service = new MCPRegistryService(
'https://registry.example.com',
new EventEmitter(),
'your-app-token',
'/v1',
);
async function deployMcpServer() {
const userEmail = '[email protected]';
const gitUrl = 'https://github.com/user/my-mcp-server.git';
try {
// 1. Add the server (triggers build pipeline)
console.log('Adding MCP server...');
const addResult = await service.addMcpServer(userEmail, gitUrl);
console.log('Build pipeline started:', addResult.data.status);
// 2. Monitor build pipeline progress
let pipelineStatus = 'in_progress';
while (pipelineStatus === 'in_progress') {
await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds
const pipeline = await service.getPipelineStatus(userEmail, gitUrl);
pipelineStatus = pipeline.data?.pipeline_status || 'unknown';
console.log('Pipeline status:', pipelineStatus);
if (pipeline.data?.stage_results) {
pipeline.data.stage_results.forEach((stage) => {
console.log(` ${stage.stage}: ${stage.status}`);
});
}
}
if (pipelineStatus !== 'completed') {
throw new Error('Build pipeline failed');
}
// 3. Get all servers to find the new one
const servers = await service.getServers(userEmail);
const newServer = servers.data.servers.find(
(s) => s.name === addResult.data.app_name,
);
if (!newServer) {
throw new Error('Server not found after build');
}
// 4. Create user settings with environment variables
console.log('Creating user settings...');
await service.createUserSettings(userEmail, gitUrl, {
API_KEY: 'your-api-key',
DEBUG: 'true',
});
// 5. Start a server instance
console.log('Starting server instance...');
const instance = await service.startMcpServer(
userEmail,
newServer._id, // Use the image ID
{
env: {
API_KEY: 'your-api-key',
DEBUG: 'true',
},
},
);
console.log('Server instance URL:', instance.data.url);
console.log(
'Server is ready! Use the URL for MCP communication via HTTP/SSE',
);
// 6. Later: Get logs
const logs = await service.getMcpServerLogs(
userEmail,
'user-id-123',
'desc',
'all',
0,
50,
);
console.log(`Retrieved ${logs.total} log entries`);
// 7. Stop the instance when done
await service.stopMcpServer(userEmail, newServer._id);
console.log('Server instance stopped');
} catch (error) {
console.error('Error:', error);
}
}
deployMcpServer();Error Handling
The SDK uses an EventEmitter for error handling. Listen to error events to handle authentication failures, network issues, and other errors:
import { EventEmitter } from 'events';
const eventEmitter = new EventEmitter();
const service = new MCPRegistryService(url, eventEmitter, appToken, version);
eventEmitter.on('error', (error) => {
console.error('Service error:', error);
// Handle error: retry, notify user, etc.
});All methods throw errors that can be caught with try/catch:
try {
const servers = await service.getServers('[email protected]');
} catch (error) {
if (error instanceof Error) {
console.error('Failed to get servers:', error.message);
}
}Types
The SDK exports the following TypeScript types:
TokenDataDto- JWT token data structure with access/refresh tokens and expirationMCPAdditionLog- Build pipeline log structureMCPUserConfig- User configuration structureMCPServer- Server information structure with tools and metadataIMCPRegistryService- Service interface for type-safe implementations
Multi-tenancy & Isolation
ContextBridge ensures complete isolation between users and organizations:
- Each user's server instances run in isolated containers
- Container naming conventions prevent cross-user access
- Network segmentation ensures secure multi-tenant deployment
- Environment variables are scoped per user and instance
- All operations require user email for proper isolation
Requirements
- Node.js >= 22.0.0
- TypeScript 5.x (for TypeScript projects)
License
ISC
