@kizunajs/mcp 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,705 @@
1
+ import { z } from "zod";
2
+ import { createPlugin } from "kizunajs/plugin";
3
+ import { ProtectedResourceMetadataSchema } from "kizunajs/schemas";
4
+ import { assertCanonicalResourceUri, buildProtectedResourceMetadata, declaredScopes, problemDetails, problemFromBody, routeStreams } from "kizunajs";
5
+ import { McpServer, acceptedContent, createMcpHandler, inputRequired } from "@modelcontextprotocol/server";
6
+ import { GUARDS_META, GUARD_SCHEMA_META, REQUEST_CONTEXT_META, ROUTER_META, ResponseError, SCHEMES_META, adapterContextOf, bearerChallenge, contractOf, extractCredential, flattenRoutes, guardDenyFor, insufficientScope, isGuardDenial, parsePath, rawResponse, requiresDenial, resolveSecurityRequirements, validateRequest, withPermissions } from "kizunajs/adapter";
7
+ import { deriveToolNames, isJsonMediaType, isStreamResponse, isSuccessStatus, isVoidSchema, readObjectShape, resolveResponseBody, resolveResponseContentType } from "kizunajs/generator";
8
+ //#region src/oauth.ts
9
+ const protectedResourceMetadataPath = (endpointPath) => `/.well-known/oauth-protected-resource${endpointPath}`;
10
+ /**
11
+ * Absolute URL the metadata route is served at: the resource's origin, any
12
+ * mount prefix the resource path carries, then the well-known path.
13
+ */
14
+ const protectedResourceMetadataUrl = (oauth, endpointPath) => {
15
+ const resource = new URL(oauth.resource);
16
+ const mountPrefix = resource.pathname.slice(0, resource.pathname.length - endpointPath.length);
17
+ return `${resource.origin}${mountPrefix}${protectedResourceMetadataPath(endpointPath)}`;
18
+ };
19
+ const assertCanonicalResource = (oauth, endpointPath) => {
20
+ assertCanonicalResourceUri(oauth.resource);
21
+ if (!new URL(oauth.resource).pathname.endsWith(endpointPath)) throw new Error(`The oauth resource "${oauth.resource}" does not end with the endpoint path "${endpointPath}".`);
22
+ };
23
+ //#endregion
24
+ //#region src/method.ts
25
+ /**
26
+ * Safe per RFC 9110: they request no change to the server's state.
27
+ */
28
+ const SAFE_METHODS = new Set([
29
+ "GET",
30
+ "HEAD",
31
+ "OPTIONS"
32
+ ]);
33
+ /**
34
+ * Idempotent per RFC 9110: repeating one has the same effect as making it once.
35
+ * Every safe method is idempotent.
36
+ */
37
+ const IDEMPOTENT_METHODS = new Set([
38
+ "GET",
39
+ "HEAD",
40
+ "OPTIONS",
41
+ "PUT",
42
+ "DELETE"
43
+ ]);
44
+ const isSafeMethod = (method) => SAFE_METHODS.has(method);
45
+ const isIdempotentMethod = (method) => IDEMPOTENT_METHODS.has(method);
46
+ //#endregion
47
+ //#region src/schema.ts
48
+ const buildToolInputSchema = (route) => {
49
+ const shape = {};
50
+ let hasParams = false;
51
+ let hasQuery = false;
52
+ let hasBody = false;
53
+ const paramNames = parsePath(route.path).paramNames;
54
+ if (paramNames.length > 0) {
55
+ hasParams = true;
56
+ const paramShape = {};
57
+ const explicitShape = route.pathParams ? readObjectShape(route.pathParams) : void 0;
58
+ for (const name of paramNames) paramShape[name] = explicitShape?.[name] ?? z.string();
59
+ shape["params"] = z.object(paramShape);
60
+ }
61
+ if (route.query) {
62
+ hasQuery = true;
63
+ shape["query"] = route.query.safeParse({}).success ? route.query.optional() : route.query;
64
+ }
65
+ if (route.body && !isVoidSchema(route.body)) {
66
+ hasBody = true;
67
+ shape["body"] = route.body.safeParse(void 0).success ? route.body.optional() : route.body;
68
+ }
69
+ if (Object.keys(shape).length === 0) return {
70
+ shape: void 0,
71
+ hasParams,
72
+ hasQuery,
73
+ hasBody
74
+ };
75
+ return {
76
+ shape,
77
+ hasParams,
78
+ hasQuery,
79
+ hasBody
80
+ };
81
+ };
82
+ /**
83
+ * The `{ status, body }` envelope a tool returns, with `body` carrying the
84
+ * route's JSON success bodies. A route with none gets `status` alone.
85
+ */
86
+ const buildToolOutputSchema = (route) => {
87
+ const bodies = [];
88
+ let someSuccessHasNoBody = false;
89
+ for (const status of Object.keys(route.responses).map(Number).sort((left, right) => left - right)) {
90
+ if (!isSuccessStatus(status)) continue;
91
+ const response = route.responses[status];
92
+ if (response === void 0) continue;
93
+ const contentType = resolveResponseContentType(response);
94
+ if (isStreamResponse(response) || contentType !== void 0 && !isJsonMediaType(contentType)) {
95
+ someSuccessHasNoBody = true;
96
+ continue;
97
+ }
98
+ const body = resolveResponseBody(response);
99
+ if (isVoidSchema(body)) {
100
+ someSuccessHasNoBody = true;
101
+ continue;
102
+ }
103
+ bodies.push(body);
104
+ }
105
+ const status = z.int().describe("The HTTP status the route answered with");
106
+ if (bodies.length === 0) return z.object({ status });
107
+ const body = bodies.length === 1 ? bodies[0] : z.union(bodies);
108
+ return z.object({
109
+ status,
110
+ body: someSuccessHasNoBody ? body.optional() : body
111
+ });
112
+ };
113
+ //#endregion
114
+ //#region src/tool-selection.ts
115
+ /**
116
+ * Tool input is JSON, so a route that reads a form body has nothing to receive
117
+ * it.
118
+ */
119
+ const takesJsonInput = (route) => route.contentType === void 0 || route.contentType === "application/json";
120
+ /**
121
+ * What a route says about publishing itself, or `undefined` when it says
122
+ * nothing.
123
+ */
124
+ const toolOptionsOf = (route) => {
125
+ if (route.tool === void 0 || route.tool === false) return void 0;
126
+ return route.tool === true ? {} : route.tool;
127
+ };
128
+ /**
129
+ * The routes a model may call: the ones that declared `tool`, less the ones
130
+ * whose shape a tool call cannot carry.
131
+ */
132
+ const selectToolRoutes = (routes) => routes.filter(({ route }) => {
133
+ if (toolOptionsOf(route) === void 0) return false;
134
+ return takesJsonInput(route) && !routeStreams(route);
135
+ });
136
+ //#endregion
137
+ //#region src/mcp-server.ts
138
+ /**
139
+ * Hints from the method's HTTP semantics, per RFC 9110. MCP already defaults
140
+ * `destructiveHint` and `openWorldHint` to true, so only the hints that make a
141
+ * tool safer than that are worth setting.
142
+ */
143
+ /**
144
+ * What the elicitation answer comes back under, and the key the retry echoes.
145
+ */
146
+ const CONFIRM_KEY = "confirm";
147
+ /**
148
+ * Ask before running, when the route said to. Returns what the caller should
149
+ * answer with instead of running: the elicitation on the first call, a refusal
150
+ * when the person declined, and nothing once they have agreed.
151
+ */
152
+ const confirmed = (route, context) => {
153
+ const message = toolOptionsOf(route)?.confirm;
154
+ if (message === void 0) return void 0;
155
+ const answer = acceptedContent(context.mcpReq?.inputResponses, CONFIRM_KEY);
156
+ if (answer === void 0) return inputRequired({ inputRequests: { [CONFIRM_KEY]: inputRequired.elicit({
157
+ message,
158
+ requestedSchema: {
159
+ type: "object",
160
+ properties: { confirm: {
161
+ type: "boolean",
162
+ title: "Go ahead"
163
+ } },
164
+ required: [CONFIRM_KEY]
165
+ }
166
+ }) } });
167
+ if (answer.confirm === true) return void 0;
168
+ return {
169
+ content: [{
170
+ type: "text",
171
+ text: "Declined, so nothing ran."
172
+ }],
173
+ isError: true
174
+ };
175
+ };
176
+ /**
177
+ * What the route says about itself, over what its method already implies.
178
+ */
179
+ const buildToolAnnotations = (route) => {
180
+ const declared = toolOptionsOf(route) ?? {};
181
+ return {
182
+ ...isSafeMethod(route.method) ? { readOnlyHint: true } : {},
183
+ ...isIdempotentMethod(route.method) ? { idempotentHint: true } : {},
184
+ ...route.method === "DELETE" ? { destructiveHint: true } : {},
185
+ ...declared.title === void 0 ? {} : { title: declared.title },
186
+ ...declared.readOnlyHint === void 0 ? {} : { readOnlyHint: declared.readOnlyHint },
187
+ ...declared.idempotentHint === void 0 ? {} : { idempotentHint: declared.idempotentHint },
188
+ ...declared.destructiveHint === void 0 ? {} : { destructiveHint: declared.destructiveHint },
189
+ ...declared.openWorldHint === void 0 ? {} : { openWorldHint: declared.openWorldHint }
190
+ };
191
+ };
192
+ const describeRoles = (route) => route.roles !== void 0 && route.roles.length > 0 ? `Roles: ${route.roles.join(", ")}` : void 0;
193
+ const describeRequires = (route) => {
194
+ const requires = route.requires;
195
+ if (requires === void 0) return void 0;
196
+ const names = Object.entries(requires).flatMap(([resource, verbs]) => verbs.map((verb) => `${resource}:${verb}`));
197
+ return names.length > 0 ? `Permissions: ${names.join(", ")}` : void 0;
198
+ };
199
+ const buildToolDescription = (route) => {
200
+ const parts = [];
201
+ const declared = toolOptionsOf(route)?.description;
202
+ if (declared) parts.push(declared);
203
+ else if (route.summary) parts.push(route.summary);
204
+ if (route.description) parts.push(route.description);
205
+ if (parts.length === 0) parts.push(`${route.method} ${route.path}`);
206
+ parts.push(`\nHTTP: ${route.method} ${route.path}`);
207
+ const requirements = resolveSecurityRequirements(route);
208
+ if (requirements.length > 0) parts.push(`Requires: ${requirements.map(({ scheme }) => scheme).join(", ")}`);
209
+ const roles = describeRoles(route);
210
+ if (roles !== void 0) parts.push(roles);
211
+ const permissions = describeRequires(route);
212
+ if (permissions !== void 0) parts.push(permissions);
213
+ return parts.join("\n");
214
+ };
215
+ const buildToolDefinitions = (routes) => {
216
+ const selected = selectToolRoutes(flattenRoutes(routes));
217
+ const names = deriveToolNames(selected.map(({ routeKey }) => ({
218
+ key: routeKey,
219
+ origin: "route"
220
+ })));
221
+ const definitions = [];
222
+ for (const { routeKey, route, routeTags } of selected) {
223
+ const name = names.get(routeKey);
224
+ definitions.push({
225
+ name,
226
+ title: route.summary,
227
+ description: buildToolDescription(route),
228
+ inputSchema: buildToolInputSchema(route),
229
+ outputSchema: buildToolOutputSchema(route),
230
+ route,
231
+ routeKey,
232
+ tags: routeTags
233
+ });
234
+ }
235
+ return definitions;
236
+ };
237
+ /**
238
+ * What a client puts in front of the model before it picks a tool.
239
+ */
240
+ const buildInstructions = (contract, definitions, authored) => {
241
+ const sections = [];
242
+ if (definitions.length > 0) sections.push("Every tool named after an HTTP route returns `{ status, body }`. A status of 400 or more means the call failed.");
243
+ const tags = contract?.tags?.tags;
244
+ if (tags !== void 0) {
245
+ const exposed = new Set(definitions.flatMap((definition) => definition.tags));
246
+ const groups = Object.entries(tags).filter(([key]) => exposed.has(key)).map(([, tag]) => tag.description ? `- ${tag.title}: ${tag.description}` : `- ${tag.title}`);
247
+ if (groups.length > 0) sections.push(`Groups:\n${groups.join("\n")}`);
248
+ }
249
+ if (authored) sections.push(authored);
250
+ return sections.join("\n\n");
251
+ };
252
+ const resolveHandler = (router, routeKey) => {
253
+ const segments = routeKey.split(".");
254
+ let current = router;
255
+ for (const segment of segments) {
256
+ if (!current || typeof current !== "object") return void 0;
257
+ current = current[segment];
258
+ }
259
+ return current;
260
+ };
261
+ /**
262
+ * The `{ status, body }` envelope every tool returns. A success also rides
263
+ * along as `structuredContent`, matching the advertised output schema.
264
+ */
265
+ const toolEnvelope = (status, body) => {
266
+ const envelope = {
267
+ status,
268
+ body
269
+ };
270
+ const isError = status >= 400;
271
+ return {
272
+ content: [{
273
+ type: "text",
274
+ text: JSON.stringify(envelope, null, 2)
275
+ }],
276
+ ...isError ? {} : { structuredContent: envelope },
277
+ isError
278
+ };
279
+ };
280
+ const toolError = (status, body) => ({
281
+ content: [{
282
+ type: "text",
283
+ text: JSON.stringify({
284
+ status,
285
+ body
286
+ }, null, 2)
287
+ }],
288
+ isError: true
289
+ });
290
+ /**
291
+ * Resolve every request context declared on the api, the way the HTTP
292
+ * pipeline does, reading the headers of the transport request. Guards and
293
+ * handlers both read the result.
294
+ */
295
+ const resolveRequestContext = async (contextResolvers, params, credentialHeaders, handlerContext) => {
296
+ const resolved = {};
297
+ if (!contextResolvers) return resolved;
298
+ for (const [name, resolver] of Object.entries(contextResolvers)) resolved[name] = await resolver({
299
+ ...handlerContext ?? {},
300
+ params,
301
+ headers: credentialHeaders ?? {}
302
+ });
303
+ return resolved;
304
+ };
305
+ const gateBody = (guardSchema, detail) => {
306
+ const filled = guardSchema?.safeParse(problemDetails(403, detail));
307
+ return filled?.success ? filled.data : { detail };
308
+ };
309
+ /**
310
+ * Run the guards a secured route requires, extracting each identity's
311
+ * credential from the MCP transport request headers, the same pipeline the
312
+ * HTTP adapters run. Returns the scheme-keyed security context for the handler
313
+ * args, or a {@link ToolCallResult} error when a guard denies or the caller's
314
+ * role is not one the route accepts or does not hold what it requires.
315
+ */
316
+ const runGuards = async (requirements, roles, requires, label, params, guards, schemes, handlerContext, credentialHeaders, requestContext, transportAuth, guardSchema) => {
317
+ const securityContext = {};
318
+ const credentialRequest = {
319
+ headers: credentialHeaders ?? {},
320
+ query: {}
321
+ };
322
+ for (const { scheme } of requirements) {
323
+ if (scheme === transportAuth?.scheme) {
324
+ if (transportAuth.context !== void 0) securityContext[scheme] = withPermissions(scheme, schemes?.[scheme], transportAuth.context);
325
+ continue;
326
+ }
327
+ const guard = guards?.[scheme];
328
+ if (!guard) return {
329
+ ok: false,
330
+ result: toolError(500, { detail: `No guard registered for security scheme "${scheme}" required by ${label}.` })
331
+ };
332
+ const schemeDefinition = schemes?.[scheme];
333
+ const credential = schemeDefinition ? extractCredential(schemeDefinition, credentialRequest) : {};
334
+ const guardResult = await guard({
335
+ ...handlerContext ?? {},
336
+ ...credential,
337
+ params,
338
+ deny: guardDenyFor(schemeDefinition),
339
+ ...Object.keys(requestContext).length > 0 ? { requestContext } : {}
340
+ });
341
+ if (isGuardDenial(guardResult)) return {
342
+ ok: false,
343
+ result: toolError(guardResult.status, guardResult.body)
344
+ };
345
+ if (guardResult && typeof guardResult === "object") securityContext[scheme] = withPermissions(scheme, schemeDefinition, guardResult);
346
+ }
347
+ const forbidden = requiresDenial({
348
+ roles,
349
+ requires,
350
+ requiredSchemes: requirements.map((requirement) => requirement.scheme),
351
+ schemes,
352
+ securityContext
353
+ });
354
+ if (forbidden !== void 0) return {
355
+ ok: false,
356
+ result: toolError(403, gateBody(guardSchema, forbidden))
357
+ };
358
+ return {
359
+ ok: true,
360
+ securityContext
361
+ };
362
+ };
363
+ const executeToolCall = async (route, routeKey, args, router, handlerContext, guards, schemes, credentialHeaders, contextResolvers, transportAuth, guardSchema) => {
364
+ const params = args.params ?? {};
365
+ const query = args.query ?? {};
366
+ const body = args.body;
367
+ const validation = validateRequest(route, {
368
+ params,
369
+ query,
370
+ body,
371
+ headers: {}
372
+ });
373
+ if (!validation.ok) return {
374
+ content: [{
375
+ type: "text",
376
+ text: JSON.stringify({
377
+ status: 400,
378
+ body: {
379
+ detail: `Validation failed: ${validation.error.stage}`,
380
+ errors: validation.error.issues
381
+ }
382
+ }, null, 2)
383
+ }],
384
+ isError: true
385
+ };
386
+ const handler = resolveHandler(router, routeKey);
387
+ if (typeof handler !== "function") return {
388
+ content: [{
389
+ type: "text",
390
+ text: JSON.stringify({
391
+ status: 500,
392
+ body: { detail: `Handler not implemented: ${routeKey}` }
393
+ }, null, 2)
394
+ }],
395
+ isError: true
396
+ };
397
+ const requestContext = await resolveRequestContext(contextResolvers, params, credentialHeaders, handlerContext);
398
+ const guardOutcome = await runGuards(resolveSecurityRequirements(route), route.roles, route.requires, `route "${routeKey}"`, params, guards, schemes, handlerContext, credentialHeaders, requestContext, transportAuth, guardSchema);
399
+ if (!guardOutcome.ok) return guardOutcome.result;
400
+ try {
401
+ const throwError = (response) => {
402
+ throw new ResponseError(response);
403
+ };
404
+ const result = await handler({
405
+ params: validation.parsed.params,
406
+ query: validation.parsed.query,
407
+ body: validation.parsed.body,
408
+ headers: validation.parsed.headers,
409
+ throwError,
410
+ ...handlerContext,
411
+ ...Object.keys(requestContext).length > 0 ? { requestContext } : {},
412
+ ...Object.keys(guardOutcome.securityContext).length > 0 ? { auth: guardOutcome.securityContext } : {}
413
+ });
414
+ return toolEnvelope(result.status, result.body);
415
+ } catch (error) {
416
+ if (error instanceof ResponseError) return toolEnvelope(error.status, error.body);
417
+ return {
418
+ content: [{
419
+ type: "text",
420
+ text: JSON.stringify({
421
+ status: 500,
422
+ body: { detail: error instanceof Error ? error.message : "Internal Server Error" }
423
+ }, null, 2)
424
+ }],
425
+ isError: true
426
+ };
427
+ }
428
+ };
429
+ /**
430
+ * Create an MCP server from a kizuna API.
431
+ *
432
+ * Each route in the routes becomes an MCP tool. When an AI assistant calls
433
+ * a tool, the corresponding handler is invoked directly.
434
+ *
435
+ * ```ts
436
+ * import { createMcpServer } from '@kizunajs/mcp';
437
+ * import { api } from './api';
438
+ *
439
+ * const server = createMcpServer(api);
440
+ * ```
441
+ */
442
+ const createMcpServer = (api, options) => {
443
+ const router = api[ROUTER_META];
444
+ const guards = api[GUARDS_META];
445
+ const schemes = api[SCHEMES_META];
446
+ const guardSchema = api[GUARD_SCHEMA_META];
447
+ const contextResolvers = api[REQUEST_CONTEXT_META];
448
+ const contract = contractOf(api);
449
+ const definitions = buildToolDefinitions(api.routes);
450
+ const server = new McpServer({
451
+ name: options?.name ?? "MCP Server",
452
+ version: options?.version ?? "1.0.0"
453
+ }, { instructions: buildInstructions(contract, definitions, options?.instructions) });
454
+ for (const definition of definitions) server.registerTool(definition.name, {
455
+ ...definition.title === void 0 ? {} : { title: definition.title },
456
+ description: definition.description,
457
+ inputSchema: definition.inputSchema.shape === void 0 ? void 0 : z.object(definition.inputSchema.shape),
458
+ outputSchema: definition.outputSchema,
459
+ annotations: buildToolAnnotations(definition.route)
460
+ }, async (args, context) => {
461
+ const refusal = confirmed(definition.route, context);
462
+ if (refusal !== void 0) return refusal;
463
+ return executeToolCall(definition.route, definition.routeKey, args ?? {}, router, options?.handlerContext, guards, schemes, options?.credentialHeaders, contextResolvers, options?.transportAuth, guardSchema);
464
+ });
465
+ return server;
466
+ };
467
+ //#endregion
468
+ //#region src/oauth-enforcement.ts
469
+ const forbiddenBody = (guardSchema, detail) => {
470
+ const filled = guardSchema?.safeParse(problemDetails(403, detail));
471
+ return filled?.success ? filled.data : { detail };
472
+ };
473
+ const joined = (scopes) => scopes.length > 0 ? scopes.join(" ") : void 0;
474
+ /**
475
+ * Run the oauth guard for one transport request and answer the verified
476
+ * context, or the HTTP denial the MCP authorization specification requires.
477
+ */
478
+ const enforceOAuth = async (args) => {
479
+ const credentialRequest = {
480
+ headers: args.headers,
481
+ query: {}
482
+ };
483
+ const credential = extractCredential(args.schemeDefinition, credentialRequest);
484
+ const presented = Object.values(credential).some((value) => value !== null);
485
+ const guardResult = await args.guard({
486
+ ...args.handlerContext,
487
+ ...credential,
488
+ params: args.params,
489
+ deny: guardDenyFor(args.schemeDefinition),
490
+ ...args.requestContext && Object.keys(args.requestContext).length > 0 ? { requestContext: args.requestContext } : {}
491
+ });
492
+ if (isGuardDenial(guardResult)) {
493
+ const challenge = guardResult.status === 401 ? bearerChallenge({
494
+ ...presented ? {
495
+ error: "invalid_token",
496
+ error_description: guardResult.body.detail
497
+ } : {},
498
+ resource_metadata: args.metadataUrl,
499
+ scope: joined(args.scopes) ?? joined(args.scopesSupported ?? [])
500
+ }) : void 0;
501
+ return {
502
+ ok: false,
503
+ denial: {
504
+ status: guardResult.status,
505
+ body: guardResult.body,
506
+ challenge
507
+ }
508
+ };
509
+ }
510
+ const context = guardResult && typeof guardResult === "object" ? withPermissions(args.scheme, args.schemeDefinition, guardResult) : void 0;
511
+ const accessCheck = {
512
+ roles: args.roles,
513
+ requires: args.requires,
514
+ requiredSchemes: [args.scheme],
515
+ schemes: { [args.scheme]: args.schemeDefinition },
516
+ securityContext: { [args.scheme]: context ?? {} }
517
+ };
518
+ const forbidden = requiresDenial(accessCheck);
519
+ if (forbidden !== void 0) {
520
+ const missingScope = insufficientScope(accessCheck);
521
+ return {
522
+ ok: false,
523
+ denial: {
524
+ status: 403,
525
+ body: forbiddenBody(args.guardSchema, forbidden),
526
+ ...missingScope.length > 0 ? { challenge: bearerChallenge({
527
+ error: "insufficient_scope",
528
+ scope: missingScope.join(" "),
529
+ resource_metadata: args.metadataUrl
530
+ }) } : {}
531
+ }
532
+ };
533
+ }
534
+ return {
535
+ ok: true,
536
+ context
537
+ };
538
+ };
539
+ const denialResponse = (denial) => rawResponse(new Response(JSON.stringify(problemFromBody(denial.status, denial.body)), {
540
+ status: denial.status,
541
+ headers: {
542
+ "content-type": "application/problem+json",
543
+ ...denial.challenge === void 0 ? {} : { "www-authenticate": denial.challenge }
544
+ }
545
+ }));
546
+ //#endregion
547
+ //#region src/server.ts
548
+ const toHeaders = (headers) => {
549
+ const built = new Headers();
550
+ for (const [name, value] of Object.entries(headers)) {
551
+ if (value === void 0) continue;
552
+ for (const entry of Array.isArray(value) ? value : [value]) built.append(name, entry);
553
+ }
554
+ return built;
555
+ };
556
+ const prepareOAuth = (oauth, endpointPath, api) => {
557
+ assertCanonicalResource(oauth, endpointPath);
558
+ const guards = api[GUARDS_META];
559
+ const schemes = api[SCHEMES_META];
560
+ const guard = guards?.[oauth.scheme];
561
+ if (guard === void 0) throw new Error(`No guard registered for security scheme "${oauth.scheme}" required by the MCP plugin's oauth configuration.`);
562
+ const schemeDefinition = schemes?.[oauth.scheme];
563
+ if (schemeDefinition === void 0) throw new Error(`No identity named "${oauth.scheme}" is registered for the MCP plugin's oauth configuration.`);
564
+ return {
565
+ oauth,
566
+ guard,
567
+ schemeDefinition,
568
+ schemes,
569
+ metadata: buildProtectedResourceMetadata({
570
+ resource: oauth.resource,
571
+ scheme: schemeDefinition
572
+ }),
573
+ metadataUrl: protectedResourceMetadataUrl(oauth, endpointPath),
574
+ scopesSupported: declaredScopes(schemeDefinition),
575
+ tools: new Map(buildToolDefinitions(api.routes).map((definition) => [definition.name, definition]))
576
+ };
577
+ };
578
+ /**
579
+ * The oauth scheme's requirement for the tool a `tools/call` body names, so
580
+ * the challenge speaks about the operation the client is attempting. The
581
+ * route's `roles` and `requires` ride along when the oauth identity is the only one on
582
+ * the route whose roles can satisfy it; otherwise the tool call checks it,
583
+ * with every guard's role in hand.
584
+ */
585
+ const toolCallTarget = (body, enforcement) => {
586
+ if (body !== null && typeof body === "object" && body.method === "tools/call") {
587
+ const callParams = body.params;
588
+ const definition = typeof callParams?.name === "string" ? enforcement.tools.get(callParams.name) : void 0;
589
+ if (definition !== void 0) {
590
+ const requirements = resolveSecurityRequirements(definition.route);
591
+ const requirement = requirements.find((candidate) => candidate.scheme === enforcement.oauth.scheme);
592
+ const oauthDecidesRequires = requirements.filter((candidate) => enforcement.schemes?.[candidate.scheme]?.roles !== void 0).every((candidate) => candidate.scheme === enforcement.oauth.scheme);
593
+ const routeParams = callParams?.arguments?.params;
594
+ return {
595
+ scopes: requirement?.scopes ?? [],
596
+ roles: requirement !== void 0 && oauthDecidesRequires ? definition.route.roles : void 0,
597
+ requires: requirement !== void 0 && oauthDecidesRequires ? definition.route.requires : void 0,
598
+ params: routeParams !== null && typeof routeParams === "object" ? routeParams : {}
599
+ };
600
+ }
601
+ }
602
+ return {
603
+ scopes: [],
604
+ roles: void 0,
605
+ requires: void 0,
606
+ params: {}
607
+ };
608
+ };
609
+ /**
610
+ * What answers the MCP endpoint: the tool list built from the routes that
611
+ * declared `tool`, and the calls a model makes against them.
612
+ */
613
+ const mcpServe = (props, api) => {
614
+ const serverApi = api;
615
+ const enforcement = props.oauth === void 0 ? void 0 : prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
616
+ return { router: {
617
+ endpoint: async (args) => {
618
+ let transportAuth;
619
+ if (enforcement !== void 0) {
620
+ const target = toolCallTarget(args.body, enforcement);
621
+ const outcome = await enforceOAuth({
622
+ scheme: enforcement.oauth.scheme,
623
+ guard: enforcement.guard,
624
+ schemeDefinition: enforcement.schemeDefinition,
625
+ metadataUrl: enforcement.metadataUrl,
626
+ scopesSupported: enforcement.scopesSupported,
627
+ scopes: target.scopes,
628
+ roles: target.roles,
629
+ requires: target.requires,
630
+ params: target.params,
631
+ headers: args.headers,
632
+ handlerContext: adapterContextOf(args),
633
+ requestContext: args.requestContext
634
+ });
635
+ if (!outcome.ok) return denialResponse(outcome.denial);
636
+ transportAuth = {
637
+ scheme: enforcement.oauth.scheme,
638
+ ...outcome.context === void 0 ? {} : { context: outcome.context }
639
+ };
640
+ }
641
+ return rawResponse(await createMcpHandler(() => createMcpServer(serverApi, {
642
+ ...props,
643
+ handlerContext: adapterContextOf(args),
644
+ credentialHeaders: args.headers,
645
+ ...transportAuth === void 0 ? {} : { transportAuth }
646
+ })).fetch(new Request("http://mcp.local/", {
647
+ method: "POST",
648
+ headers: toHeaders(args.headers),
649
+ body: JSON.stringify(args.body)
650
+ })));
651
+ },
652
+ ...enforcement === void 0 ? {} : { protectedResourceMetadata: () => rawResponse(new Response(JSON.stringify(enforcement.metadata), {
653
+ status: 200,
654
+ headers: { "content-type": "application/json" }
655
+ })) }
656
+ } };
657
+ };
658
+ //#endregion
659
+ //#region src/plugin.ts
660
+ const declare = (slug, props) => {
661
+ const endpointPath = props.path ?? "/mcp";
662
+ return createPlugin({
663
+ slug,
664
+ routes: {
665
+ endpoint: {
666
+ method: "POST",
667
+ path: endpointPath,
668
+ summary: "MCP (Model Context Protocol) endpoint",
669
+ body: z.unknown(),
670
+ responses: { 200: z.unknown() }
671
+ },
672
+ ...props.oauth === void 0 ? {} : { protectedResourceMetadata: {
673
+ method: "GET",
674
+ path: protectedResourceMetadataPath(endpointPath),
675
+ summary: "OAuth protected resource metadata",
676
+ responses: { 200: ProtectedResourceMetadataSchema }
677
+ } }
678
+ },
679
+ props,
680
+ serve: (pluginProps, api) => mcpServe(pluginProps, api)
681
+ });
682
+ };
683
+ /**
684
+ * Let AI assistants use the API. Serves an MCP (Model Context Protocol)
685
+ * endpoint where every route declaring `tool` is one an assistant can discover
686
+ * and call, behind the same guards as the HTTP endpoints.
687
+ *
688
+ * The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
689
+ * adapter, and it stays out of `api.routes` so the client and the generators do
690
+ * not see it.
691
+ *
692
+ * @example
693
+ * ```ts
694
+ * export default defineConfig({
695
+ * routes,
696
+ * plugins: [mcpPlugin({ name: 'My API' })],
697
+ * });
698
+ * ```
699
+ */
700
+ function mcpPlugin(props) {
701
+ const settings = props ?? {};
702
+ return declare(settings.slug ?? "mcp", settings);
703
+ }
704
+ //#endregion
705
+ export { buildInstructions, buildToolDefinitions, createMcpServer, mcpPlugin };