Files
devcon-workshop-mcp-tutorial/server.js
2026-04-20 10:20:20 +03:00

96 lines
2.7 KiB
JavaScript

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
import http from "node:http";
function createServer() {
const server = new McpServer({
name: "devcon-workshop-server",
version: "1.0.0",
});
// ... register tools here ...
server.registerTool(
"add",
{
"description": "Adds two numbers together",
"inputSchema": {
a: z.number().describe("The first number to add"),
b: z.number().describe("The second number to add"),
},
},
async ({ a, b }) => ({
content: [{type: "text", text: `Result: ${a + b}`}],
})
);
server.registerTool(
"greet",
{
"description": "Greets a person by language",
"inputSchema": {
name: z.string().describe("The name of the person to greet"),
language: z.enum(["english", "spanish", "french"]).describe("The language to greet in"),
},
},
async ({name, language}) => {
const greetings = {
english: `Hello, ${name}! Welcome to the DevCon MCP Workshop.`,
french: `Bonjour, ${name} ! Bienvenue au Workshop MCP DevCon.`,
spanish: `¡Hola, ${name}! Bienvenido al Workshop MCP de DevCon.`,
};
return {
content: [{type: "text", text: greetings[language]}],
};
}
)
server.registerTool(
"estimate_cost",
{
"description": "Estimates the cost of a material based on its volume and type",
"inputSchema": {
material: z.enum(["concrete", "steel", "timber", "glass"]).describe("The type of material"),
volume: z.number().describe("The volume of the material in cubic meters"),
}
},
async ({ material, volume }) => {
const baseCosts = {
concrete: 150,
steel: 950,
timber: 400,
glass: 1200
};
const cost = baseCosts[material] * volume;
return {
content: [{type: "text", text: `Cost Estimate: ${volume}m³ of ${material} at ${baseCosts[material]}/m³ = $${cost.toFixed(2)}`}],
};
}
)
return server;
}
const PORT = 3000;
const httpServer = http.createServer(async (req, res) => {
if (req.url !== "/mcp") {
res.writeHead(404).end("Not found");
return;
}
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
});
res.on("close", () => transport.close());
const server = createServer();
await server.connect(transport);
await transport.handleRequest(req, res);
});
httpServer.listen(PORT, () => {
console.log(`MCP server running at http://localhost:${PORT}/mcp`);
});