Content
## Project Introduction
MCP Client is a Node.js client implementation based on the Model Context Protocol (MCP) that allows your application to connect to various MCP servers and interact with them through large language models (LLMs). MCP (Model Context Protocol) is an open protocol for standardizing how applications provide context to LLMs.

## Core Features
- Supports connecting to any MCP-compliant server
- Supports LLM capabilities compatible with the OpenAI API format
- Automatic discovery and use of tools provided by the server
- Comprehensive logging system, including API requests and tool calls
- Interactive command-line interface
- Supports tool calls and result processing
## System Requirements
- Node.js 17 or higher
- LLM API key (Ollama is not supported yet)
- Disk space for storing log files (located in the `logs/` directory)
## Installation
### 1. Clone the Repository
```bash
git clone https://github.com/ConardLi/mcp-client-nodejs.git
cd mcp-client-nodejs
```
### 2. Install Dependencies
```bash
npm install
```
Required dependencies:
- @modelcontextprotocol/sdk
- openai
- dotenv
- typescript (dev dependency)
- @types/node (dev dependency)
### 3. Configure Environment Variables
Copy the example environment variables file and set your LLM API key:
```bash
cp .env.example .env
```
Then edit the `.env` file to fill in your LLM API key, model provider API address, and model name:
```
OPENAI_API_KEY=your_api_key_here
MODEL_NAME=xxx
BASE_URL=xxx
```
### 4. Build the Project
```bash
npm run build
```
## Usage
To start the MCP client, you can use the following methods:
### 1. Directly Specify the Server Script Path
```bash
node build/index.js <server script path>
```
Where `<server script path>` is the path to the MCP server script, which can be a JavaScript (.js) or Python (.py) file.
### 2. Use a Configuration File
```bash
node build/index.js <server identifier> <configuration file path>
```
Where `<server identifier>` is the server name defined in the configuration file, and `<configuration file path>` is the path to the JSON file containing the server definition.
```json
{
"mcpServers": {
"time": {
"command": "node",
"args": [
"/Users/xxx/mcp/dist/index.js"
],
"description": "Custom Node.js MCP server"
},
"mongodb": {
"command": "npx",
"args": [
"mcp-mongo-server",
"mongodb://localhost:27017/studentManagement?authSource=admin"
]
}
},
"defaultServer": "mongodb",
"system": "Custom system prompt"
}
```
### 3. Use npm Package (npx)
You can run this package directly through npx without cloning and building locally:
```bash
# Directly connect to the script
$ npx mcp-client-nodejs /path/to/mcp-server.js
# Connect through configuration file
$ npx mcp-client-nodejs mongodb ./mcp-servers.json
```
> Note: You need to configure model-related information in the `.env` file in the current running directory.
### Example
Directly connect to a JavaScript MCP server:
```bash
node build/index.js /path/to/weather-server/build/index.js
```
Directly connect to a Python MCP server:
```bash
node build/index.js /path/to/mcp-server.py
```
Connect to a server using a configuration file:
```bash
node build/index.js mongodb ./mcp-servers.json
```
Run using npx:
```bash
# Directly connect to the script
$ npx mcp-client-nodejs /path/to/mcp-server.js
# Connect through configuration file
$ npx mcp-client-nodejs mongodb./mcp-servers.json
```

## Working Principle

1. **Server Connection**: The client connects to the specified MCP server
2. **Tool Discovery**: Automatically obtains the list of available tools provided by the server
3. **Query Processing**:
- Sends user queries to the LLM
- The LLM decides whether to use tools
- If necessary, the client executes tool calls through the server
- Returns tool results to the LLM
- The LLM provides the final response
4. **Interactive Loop**: Users can continuously input queries until they type "quit" to exit
## Logging System
MCP Client includes a comprehensive logging system that records all key operations and communications in detail. Log files are saved in the `logs/` directory in JSON format for easy query and analysis.

### Log Types
- **LLM Requests and Responses** - Records all communications with the LLM API
- **Tool Calls and Results** - Records all tool call parameters and return results
- **Error Messages** - Records any errors during system operation
### Log Naming and Format
Log files are uniformly named as `[index] [log_type] YYYY-MM-DD HH:MM:SS.json`, including a serial number, log type, and timestamp, making it convenient to view the entire session in chronological order.
## Architecture Design

MCP Client is based on a modular client-server architecture:
- **Transport Layer**: Uses the Stdio transport mechanism to communicate with the server
- **Protocol Layer**: Uses the MCP protocol to handle requests/responses and tool calls
- **Model Layer**: Provides LLM capabilities through the OpenAI SDK
### Core Components
- **MCPClient Class**: Manages server connections, processes queries, and tool calls
- **Client Object**: MCP SDK-provided client implementation
- **StdioClientTransport**: Transport implementation based on standard input/output
## Best Practices
- **Error Handling**: Use TypeScript type system for better error detection
- **Security**: Store API keys securely in the `.env` file
- **Tool Permissions**: Pay attention to tool permissions and security
## Troubleshooting
### Server Path Issues
- Ensure the server script path is correct
- If relative paths do not work, use absolute paths
- Windows users ensure to use forward slashes (/) or escaped backslashes (\\) in paths
- Verify that the server file has the correct extension (.js or .py)
### Response Time
- The first response may take up to 30 seconds to return
- This is normal and occurs during server initialization, query processing, and tool execution
- Subsequent responses are usually faster
### Common Error Messages
- `Error: Cannot find module`: Check the build folder and ensure TypeScript compilation is successful
- `Connection refused`: Ensure the server is running and the path is correct
- `Tool execution failed`: Verify that the environment variables required by the tool are set
- `OPENAI_API_KEY is not set`: Check your `.env` file and environment variables
- `TypeError`: Ensure correct types are used for tool parameters
## License
Apache License 2.0
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.