import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new McpServer({
name: "poke-api",
version: "1.0.0",
});
// 入力スキーマ(zod)
const inputSchema = z.object({
nameOrId: z.string(),
});
// タイプでポケモンを検索するための入力スキーマ
const typeInputSchema = z.object({
typeName: z.string(),
});
// 出力スキーマ(zod)
// const outputSchema = z.object({
// name: z.string(),
// id: z.number(),
// height: z.number(),
// weight: z.number(),
// types: z.array(z.string()),
// });
// POKEAPIからポケモン情報を取得
type PokeApiResponse = {
name: string;
id: number;
height: number;
weight: number;
types: { type: { name: string } }[];
};
async function getPokemonInfo(nameOrId: string) {
const res = await fetch(
`https://pokeapi.co/api/v2/pokemon/${encodeURIComponent(nameOrId)}`
);
if (!res.ok) throw new Error("Not found");
const data = (await res.json()) as PokeApiResponse;
return {
name: data.name,
id: data.id,
height: data.height,
weight: data.weight,
types: data.types.map((t) => t.type.name),
};
}
server.tool("get-pokemon-info", inputSchema.shape, async (args) => {
const data = await getPokemonInfo(args.nameOrId);
return {
content: [
{
type: "text",
text: JSON.stringify(data, null, 2),
},
],
};
});
// POKEAPIからタイプでポケモン一覧を取得
async function getPokemonByType(typeName: string) {
const res = await fetch(
`https://pokeapi.co/api/v2/type/${encodeURIComponent(typeName)}`
);
if (!res.ok) throw new Error("Type not found");
const data = await res.json();
// data.pokemonは {pokemon: {name, url}, slot} の配列
return data.pokemon.map((p: any) => p.pokemon.name);
}
server.tool("get-pokemon-by-type", typeInputSchema.shape, async (args) => {
const names = await getPokemonByType(args.typeName);
return {
content: [
{
type: "text",
text: JSON.stringify(names, null, 2),
},
],
};
});
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Poke API MCP Server running on stdio");
}
main().catch((e) => {
console.error("Fatal error in main():", e);
process.exit(1);
});