-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.ts
76 lines (68 loc) · 1.95 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
const WeatherSchema = z.object({ location: z.string() });
// Create server instance
const server = new Server(
{ name: "weather", version: "1.0.0" },
{ capabilities: { tools: {} } },
);
// List available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "check-weather",
description: "Check the weather for a location",
inputSchema: {
type: "object",
properties: {
location: {
type: "string",
description: "The location to check the weather for",
},
},
required: ["location"],
},
},
],
};
});
// Handle tool execution
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
if (name === "check-weather") {
const { location } = WeatherSchema.parse(args);
const weather = await getWeather(location);
return { content: [{ type: "text", text: weather }] };
} else {
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
if (error instanceof z.ZodError) {
throw new Error(
`Invalid arguments: ${error.errors
.map((e) => `${e.path.join(".")}: ${e.message}`)
.join(", ")}`,
);
}
throw error;
}
});
// Fake weather API
async function getWeather(location: string): Promise<string> {
return `It's bright and sunny in ${location} today.`;
}
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});