MCP Client logo

MCP Client

by 1999AZZAR

A TypeScript client for interacting with MCP (Model Context Protocol) servers. It includes specialized clients for Wikipedia, Dictionary, Google Search, and LRU Caching services.

View on GitHub

Last updated: N/A

MCP Client

A TypeScript client for interacting with MCP (Model Context Protocol) servers, including specialized clients for Wikipedia, Dictionary, Google Search, and LRU Caching services.

Features

  • TypeScript support with full type definitions
  • Support for JSON-RPC 2.0 protocol
  • Batch request support
  • Configurable timeouts and headers
  • Comprehensive error handling
  • Specialized clients for different MCP services
  • Promise-based API

Installation

npm install @your-org/mcp-client
# or
yarn add @your-org/mcp-client

Basic Usage

MCP Client

The base MCP client provides a simple interface for making JSON-RPC requests:

import { MCPClient } from '@your-org/mcp-client';

// Create a new client instance
const client = new MCPClient({
  url: 'http://localhost:3000', // Your MCP server URL
  timeout: 30000, // Optional, defaults to 30000ms
  headers: {
    // Optional headers
    'X-Custom-Header': 'value'
  }
});

// Make a request
async function fetchData() {
  try {
    const result = await client.request('methodName', { param1: 'value1' });
    console.log('Result:', result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Make batch requests
async function fetchBatchData() {
  try {
    const results = await client.batchRequest([
      { method: 'method1', params: { param1: 'value1' } },
      { method: 'method2', params: { param2: 'value2' } },
    ]);
    console.log('Results:', results);
  } catch (error) {
    console.error('Error:', error);
  }
}

Specialized Clients

Wikipedia Client

import { WikipediaClient } from '@your-org/mcp-client';

const wikiClient = new WikipediaClient({
  url: 'http://wikipedia-mcp-server:3000',
});

// Search Wikipedia
const searchResults = await wikiClient.search('TypeScript');

// Get a specific page
const page = await wikiClient.getPage('TypeScript');

// Get page by ID
const pageById = await wikiClient.getPageById(12345);

Dictionary Client

import { DictionaryClient } from '@your-org/mcp-client';

const dictClient = new DictionaryClient({
  url: 'http://dictionary-mcp-server:3000',
});

// Look up a word
const definitions = await dictClient.lookup('serendipity');

// Get synonyms
const synonyms = await dictClient.getSynonyms('happy');

// Get antonyms
const antonyms = await dictClient.getAntonyms('happy');

Google Search Client

import { GoogleSearchClient } from '@your-org/mcp-client';

const searchClient = new GoogleSearchClient({
  url: 'http://google-search-mcp-server:3000',
});

// Web search
const webResults = await searchClient.search('latest TypeScript features', {
  numResults: 5,
  country: 'US',
  language: 'en'
});

// Image search
const imageResults = await searchClient.searchImages('cute puppies');

// News search
const newsResults = await searchClient.searchNews('technology');

LRU Cache Client

import { LRUCacheClient } from '@your-org/mcp-client';

const cacheClient = new LRUCacheClient({
  url: 'http://lru-cache-mcp-server:3000',
});

// Set a value with TTL (in milliseconds)
await cacheClient.set('user:123', { name: 'John', age: 30 }, { ttl: 3600000 });

// Get a value
const user = await cacheClient.get('user:123');

// Check if key exists
const hasKey = await cacheClient.has('user:123');

// Delete a key
await cacheClient.delete('user:123');

// Get cache size
const size = await cacheClient.size();

// Get all keys
const keys = await cacheClient.keys();

// Clear the cache
await cacheClient.clear();

Error Handling

All client methods return Promises that reject with an error if the request fails. The error object contains detailed information about what went wrong:

try {
  const result = await client.request('someMethod', { param: 'value' });
} catch (error) {
  if (error.isAxiosError) {
    // Network or HTTP error
    console.error('Request failed:', error.message);
    if (error.response) {
      console.error('Status:', error.response.status);
      console.error('Data:', error.response.data);
    }
  } else {
    // MCP protocol error
    console.error('MCP Error:', error.message);
    if (error.code) {
      console.error('Error code:', error.code);
    }
  }
}

API Reference

MCPClient

new MCPClient(options: MCPClientOptions)

Creates a new MCP client instance.

Options:

  • url: The URL of the MCP server (required)
  • timeout: Request timeout in milliseconds (default: 30000)
  • headers: Additional headers to include in requests
Methods
  • request<T = any>(method: string, params?: Record<string, any>): Promise<T>

    • Makes a JSON-RPC request to the server
    • Returns a Promise that resolves with the result
  • batchRequest<T = any>(requests: Array<{ method: string; params: Record<string, any> }>): Promise<T[]>

    • Makes multiple JSON-RPC requests in a single batch
    • Returns a Promise that resolves with an array of results

Development

  1. Clone the repository
  2. Install dependencies: npm install
  3. Build the project: npm run build
  4. Run tests: npm test

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

MIT The client throws errors for:

  • Network issues
  • HTTP errors
  • MCP protocol errors (error responses from the server)

API

new MCPClient(options: MCPClientOptions)

Creates a new MCP client instance.

Options
  • url: The URL of the MCP server (required)
  • timeout: Request timeout in milliseconds (default: 30000)
  • headers: Additional headers to include in requests

client.request<T>(method: string, params?: Record<string, any>): Promise<T>

Makes a request to the MCP server.

client.batchRequest<T>(requests: Array<{ method: string; params: Record<string, any> }>): Promise<T[]>

Makes a batch request to the MCP server.

Development

  1. Clone the repository
  2. Install dependencies: npm install
  3. Build the project: npm run build
  4. Run tests: npm test

License

MIT