bookSearch.ts•1.67 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerBookSearch(server: McpServer) {
server.tool(
"book-search",
"Search books by title or author using Open Library",
{
title: z.string().optional().describe("Book title"),
author: z.string().optional().describe("Author name"),
limit: z.string().optional().describe("Max results (default 5)"),
},
async ({ title, author, limit }) => {
const params = new URLSearchParams();
if (title) params.append("title", title);
if (author) params.append("author", author);
const url = `https://openlibrary.org/search.json?${params.toString()}`;
const ctrl = new AbortController();
const id = setTimeout(() => ctrl.abort(), 8000);
try {
const res = await fetch(url, { signal: ctrl.signal });
const data = await res.json();
const max = Math.max(1, Math.min(Number(limit) || 5, 20));
const results = (data.docs || []).slice(0, max).map((d: any) => ({
title: d.title,
author: d.author_name ? d.author_name[0] : undefined,
first_publish_year: d.first_publish_year,
}));
return {
content: [
{
type: "text",
text: JSON.stringify({ results }, null, 2),
},
],
};
} catch (err: any) {
return {
content: [
{
type: "text",
text: JSON.stringify({ error: err.message }),
},
],
};
} finally {
clearTimeout(id);
}
}
);
}