Content
## Project Introduction
MCP Client is a Node.js client implementation based on the Model Context Protocol (using Function Calling). It allows your application to connect to various MCP servers and interact with these servers through Large Language Models (LLMs). MCP (Model Context Protocol) is an open protocol that standardizes how applications provide context to LLMs.

## Core Features
- Supports connecting to any MCP-compliant server
- Supports LLM capabilities compatible with OpenAI API format
- Automatically discovers and uses tools provided by servers
- Comprehensive logging system, including API requests and tool calls
- Interactive command-line interface
- Supports tool calling and result processing
## System Requirements
- Node.js 17 or higher
- LLM API key (Ollama not currently supported)
- Disk space for 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 file and set your LLM API key:
```bash
cp .env.example .env
```
Then edit the `.env` file to include 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 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 Configuration File
```bash
node build/index.js <server identifier> <config file path>
```
Where `<server identifier>` is the server name defined in the configuration file, and `<config file path>` is the path to the JSON file containing server definitions.
```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 via npx without cloning and building locally:
```bash
# Connect to script directly
$ npx mcp-client-nodejs /path/to/mcp-server.js
# Connect via config file
$ npx mcp-client-nodejs mongodb ./mcp-servers.json
```
> Note: You need to configure model-related information in the .env file in the current working directory
### Examples
Connect to JavaScript MCP server directly:
```bash
node build/index.js /path/to/weather-server/build/index.js
```
Connect to Python MCP server directly:
```bash
node build/index.js /path/to/mcp-server.py
```
Connect to server via configuration file:
```bash
node build/index.js mongodb ./mcp-servers.json
```
Run using npx:
```bash
# Connect to script directly
$ npx mcp-client-nodejs /path/to/mcp-server.js
# Connect via config file
$ npx mcp-client-nodejs mongodb./mcp-servers.json
```

## How It Works

1. **Server Connection**: The client connects to the specified MCP server
2. **Tool Discovery**: Automatically retrieves the list of available tools provided by the server
3. **Query Processing**:
- Send user query to LLM
- LLM decides if tools need to be used
- If needed, the client executes tool calls through the server
- Return tool results to LLM
- LLM provides final response
4. **Interactive Loop**: Users can continuously input queries until typing "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 querying 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 consistently named `[index] [log_type] YYYY-MM-DD HH:MM:SS.json`, containing sequence number, log type, and timestamp for easy chronological viewing of the entire session.
## Architecture Design

MCP Client is based on a modular client-server architecture:
- **Transport Layer**: Uses Stdio transport mechanism to communicate with the server
- **Protocol Layer**: Uses MCP protocol for request/response and tool calling
- **Model Layer**: Provides LLM capabilities through OpenAI SDK
### Core Components
- **MCPClient Class**: Manages server connections, query processing, and tool calls
- **Client Object**: The client implementation provided by MCP SDK
- **StdioClientTransport**: Standard input/output-based transport implementation
## Best Practices
- **Error Handling**: Use TypeScript type system for better error detection
- **Security**: Securely store API keys in .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 don't work, use absolute paths
- Windows users should ensure forward slashes (/) or escaped backslashes (\\) are used in paths
- Verify the server file has the correct extension (.js or .py)
### Response Time
- The first response may take up to 30 seconds
- This is normal, occurring 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 succeeded
- `Connection refused`: Ensure the server is running and the path is correct
- `Tool execution failed`: Verify 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.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.
Filesystem
Node.js MCP Server for filesystem operations with dynamic access control.