fetch_json
Retrieve JSON data from any URL with optional custom headers for web content integration.
Instructions
Fetch a JSON file from a URL
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | URL of the JSON to fetch | |
| headers | No | Optional headers to include in the request |
Implementation Reference
- src/Fetcher.ts:45-58 (handler)The core handler function for 'fetch_json' that performs the HTTP fetch, parses the JSON response, stringifies it, and returns it in the expected MCP format or an error.static async json(requestPayload: RequestPayload) { try { const response = await this._fetch(requestPayload); const json = await response.json(); return { content: [{ type: "text", text: JSON.stringify(json) }], isError: false, }; } catch (error) { return { content: [{ type: "text", text: (error as Error).message }], isError: true, }; }
- src/index.ts:83-100 (registration)Tool registration in the ListTools handler, defining the name, description, and input schema for 'fetch_json'.{ name: "fetch_json", description: "Fetch a JSON file from a URL", inputSchema: { type: "object", properties: { url: { type: "string", description: "URL of the JSON to fetch", }, headers: { type: "object", description: "Optional headers to include in the request", }, }, required: ["url"], }, },
- src/types.ts:1-8 (schema)Zod schema used for validating the input parameters (url and optional headers) for the fetch_json tool.import { z } from "zod"; export const RequestPayloadSchema = z.object({ url: z.string().url(), headers: z.record(z.string()).optional(), }); export type RequestPayload = z.infer<typeof RequestPayloadSchema>;
- src/Fetcher.ts:6-30 (helper)Shared private helper method for performing the fetch request with custom User-Agent and error handling, used by fetch_json.private static async _fetch({ url, headers, }: RequestPayload): Promise<Response> { try { const response = await fetch(url, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", ...headers, }, }); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } return response; } catch (e: unknown) { if (e instanceof Error) { throw new Error(`Failed to fetch ${url}: ${e.message}`); } else { throw new Error(`Failed to fetch ${url}: Unknown error`); } } }
- src/index.ts:114-117 (handler)Dispatch handler in the main CallToolRequestSchema that routes 'fetch_json' calls to the Fetcher.json implementation.if (request.params.name === "fetch_json") { const fetchResult = await Fetcher.json(validatedArgs); return fetchResult; }