Here's an example of setting up a basic MCP server and client using the @modelcontextprotocol/sdk library.
Server Setup
First, create a new file called server.js and add the following code:
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
// Create a new MCP server
const server = new Server({
// Define a tool that the client can use
tools: [
{
id: 'echo',
name: 'Echo Tool',
description: 'Echoes back the input',
execute: async (input) => {
return { output: input };
},
},
],
});
// Create a new StdioServerTransport instance
const transport = new StdioServerTransport();
// Start the server
server.listen(transport);
console.log('MCP server started. Waiting for client connection...');
Client Setup
Next, create a new file called client.js and add the following code:
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
// Create a new MCP client
const client = new Client({
// Define the transport layer (in this case, Stdio)
transport: new StdioClientTransport(),
});
// Connect to the server
client.connect();
// Once connected, get the list of available tools
client.on('connected', async () => {
const tools = await client.getTools();
console.log('Available tools:', tools);
// Use the 'echo' tool
const tool = tools.find((t) => t.id === 'echo');
if (tool) {
const input = 'Hello, world!';
const output = await client.executeTool(tool.id, input);
console.log(`Output: ${output.output}`);
}
});
// Handle any errors that occur
client.on('error', (error) => {
console.error('Error occurred:', error);
});
Running the Example
To run the example, open two terminal windows. In the first window, run the server:
node server.js
In the second window, run the client:
node client.js
The client should connect to the server, retrieve the list of available tools, and use the 'echo' tool to send a message to the server. The server should respond with the echoed message, which the client will then print to the console.
Note that this is a very basic example, and you'll likely want to add more tools, error handling, and other features to your MCP server and client. However, this should give you a good starting point for understanding how to use the @modelcontextprotocol/sdk library.