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