api/src/routes/mcp.ts

142 lines · 4192 bytes

12 symbols in this file
  1// MCP HTTP/SSE endpoints, tools reuse the same data layer as public routes
  2import { Hono } from 'hono'
  3import { allServices, categories, findService, slugify } from '@/lib/data'
  4import { search } from '@/lib/search'
  5import type { HonoEnv } from '@/types'
  6
  7const app = new Hono<HonoEnv>()
  8
  9interface JsonRpcReq {
 10  jsonrpc: '2.0'
 11  id?: number | string
 12  method: string
 13  params?: Record<string, unknown>
 14}
 15
 16interface Tool {
 17  name: string
 18  description: string
 19  inputSchema: Record<string, unknown>
 20}
 21
 22const obj = (properties: Record<string, unknown>, required: string[] = []) => ({
 23  type: 'object',
 24  properties,
 25  ...(required.length ? { required } : {}),
 26})
 27
 28const str = { type: 'string' }
 29const num = { type: 'number' }
 30
 31const tools: Tool[] = [
 32  {
 33    name: 'search_services',
 34    description: 'Full-text search privacy services',
 35    inputSchema: obj({ q: str, limit: num }, ['q']),
 36  },
 37  {
 38    name: 'get_service',
 39    description: 'Fetch one service by slug',
 40    inputSchema: obj({ slug: str }, ['slug']),
 41  },
 42  {
 43    name: 'list_categories',
 44    description: 'List all categories with sections',
 45    inputSchema: obj({}),
 46  },
 47  {
 48    name: 'compare_services',
 49    description: 'Return two services side by side',
 50    inputSchema: obj({ a: str, b: str }, ['a', 'b']),
 51  },
 52  {
 53    name: 'recommend_alternative',
 54    description: 'Recommend services in the same section',
 55    inputSchema: obj({ slug: str, limit: num }, ['slug']),
 56  },
 57]
 58
 59const summariseCategories = () =>
 60  categories().map((category) => ({
 61    name: category.name,
 62    slug: slugify(category.name),
 63    sections: (category.sections ?? []).map((section) => ({
 64      name: section.name,
 65      slug: slugify(section.name),
 66    })),
 67  }))
 68
 69const recommend = (slug: string, limit: number) => {
 70  const service = findService(slug)
 71  if (!service) return { error: 'not_found' }
 72  const peers = allServices().filter(
 73    (peer) => peer.sectionSlug === service.sectionSlug && peer.slug !== service.slug,
 74  )
 75  return peers.slice(0, limit)
 76}
 77
 78// Dispatch a single MCP tool call to the in-process handler
 79const runTool = (name: string, args: Record<string, unknown>): unknown => {
 80  if (name === 'search_services') {
 81    return search(String(args.q ?? ''), Number(args.limit ?? 20))
 82  }
 83  if (name === 'get_service') {
 84    return findService(String(args.slug)) ?? { error: 'not_found' }
 85  }
 86  if (name === 'list_categories') return summariseCategories()
 87  if (name === 'compare_services') {
 88    return { a: findService(String(args.a)), b: findService(String(args.b)) }
 89  }
 90  if (name === 'recommend_alternative') {
 91    return recommend(String(args.slug), Number(args.limit ?? 5))
 92  }
 93  return { error: `unknown_tool:${name}` }
 94}
 95
 96const initializeResult = {
 97  protocolVersion: '2024-11-05',
 98  capabilities: { tools: {} },
 99  serverInfo: { name: 'awesome-privacy', version: '1.0.0' },
100}
101
102// MCP server, handles initialize, tools/list and tools/call
103const handle = (req: JsonRpcReq) => {
104  const id = req.id ?? null
105  if (req.method === 'initialize') {
106    return { jsonrpc: '2.0', id, result: initializeResult }
107  }
108  if (req.method === 'tools/list') {
109    return { jsonrpc: '2.0', id, result: { tools } }
110  }
111  if (req.method === 'tools/call') {
112    const params = req.params ?? {}
113    const name = String(params.name)
114    const args = (params.arguments ?? {}) as Record<string, unknown>
115    const output = runTool(name, args)
116    const content = [{ type: 'text', text: JSON.stringify(output) }]
117    return { jsonrpc: '2.0', id, result: { content } }
118  }
119  return { jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found' } }
120}
121
122app.post('/mcp', async (c) => c.json(handle(await c.req.json())))
123
124// SSE handshake, emits the tool list once and stays open
125app.get('/sse', () => {
126  const encoder = new TextEncoder()
127  const stream = new ReadableStream({
128    start(controller) {
129      const payload = JSON.stringify({ tools })
130      controller.enqueue(encoder.encode(`event: ready\ndata: ${payload}\n\n`))
131    },
132  })
133  return new Response(stream, {
134    headers: {
135      'content-type': 'text/event-stream',
136      'cache-control': 'no-cache',
137      connection: 'keep-alive',
138    },
139  })
140})
141
142export default app