A reference implementation for connecting to MCP (Model Context Protocol) servers.
This is a companion to mcp-rag-server, demonstrating client-side MCP integration.
You want to connect to MCP servers but:
- SDK documentation is sparse — the protocol is new, examples are few
- Transport handling is complex — stdio vs SSE, connection lifecycle
- Tool discovery needs patterns — listing, calling, handling responses
- Error handling varies — different servers, different behaviors
MCP Client Example provides:
- Clean client wrapper — connect, discover, invoke in a few lines
- Multiple transports — stdio (subprocess) and SSE (HTTP) support
- Type-safe API — full TypeScript definitions
- Working examples — basic usage, RAG integration, interactive CLI
import { MCPClient } from '@danmonteiro/mcp-client-example';
const client = new MCPClient({
command: 'node',
args: ['./mcp-server/dist/index.js'],
});
await client.connect();
const tools = await client.listTools();
const result = await client.callTool('rag_query', { query: 'How does auth work?' });
await client.disconnect();npm install @danmonteiro/mcp-client-exampleimport { MCPClient } from '@danmonteiro/mcp-client-example';
// Stdio transport (spawn a subprocess)
const client = new MCPClient({
command: 'npx',
args: ['-y', '@anthropic/mcp-server-example'],
debug: true,
});
// OR SSE transport (connect to HTTP endpoint)
const sseClient = new MCPClient({
sseUrl: 'http://localhost:3000/mcp',
debug: true,
});
await client.connect();// List available tools
const tools = await client.listTools();
console.log(tools);
// [{ name: 'rag_query', description: '...', inputSchema: {...} }, ...]
// Call a tool
const result = await client.callTool('rag_query', {
query: 'What is the architecture?',
topK: 5,
});
console.log(result.content);
// [{ type: 'text', text: '{"answer": "...", "sources": [...]}' }]await client.disconnect();class MCPClient {
constructor(config: MCPClientConfig);
// Connection
connect(): Promise<ServerCapabilities>;
disconnect(): Promise<void>;
isConnected(): boolean;
getTransportType(): 'stdio' | 'sse';
// Tools
listTools(): Promise<MCPTool[]>;
callTool(name: string, args?: Record<string, unknown>): Promise<ToolCallResult>;
// Resources
listResources(): Promise<MCPResource[]>;
readResource(uri: string): Promise<string>;
// Prompts
listPrompts(): Promise<MCPPrompt[]>;
getPrompt(name: string, args?: Record<string, string>): Promise<PromptResult>;
}interface MCPClientConfig {
// Stdio transport (spawn subprocess)
command?: string;
args?: string[];
env?: Record<string, string>;
// SSE transport (HTTP connection)
sseUrl?: string;
// Options
timeout?: number; // Connection timeout (default: 30000ms)
debug?: boolean; // Enable debug logging
}npx tsx examples/basic-usage.tsConnects to an MCP server, lists tools, and demonstrates invocation.
# Set up mcp-rag-server first
export CHROMA_URL=http://localhost:8000
export OPENAI_API_KEY=sk-...
npx tsx examples/rag-server.tsShows how to connect to mcp-rag-server for RAG queries.
npx tsx examples/interactive-cli.ts node ./path/to/server.jsA REPL for exploring any MCP server interactively.
const client = new MCPClient({
command: 'node',
args: ['./mcp-rag-server/dist/index.js'],
env: {
CHROMA_URL: 'http://localhost:8000',
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
},
});
await client.connect();
// Query the RAG system
const result = await client.callTool('rag_query', {
query: 'How does the authentication system work?',
topK: 5,
threshold: 0.7,
});
const data = JSON.parse(result.content[0].text);
console.log(data.answer);
console.log(`Sources: ${data.sources.length}`);Configure in claude_desktop_config.json:
{
"mcpServers": {
"my-rag": {
"command": "node",
"args": ["./mcp-rag-server/dist/index.js"],
"env": {
"CHROMA_URL": "http://localhost:8000"
}
}
}
}Then use this client to test the same server programmatically.
mcp-client-example/
├── src/
│ ├── index.ts # Exports
│ ├── client.ts # MCPClient implementation
│ └── types.ts # Type definitions
├── examples/
│ ├── basic-usage.ts # Basic connection example
│ ├── rag-server.ts # RAG server integration
│ └── interactive-cli.ts # Interactive REPL
├── package.json
└── README.md
This repo demonstrates programmatic access to context continuity services — connecting custom applications to MCP-based memory systems.
| Layer | Role | This Repo |
|---|---|---|
| Intra-session | Short-term memory | — |
| Document-scoped | Injected content | — |
| Retrieved | Connect to semantic memory via MCP | mcp-client-example |
| Progressive | Staged responses | — |
While Claude Code and Claude Desktop have built-in MCP support, this client enables custom applications to access the same context continuity capabilities — RAG queries, document indexing, and knowledge base search.
Related repos:
- mcp-rag-server — The MCP server this client connects to
- rag-pipeline — The RAG backend powering the server
- chatbot-widget — Session cache, Research Mode, conversation export
- ai-orchestrator — Multi-model routing for AI responses
Contributions welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feat/new-feature) - Make changes with semantic commits
- Open a PR with clear description
MIT License - see LICENSE for details.
Built with Claude Code.
Co-Authored-By: Claude <noreply@anthropic.com>