Skip to main content

Client SDK Reference

This document provides a comprehensive reference for the MCP Client SDK, which simplifies communication with MCP servers in your applications.

Overview

The MCP Client SDK is a JavaScript/TypeScript library that provides a convenient interface for interacting with MCP servers. It abstracts away the details of the protocol, handling authentication, request formatting, and response parsing.

Installation

npm / yarn

# Using npm
npm install @trmx/client

# Using yarn
yarn add @trmx/client

Basic Usage

Importing the SDK

// ESM
import { MCPClient } from '@trmx/client';

// CommonJS
const { MCPClient } = require('@trmx/client');

Creating a Client

const client = new MCPClient({
serverUrl: 'https://your-mcp-server.trmx.ai',
apiKey: 'your-api-key', // Optional, depending on server configuration
});

Sending a Message

async function main() {
try {
// Create a conversation
const conversation = client.createConversation({
contextId: 'user-123', // Unique identifier for this conversation
});

// Send a message
const response = await conversation.sendMessage('Hello, what can you help me with today?');

console.log('AI response:', response.content);

// Continue the conversation
const followUpResponse = await conversation.sendMessage('Tell me more about that');

console.log('Follow-up response:', followUpResponse.content);
} catch (error) {
console.error('Error:', error);
}
}

main();

Client Configuration

The MCPClient constructor accepts a configuration object with these options:

const client = new MCPClient({
// Required
serverUrl: 'https://your-mcp-server.trmx.ai',

// Authentication (choose one)
apiKey: 'your-api-key',
auth: {
type: 'oauth',
token: 'your-oauth-token',
},

// Optional settings
timeout: 30000, // Request timeout in milliseconds (default: 30000)
retry: {
maxRetries: 3, // Maximum number of retries (default: 3)
initialDelay: 1000, // Initial retry delay in milliseconds (default: 1000)
maxDelay: 5000, // Maximum retry delay in milliseconds (default: 5000)
},
headers: {
'User-Agent': 'MyApp/1.0.0',
'X-Custom-Header': 'custom-value',
},
fetch: customFetchFunction, // Custom fetch implementation
});

Conversations

Creating a Conversation

const conversation = client.createConversation({
contextId: 'user-123-conversation-456', // Unique identifier for this conversation
systemPrompt: 'You are a helpful assistant that provides accurate and concise information.', // Optional
streaming: false, // Whether to use streaming responses (default: false)
metadata: { // Optional metadata
userId: 'user-123',
sessionId: 'session-789',
timezone: 'America/Los_Angeles',
},
});

Sending Messages

// Send a simple text message
const response = await conversation.sendMessage('What is the capital of France?');

// Send a message with attachments
const responseWithAttachment = await conversation.sendMessage({
content: 'What can you tell me about this image?',
attachments: [
{
type: 'image',
mimeType: 'image/jpeg',
data: base64EncodedImage, // Base64-encoded image data
// Alternatively, you can provide a URL
// url: 'https://example.com/image.jpg',
},
],
});

// Send a message with specific options
const responseWithOptions = await conversation.sendMessage('Generate a story about space', {
temperature: 0.7, // Control randomness (0-1)
maxTokens: 500, // Maximum tokens in response
tools: ['calculator', 'weather'], // Restrict available tools for this message
});

Streaming Responses

// Create a streaming conversation
const streamingConversation = client.createConversation({
contextId: 'user-456',
streaming: true, // Enable streaming
});

// Send a message with streaming response
const stream = await streamingConversation.sendMessage('Write a short story about space travel');

// Handle streaming chunks
stream.on('data', (chunk) => {
process.stdout.write(chunk.content);
});

stream.on('end', () => {
console.log('\n\nStream complete!');
});

stream.on('error', (error) => {
console.error('Stream error:', error);
});

Managing Conversation Context

// Get conversation context
const context = await conversation.getContext();
console.log('Conversation history:', context.messages);

// Reset conversation context
await conversation.resetContext({
systemPrompt: 'New system prompt for reset conversation',
});

// Delete conversation context
await conversation.deleteContext();

Tools

Listing Available Tools

// List all available tools
const tools = await client.tools.list();
console.log('Available tools:', tools);

// Check if a specific tool is available
const hasCalculator = tools.some(tool => tool.name === 'calculator');

Calling Tools Directly

// Call a tool directly
const calculationResult = await client.tools.call({
name: 'calculator',
arguments: {
operation: 'multiply',
a: 5,
b: 3,
},
});

console.log('Calculation result:', calculationResult.result);

Resources

Listing Available Resources

// List all available resources
const resources = await client.resources.list();
console.log('Available resources:', resources);

Querying Resources

// Query a resource
const knowledgeBaseResults = await client.resources.query({
name: 'knowledge_base',
query: 'password reset',
limit: 5,
});

console.log('Knowledge base results:', knowledgeBaseResults.items);

Error Handling

The SDK provides detailed error information for better debugging:

try {
const response = await conversation.sendMessage('Hello');
} catch (error) {
if (error instanceof MCPError) {
console.error(`MCP Error (${error.code}): ${error.message}`);
if (error.data) {
console.error('Error details:', error.data);
}
} else {
console.error('Network or other error:', error);
}
}

Common Error Codes

CodeDescription
UNAUTHORIZEDAuthentication failed or not provided
FORBIDDENYou don't have permission to access this resource
NOT_FOUNDThe requested resource was not found
CONTEXT_NOT_FOUNDThe specified conversation context was not found
TOOL_NOT_FOUNDThe specified tool was not found
RESOURCE_NOT_FOUNDThe specified resource was not found
RATE_LIMIT_EXCEEDEDYou've exceeded the rate limit
INVALID_REQUESTThe request was invalid or malformed
INTERNAL_ERRORAn internal server error occurred

Advanced Usage

Request Interceptors

client.interceptors.request.use((config) => {
// Modify request config before it's sent
config.headers['X-Request-ID'] = generateRequestId();
return config;
});

Response Interceptors

client.interceptors.response.use(
(response) => {
// Process successful responses
console.log(`Request completed in ${response.timings.total}ms`);
return response;
},
(error) => {
// Process errors
console.error('Request failed:', error);
return Promise.reject(error);
}
);

Custom Authentication

// Custom authentication handler
client.setAuthHandler(async (request) => {
const token = await getTokenFromAuthService();
request.headers['Authorization'] = `Bearer ${token}`;
return request;
});

Middleware Support

// Add middleware
client.use(async (ctx, next) => {
const startTime = Date.now();
await next();
const duration = Date.now() - startTime;
console.log(`Request to ${ctx.request.url} took ${duration}ms`);
});

TypeScript Support

The SDK provides full TypeScript support for better developer experience:

import { MCPClient, Conversation, MessageResponse, StreamResponse } from '@trmx/client';

// Client configuration type
interface ClientConfig {
serverUrl: string;
apiKey?: string;
auth?: {
type: 'oauth' | 'jwt' | 'custom';
token: string;
};
timeout?: number;
retry?: {
maxRetries?: number;
initialDelay?: number;
maxDelay?: number;
};
headers?: Record<string, string>;
}

// Create typed client
const client: MCPClient = new MCPClient({
serverUrl: 'https://your-mcp-server.trmx.ai',
apiKey: 'your-api-key',
});

// Create typed conversation
const conversation: Conversation = client.createConversation({
contextId: 'user-123',
});

// Get typed response
async function getResponse(): Promise<MessageResponse> {
return await conversation.sendMessage('Hello');
}

Browser Support

The SDK works in modern browsers, Node.js, and React Native environments. For older browsers, you may need polyfills for fetch and EventSource.

<!-- Include from CDN -->
<script src="https://cdn.jsdelivr.net/npm/@trmx/client@1.0.0/dist/mcp-client.min.js"></script>

<script>
// Access global MCPClient
const client = new MCPClient({
serverUrl: 'https://your-mcp-server.trmx.ai',
apiKey: 'your-api-key',
});

// Use client as normal
async function sendMessage() {
const conversation = client.createConversation({
contextId: 'browser-user-123',
});

const response = await conversation.sendMessage('Hello from browser!');
document.getElementById('response').textContent = response.content;
}
</script>

Next Steps