Sponsored by Deepsite.site

MCP Client

Created By
1999AZZAR7 months ago
TypeScript client for interacting with MCP (Model Context Protocol) servers
Content

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

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
CursorThe AI Code Editor
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Playwright McpPlaywright MCP server
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
Serper MCP ServerA Serper MCP Server
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
Amap Maps高德地图官方 MCP Server
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
DeepChatYour AI Partner on Desktop
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
ChatWiseThe second fastest AI chatbot™
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
WindsurfThe new purpose-built IDE to harness magic
Tavily Mcp
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.