|
| 1 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 2 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 3 | +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; |
| 4 | +import type { |
| 5 | + CallToolResult, |
| 6 | + ReadResourceResult, |
| 7 | +} from "@modelcontextprotocol/sdk/types.js"; |
| 8 | +import * as cheerio from "cheerio"; |
| 9 | +import cors from "cors"; |
| 10 | +import express, { type Request, type Response } from "express"; |
| 11 | +import fs from "node:fs/promises"; |
| 12 | +import path from "node:path"; |
| 13 | +import { z } from "zod"; |
| 14 | +import { RESOURCE_MIME_TYPE, RESOURCE_URI_META_KEY } from "../../dist/src/app"; |
| 15 | + |
| 16 | +const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3001; |
| 17 | +const DIST_DIR = path.join(import.meta.dirname, "dist"); |
| 18 | + |
| 19 | +type PageInfo = { url: string; title: string }; |
| 20 | + |
| 21 | +// Helper to derive title from Wikipedia URL |
| 22 | +function extractTitleFromUrl(url: string): string { |
| 23 | + try { |
| 24 | + const urlObj = new URL(url); |
| 25 | + const path = urlObj.pathname; |
| 26 | + const title = path.replace("/wiki/", ""); |
| 27 | + return decodeURIComponent(title).replace(/_/g, " "); |
| 28 | + } catch { |
| 29 | + return url; // Fallback to URL if parsing fails |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Wikipedia namespace prefixes to exclude from link extraction |
| 34 | +const EXCLUDED_PREFIXES = [ |
| 35 | + "Wikipedia:", |
| 36 | + "Help:", |
| 37 | + "File:", |
| 38 | + "Special:", |
| 39 | + "Talk:", |
| 40 | + "Template:", |
| 41 | + "Category:", |
| 42 | + "Portal:", |
| 43 | + "Draft:", |
| 44 | + "Module:", |
| 45 | + "MediaWiki:", |
| 46 | + "User:", |
| 47 | + "Main_Page", |
| 48 | +]; |
| 49 | + |
| 50 | +// Extract wiki links from HTML, filtering out special pages and self-links |
| 51 | +function extractWikiLinks(pageUrl: URL, html: string): PageInfo[] { |
| 52 | + const $ = cheerio.load(html); |
| 53 | + |
| 54 | + return [ |
| 55 | + ...new Set( |
| 56 | + $('a[href^="/wiki/"]') |
| 57 | + .map((_, el) => $(el).attr("href")) |
| 58 | + .get() |
| 59 | + .filter( |
| 60 | + (href): href is string => |
| 61 | + href !== undefined && |
| 62 | + href !== pageUrl.pathname && |
| 63 | + !href.includes("#") && |
| 64 | + !EXCLUDED_PREFIXES.some((prefix) => href.includes(prefix)), |
| 65 | + ), |
| 66 | + ), |
| 67 | + ].map((href) => ({ |
| 68 | + url: `${pageUrl.origin}${href}`, |
| 69 | + title: extractTitleFromUrl(`${pageUrl.origin}${href}`), |
| 70 | + })); |
| 71 | +} |
| 72 | + |
| 73 | +const server = new McpServer({ |
| 74 | + name: "Wiki Explorer", |
| 75 | + version: "1.0.0", |
| 76 | +}); |
| 77 | + |
| 78 | +// Register the get-first-degree-links tool and its associated UI resource |
| 79 | +{ |
| 80 | + const resourceUri = "ui://wiki-explorer/mcp-app.html"; |
| 81 | + |
| 82 | + server.registerTool( |
| 83 | + "get-first-degree-links", |
| 84 | + { |
| 85 | + title: "Get First-Degree Links", |
| 86 | + description: |
| 87 | + "Returns all Wikipedia pages that the given page links to directly.", |
| 88 | + inputSchema: z.object({ |
| 89 | + url: z.string().url().describe("Wikipedia page URL"), |
| 90 | + }), |
| 91 | + _meta: { [RESOURCE_URI_META_KEY]: resourceUri }, |
| 92 | + }, |
| 93 | + async ({ url }): Promise<CallToolResult> => { |
| 94 | + let title = url; |
| 95 | + |
| 96 | + try { |
| 97 | + if (!url.match(/^https?:\/\/[a-z]+\.wikipedia\.org\/wiki\//)) { |
| 98 | + throw new Error("Not a valid Wikipedia URL"); |
| 99 | + } |
| 100 | + |
| 101 | + title = extractTitleFromUrl(url); |
| 102 | + |
| 103 | + const response = await fetch(url); |
| 104 | + |
| 105 | + if (!response.ok) { |
| 106 | + throw new Error( |
| 107 | + response.status === 404 |
| 108 | + ? "Page not found" |
| 109 | + : `Fetch failed: ${response.status}`, |
| 110 | + ); |
| 111 | + } |
| 112 | + |
| 113 | + const html = await response.text(); |
| 114 | + const links = extractWikiLinks(new URL(url), html); |
| 115 | + |
| 116 | + const result = { page: { url, title }, links, error: null }; |
| 117 | + return { content: [{ type: "text", text: JSON.stringify(result) }] }; |
| 118 | + } catch (err) { |
| 119 | + const error = err instanceof Error ? err.message : String(err); |
| 120 | + const result = { page: { url, title }, links: [], error }; |
| 121 | + return { content: [{ type: "text", text: JSON.stringify(result) }] }; |
| 122 | + } |
| 123 | + }, |
| 124 | + ); |
| 125 | + |
| 126 | + server.registerResource( |
| 127 | + resourceUri, |
| 128 | + resourceUri, |
| 129 | + {}, |
| 130 | + async (): Promise<ReadResourceResult> => { |
| 131 | + const html = await fs.readFile( |
| 132 | + path.join(DIST_DIR, "mcp-app.html"), |
| 133 | + "utf-8", |
| 134 | + ); |
| 135 | + |
| 136 | + return { |
| 137 | + contents: [ |
| 138 | + { uri: resourceUri, mimeType: RESOURCE_MIME_TYPE, text: html }, |
| 139 | + ], |
| 140 | + }; |
| 141 | + }, |
| 142 | + ); |
| 143 | +} |
| 144 | + |
| 145 | +async function main() { |
| 146 | + if (process.argv.includes("--stdio")) { |
| 147 | + const transport = new StdioServerTransport(); |
| 148 | + await server.connect(transport); |
| 149 | + console.error("Wiki Explorer server running in stdio mode"); |
| 150 | + } else { |
| 151 | + const app = express(); |
| 152 | + app.use(cors()); |
| 153 | + app.use(express.json()); |
| 154 | + |
| 155 | + app.post("/mcp", async (req: Request, res: Response) => { |
| 156 | + try { |
| 157 | + const transport = new StreamableHTTPServerTransport({ |
| 158 | + sessionIdGenerator: undefined, |
| 159 | + enableJsonResponse: true, |
| 160 | + }); |
| 161 | + res.on("close", () => { |
| 162 | + transport.close(); |
| 163 | + }); |
| 164 | + |
| 165 | + await server.connect(transport); |
| 166 | + |
| 167 | + await transport.handleRequest(req, res, req.body); |
| 168 | + } catch (error) { |
| 169 | + console.error("Error handling MCP request:", error); |
| 170 | + if (!res.headersSent) { |
| 171 | + res.status(500).json({ |
| 172 | + jsonrpc: "2.0", |
| 173 | + error: { code: -32603, message: "Internal server error" }, |
| 174 | + id: null, |
| 175 | + }); |
| 176 | + } |
| 177 | + } |
| 178 | + }); |
| 179 | + |
| 180 | + const httpServer = app.listen(PORT, () => { |
| 181 | + console.log( |
| 182 | + `Wiki Explorer server listening on http://localhost:${PORT}/mcp`, |
| 183 | + ); |
| 184 | + }); |
| 185 | + |
| 186 | + function shutdown() { |
| 187 | + console.log("\nShutting down..."); |
| 188 | + httpServer.close(() => { |
| 189 | + console.log("Server closed"); |
| 190 | + process.exit(0); |
| 191 | + }); |
| 192 | + } |
| 193 | + |
| 194 | + process.on("SIGINT", shutdown); |
| 195 | + process.on("SIGTERM", shutdown); |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +main().catch(console.error); |
0 commit comments