Basic Connection Guide
Learn how to establish your first MCP connection with detailed examples for different scenarios and transports.
Prerequisites
- OmniMCP installed (
npm install omnimcp
) - An MCP server to connect to
- Node.js 16+ environment
Simple Local Connection
Let`s start with the most basic connection to a local MCP server:
// basic-connection.js import { MCPClient } from '@omnimcp/client'; async function main() { // Create client instance const client = new MCPClient('my-first-app', '1.0.0'); try { // Connect to local server await client.connect({ type: 'stdio', options: { command: 'node', args: ['./my-mcp-server.js'] } }); console.log('Connected!'); console.log('Server info:', client.serverInfo); // List available tools const tools = await client.tools.list(); console.log('Available tools:', tools.map(t => t.name)); } catch (error) { console.error('Connection failed:', error.message); } finally { // Always disconnect when done await client.disconnect(); } } main();
Connecting to Different Server Types
Python MCP Server
await client.connect({ type: 'stdio', options: { command: 'python', args: ['-m', 'my_mcp_server'], env: { PYTHONUNBUFFERED: '1' // Important for stdio } } });
Binary MCP Server
await client.connect({ type: 'stdio', options: { command: './mcp-server-binary', args: ['--config', 'server.json'], cwd: '/path/to/server/directory' } });
Remote HTTP Server
await client.connect({ type: 'http', options: { url: 'https://api.example.com/mcp', headers: { 'Authorization': 'Bearer ' + process.env.API_TOKEN, 'Content-Type': 'application/json' } } });
Handling Connection Events
Monitor connection lifecycle with event handlers:
const client = new MCPClient('event-example', '1.0.0'); // Connection established client.on('connected', (serverInfo) => { console.log('Connected to:', serverInfo.name); console.log('Server version:', serverInfo.version); }); // Connection lost client.on('disconnected', (reason) => { console.log('Disconnected:', reason); }); // Errors client.on('error', (error) => { console.error('Error occurred:', error.message); }); // Connect await client.connect(config);
Connection with Retry
Implement robust connection handling with automatic retries:
import { MCPClient } from '@omnimcp/client'; import { retry } from '@omnimcp/core'; async function connectWithRetry() { const client = new MCPClient('retry-example', '1.0.0'); const connection = await retry( async () => { console.log('Attempting to connect...'); await client.connect({ type: 'stdio', options: { command: 'mcp-server', args: ['--port', '3000'] } }); return client; }, { maxAttempts: 5, initialDelay: 1000, maxDelay: 30000, backoffFactor: 2, onRetry: (attempt, error) => { console.log(`Retry attempt ${attempt} after error: ${error.message}`); } } ); return connection; }
Connection Pooling
For applications that need multiple connections:
class MCPConnectionPool { private pool: MCPClient[] = []; private available: MCPClient[] = []; constructor( private size: number, private config: TransportConfig ) {} async initialize() { for (let i = 0; i < this.size; i++) { const client = new MCPClient(`pool-client-${i}`, '1.0.0'); await client.connect(this.config); this.pool.push(client); this.available.push(client); } } async acquire(): Promise<MCPClient> { if (this.available.length === 0) { // Wait for available connection await new Promise(resolve => { const checkAvailable = setInterval(() => { if (this.available.length > 0) { clearInterval(checkAvailable); resolve(undefined); } }, 100); }); } return this.available.pop()!; } release(client: MCPClient) { this.available.push(client); } async destroy() { await Promise.all( this.pool.map(client => client.disconnect()) ); } }
Testing Your Connection
Create a simple test script to verify your connection:
// test-connection.js import { MCPClient } from '@omnimcp/client'; async function testConnection(config) { console.log('๐ Testing MCP connection...'); const client = new MCPClient('connection-test', '1.0.0'); const startTime = Date.now(); try { // Test connection await client.connect(config); console.log('โ Connection successful!'); // Test server info console.log('๐ Server info:', { name: client.serverInfo.name, version: client.serverInfo.version, capabilities: client.serverInfo.capabilities }); // Test tool listing const tools = await client.tools.list(); console.log(`๐ง Found ${tools.length} tools`); // Test simple tool call (if available) if (tools.length > 0) { const testTool = tools[0]; console.log(`๐งช Testing tool: ${testTool.name}`); try { const result = await client.tools.call({ name: testTool.name, arguments: {} }); console.log('โ Tool call successful'); } catch (error) { console.log('โ ๏ธ Tool call failed:', error.message); } } const elapsed = Date.now() - startTime; console.log(`โฑ๏ธ Total time: ${elapsed}ms`); } catch (error) { console.error('โ Connection failed:', error.message); if (error.context) { console.error('๐ Error context:', error.context); } } finally { await client.disconnect(); console.log('๐ Disconnected'); } } // Run test testConnection({ type: 'stdio', options: { command: 'mcp-server' } });
Common Issues and Solutions
Server Not Starting
If your server fails to start, check:
- Command path is correct
- Server has execute permissions
- Required dependencies are installed
- Environment variables are set
Connection Timeout
Increase timeout for slow-starting servers:
await client.connect({ type: 'stdio', options: { command: 'slow-server', connectionTimeout: 30000 // 30 seconds } });
Protocol Mismatch
Ensure client and server use compatible protocol versions:
const client = new MCPClient('my-app', '1.0.0', { protocolVersion: '2024-11-05' // Specify version explicitly });
Next Steps
- Learn about AI integration
- Explore advanced patterns
- See complete API reference