Below is a basic example of a TypeScript MCP (Message Control Program) server that includes stubs to call a JSON service using basic authentication. This example uses the http module for creating the server and the axios library for making HTTP requests to the JSON service.
Before running the code, ensure you have Node.js and TypeScript installed on your machine. You'll also need to install the required packages (axios, @types/axios, @types/node) using npm or yarn.
First, initialize a new Node.js project and install the necessary packages:
npm init -y
npm install axios
npm install -D @types/axios @types/node typescript
Then, create a tsconfig.json file for TypeScript configuration:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Now, create a file named mcpServer.ts and add the following code:
import axios, { AxiosRequestConfig } from 'axios';
import * as http from 'http';
// Basic authentication credentials
const authUsername = 'your_username';
const authPassword = 'your_password';
// JSON service URL
const jsonServiceUrl = 'https://example.com/json-service';
// Create an HTTP server
const server = http.createServer((req, res) => {
// Handle incoming requests
if (req.url === '/call-json-service' && req.method === 'GET') {
callJsonService(req, res);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found\n');
}
});
// Function to call the JSON service with basic authentication
async function callJsonService(req: http.IncomingMessage, res: http.ServerResponse) {
try {
const auth = Buffer.from(`${authUsername}:${authPassword}`, 'utf8').toString('base64');
const config: AxiosRequestConfig = {
method: 'get',
url: jsonServiceUrl,
headers: {
'Authorization': `Basic ${auth}`,
'Content-Type': 'application/json',
},
};
const response = await axios(config);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(response.data));
} catch (error) {
console.error('Error calling JSON service:', error);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error\n');
}
}
// Start the server
const port = 3000;
server.listen(port, () => {
console.log(`MCP server listening on port ${port}`);
});
Replace 'your_username', 'your_password', and 'https://example.com/json-service' with your actual credentials and the URL of the JSON service you want to call.
To compile and run the TypeScript code, add a script to your package.json:
"scripts": {
"build": "tsc",
"start": "node dist/mcpServer.js"
}
Then, you can build and start your server using:
npm run build
npm start
Your MCP server should now be running on port 3000, and you can test it by visiting http://localhost:3000/call-json-service in your web browser or using a tool like curl.