|
| 1 | +import express from 'express'; |
| 2 | +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; |
| 3 | +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; |
| 4 | +import { z } from 'zod'; |
| 5 | +import Fuse from 'fuse.js'; |
| 6 | +import { CallToolRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, ListResourcesRequestSchema, SubscribeRequestSchema, UnsubscribeRequestSchema } from "@modelcontextprotocol/sdk/types.js"; |
| 7 | +import { zodToJsonSchema } from "zod-to-json-schema"; |
| 8 | +import { SPECIES_DATA } from './data/species.js'; |
| 9 | +import { RESOURCES } from './data/resources.js'; |
| 10 | +import { timestamp, formatSpeciesText } from './utils/utils.js'; |
| 11 | +const app = express(); |
| 12 | +app.use(express.json()); |
| 13 | +// Create the MCP server once (reused across requests) |
| 14 | +const server = new Server({ |
| 15 | + name: "biological-species-mcp-server", |
| 16 | + version: "1.0.0", |
| 17 | +}, { |
| 18 | + capabilities: { |
| 19 | + resources: { subscribe: true }, |
| 20 | + tools: {}, |
| 21 | + }, |
| 22 | +}); |
| 23 | +// Tool input schemas |
| 24 | +const SearchSpeciesDataSchema = z.object({ |
| 25 | + searchTerms: z.string().describe("keywords to search for facts about species") |
| 26 | +}); |
| 27 | +const ListSpeciesSchema = z.object({}); |
| 28 | +// Configure Fuse.js for fuzzy searching |
| 29 | +const fuseOptions = { |
| 30 | + keys: ['name', 'description'], |
| 31 | + threshold: 0.4, // 0 = exact match, 1 = match anything |
| 32 | + includeScore: true, |
| 33 | + minMatchCharLength: 2 |
| 34 | +}; |
| 35 | +const fuse = new Fuse(RESOURCES, fuseOptions); |
| 36 | +// Handler: List available tools |
| 37 | +server.setRequestHandler(ListToolsRequestSchema, async () => { |
| 38 | + return { |
| 39 | + tools: [ |
| 40 | + { |
| 41 | + name: "searchSpeciesData", |
| 42 | + description: "Search for species resources by title keywords. Returns up to 5 matching resource links (text, images, data packages).", |
| 43 | + inputSchema: zodToJsonSchema(SearchSpeciesDataSchema), |
| 44 | + }, |
| 45 | + { |
| 46 | + name: "listSpecies", |
| 47 | + description: "Get a list of all available species names in the database.", |
| 48 | + inputSchema: zodToJsonSchema(ListSpeciesSchema), |
| 49 | + }, |
| 50 | + ], |
| 51 | + }; |
| 52 | +}); |
| 53 | +// Handler: Call tool |
| 54 | +server.setRequestHandler(CallToolRequestSchema, async (request) => { |
| 55 | + const { name, arguments: args } = request.params; |
| 56 | + if (name === "searchSpeciesData") { |
| 57 | + const validatedArgs = SearchSpeciesDataSchema.parse(args); |
| 58 | + const { searchTerms } = validatedArgs; |
| 59 | + console.log(`${timestamp()} 🔍 Client called tool: searchSpeciesData with terms '${searchTerms}'`); |
| 60 | + // Use Fuse.js for fuzzy search |
| 61 | + const searchResults = fuse.search(searchTerms); |
| 62 | + if (searchResults.length === 0) { |
| 63 | + console.log(`${timestamp()} ⚠️ No resources found for client search: "${searchTerms}"`); |
| 64 | + return { |
| 65 | + content: [ |
| 66 | + { |
| 67 | + type: "text", |
| 68 | + text: `No resources found matching: "${searchTerms}". Try keywords like 'butterfly', 'panda', 'photo', 'overview', or 'data'.`, |
| 69 | + }, |
| 70 | + ], |
| 71 | + }; |
| 72 | + } |
| 73 | + // Return top 5 results |
| 74 | + const results = searchResults.slice(0, 5).map(result => result.item); |
| 75 | + console.log(`${timestamp()} ✅ Returning ${results.length} matching resources to client`); |
| 76 | + const content = [ |
| 77 | + { |
| 78 | + type: "text", |
| 79 | + text: `Found ${results.length} resource(s) matching "${searchTerms}":\n\n${results.map((r, i) => `${i + 1}. ${r.name}`).join('\n')}`, |
| 80 | + }, |
| 81 | + ]; |
| 82 | + // Add resource references |
| 83 | + results.forEach(resource => { |
| 84 | + content.push({ |
| 85 | + type: "resource_link", |
| 86 | + uri: resource.uri, |
| 87 | + name: resource.name, |
| 88 | + description: resource.description, |
| 89 | + mimeType: resource.mimeType, |
| 90 | + annotations: { |
| 91 | + audience: ["assistant"], |
| 92 | + priority: 0.8 |
| 93 | + } |
| 94 | + }); |
| 95 | + }); |
| 96 | + return { content }; |
| 97 | + } |
| 98 | + if (name === "listSpecies") { |
| 99 | + console.log(`${timestamp()} 📋 Client called tool: listSpecies`); |
| 100 | + // Get only species names |
| 101 | + const speciesNames = SPECIES_DATA.map(species => species.commonName); |
| 102 | + console.log(`${timestamp()} ✅ Returning ${speciesNames.length} species names to client`); |
| 103 | + return { |
| 104 | + content: [ |
| 105 | + { |
| 106 | + type: "text", |
| 107 | + text: JSON.stringify(speciesNames, null, 2), |
| 108 | + }, |
| 109 | + ], |
| 110 | + }; |
| 111 | + } |
| 112 | + throw new Error(`Unknown tool: ${name}`); |
| 113 | +}); |
| 114 | +// Handler: List resources |
| 115 | +server.setRequestHandler(ListResourcesRequestSchema, async () => { |
| 116 | + console.log(`${timestamp()} 📋 Client requesting list of all ${RESOURCES.length} resources`); |
| 117 | + return { |
| 118 | + resources: RESOURCES.map(r => ({ |
| 119 | + uri: r.uri, |
| 120 | + name: r.name, |
| 121 | + description: r.description, |
| 122 | + mimeType: r.mimeType, |
| 123 | + })) |
| 124 | + }; |
| 125 | +}); |
| 126 | +// Handler: Read resource |
| 127 | +server.setRequestHandler(ReadResourceRequestSchema, async (request) => { |
| 128 | + const uri = request.params.uri; |
| 129 | + console.log(`${timestamp()} 📖 Client reading resource: ${uri}`); |
| 130 | + // Find the resource |
| 131 | + const resource = RESOURCES.find(r => r.uri === uri); |
| 132 | + if (!resource) { |
| 133 | + throw new Error(`Unknown resource: ${uri}`); |
| 134 | + } |
| 135 | + const species = SPECIES_DATA.find(s => s.id === resource.speciesId); |
| 136 | + if (!species) { |
| 137 | + throw new Error(`Species not found for resource: ${uri}`); |
| 138 | + } |
| 139 | + console.log(`${timestamp()} 📄 Client requested: ${species.commonName} - ${resource.resourceType}`); |
| 140 | + // Return content based on resource type |
| 141 | + if (resource.resourceType === 'text') { |
| 142 | + const content = formatSpeciesText(species); |
| 143 | + console.log(`${timestamp()} 📝 Returning text content to client (${content.length} characters)`); |
| 144 | + return { |
| 145 | + contents: [ |
| 146 | + { |
| 147 | + uri, |
| 148 | + mimeType: "text/plain", |
| 149 | + text: content, |
| 150 | + }, |
| 151 | + ], |
| 152 | + }; |
| 153 | + } |
| 154 | + if (resource.resourceType === 'image') { |
| 155 | + console.log(`${timestamp()} 🖼️ Returning image to client for ${species.commonName}`); |
| 156 | + return { |
| 157 | + contents: [ |
| 158 | + { |
| 159 | + uri, |
| 160 | + mimeType: "image/png", |
| 161 | + blob: species.image, |
| 162 | + }, |
| 163 | + ], |
| 164 | + }; |
| 165 | + } |
| 166 | + throw new Error(`Unknown resource type: ${resource.resourceType}`); |
| 167 | +}); |
| 168 | +// Handler: Subscribe to resource updates |
| 169 | +server.setRequestHandler(SubscribeRequestSchema, async (request) => { |
| 170 | + const { uri } = request.params; |
| 171 | + console.log(`${timestamp()} 🔔 Client subscribed to: ${uri}`); |
| 172 | + return {}; |
| 173 | +}); |
| 174 | +// Handler: Unsubscribe from resource updates |
| 175 | +server.setRequestHandler(UnsubscribeRequestSchema, async (request) => { |
| 176 | + const { uri } = request.params; |
| 177 | + console.log(`${timestamp()} 🔕 Client unsubscribed from: ${uri}`); |
| 178 | + return {}; |
| 179 | +}); |
| 180 | +// Handle MCP requests (stateless mode) |
| 181 | +app.post('/mcp', async (req, res) => { |
| 182 | + try { |
| 183 | + // Create new transport for each request to prevent request ID collisions |
| 184 | + const transport = new StreamableHTTPServerTransport({ |
| 185 | + sessionIdGenerator: undefined, |
| 186 | + enableJsonResponse: true |
| 187 | + }); |
| 188 | + res.on('close', () => { |
| 189 | + transport.close(); |
| 190 | + }); |
| 191 | + await server.connect(transport); |
| 192 | + await transport.handleRequest(req, res, req.body); |
| 193 | + } |
| 194 | + catch (error) { |
| 195 | + console.error(`${timestamp()} Error handling MCP request:`, error); |
| 196 | + if (!res.headersSent) { |
| 197 | + res.status(500).json({ |
| 198 | + jsonrpc: '2.0', |
| 199 | + error: { |
| 200 | + code: -32603, |
| 201 | + message: 'Internal server error' |
| 202 | + }, |
| 203 | + id: null |
| 204 | + }); |
| 205 | + } |
| 206 | + } |
| 207 | +}); |
| 208 | +const PORT = parseInt(process.env.PORT || '3000'); |
| 209 | +app.listen(PORT, () => { |
| 210 | + console.log(`${timestamp()} 🚀 Species MCP Server running on http://localhost:${PORT}/mcp`); |
| 211 | + console.log(`${timestamp()} 📚 Loaded ${SPECIES_DATA.length} species and ${RESOURCES.length} resources`); |
| 212 | +}).on('error', error => { |
| 213 | + console.error(`${timestamp()} Server error:`, error); |
| 214 | + process.exit(1); |
| 215 | +}); |
0 commit comments