Testing an MCP (Model Context Protocol) server locally in your Node.js app involves a few steps, including setting up the server, creating mock clients, and verifying that it correctly handles requests/responses as per the MCP specification.
Here's a step-by-step guide to help you test your MCP server implementation locally:
✅ 1. Understand What You're Building
MCP is a protocol for connecting tools and models in a language model context. It defines how a client (e.g., a language model runtime) can interact with a server (e.g., a tool backend like a code interpreter or database query tool).
The main components:
- Initialization: The client and server negotiate capabilities.
- Request-response loops: Clients send
callTool requests; servers respond with results or stream updates.
🧪 2. Implement Your Server in Node.js
You'll probably be using HTTP or WebSocket transport. Let's assume HTTP for simplicity.
Example: Basic Express-based MCP Server
// mcp-server.js
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.post('/mcp', (req, res) => {
const request = req.body;
console.log('Received request:', request);
if (request.method === 'initialize') {
return res.json({
requestId: request.requestId,
method: 'initialize',
result: {
capabilities: {
supportsTools: true,
supportsStreaming: true,
},
},
});
}
if (request.method === 'callTool') {
// Simulate a simple tool response
const { toolName, arguments } = request.params;
console.log(`Calling tool: ${toolName} with args`, arguments);
return res.json({
requestId: request.requestId,
method: 'callTool',
result: {
content: `Mocked result of calling ${toolName} with ${JSON.stringify(arguments)}`,
},
});
}
res.status(400).json({ error: 'Unknown method' });
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`MCP Server running at http://localhost:${PORT}/mcp`);
});
🧪 3. Write a Local Client to Test It
Now write a small script to simulate a client that sends valid MCP requests.
Example: Testing the Server with a Simple Client
// mcp-client.js
import axios from 'axios';
const CLIENT_ID = 'test-client';
const SERVER_URL = 'http://localhost:3000/mcp';
async function sendRequest(method, params = {}) {
const requestId = Math.random().toString(36).substring(2);
const payload = {
requestId,
method,
params,
};
console.log('Sending request:', payload);
try {
const response = await axios.post(SERVER_URL, payload);
console.log('Server response:', response.data);
return response.data;
} catch (error) {
console.error('Error sending request:', error.message);
return null;
}
}
async function testMcpServer() {
// Step 1: Initialize
const initResponse = await sendRequest('initialize', {
clientName: CLIENT_ID,
});
if (!initResponse || !initResponse.result) {
console.error('Initialization failed');
return;
}
// Step 2: Call a tool
await sendRequest('callTool', {
toolName: 'example-tool',
arguments: {
input: 'hello world',
},
});
}
testMcpServer();
🧪 4. Run and Test Locally
Terminal 1: Start the server
node mcp-server.js
Terminal 2: Run the client
node mcp-client.js
You should see logs like:
Server running at http://localhost:3000/mcp
Sending request: { requestId: ..., method: 'initialize', ... }
Received request: { ... }
Server response: { ... }
This confirms your server receives and responds correctly.
🧪 5. Use Tools Like Postman or curl
You can also manually test by sending raw JSON via curl or Postman.
Example with curl:
curl -X POST http://localhost:3000/mcp \
-H "Content-Type: application/json" \
-d '{
"requestId": "123",
"method": "initialize",
"params": {
"clientName": "manual-tester"
}
}'
🧪 6. Add Streaming Support (Optional)
If your server supports streaming (supportsStreaming: true), you’ll need to handle responses that use multipart/mixed or chunked transfer encoding.
Use Express streaming:
res.writeHead(200, {
'Content-Type': 'application/json',
});
res.write(JSON.stringify(...));
res.write(JSON.stringify(...));
res.end();
Then update your client to read chunks properly.
🧪 7. Automate Tests (Optional)
Use Jest or Mocha to automate testing different scenarios:
// mcp.test.js
import axios from 'axios';
describe('MCP Server', () => {
it('should initialize successfully', async () => {
const res = await axios.post('http://localhost:3000/mcp', {
requestId: '1',
method: 'initialize',
params: { clientName: 'test' },
});
expect(res.status).toBe(200);
expect(res.data.result.capabilities.supportsTools).toBe(true);
});
});
Run tests:
npm test mcp.test.js
✅ Summary
| Step | Action |
|---|
| 1 | Build a basic MCP server using Express |
| 2 | Send test requests using a local client |
| 3 | Log inputs and outputs to debug behavior |
| 4 | Use curl or Postman for manual testing |
| 5 | Add support for streaming if needed |
| 6 | Automate tests using Jest |
Would you like a complete starter template or GitHub repo for this? I can generate one for you.