import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import fs from "node:fs/promises";
const server = new McpServer({
name: "test",
version: "1.0.0",
capabilities: {
resources: {},
tools: {},
prompts: {},
},
});
server.resource(
"get-users",
"users://all",
{
description: "Get all users",
title: "Get Users",
mimeType: "application/json",
},
async (uri) => {
const users = await import("./data/users.json", { with: { type: "json" } }).then((m) => m.default);
return {
contents: [{ uri: uri.href, text: JSON.stringify(users), mimeType: "application/json" }],
};
}
);
server.tool(
"create-user",
"Create a new user",
{
name: z.string(),
email: z.string(),
password: z.string(),
address: z.string(),
phone: z.string(),
},
{
title: "Create User",
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
description: "Create a new user",
},
async (params) => {
try {
await createUser(params);
return {
content: [{ type: "text", text: "User created" }],
};
} catch {
return {
content: [{ type: "text", text: "Failed to save user" }],
};
}
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
async function createUser(user: { name: string; email: string; password: string; address: string; phone: string }) {
const users = await import("./data/users.json", { with: { type: "json" } }).then((m) => m.default);
const id = users.length + 1;
users.push({ id, ...user });
await fs.writeFile("./src/data/users.json", JSON.stringify(users, null, 2));
return id;
}
main();