Okay, I will create a simple TypeScript project that demonstrates the Model-Context-Protocol (MCP) architecture, focusing on a basic server and client interaction. I'll keep it as straightforward as possible with ample comments.
Here's the plan:
- Project Setup: I'll outline the basic project structure.
- MCP Server: A simple server that holds a "model" (e.g., a simple counter) and allows clients to "contextually" interact with it (e.g., increment/decrement the counter).
- MCP Client: A client that connects to the server and sends commands to modify the model.
- Communication: I'll use basic
WebSocket communication for simplicity.
- Code Comments: I'll include detailed comments to explain each part of the code.
Let's start!
Alright, here's a basic implementation of an MCP-like system using WebSockets and TypeScript. I've focused on simplicity and clear explanations.
1. Project Setup
First, you'll need to set up a basic TypeScript project[1]. If you don't already have a tsconfig.json, create one with tsc --init. You'll also need to install the ws package for WebSocket support: npm install ws.
2. MCP Server (server.ts)
// server.ts
import { WebSocketServer, WebSocket } from 'ws';
// Define the port the server will listen on
const PORT = 8080;
// Our simple "model": a counter
let counter = 0;
// Function to handle incrementing the counter
function incrementCounter() {
counter++;
console.log(`Counter incremented: ${counter}`);
// Notify all clients about the change
broadcastCounter();
}
// Function to handle decrementing the counter
function decrementCounter() {
counter--;
console.log(`Counter decremented: ${counter}`);
// Notify all clients about the change
broadcastCounter();
}
// Function to broadcast the counter value to all connected clients
function broadcastCounter() {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type: 'counterUpdate', value: counter })); // Send the counter value as JSON
}
});
}
// Create a WebSocket Server instance
const wss = new WebSocketServer({ port: PORT });
// Event listener for when a client connects to the server
wss.on('connection', ws => {
console.log('Client connected');
// Send the initial counter value to the newly connected client
ws.send(JSON.stringify({ type: 'counterUpdate', value: counter }));
// Event listener for messages received from the client
ws.on('message', message => {
console.log(`Received message: ${message}`);
try {
const parsedMessage = JSON.parse(message.toString()); // Parse the message as JSON
console.log("parsedMessage", parsedMessage);
// Handle different message types (MCP-like "contextual" commands)
if (parsedMessage.type === 'increment') {
incrementCounter();
} else if (parsedMessage.type === 'decrement') {
decrementCounter();
} else {
console.log(`Unknown message type: ${parsedMessage.type}`);
}
} catch (error) {
console.error('Failed to parse message:', error);
}
});
// Event listener for when the client disconnects
ws.on('close', () => {
console.log('Client disconnected');
});
// Event listener for errors
ws.on('error', error => {
console.error('WebSocket error:', error);
});
});
console.log(`WebSocket server started on port ${PORT}`);
Explanation:
- Imports: Imports necessary classes from the
ws library.
PORT: Defines the port the server will listen on[1].
counter: Our simple "model" – an integer counter.
incrementCounter and decrementCounter: Functions to modify the model. They also call broadcastCounter to inform all clients of the change.
broadcastCounter: Sends the current value of the counter to all connected clients. This is a crucial part of the "Model-Context" interaction – the server pushes updates to the clients.
WebSocketServer: Creates a new WebSocket server that listens for connections on the specified port[1].
wss.on('connection', ...): This is the main connection handler. It's called whenever a client connects to the server.
- It sends the initial counter value to the new client.
- It sets up a message handler (
ws.on('message', ...) to process commands from the client[3].
- It sets up handlers for
close and error events[3][4].
- Message Handling: The
ws.on('message', ...) handler parses incoming messages as JSON. It then checks the type property to determine the action to take (increment or decrement). This is where you would extend the server to handle more complex commands and data. This is the "context" part – the client is sending commands that operate on the server's model.
- Error Handling: Basic error handling for message parsing and WebSocket errors.
3[5]. MCP Client (client.ts)
// client.ts
import WebSocket from 'ws';
// Server address
const SERVER_URL = 'ws://localhost:8080';
// Create a new WebSocket client
const ws = new WebSocket(SERVER_URL);
// Event listener for when the connection is opened
ws.on('open', () => {
console.log('Connected to server');
// Send an initial message (optional)
// ws.send(JSON.stringify({ type: 'increment' }));
});
// Event listener for messages received from the server
ws.on('message', message => {
try {
const parsedMessage = JSON.parse(message.toString()); // Parse the message as JSON
console.log('Received message:', parsedMessage);
// Handle different message types
if (parsedMessage.type === 'counterUpdate') {
console.log(`Counter value: ${parsedMessage.value}`);
} else {
console.log(`Unknown message type: ${parsedMessage.type}`);
}
} catch (error) {
console.error('Failed to parse message:', error);
}
});
// Event listener for when the connection is closed
ws.on('close', () => {
console.log('Disconnected from server');
});
// Event listener for errors
ws.on('error', error => {
console.error('WebSocket error:', error);
});
// Function to send a command to the server
function sendCommand(type: string) {
ws.send(JSON.stringify({ type: type }));
}
// Example usage: Send increment and decrement commands every few seconds
let incrementing = true;
setInterval(() => {
if (incrementing) {
sendCommand('increment');
} else {
sendCommand('decrement');
}
incrementing = !incrementing;
}, 2000);
Explanation:
- Imports: Imports the
WebSocket class from the ws library[1][3].
SERVER_URL: Defines the address of the WebSocket server.
WebSocket: Creates a new WebSocket client and connects to the server[3].
ws.on('open', ...): This handler is called when the connection to the server is successfully established.
- It sends an optional initial message.
ws.on('message', ...): This handler is called whenever the client receives a message from the server.
- It parses the message as JSON[2].
- It checks the
type property to determine the action to take (in this case, it expects counterUpdate messages).
ws.on('close', ...) and ws.on('error', ...): Handlers for connection close and error events.
sendCommand(type: string): A helper function to send commands to the server.
- Example Usage: The
setInterval function demonstrates how to periodically send increment and decrement commands to the server.
4. Running the Project
- Compile: Compile both
server.ts and client.ts using tsc server.ts client.ts.
- Run the server:
node server.js.
- Run the client:
node client.js.
You should see the server logging connection/disconnection events and the counter value changes. The client will also log the counter value updates it receives from the server.
Key MCP Concepts Demonstrated:
- Model: The
counter variable on the server is a very simple model.
- Context: The
increment and decrement message types represent contextual commands that the client sends to the server to modify the model.
- Protocol: The JSON-based message format and the defined
type property establish a simple protocol for communication.
- Server as the Source of Truth: The server maintains the state of the model and pushes updates to the clients.
How to Extend This Example:
- More Complex Model: Instead of a simple counter, use an object with multiple properties or a more complex data structure.
- More Commands: Add more message types to support additional operations on the model.
- Data Validation: Implement input validation on the server to ensure that client commands are valid.
- Error Handling: Provide more informative error messages to the client.
- Authentication: Add authentication to ensure that only authorized clients can connect to the server.
- Real MCP Implementation: Use a real MCP implementation from Anthropic as described here: https://www.anthropic.com/claude/model-context-protocol. This would involve using the MCP SDK.
This example provides a foundation for understanding the basic principles of MCP. By extending it with more features and complexity, you can create more sophisticated and powerful applications.