Open History to see the last commit
1/**
2 * MCP server endpoint (PLAN.md task 7.1) — stateless streamable-HTTP:
3 * every request is a self-contained JSON-RPC POST answered with JSON (no
4 * SSE session state to hold on Workers). Tools reuse the Phase 4 service
5 * functions directly.
6 */
7import type { Db } from '#/db/index.ts'
8import { activities, changeTypes } from '#/db/schema.ts'
9import type { Activity, ChangeType } from '#/db/schema.ts'
10import { listChanges } from '#/server/changes-api.ts'
11import { getModelDetail, listModelsCatalog } from '#/server/catalog.ts'
12import { estimateCost } from '#/server/estimate.ts'
13import { llmsTxt } from '#/server/llms-txt.ts'
14import {
15 getEndpointSchema,
16 getProviderSchemaIndex,
17 getSystemSchemaIndex,
18 providerExists,
19} from '#/server/schemas-api.ts'
20import { validatePayload } from '#/server/validate.ts'
21
22export const MCP_PROTOCOL_VERSION = '2025-03-26'
23
24interface JsonRpcRequest {
25 jsonrpc: '2.0'
26 id?: number | string | null
27 method: string
28 params?: Record<string, unknown>
29}
30
31export interface ToolDefinition {
32 name: string
33 description: string
34 inputSchema: Record<string, unknown>
35}
36
37export const TOOLS: Array<ToolDefinition> = [
38 {
39 name: 'list_models',
40 description:
41 'Cross-provider model catalog: which AI models exist right now, filterable by activity (chat/image/video/audio/embeddings/moderation), provider, capability flag (a flag the model is stated to support, e.g. tools), or free text.',
42 inputSchema: {
43 type: 'object',
44 properties: {
45 activity: { type: 'string', enum: [...activities] },
46 provider: { type: 'string' },
47 capability: { type: 'string' },
48 q: { type: 'string' },
49 },
50 },
51 },
52 {
53 name: 'get_model',
54 description:
55 'Full metadata for one model (context window, modalities, pricing, capabilities). Accepts the model slug or raw provider id.',
56 inputSchema: {
57 type: 'object',
58 properties: {
59 provider: { type: 'string' },
60 modelId: { type: 'string' },
61 },
62 required: ['provider', 'modelId'],
63 },
64 },
65 {
66 name: 'list_schemas',
67 description:
68 'Index of every schema on the system: provider → activity → endpoint ids. Pass provider to narrow to one provider. Use it to discover valid get_schema arguments.',
69 inputSchema: {
70 type: 'object',
71 properties: {
72 provider: {
73 type: 'string',
74 description: 'Optional provider id to narrow the index.',
75 },
76 },
77 },
78 },
79 {
80 name: 'get_schema',
81 description:
82 'Self-contained JSON Schema ($defs-bundled) for a provider endpoint — request (input) or response (output) shape.',
83 inputSchema: {
84 type: 'object',
85 properties: {
86 provider: { type: 'string' },
87 activity: { type: 'string', enum: [...activities] },
88 endpointId: {
89 type: 'string',
90 description:
91 "Path-derived id (e.g. 'v1/messages' or 'chat/completions') or a listed model rawId, which aliases onto that activity's generation route.",
92 },
93 kind: { type: 'string', enum: ['input', 'output'] },
94 version: {
95 type: 'string',
96 description: 'Content hash of a historical version.',
97 },
98 },
99 required: ['provider', 'activity', 'endpointId'],
100 },
101 },
102 {
103 name: 'validate_payload',
104 description:
105 'Validate a request/response payload against the current stored schema for a provider endpoint before spending tokens on a real call.',
106 inputSchema: {
107 type: 'object',
108 properties: {
109 provider: { type: 'string' },
110 endpointId: { type: 'string' },
111 kind: { type: 'string', enum: ['input', 'output'] },
112 payload: { description: 'The payload to validate.' },
113 },
114 required: ['provider', 'endpointId', 'payload'],
115 },
116 },
117 {
118 name: 'estimate_cost',
119 description:
120 'Evaluate the stored rate card for a model. Pass request-bound levers in request and usage-bound levers (input_tokens, output_tokens, …) in usage. Returns { amount, currency, usd?, cardSource, estimated }: amount is in currency (ISO 4217, never converted) and usd (deprecated) repeats it only for a USD card. A non-empty estimated names omitted usage the card filled by the published estimate method of its source, so amount is then an estimate, not the billed price.',
121 inputSchema: {
122 type: 'object',
123 properties: {
124 provider: { type: 'string' },
125 model: { type: 'string' },
126 request: { type: 'object' },
127 usage: { type: 'object' },
128 },
129 required: ['provider', 'model'],
130 },
131 },
132 {
133 name: 'recent_changes',
134 description:
135 'Changelog feed of model/schema/endpoint changes (cursor-paginated, newest first). A model.updated payload includes changed: the fact paths that differ. A source hash, an extract time, and operand or values order are not changes.',
136 inputSchema: {
137 type: 'object',
138 properties: {
139 since: {
140 type: 'integer',
141 description: 'Unix epoch seconds lower bound.',
142 },
143 provider: { type: 'string' },
144 type: { type: 'string', enum: [...changeTypes] },
145 limit: { type: 'integer', minimum: 1, maximum: 200 },
146 cursor: { type: 'string' },
147 },
148 },
149 },
150]
151
152const isRecord = (value: unknown): value is Record<string, unknown> =>
153 typeof value === 'object' && value !== null && !Array.isArray(value)
154
155function rpcResult(id: JsonRpcRequest['id'], result: unknown) {
156 return { jsonrpc: '2.0' as const, id: id ?? null, result }
157}
158
159function rpcError(id: JsonRpcRequest['id'], code: number, message: string) {
160 return { jsonrpc: '2.0' as const, id: id ?? null, error: { code, message } }
161}
162
163function toolText(value: unknown, isError = false) {
164 return {
165 content: [{ type: 'text', text: JSON.stringify(value, null, 1) }],
166 isError,
167 }
168}
169
170async function callTool(
171 db: Db,
172 name: string,
173 args: Record<string, unknown>,
174): Promise<ReturnType<typeof toolText>> {
175 switch (name) {
176 case 'list_models': {
177 const result = await listModelsCatalog(db, {
178 activity: args.activity as Activity | undefined,
179 provider: args.provider as string | undefined,
180 capability: args.capability as string | undefined,
181 q: args.q as string | undefined,
182 })
183 return toolText(result)
184 }
185 case 'get_model': {
186 const model = await getModelDetail(
187 db,
188 String(args.provider ?? ''),
189 String(args.modelId ?? ''),
190 )
191 if (!model) {
192 return toolText(
193 {
194 error: 'unknown_model',
195 hint: 'Use list_models to find valid ids.',
196 },
197 true,
198 )
199 }
200 return toolText(model)
201 }
202 case 'list_schemas': {
203 const provider = args.provider as string | undefined
204 if (provider === undefined || provider === '') {
205 return toolText(await getSystemSchemaIndex(db))
206 }
207 if (!(await providerExists(db, provider))) {
208 return toolText(
209 {
210 error: 'unknown_provider',
211 hint: 'Call list_schemas without arguments for the full provider → endpoint index.',
212 },
213 true,
214 )
215 }
216 return toolText(await getProviderSchemaIndex(db, provider))
217 }
218 case 'get_schema': {
219 const kind = args.kind === 'output' ? 'output' : 'input'
220 const schema = await getEndpointSchema(
221 db,
222 String(args.provider ?? ''),
223 args.activity as Activity,
224 String(args.endpointId ?? ''),
225 kind,
226 args.version as string | undefined,
227 )
228 if (!schema) {
229 return toolText(
230 {
231 error: 'unknown_schema',
232 hint: 'Check provider/activity/endpointId; list endpoints via the schema index at /v1/schemas/{provider}.',
233 },
234 true,
235 )
236 }
237 return toolText(schema)
238 }
239 case 'validate_payload': {
240 const outcome = await validatePayload(db, {
241 provider: String(args.provider ?? ''),
242 endpointId: String(args.endpointId ?? ''),
243 kind: args.kind === 'output' ? 'output' : undefined,
244 payload: args.payload,
245 })
246 if (!outcome.ok) {
247 return toolText({ error: outcome.code, message: outcome.message }, true)
248 }
249 return toolText(outcome.result)
250 }
251 case 'estimate_cost': {
252 const outcome = await estimateCost(db, {
253 provider: String(args.provider ?? ''),
254 model: String(args.model ?? ''),
255 request: isRecord(args.request) ? args.request : undefined,
256 usage: isRecord(args.usage) ? args.usage : undefined,
257 })
258 if (!outcome.ok) {
259 return toolText({ error: outcome.code, message: outcome.message }, true)
260 }
261 return toolText(outcome.result)
262 }
263 case 'recent_changes': {
264 const outcome = await listChanges(db, {
265 since: args.since as number | undefined,
266 provider: args.provider as string | undefined,
267 type: args.type as ChangeType | undefined,
268 limit: args.limit as number | undefined,
269 cursor: args.cursor as string | undefined,
270 })
271 if (!outcome.ok) {
272 return toolText({ error: outcome.code, message: outcome.message }, true)
273 }
274 return toolText(outcome.result)
275 }
276 default:
277 return toolText(
278 {
279 error: 'unknown_tool',
280 message: `Unknown tool '${name}'. Available: ${TOOLS.map((t) => t.name).join(', ')}.`,
281 },
282 true,
283 )
284 }
285}
286
287/** Handle one MCP request (POST /mcp). */
288export async function handleMcpRequest(
289 db: Db,
290 request: Request,
291): Promise<Response> {
292 if (request.method === 'GET') {
293 // Stateless server: no SSE stream to subscribe to.
294 return new Response(null, { status: 405, headers: { Allow: 'POST' } })
295 }
296 if (request.method !== 'POST') {
297 return new Response(null, { status: 405, headers: { Allow: 'POST' } })
298 }
299
300 let rpc: JsonRpcRequest
301 try {
302 rpc = (await request.json()) as JsonRpcRequest
303 } catch {
304 return Response.json(rpcError(null, -32700, 'Parse error'), { status: 400 })
305 }
306
307 // Notifications get a body-less 202 per streamable HTTP.
308 if (rpc.method.startsWith('notifications/')) {
309 return new Response(null, { status: 202 })
310 }
311
312 switch (rpc.method) {
313 case 'initialize':
314 return Response.json(
315 rpcResult(rpc.id, {
316 protocolVersion: MCP_PROTOCOL_VERSION,
317 capabilities: { tools: {} },
318 serverInfo: {
319 name: 'modelschemas',
320 version: '0.1.0',
321 description:
322 'Live AI model schemas: catalog, JSON Schemas, validation, change feed.',
323 },
324 // Shared with the GET / narrative root (task 11.2) — one source.
325 instructions: llmsTxt,
326 }),
327 )
328 case 'ping':
329 return Response.json(rpcResult(rpc.id, {}))
330 case 'tools/list':
331 return Response.json(rpcResult(rpc.id, { tools: TOOLS }))
332 case 'tools/call': {
333 const name = String(rpc.params?.name ?? '')
334 const args = (rpc.params?.arguments ?? {}) as Record<string, unknown>
335 return Response.json(rpcResult(rpc.id, await callTool(db, name, args)))
336 }
337 default:
338 return Response.json(
339 rpcError(rpc.id, -32601, `Method not found: ${rpc.method}`),
340 )
341 }
342}