Package Exports
- @mcpweb-org/sdk
Readme
MCPaaS TypeScript SDK
The official TypeScript SDK for MCPaaS (Model Context Protocol as a Service) - build, deploy, and monitor MCP servers with automatic analytics and observability.
🚀 Ready in 2 minutes - Get your MCP server running with built-in analytics, HTTP routing, and API integrations
📚 Table of Contents
- Quick Start
- Installation
- Core Components
- Step-by-Step Tutorials
- Examples
- API Reference
- Best Practices
- Troubleshooting
🚀 Quick Start
Get running in under 2 minutes:
# 1. Install the SDK
npm install @mcpweb-org/sdk
# 2. Create a new TypeScript project
mkdir my-mcpaas-server
cd my-mcpaas-server
npm init -y
npm install @mcpweb-org/sdk typescript @types/node zod
npx tsc --init
# 3. Create your server file
touch server.tsThen add this code to server.ts:
import { BunMCP } from '@mcpweb-org/sdk';
import { z } from 'zod';
// ✨ Create server with automatic analytics
const server = new BunMCP({
name: 'my-awesome-server',
version: '1.0.0',
}, 'your-app-id', 'your-api-key');
// 🛠️ Add a tool in 30 seconds
server.registerTool('greet', {
title: 'Greeting Tool',
description: 'Say hello to someone',
inputSchema: {
name: z.string().describe('Person to greet'),
style: z.enum(['formal', 'casual']).default('casual')
}
}, async ({ name, style }) => {
const greeting = style === 'formal'
? `Good day, ${name}.`
: `Hey ${name}! 👋`;
return {
content: [{
type: 'text',
text: greeting
}]
};
});
// 🚀 Start your server
await server.start();
console.log('🎉 Server running! Try calling the greet tool.');Run it:
# 4. Set environment variables
echo "MCPAAS_API_BASE_URL=https://us-central1-mcpaas-dev.cloudfunctions.net/analytics" > .env
echo "MCPAAS_APP_ID=your-app-id" >> .env
echo "MCPAAS_API_KEY=your-api-key" >> .env
# 5. Start your server
npx tsx server.ts
# or compile and run: npx tsc && node server.jsThat's it! Your MCP server is running with built-in analytics, error tracking, and performance monitoring.
📦 Installation
# npm
npm install @mcpweb-org/sdk
# yarn
yarn add @mcpweb-org/sdk
# pnpm
pnpm add @mcpweb-org/sdkRequirements:
- Node.js 18+
- TypeScript 5.0+ (recommended)
🧩 Core Components
🎯 What Should I Use?
| Component | Use Case | When to Choose |
|---|---|---|
| BunMCP | Core MCP server | ✅ Always start here |
| BunExpress | Drop-in Express replacement with MCP | ✅ Migrating from Express servers |
| BunLog | Custom logging | ✅ Production debugging |
| registerAPI | External API integration | ✅ Connecting to 3rd party APIs |
✨ Key Features
🚀 Simplified Development
- Drop-in Replacement: Use
BunMCPinstead of the official MCP SDK - Single Import: Everything you need from one package
- TypeScript First: Full type safety and IntelliSense support
- Zero Configuration: Works out of the box with sensible defaults
📊 Built-in Analytics
- Automatic Tracking: Tool performance, resource usage, errors
- Real-time Monitoring: Server health, memory usage, response times
- Custom Metrics: Add your own performance indicators
- Dashboard Integration: Visual insights in MCPaaS portal
🛠️ Enhanced Developer Experience
- Error Handling: Comprehensive error types and debugging info
- Performance Monitoring: Built-in timing and resource tracking
- Session Management: Automatic session lifecycle tracking
- Batch Processing: Efficient analytics data transmission
⚡ High-Performance Components
- BunExpress: Drop-in replacement for Express servers with full MCP support
- BunLog: Lightweight logging with production toggle capabilities
- RegisterAPI: Transform any HTTP API into MCP tools automatically
- Optimized Performance: High-performance Node.js implementation
🌐 HTTP & API Integration
- Express Server Mounting: Mount MCP protocol over any Express server
- Drop-in Migration: Replace Express servers with zero code changes
- API Transformation: Convert external APIs to MCP tools with templates
- Middleware Support: Full Express.js middleware ecosystem compatibility
- CORS & Security: Built-in cross-origin and security features
🎓 Step-by-Step Tutorials
Tutorial 1: Your First MCP Tool (2 minutes)
import { BunMCP } from '@mcpweb-org/sdk';
import { z } from 'zod';
// Step 1: Create server
const server = new BunMCP({
name: 'tutorial-server',
version: '1.0.0'
}, process.env.MCPAAS_APP_ID!, process.env.MCPAAS_API_KEY!);
// Step 2: Add a simple tool
server.registerTool('flip-coin', {
title: 'Coin Flipper',
description: 'Flip a virtual coin',
inputSchema: {
// No inputs needed!
}
}, async () => {
const result = Math.random() > 0.5 ? 'heads' : 'tails';
return {
content: [{
type: 'text',
text: `🪙 Coin flip result: ${result.toUpperCase()}!`
}]
};
});
// Step 3: Start server
await server.start();Tutorial 2: Mounting MCP on Express Server (3 minutes)
import { BunMCP, BunExpress } from '@mcpweb-org/sdk';
// Step 1: Setup MCP server (from Tutorial 1)
const mcpServer = new BunMCP({
name: 'web-server',
version: '1.0.0'
}, process.env.MCPAAS_APP_ID!, process.env.MCPAAS_API_KEY!);
// Add your MCP tools here...
// Step 2: Mount MCP on Express server
const server = new BunExpress({
bunMCP: mcpServer,
options: {
port: 3000,
cors: true,
json: true
}
});
// Step 3:(Optional) Add additional custom REST APIs
server.get('/api/flip', async (req, res) => {
// Call your MCP tool from HTTP!
const result = Math.random() > 0.5 ? 'heads' : 'tails';
res.json({ result, timestamp: new Date().toISOString() });
});
server.post('/api/greet', async (req, res) => {
const { name } = req.body;
res.json({ message: `Hello ${name}!` });
});
// Step 4: Start server
await server.start();
console.log('🌐 Server running on http://localhost:3000');
console.log('🧪 Try: curl http://localhost:3000/api/flip');Tutorial 3: External API Integration (5 minutes)
// Step 1: Transform GitHub API into MCP tool
server.registerAPI('github-user', {
title: 'GitHub User Info',
description: 'Get GitHub user information',
inputSchema: {
username: z.string().describe('GitHub username')
}
}, {
method: 'GET',
url: 'https://api.github.com/users/{{username}}',
headers: {
'User-Agent': 'MCPaaS-SDK',
'Accept': 'application/vnd.github.v3+json'
}
});
// Step 2: Use weather API with API key
server.registerAPI('weather', {
title: 'Current Weather',
description: 'Get current weather for a city',
inputSchema: {
city: z.string(),
units: z.enum(['metric', 'imperial']).default('metric')
}
}, {
method: 'GET',
url: 'https://api.openweathermap.org/data/2.5/weather',
headers: {
'Authorization': `Bearer ${process.env.OPENWEATHER_API_KEY}`
},
queryParams: {
q: '{{city}}',
units: '{{units}}'
}
});
// Done! Your external APIs are now MCP tools 🎉Tutorial 4: Bulk API Registration with OpenAPI (2 minutes)
Register entire API suites instantly using OpenAPI specifications:
import { BunMCP, OpenAPISchema } from '@mcpweb-org/sdk';
// Step 1: Define or load your OpenAPI schema
const githubAPISchema: OpenAPISchema = {
openapi: "3.0.0",
info: {
title: "GitHub API",
version: "1.0.0"
},
servers: [{ url: "https://api.github.com" }],
paths: {
"/users/{username}": {
get: {
operationId: "getUser",
summary: "Get user information",
parameters: [{
name: "username",
in: "path",
required: true,
schema: { type: "string" }
}],
responses: { "200": { description: "User data" } }
}
},
"/users/{username}/repos": {
get: {
operationId: "getUserRepos",
summary: "List user repositories",
parameters: [
{
name: "username",
in: "path",
required: true,
schema: { type: "string" }
},
{
name: "type",
in: "query",
schema: { type: "string", enum: ["all", "owner", "member"] }
}
],
responses: { "200": { description: "Repository list" } }
}
}
}
};
// Step 2: Register entire API with one call
server.registerOpenAPI(githubAPISchema);
// Result: All endpoints automatically become MCP tools!
// ✅ getUser tool - Get user information
// ✅ getUserRepos tool - List user repositories
// ✅ Full type safety with Zod validation
// ✅ Automatic parameter extraction and templatingInstallation
npm install @mcpaas/sdk
# or
yarn add @mcpaas/sdkCore Concepts
BunMCP
The main server class that replaces the official MCP SDK:
import { BunMCP } from '@mcpaas/sdk';
const server = new BunMCP(
{
name: 'my-server',
version: '1.0.0'
},
'app-id', // Your MCPaaS app ID
'api-key' // Your MCPaaS API key
);BunExpress
Drop-in replacement for Express servers with full MCP support. BunExpress mounts MCP over Express, giving you all the Express functionality you know with automatic MCP protocol integration:
import { BunExpress } from '@mcpaas/sdk';
const server = new BunExpress({
bunMCP: mcpServer, // Your BunMCP instance
options: {
port: 3000,
host: 'localhost',
cors: true,
json: true
}
});
// Express.js-style routing
server.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'John' }]);
});
server.post('/api/users', (req, res) => {
res.json({ message: 'User created', data: req.body });
});
// Start the server
await server.start();BunExpress Features:
- 🚀 Drop-in Express Replacement: Seamlessly replace your existing Express servers
- 🛣️ Full Express Compatibility: All Express.js routing and middleware works as expected
- 🔌 MCP Integration: Automatic MCP protocol endpoints mounted on your Express server
- 🌐 CORS Support: Built-in cross-origin resource sharing
- 📝 JSON Parsing: Automatic request body parsing
- 🏥 Health Checks: Built-in
/healthand/statusendpoints - ⚡ Middleware Support: Complete Express.js middleware ecosystem compatibility
BunLog
Lightweight logging utility with toggle capability:
import { BunLog } from '@mcpaas/sdk';
const logger = new BunLog({ disable: false });
logger.log('Server started');
logger.log('Processing request:', requestData);BunLog Features:
- 🔇 Toggle Logging: Enable/disable logging globally
- 🎯 Simple API: Familiar console.log-style interface
- 📊 Performance: Minimal overhead when disabled
- 🔧 Debug Mode: Perfect for development vs production
RegisterAPI Method
Transform any HTTP API into an MCP tool with automatic integration:
// Register external APIs as MCP tools
server.registerAPI('weather-api', {
title: 'Weather API',
description: 'Get current weather data',
inputSchema: {
city: z.string().describe('City name'),
units: z.enum(['metric', 'imperial']).optional()
}
}, {
method: 'GET',
url: 'https://api.openweathermap.org/data/2.5/weather',
headers: {
'Authorization': `Bearer ${API_KEY}`
},
queryParams: {
q: '{{city}}', // Template from input
units: '{{units}}'
}
});
// Register internal APIs
server.registerAPI('user-service', {
title: 'User Management',
description: 'Create new user account',
inputSchema: {
name: z.string(),
email: z.string().email()
}
}, {
method: 'POST',
url: 'http://localhost:8080/api/users',
headers: {
'Content-Type': 'application/json'
},
body: {
name: '{{name}}',
email: '{{email}}',
created_at: '{{$now}}' // Built-in template functions
}
});RegisterAPI Features:
- 🌐 Any HTTP API: Support for GET, POST, PUT, DELETE, PATCH
- 📝 Template System: Dynamic parameter injection with
{{param}} - 🔧 Built-in Functions:
{{$now}},{{$uuid}},{{$timestamp}} - 🛡️ Type Safety: Full TypeScript validation for inputs and outputs
- 📊 Auto Analytics: Automatic performance tracking and error monitoring
- 🔁 Retry Logic: Built-in retry mechanisms for failed requests
- 🏷️ Header Support: Custom headers, authentication, content types
SDK Usage (Legacy API Client)
For platform management operations:
import { MCPaaSClient } from '@mcpaas/sdk/client';
const client = new MCPaaSClient({
apiKey: 'your-api-key',
baseUrl: 'https://api.mcpaas.dev', // Optional, defaults to production
timeout: 30000 // Optional, defaults to 10 seconds
});Tool Registration
Register tools with automatic analytics tracking:
server.registerTool('tool-name', toolConfig, async (args) => {
// Your tool implementation
// Analytics automatically tracked:
// - Execution time
// - Input/output sizes
// - Success/failure
// - Memory usage
return { content: [{ type: 'text', text: 'response' }] };
});Resource Registration
Register resources with access pattern tracking:
server.registerResource('resource-name', 'resource://uri', resourceConfig, async () => {
// Analytics tracked:
// - Access frequency
// - Response sizes
// - Cache effectiveness
return { content: 'resource data' };
});Prompt Registration
Register prompts with generation analytics:
server.registerPrompt('prompt-name', promptConfig, async (args) => {
// Analytics tracked:
// - Generation time
// - Template complexity
// - Usage patterns
return { messages: [...] };
});Analytics Overview
Analytics are automatically collected for every operation:
// Get analytics collector for custom tracking
const analytics = server.analyticsCollector;
// Track custom metrics
analytics.trackPerformance({
customMetrics: {
databaseQueries: 5,
cacheHitRate: 0.85
}
});
// Track tool execution manually
const eventId = analytics.trackToolStart('custom-tool');
// ... perform work ...
analytics.trackToolComplete(eventId, 'custom-tool', {
customMetrics: { accuracy: 0.95 }
});Examples
Complete BunExpress Server
import { BunMCP, BunExpress } from '@mcpaas/sdk';
import { z } from 'zod';
// Setup MCPaaS server with tools and resources
const setupMCPServer = () => {
const bunMCP = new BunMCP({
name: "mcpaas-express-server",
description: "High-performance server with BunExpress",
version: "1.0.0",
capabilities: {
tools: true,
resources: true,
prompts: true,
},
}, 'your-app-id', 'your-api-key');
// Register calculation tool
bunMCP.registerTool('calculate', {
title: 'Calculator',
description: 'Perform arithmetic calculations',
inputSchema: {
operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
a: z.number(),
b: z.number(),
},
}, async ({ operation, a, b }) => {
let result: number;
switch (operation) {
case 'add': result = a + b; break;
case 'subtract': result = a - b; break;
case 'multiply': result = a * b; break;
case 'divide':
if (b === 0) throw new Error('Division by zero');
result = a / b;
break;
}
return {
content: [{
type: 'text',
text: `${a} ${operation} ${b} = ${result}`,
}],
};
});
// Register weather API as MCP tool
bunMCP.registerAPI('weather', {
title: 'Weather API',
description: 'Get current weather',
inputSchema: {
city: z.string().describe('City name'),
units: z.enum(['metric', 'imperial']).default('metric')
}
}, {
method: 'GET',
url: 'https://api.openweathermap.org/data/2.5/weather',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
},
queryParams: {
q: '{{city}}',
units: '{{units}}'
}
});
return bunMCP;
};
// Create BunExpress server
const server = new BunExpress({
bunMCP: setupMCPServer(),
options: {
port: 3000,
host: 'localhost',
cors: true,
json: true
}
});
// Add REST API routes
server.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
]);
});
server.post('/api/users', (req, res) => {
const { name, email } = req.body;
const newUser = { id: Date.now(), name, email };
res.json({ message: 'User created', user: newUser });
});
// Add middleware for logging
server.use('/api', (req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);
next();
});
// Start server
await server.start();
console.log('🚀 BunExpress server running on http://localhost:3000');BunLog Usage Example
import { BunLog } from '@mcpaas/sdk';
// Create logger (disable in production)
const logger = new BunLog({
disable: process.env.NODE_ENV === 'production'
});
// Use throughout your application
logger.log('Server starting...');
logger.log('Processing request:', { userId: 123, action: 'login' });
logger.log('Database connected successfully');
// Conditional logging
if (process.env.DEBUG) {
const debugLogger = new BunLog({ disable: false });
debugLogger.log('Debug information:', complexObject);
}RegisterAPI Advanced Examples
// GitHub API integration
server.registerAPI('github-repos', {
title: 'GitHub Repositories',
description: 'Get user repositories from GitHub',
inputSchema: {
username: z.string(),
type: z.enum(['all', 'public', 'private']).default('public'),
sort: z.enum(['created', 'updated', 'pushed', 'full_name']).default('updated')
}
}, {
method: 'GET',
url: 'https://api.github.com/users/{{username}}/repos',
headers: {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'MCPaaS-SDK'
},
queryParams: {
type: '{{type}}',
sort: '{{sort}}',
per_page: '50'
}
});
// Internal microservice with authentication
server.registerAPI('user-profile', {
title: 'User Profile Service',
description: 'Update user profile information',
inputSchema: {
userId: z.string(),
name: z.string().optional(),
email: z.string().email().optional(),
avatar: z.string().url().optional()
}
}, {
method: 'PATCH',
url: 'http://user-service:8080/api/users/{{userId}}',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer {{$env.USER_SERVICE_TOKEN}}',
'X-Request-ID': '{{$uuid}}'
},
body: {
name: '{{name}}',
email: '{{email}}',
avatar: '{{avatar}}',
updated_at: '{{$now}}',
updated_by: 'mcpaas-sdk'
}
});
// Database API with custom error handling
server.registerAPI('database-query', {
title: 'Database Query',
description: 'Execute SQL queries safely',
inputSchema: {
table: z.string(),
filters: z.record(z.any()).optional(),
limit: z.number().max(1000).default(100)
}
}, {
method: 'POST',
url: 'http://db-proxy:3000/query',
headers: {
'Content-Type': 'application/json',
'X-API-Key': '{{$env.DB_API_KEY}}'
},
body: {
query: 'SELECT * FROM {{table}} {{#if filters}}WHERE {{filters}} {{/if}}LIMIT {{limit}}',
timestamp: '{{$timestamp}}'
},
timeout: 30000,
retries: 3
});Basic Calculator Tool
import { BunMCP } from '@mcpaas/sdk';
const server = new BunMCP({
name: 'calculator',
version: '1.0.0'
}, 'app-id', 'api-key');
server.registerTool('add', {
title: 'Add Numbers',
description: 'Add two numbers together',
inputSchema: {
a: z.number().describe('First number'),
b: z.number().describe('Second number')
}
}, async ({ a, b }) => {
const result = a + b;
return {
content: [{
type: 'text',
text: `${a} + ${b} = ${result}`
}]
};
});
await server.start();Database Resource
import { MCPServer } from '@mcpaas/sdk';
const server = new MCPServer({
name: 'database-server',
version: '1.0.0'
}, 'app-id', 'api-key');
server.registerResource('users', 'db://users', {
name: 'users',
description: 'User database',
mimeType: 'application/json'
}, async () => {
const users = await fetchUsersFromDatabase();
return {
content: JSON.stringify(users),
mimeType: 'application/json'
};
});
server.start();Custom Analytics
import { MCPServer } from '@mcpaas/sdk';
const server = new MCPServer({
name: 'ai-service',
version: '1.0.0'
}, 'app-id', 'api-key');
server.registerTool('generate', {
name: 'generate',
description: 'Generate AI content',
inputSchema: {
type: 'object',
properties: {
prompt: { type: 'string' }
}
}
}, async (args) => {
const analytics = server.analyticsCollector;
const startTime = Date.now();
const content = await generateAIContent(args.prompt);
const duration = Date.now() - startTime;
// Track custom business metrics
analytics.trackPerformance({
customMetrics: {
promptLength: args.prompt.length,
responseLength: content.length,
generationTime: duration,
modelConfidence: 0.87
}
});
return {
content: [{
type: 'text',
text: content
}]
};
});
server.start();Analytics & Observability
See ANALYTICS.md for comprehensive documentation on the built-in analytics system, including:
- 🔧 Tool-Specific Analytics - Performance, success rates, custom metrics
- 📚 Resource Access Tracking - Usage patterns, cache hit rates
- 💬 Prompt Analytics - Generation times, template complexity
- 🖥️ Server Health Monitoring - Memory, CPU, connection tracking
- 🚨 Error Tracking - Comprehensive error classification and debugging
- 📊 Dashboard Integration - Visual insights in MCPaaS portal
API Reference
BunMCP Class
Constructor
new BunMCP(
serverConfig: MCPServerConfig,
serverId: string,
apiKey: string,
disableLogging?: boolean
)Core Methods
registerTool(name, config, handler)- Register MCP tool with analyticsregisterResource(name, uri, config, handler)- Register MCP resourceregisterPrompt(name, config, handler)- Register MCP promptregisterAPI(name, config, apiSpec)- Transform HTTP API into MCP toolregisterOpenAPI(openApiSchema)- Bulk register APIs from OpenAPI schemaconnect(transport)- Connect to MCP transportclose()- Close connection and cleanup
HTTP Server Methods
start(options)- Start HTTP serverstop()- Stop HTTP server
Information Methods
getStats()- Get server statisticslistTools()- Get registered tools summarylistResources()- Get registered resources summarylistPrompts()- Get registered prompts summary
BunExpress Class
Constructor
new BunExpress({
bunMCP: BunMCP, // MCP server instance
options: {
port: number, // Server port
host?: string, // Bind host
cors?: boolean, // Enable CORS
json?: boolean // Enable JSON parsing
}
})HTTP Methods
get(path, handler)- Register GET routepost(path, handler)- Register POST routeput(path, handler)- Register PUT routedelete(path, handler)- Register DELETE routeuse(path?, middleware)- Add middleware
Server Control
start()- Start HTTP serverstop()- Stop HTTP serverhealth()- Get server health status
Built-in Endpoints
GET /health- Health check endpointGET /status- Server status with metrics
BunLog Class
Constructor
new BunLog({
disable: boolean // Set to true to disable logging
})Methods
log(message, ...args)- Log message (only if enabled)
RegisterAPI Configuration
API Specification Object
{
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
url: string, // API endpoint URL
headers?: Record<string, string>, // HTTP headers
queryParams?: Record<string, string>, // Query parameters
body?: Record<string, any>, // Request body (POST/PUT/PATCH)
timeout?: number, // Request timeout in ms
retries?: number // Number of retry attempts
}Template Variables
{{paramName}}- Inject input parameter{{$now}}- Current ISO timestamp{{$uuid}}- Generate UUID{{$timestamp}}- Unix timestamp{{$env.VAR_NAME}}- Environment variable
Analytics Collector
Methods
trackTool(eventType, data)- Track tool eventstrackEvent(data)- Track custom eventsflush()- Force send pending analyticsenable()- Enable analytics collectiondisable()- Disable analytics collection
Configuration
Environment Variables
MCPAAS_APP_ID=your-app-id
MCPAAS_API_KEY=your-api-key
MCPAAS_ANALYTICS_ENDPOINT=https://analytics.mcpaas.com/v1
MCPAAS_ANALYTICS_BATCH_SIZE=50
MCPAAS_ANALYTICS_FLUSH_INTERVAL=30000Analytics Configuration
// Configure analytics behavior
const analytics = server.analyticsCollector;
analytics.configure({
batchSize: 100, // Events per batch
flushInterval: 60000, // Flush every 60 seconds
endpoint: 'custom-url', // Custom analytics endpoint
enabled: true // Enable/disable analytics
});TypeScript Types
All types are fully exported for use in your applications:
import {
MCPServer,
ToolConfig,
ResourceConfig,
PromptConfig,
MCPAnalyticsCollector,
ToolExecutionMetrics,
PerformanceMetrics,
// ... and more
} from '@mcpaas/sdk';Migration from Official MCP SDK
Migrating is simple - just replace imports:
// Before (official SDK)
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
// After (MCPaaS SDK)
import { MCPServer as Server } from '@mcpaas/sdk';
// Everything else works the same, with added analytics!Examples & Demos
- Basic Usage:
examples/basic-server.ts - Analytics Demo:
examples/analytics-demo.ts - Database Integration:
examples/database-server.ts - File System:
examples/filesystem-server.ts - API Wrapper:
examples/api-wrapper.tsmcp login
Set API key directly
mcp config set-key YOUR_API_KEY
Check authentication status
mcp auth status
### Project Management
```bash
# List projects
mcp projects list
# Create new project
mcp projects create my-project --framework typescript
# Get project details
mcp projects show my-project
# Delete project
mcp projects delete my-projectDeployments
# Deploy current directory
## 💡 Best Practices
### 🔧 Development Tips
```typescript
// ✅ DO: Use environment variables for configuration
const server = new BunMCP({
name: process.env.SERVER_NAME || 'my-server',
version: process.env.VERSION || '1.0.0'
}, process.env.MCPAAS_APP_ID!, process.env.MCPAAS_API_KEY!);
// ✅ DO: Add proper error handling
server.registerTool('safe-calculator', {
title: 'Safe Calculator',
inputSchema: {
expression: z.string().regex(/^[\d+\-*/\s()]+$/, 'Invalid expression')
}
}, async ({ expression }) => {
try {
// Use a safe eval library instead of eval()
const result = safeEval(expression);
return { content: [{ type: 'text', text: `Result: ${result}` }] };
} catch (error) {
throw new Error(`Calculation failed: ${error.message}`);
}
});
// ✅ DO: Use descriptive input schemas
const goodSchema = {
email: z.string().email().describe('User email address'),
age: z.number().min(0).max(150).describe('User age in years'),
role: z.enum(['admin', 'user']).describe('User role level')
};
// ❌ DON'T: Use vague schemas
const badSchema = {
data: z.string(),
value: z.number()
};🚀 Performance Tips
// ✅ DO: Use BunLog for conditional logging
const logger = new BunLog({
disable: process.env.NODE_ENV === 'production'
});
// ✅ DO: Batch API calls when possible
server.registerAPI('batch-users', {
title: 'Get Multiple Users',
inputSchema: {
userIds: z.array(z.string()).max(50, 'Max 50 users per request')
}
}, {
method: 'POST',
url: 'https://api.example.com/users/batch',
body: { ids: '{{userIds}}' }
});
// ✅ DO: Set reasonable timeouts
server.registerAPI('external-service', config, {
method: 'GET',
url: 'https://slow-api.com/data',
timeout: 5000, // 5 seconds
retries: 3
});🛡️ Security Best Practices
// ✅ DO: Validate all inputs
server.registerTool('file-reader', {
inputSchema: {
filename: z.string()
.regex(/^[a-zA-Z0-9._-]+$/, 'Invalid filename')
.max(100, 'Filename too long')
}
}, async ({ filename }) => {
// Prevent path traversal
if (filename.includes('..') || filename.includes('/')) {
throw new Error('Invalid filename');
}
// Continue with safe file operations...
});
// ✅ DO: Use environment variables for secrets
const apiConfig = {
method: 'GET',
url: 'https://api.service.com/data',
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN}`,
'X-API-Key': process.env.API_KEY
}
};
// ❌ DON'T: Hardcode secrets
const badConfig = {
headers: {
'Authorization': 'Bearer sk-1234567890abcdef' // Never do this!
}
};🐛 Troubleshooting
Common Issues
1. "MCPAAS_API_BASE_URL is undefined"
# Solution: Set environment variables
echo "MCPAAS_API_BASE_URL=https://api.mcpaas.dev" >> .env
echo "MCPAAS_API_KEY=your-api-key" >> .env
# Or export them
export MCPAAS_API_BASE_URL="https://api.mcpaas.dev"
export MCPAAS_API_KEY="your-api-key"2. "Cannot connect to transport"
// Check your server configuration
const server = new BunMCP({
name: 'test-server',
version: '1.0.0',
capabilities: {
tools: true, // ← Make sure this is set
resources: true,
prompts: true
}
}, appId, apiKey);
// Wait for server to be ready
await server.start();
console.log('✅ Server ready');3. "Tool execution failed"
// Add detailed error logging
server.registerTool('debug-tool', config, async (args) => {
try {
console.log('📥 Input:', args);
const result = await processData(args);
console.log('📤 Output:', result);
return result;
} catch (error) {
console.error('❌ Tool error:', error);
throw new Error(`Processing failed: ${error.message}`);
}
});4. "External API calls timing out"
// Increase timeout and add retries
server.registerAPI('slow-api', config, {
method: 'GET',
url: 'https://slow-service.com/api',
timeout: 30000, // 30 seconds
retries: 5, // Retry 5 times
headers: {
'Connection': 'keep-alive'
}
});Debug Mode
// Enable debug logging
process.env.DEBUG = 'mcpaas:*';
// Or use BunLog for custom debugging
const debugLogger = new BunLog({ disable: false });
debugLogger.log('🔍 Debug info:', { server: server.getStats() });Health Checking
// Check server health
const stats = server.getStats();
console.log('📊 Server Status:', {
connected: stats.isConnected,
tools: stats.toolsCount,
resources: stats.resourcesCount,
uptime: process.uptime()
});
// For BunExpress servers
const health = server.health();
console.log('🏥 Health Check:', health);Performance Monitoring
// Monitor tool performance
server.registerTool('monitored-tool', config, async (args) => {
const startTime = Date.now();
try {
const result = await heavyOperation(args);
const duration = Date.now() - startTime;
if (duration > 5000) {
console.warn(`⚠️ Slow tool execution: ${duration}ms`);
}
return result;
} catch (error) {
console.error(`❌ Tool failed after ${Date.now() - startTime}ms`);
throw error;
}
});📞 Getting Help
Quick Help
| Issue Type | Where to Look |
|---|---|
| 🐛 Bugs | GitHub Issues |
| � Documentation | docs.mcpaas.com |
| 💬 Questions | Discord Community |
| � Support | support@mcpaas.com |
Before Asking for Help
- ✅ Check this README
- ✅ Look at the examples
- ✅ Search existing issues
- ✅ Try the troubleshooting steps above
Creating a Good Issue Report
## � Bug Report
**Environment:**
- SDK Version: 0.1.2
- Node/Bun Version: Node 18.17.0
- OS: macOS 14.0
**What happened:**
Clear description of the issue
**Expected behavior:**
What you expected to happen
**Code to reproduce:**
```typescript
// Minimal code that reproduces the issueError logs:
Paste any error messages here
## License
MIT License - see [LICENSE](./LICENSE) file for details.
---
**Made with ❤️ by the MCPaaS team**
[](https://www.npmjs.com/package/@mcpweb-org/sdk)
[](https://github.com/mcpaas/sdk)
[](https://discord.gg/mcpaas)