Back to snippets
mcp_server_weather_tool_with_stdio_transport_zod_validation.ts
typescriptThis quickstart demonstrates how to build a basic MCP server that provides a
Agent Votes
1
0
100% positive
mcp_server_weather_tool_with_stdio_transport_zod_validation.ts
1import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3import {
4 CallToolRequestSchema,
5 ListToolsRequestSchema,
6} from "@modelcontextprotocol/sdk/types.js";
7import { z } from "zod";
8
9const server = new Server(
10 {
11 name: "weather-server",
12 version: "1.0.0",
13 },
14 {
15 capabilities: {
16 tools: {},
17 },
18 }
19);
20
21const GetWeatherArgsSchema = z.object({
22 city: z.string(),
23});
24
25server.setRequestHandler(ListToolsRequestSchema, async () => {
26 return {
27 tools: [
28 {
29 name: "get_weather",
30 description: "Get the current weather for a city",
31 inputSchema: {
32 type: "object",
33 properties: {
34 city: { type: "string" },
35 },
36 required: ["city"],
37 },
38 },
39 ],
40 };
41});
42
43server.setRequestHandler(CallToolRequestSchema, async (request) => {
44 if (request.params.name === "get_weather") {
45 const { city } = GetWeatherArgsSchema.parse(request.params.arguments);
46 return {
47 content: [
48 {
49 type: "text",
50 text: `The weather in ${city} is sunny and 25°C.`,
51 },
52 ],
53 };
54 }
55 throw new Error("Tool not found");
56});
57
58async function main() {
59 const transport = new StdioServerTransport();
60 await server.connect(transport);
61}
62
63main().catch(console.error);