Client API
Complete API reference for RouterMCPClient and RouterMCPSession.
Client API
The TypeScript SDK provides two main classes: RouterMCPClient for single-user scenarios and RouterMCPSession for multi-user applications.
RouterMCPClient
Constructor
import { RouterMCPClient } from '@routermcp/sdk';
const client = new RouterMCPClient({
url: string; // Required: RouterMCP server URL
apiKey?: string; // API key for authentication
userId?: string; // User ID for OAuth token storage
timeout?: number; // Request timeout in ms (default: 30000)
headers?: Record<string, string>; // Custom HTTP headers
oauth?: OAuthConfig; // OAuth adapter configuration
debug?: boolean; // Enable debug logging
});connect()
Initialize the connection and perform MCP handshake.
const capabilities = await client.connect();
// Returns: InitializeResult with server capabilitiesdisconnect()
Close the connection and clean up resources.
await client.disconnect();listTools()
List all available tools from aggregated MCP servers.
const tools = await client.listTools();
for (const tool of tools) {
console.log(`${tool.name}: ${tool.description}`);
console.log('Input schema:', tool.inputSchema);
}Returns: Tool[]
interface Tool {
name: string;
description?: string;
inputSchema: {
type: 'object';
properties: Record<string, unknown>;
required?: string[];
};
}callTool()
Execute a tool with the given arguments.
const result = await client.callTool('tool_name', {
arg1: 'value1',
arg2: 123,
});
// Access result content
for (const item of result.content) {
if (item.type === 'text') {
console.log(item.text);
}
}Returns: ToolResult
interface ToolResult {
content: Array<{ type: string; text?: string; [key: string]: unknown }>;
isError: boolean;
}callToolTyped()
Execute a tool and parse the result with a Zod schema.
import { z } from 'zod';
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
});
const user = await client.callToolTyped('get_user', { id: '123' }, UserSchema);
// user is typed as { id: string, name: string, email: string }listResources()
List available resources.
const resources = await client.listResources();
for (const resource of resources) {
console.log(`${resource.uri}: ${resource.name}`);
}readResource()
Read a resource by URI.
const content = await client.readResource('file:///path/to/file.txt');listPrompts()
List available prompts.
const prompts = await client.listPrompts();
for (const prompt of prompts) {
console.log(`${prompt.name}: ${prompt.description}`);
}getPrompt()
Get a prompt with arguments.
const result = await client.getPrompt('summarize', {
text: 'Long text to summarize...',
});createSession()
Create a new session for a different user.
const session = client.createSession({ userId: 'user-456' });
await session.connect();
// Use session for user-456's requests
await session.disconnect();RouterMCPSession
Sessions are created via client.createSession() and provide the same API as the client but with a different user context.
const client = new RouterMCPClient({
url: 'https://gateway.routermcp.com/v1/mcp/my-project',
userId: 'admin',
oauth: { adapter: cloudAdapter({ apiKey: 'key' }) },
});
await client.connect();
// Create sessions for different users
const user1Session = client.createSession({ userId: 'user-1' });
const user2Session = client.createSession({ userId: 'user-2' });
await user1Session.connect();
await user2Session.connect();
// Each session uses its own OAuth tokens
await user1Session.callTool('gmail_send', { to: 'a@example.com', body: 'Hi' });
await user2Session.callTool('gmail_send', { to: 'b@example.com', body: 'Hello' });
await user1Session.disconnect();
await user2Session.disconnect();
await client.disconnect();Session Methods
Sessions support the same methods as the client:
connect()/disconnect()listTools()/callTool()/callToolTyped()listResources()/readResource()listPrompts()/getPrompt()
Sessions share the transport configuration with the parent client but maintain separate MCP sessions and OAuth token contexts.
Error Handling
import { MCPError, TransportError, ConfigError } from '@routermcp/sdk';
try {
await client.callTool('unknown_tool', {});
} catch (error) {
if (error instanceof TransportError) {
console.error('Network error:', error.message, error.code);
} else if (error instanceof MCPError) {
console.error('MCP error:', error.message);
} else {
throw error;
}
}Error Types
| Error | Description |
|---|---|
MCPError | Base error for all MCP operations |
TransportError | HTTP or network-level errors |
ConfigError | Configuration validation errors |
OAuthError | OAuth flow or token errors |