newsapi.ts•3.3 kB
import { BaseApiClient } from "../../core/base-api.js";
import { loadConfig } from "../../core/config.js";
import { ToolRegistration } from "../../core/types.js";
class NewsApiClient extends BaseApiClient {
private readonly apiKey: string;
constructor(apiKey: string) {
super("https://newsapi.org");
this.apiKey = apiKey;
}
topHeadlines(country?: string, category?: string) {
return this.request("/v2/top-headlines", {
headers: { Authorization: `Bearer ${this.apiKey}` },
query: { country, category },
});
}
search(query: string, from_date?: string, to_date?: string) {
return this.request("/v2/everything", {
headers: { Authorization: `Bearer ${this.apiKey}` },
query: { q: query, from: from_date, to: to_date, sortBy: "publishedAt" },
});
}
sources(category?: string, country?: string) {
return this.request("/v2/top-headlines/sources", {
headers: { Authorization: `Bearer ${this.apiKey}` },
query: { category, country },
});
}
}
export function registerNewsApi(): ToolRegistration {
const cfg = loadConfig();
const client = new NewsApiClient(cfg.newsApiKey || "");
return {
tools: [
{
name: "get_top_headlines",
description: "Get top headlines by country and category",
inputSchema: {
type: "object",
properties: {
country: { type: "string" },
category: { type: "string" },
},
},
},
{
name: "search_news",
description: "Search news articles",
inputSchema: {
type: "object",
properties: {
query: { type: "string" },
from_date: { type: "string" },
to_date: { type: "string" },
},
required: ["query"],
},
},
{
name: "get_sources",
description: "List news sources",
inputSchema: {
type: "object",
properties: {
category: { type: "string" },
country: { type: "string" },
},
},
},
],
handlers: {
async get_top_headlines(args: Record<string, unknown>) {
if (!cfg.newsApiKey) throw new Error("NEWS_API_KEY is not configured");
const country = args.country ? String(args.country) : undefined;
const category = args.category ? String(args.category) : undefined;
return client.topHeadlines(country, category);
},
async search_news(args: Record<string, unknown>) {
if (!cfg.newsApiKey) throw new Error("NEWS_API_KEY is not configured");
const query = String(args.query || "");
if (!query) throw new Error("query is required");
const from_date = args.from_date ? String(args.from_date) : undefined;
const to_date = args.to_date ? String(args.to_date) : undefined;
return client.search(query, from_date, to_date);
},
async get_sources(args: Record<string, unknown>) {
if (!cfg.newsApiKey) throw new Error("NEWS_API_KEY is not configured");
const category = args.category ? String(args.category) : undefined;
const country = args.country ? String(args.country) : undefined;
return client.sources(category, country);
},
},
};
}