@kizunajs/mcp 2.0.0-beta.3 → 2.0.0-beta.31

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.cjs CHANGED
@@ -7,6 +7,19 @@ let _modelcontextprotocol_server = require("@modelcontextprotocol/server");
7
7
  let kizunajs_adapter = require("kizunajs/adapter");
8
8
  let kizunajs_generator = require("kizunajs/generator");
9
9
  //#region src/oauth.ts
10
+ const McpOAuthSchema = zod.z.object({
11
+ /**
12
+ * Canonical URI of the MCP endpoint as clients reach it: absolute, no
13
+ * fragment, ending in the endpoint's `path`. The RFC 9728 `resource`
14
+ * value and the RFC 8707 audience your guard checks tokens against.
15
+ */
16
+ resource: zod.z.string(),
17
+ /**
18
+ * Name of the identity whose guard verifies the token on every request.
19
+ * Its `issuer` and flow scopes become the metadata document.
20
+ */
21
+ scheme: zod.z.string()
22
+ });
10
23
  const protectedResourceMetadataPath = (endpointPath) => `/.well-known/oauth-protected-resource${endpointPath}`;
11
24
  /**
12
25
  * Absolute URL the metadata route is served at: the resource's origin, any
@@ -46,40 +59,6 @@ const isSafeMethod = (method) => SAFE_METHODS.has(method);
46
59
  const isIdempotentMethod = (method) => IDEMPOTENT_METHODS.has(method);
47
60
  //#endregion
48
61
  //#region src/schema.ts
49
- const buildToolInputSchema = (route) => {
50
- const shape = {};
51
- let hasParams = false;
52
- let hasQuery = false;
53
- let hasBody = false;
54
- const paramNames = (0, kizunajs_adapter.parsePath)(route.path).paramNames;
55
- if (paramNames.length > 0) {
56
- hasParams = true;
57
- const paramShape = {};
58
- const explicitShape = route.pathParams ? (0, kizunajs_generator.readObjectShape)(route.pathParams) : void 0;
59
- for (const name of paramNames) paramShape[name] = explicitShape?.[name] ?? zod.z.string();
60
- shape["params"] = zod.z.object(paramShape);
61
- }
62
- if (route.query) {
63
- hasQuery = true;
64
- shape["query"] = route.query.safeParse({}).success ? route.query.optional() : route.query;
65
- }
66
- if (route.body && !(0, kizunajs_generator.isVoidSchema)(route.body)) {
67
- hasBody = true;
68
- shape["body"] = route.body.safeParse(void 0).success ? route.body.optional() : route.body;
69
- }
70
- if (Object.keys(shape).length === 0) return {
71
- shape: void 0,
72
- hasParams,
73
- hasQuery,
74
- hasBody
75
- };
76
- return {
77
- shape,
78
- hasParams,
79
- hasQuery,
80
- hasBody
81
- };
82
- };
83
62
  /**
84
63
  * The `{ status, body }` envelope a tool returns, with `body` carrying the
85
64
  * route's JSON success bodies. A route with none gets `status` alone.
@@ -112,29 +91,6 @@ const buildToolOutputSchema = (route) => {
112
91
  });
113
92
  };
114
93
  //#endregion
115
- //#region src/tool-selection.ts
116
- /**
117
- * Tool input is JSON, so a route that reads a form body has nothing to receive
118
- * it.
119
- */
120
- const takesJsonInput = (route) => route.contentType === void 0 || route.contentType === "application/json";
121
- /**
122
- * What a route says about publishing itself, or `undefined` when it says
123
- * nothing.
124
- */
125
- const toolOptionsOf = (route) => {
126
- if (route.tool === void 0 || route.tool === false) return void 0;
127
- return route.tool === true ? {} : route.tool;
128
- };
129
- /**
130
- * The routes a model may call: the ones that declared `tool`, less the ones
131
- * whose shape a tool call cannot carry.
132
- */
133
- const selectToolRoutes = (routes) => routes.filter(({ route }) => {
134
- if (toolOptionsOf(route) === void 0) return false;
135
- return takesJsonInput(route) && !(0, kizunajs.routeStreams)(route);
136
- });
137
- //#endregion
138
94
  //#region src/mcp-server.ts
139
95
  /**
140
96
  * Hints from the method's HTTP semantics, per RFC 9110. MCP already defaults
@@ -144,28 +100,36 @@ const selectToolRoutes = (routes) => routes.filter(({ route }) => {
144
100
  /**
145
101
  * What the elicitation answer comes back under, and the key the retry echoes.
146
102
  */
147
- const CONFIRM_KEY = "confirm";
103
+ const APPROVAL_KEY = "approved";
104
+ /**
105
+ * How long a client may keep the tool list. It changes only when the app
106
+ * deploys. `private`, because the endpoint may sit behind a credential a shared
107
+ * cache should not answer for.
108
+ */
109
+ const TOOL_LIST_CACHE = {
110
+ ttlMs: 300 * 1e3,
111
+ cacheScope: "private"
112
+ };
148
113
  /**
149
- * Ask before running, when the route said to. Returns what the caller should
150
- * answer with instead of running: the elicitation on the first call, a refusal
151
- * when the person declined, and nothing once they have agreed.
114
+ * Ask the person before running, when the call needs approval. Returns the
115
+ * elicitation on the first call, a refusal when they declined, and nothing once
116
+ * they approved.
152
117
  */
153
- const confirmed = (route, context) => {
154
- const message = toolOptionsOf(route)?.confirm;
155
- if (message === void 0) return void 0;
156
- const answer = (0, _modelcontextprotocol_server.acceptedContent)(context.mcpReq?.inputResponses, CONFIRM_KEY);
157
- if (answer === void 0) return (0, _modelcontextprotocol_server.inputRequired)({ inputRequests: { [CONFIRM_KEY]: _modelcontextprotocol_server.inputRequired.elicit({
158
- message,
118
+ const approval = (route, context) => {
119
+ if ((0, kizunajs_adapter.toolOptionsOf)(route)?.needsApproval !== true) return void 0;
120
+ const answer = (0, _modelcontextprotocol_server.acceptedContent)(context.mcpReq?.inputResponses, APPROVAL_KEY);
121
+ if (answer === void 0) return (0, _modelcontextprotocol_server.inputRequired)({ inputRequests: { [APPROVAL_KEY]: _modelcontextprotocol_server.inputRequired.elicit({
122
+ message: `Allow "${(0, kizunajs_adapter.toolOptionsOf)(route)?.title ?? route.summary ?? `${route.method} ${route.path}`}"?`,
159
123
  requestedSchema: {
160
124
  type: "object",
161
- properties: { confirm: {
125
+ properties: { approved: {
162
126
  type: "boolean",
163
- title: "Go ahead"
127
+ title: "Allow"
164
128
  } },
165
- required: [CONFIRM_KEY]
129
+ required: [APPROVAL_KEY]
166
130
  }
167
131
  }) } });
168
- if (answer.confirm === true) return void 0;
132
+ if (answer.approved === true) return void 0;
169
133
  return {
170
134
  content: [{
171
135
  type: "text",
@@ -175,10 +139,24 @@ const confirmed = (route, context) => {
175
139
  };
176
140
  };
177
141
  /**
142
+ * What the SDK publishes for a tool. Input passes through unchecked, so the
143
+ * call is validated once, by `validateRequest`, as an HTTP request is. Output
144
+ * keeps the route's own check.
145
+ */
146
+ const publishedSchema = (jsonSchema, check) => ({ "~standard": {
147
+ version: 1,
148
+ vendor: "kizuna",
149
+ validate: check === void 0 ? (value) => ({ value }) : check["~standard"].validate,
150
+ jsonSchema: {
151
+ input: () => jsonSchema,
152
+ output: () => jsonSchema
153
+ }
154
+ } });
155
+ /**
178
156
  * What the route says about itself, over what its method already implies.
179
157
  */
180
158
  const buildToolAnnotations = (route) => {
181
- const declared = toolOptionsOf(route) ?? {};
159
+ const declared = (0, kizunajs_adapter.toolOptionsOf)(route) ?? {};
182
160
  return {
183
161
  ...isSafeMethod(route.method) ? { readOnlyHint: true } : {},
184
162
  ...isIdempotentMethod(route.method) ? { idempotentHint: true } : {},
@@ -190,61 +168,58 @@ const buildToolAnnotations = (route) => {
190
168
  ...declared.openWorldHint === void 0 ? {} : { openWorldHint: declared.openWorldHint }
191
169
  };
192
170
  };
193
- const describeRoles = (route) => route.roles !== void 0 && route.roles.length > 0 ? `Roles: ${route.roles.join(", ")}` : void 0;
194
- const describeRequires = (route) => {
195
- const requires = route.requires;
196
- if (requires === void 0) return void 0;
197
- const names = Object.entries(requires).flatMap(([resource, verbs]) => verbs.map((verb) => `${resource}:${verb}`));
198
- return names.length > 0 ? `Permissions: ${names.join(", ")}` : void 0;
199
- };
200
- const buildToolDescription = (route) => {
201
- const parts = [];
202
- const declared = toolOptionsOf(route)?.description;
203
- if (declared) parts.push(declared);
204
- else if (route.summary) parts.push(route.summary);
205
- if (route.description) parts.push(route.description);
206
- if (parts.length === 0) parts.push(`${route.method} ${route.path}`);
207
- parts.push(`\nHTTP: ${route.method} ${route.path}`);
208
- const requirements = (0, kizunajs_adapter.resolveSecurityRequirements)(route);
209
- if (requirements.length > 0) parts.push(`Requires: ${requirements.map(({ scheme }) => scheme).join(", ")}`);
210
- const roles = describeRoles(route);
211
- if (roles !== void 0) parts.push(roles);
212
- const permissions = describeRequires(route);
213
- if (permissions !== void 0) parts.push(permissions);
214
- return parts.join("\n");
215
- };
216
- const buildToolDefinitions = (routes) => {
217
- const selected = selectToolRoutes((0, kizunajs_adapter.flattenRoutes)(routes));
171
+ const buildMcpTools = (routes) => {
172
+ const selected = (0, kizunajs_adapter.selectToolRoutes)((0, kizunajs_adapter.flattenRoutes)(routes));
218
173
  const names = (0, kizunajs_generator.deriveToolNames)(selected.map(({ routeKey }) => ({
219
174
  key: routeKey,
220
175
  origin: "route"
221
176
  })));
222
177
  const definitions = [];
223
- for (const { routeKey, route, routeTags } of selected) {
178
+ for (const { routeKey, route, routeGroups } of selected) {
224
179
  const name = names.get(routeKey);
225
180
  definitions.push({
226
181
  name,
227
182
  title: route.summary,
228
- description: buildToolDescription(route),
229
- inputSchema: buildToolInputSchema(route),
183
+ description: (0, kizunajs_adapter.describeTool)(route),
184
+ inputSchema: (0, kizunajs_adapter.buildToolInputSchema)(route),
230
185
  outputSchema: buildToolOutputSchema(route),
231
186
  route,
232
187
  routeKey,
233
- tags: routeTags
188
+ groups: routeGroups
234
189
  });
235
190
  }
236
191
  return definitions;
237
192
  };
193
+ const publishedTools = /* @__PURE__ */ new WeakMap();
194
+ /**
195
+ * Every tool with its schemas converted, built once per API rather than on
196
+ * every MCP request.
197
+ */
198
+ const publishedToolsFor = (routes) => {
199
+ const cached = publishedTools.get(routes);
200
+ if (cached) return cached;
201
+ const built = buildMcpTools(routes).map((definition) => ({
202
+ definition,
203
+ inputSchema: publishedSchema((0, kizunajs_adapter.toolInputJsonSchema)(definition.route)),
204
+ outputSchema: publishedSchema((0, kizunajs_adapter.toolJsonSchema)(definition.outputSchema, "output"), definition.outputSchema),
205
+ annotations: buildToolAnnotations(definition.route)
206
+ }));
207
+ publishedTools.set(routes, built);
208
+ return built;
209
+ };
238
210
  /**
239
211
  * What a client puts in front of the model before it picks a tool.
240
212
  */
241
213
  const buildInstructions = (contract, definitions, authored) => {
242
214
  const sections = [];
243
215
  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.");
244
- const tags = contract?.tags?.tags;
245
- if (tags !== void 0) {
246
- const exposed = new Set(definitions.flatMap((definition) => definition.tags));
247
- const groups = Object.entries(tags).filter(([key]) => exposed.has(key)).map(([, tag]) => tag.description ? `- ${tag.title}: ${tag.description}` : `- ${tag.title}`);
216
+ const declared = contract?.groups?.groups;
217
+ if (declared !== void 0) {
218
+ const exposed = new Set(definitions.flatMap((definition) => definition.groups));
219
+ const groups = [...declared.values()].filter((group) => exposed.has(group.path)).map((group) => {
220
+ const name = group.lineage.map((path) => declared.get(path).title).join(" / ");
221
+ return group.description ? `- ${name}: ${group.description}` : `- ${name}`;
222
+ });
248
223
  if (groups.length > 0) sections.push(`Groups:\n${groups.join("\n")}`);
249
224
  }
250
225
  if (authored) sections.push(authored);
@@ -272,7 +247,7 @@ const toolEnvelope = (status, body) => {
272
247
  return {
273
248
  content: [{
274
249
  type: "text",
275
- text: JSON.stringify(envelope, null, 2)
250
+ text: JSON.stringify(envelope)
276
251
  }],
277
252
  ...isError ? {} : { structuredContent: envelope },
278
253
  isError
@@ -284,7 +259,7 @@ const toolError = (status, body) => ({
284
259
  text: JSON.stringify({
285
260
  status,
286
261
  body
287
- }, null, 2)
262
+ })
288
263
  }],
289
264
  isError: true
290
265
  });
@@ -332,11 +307,10 @@ const runGuards = async (requirements, roles, requires, label, params, guards, s
332
307
  };
333
308
  const schemeDefinition = schemes?.[scheme];
334
309
  const credential = schemeDefinition ? (0, kizunajs_adapter.extractCredential)(schemeDefinition, credentialRequest) : {};
335
- const guardResult = await guard({
310
+ const guardResult = await (0, kizunajs_adapter.callGuard)(guard, schemeDefinition, {
336
311
  ...handlerContext ?? {},
337
312
  ...credential,
338
313
  params,
339
- deny: (0, kizunajs_adapter.guardDenyFor)(schemeDefinition),
340
314
  ...Object.keys(requestContext).length > 0 ? { requestContext } : {}
341
315
  });
342
316
  if ((0, kizunajs_adapter.isGuardDenial)(guardResult)) return {
@@ -369,21 +343,16 @@ const executeToolCall = async (route, routeKey, args, router, handlerContext, gu
369
343
  params,
370
344
  query,
371
345
  body,
372
- headers: {}
346
+ headers: credentialHeaders ?? {}
373
347
  });
374
- if (!validation.ok) return {
375
- content: [{
376
- type: "text",
377
- text: JSON.stringify({
378
- status: 400,
379
- body: {
380
- detail: `Validation failed: ${validation.error.stage}`,
381
- errors: validation.error.issues
382
- }
383
- }, null, 2)
384
- }],
385
- isError: true
386
- };
348
+ if (!validation.ok) {
349
+ const formatted = (0, kizunajs_adapter.formatValidationError)(validation.error);
350
+ return toolEnvelope(400, (0, kizunajs.problemDetails)(400, formatted.detail, { errors: formatted.issues.map((issue) => ({
351
+ code: issue.code ?? "custom",
352
+ path: issue.path,
353
+ message: issue.message
354
+ })) }));
355
+ }
387
356
  const handler = resolveHandler(router, routeKey);
388
357
  if (typeof handler !== "function") return {
389
358
  content: [{
@@ -391,7 +360,7 @@ const executeToolCall = async (route, routeKey, args, router, handlerContext, gu
391
360
  text: JSON.stringify({
392
361
  status: 500,
393
362
  body: { detail: `Handler not implemented: ${routeKey}` }
394
- }, null, 2)
363
+ })
395
364
  }],
396
365
  isError: true
397
366
  };
@@ -415,16 +384,8 @@ const executeToolCall = async (route, routeKey, args, router, handlerContext, gu
415
384
  return toolEnvelope(result.status, result.body);
416
385
  } catch (error) {
417
386
  if (error instanceof kizunajs_adapter.ResponseError) return toolEnvelope(error.status, error.body);
418
- return {
419
- content: [{
420
- type: "text",
421
- text: JSON.stringify({
422
- status: 500,
423
- body: { detail: error instanceof Error ? error.message : "Internal Server Error" }
424
- }, null, 2)
425
- }],
426
- isError: true
427
- };
387
+ console.error(`[kizuna] tool "${routeKey}" threw:`, error);
388
+ return toolEnvelope(500, (0, kizunajs.problemDetails)(500, "Internal Server Error"));
428
389
  }
429
390
  };
430
391
  /**
@@ -447,19 +408,22 @@ const createMcpServer = (api, options) => {
447
408
  const guardSchema = api[kizunajs_adapter.GUARD_SCHEMA_META];
448
409
  const contextResolvers = api[kizunajs_adapter.REQUEST_CONTEXT_META];
449
410
  const contract = (0, kizunajs_adapter.contractOf)(api);
450
- const definitions = buildToolDefinitions(api.routes);
411
+ const tools = publishedToolsFor(api.routes);
451
412
  const server = new _modelcontextprotocol_server.McpServer({
452
413
  name: options?.name ?? "MCP Server",
453
414
  version: options?.version ?? "1.0.0"
454
- }, { instructions: buildInstructions(contract, definitions, options?.instructions) });
455
- for (const definition of definitions) server.registerTool(definition.name, {
415
+ }, {
416
+ instructions: buildInstructions(contract, tools.map(({ definition }) => definition), options?.instructions),
417
+ cacheHints: { "tools/list": TOOL_LIST_CACHE }
418
+ });
419
+ for (const { definition, inputSchema, outputSchema, annotations } of tools) server.registerTool(definition.name, {
456
420
  ...definition.title === void 0 ? {} : { title: definition.title },
457
421
  description: definition.description,
458
- inputSchema: definition.inputSchema.shape === void 0 ? void 0 : zod.z.object(definition.inputSchema.shape),
459
- outputSchema: definition.outputSchema,
460
- annotations: buildToolAnnotations(definition.route)
422
+ inputSchema,
423
+ outputSchema,
424
+ annotations
461
425
  }, async (args, context) => {
462
- const refusal = confirmed(definition.route, context);
426
+ const refusal = approval(definition.route, context);
463
427
  if (refusal !== void 0) return refusal;
464
428
  return executeToolCall(definition.route, definition.routeKey, args ?? {}, router, options?.handlerContext, guards, schemes, options?.credentialHeaders, contextResolvers, options?.transportAuth, guardSchema);
465
429
  });
@@ -483,11 +447,10 @@ const enforceOAuth = async (args) => {
483
447
  };
484
448
  const credential = (0, kizunajs_adapter.extractCredential)(args.schemeDefinition, credentialRequest);
485
449
  const presented = Object.values(credential).some((value) => value !== null);
486
- const guardResult = await args.guard({
450
+ const guardResult = await (0, kizunajs_adapter.callGuard)(args.guard, args.schemeDefinition, {
487
451
  ...args.handlerContext,
488
452
  ...credential,
489
453
  params: args.params,
490
- deny: (0, kizunajs_adapter.guardDenyFor)(args.schemeDefinition),
491
454
  ...args.requestContext && Object.keys(args.requestContext).length > 0 ? { requestContext: args.requestContext } : {}
492
455
  });
493
456
  if ((0, kizunajs_adapter.isGuardDenial)(guardResult)) {
@@ -573,19 +536,20 @@ const prepareOAuth = (oauth, endpointPath, api) => {
573
536
  }),
574
537
  metadataUrl: protectedResourceMetadataUrl(oauth, endpointPath),
575
538
  scopesSupported: (0, kizunajs.declaredScopes)(schemeDefinition),
576
- tools: new Map(buildToolDefinitions(api.routes).map((definition) => [definition.name, definition]))
539
+ tools: new Map(buildMcpTools(api.routes).map((definition) => [definition.name, definition]))
577
540
  };
578
541
  };
542
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
579
543
  /**
580
- * The oauth scheme's requirement for the tool a `tools/call` body names, so
544
+ * The oauth scheme's requirement for the tool a `tools/call` message names, so
581
545
  * the challenge speaks about the operation the client is attempting. The
582
546
  * route's `roles` and `requires` ride along when the oauth identity is the only one on
583
547
  * the route whose roles can satisfy it; otherwise the tool call checks it,
584
548
  * with every guard's role in hand.
585
549
  */
586
- const toolCallTarget = (body, enforcement) => {
587
- if (body !== null && typeof body === "object" && body.method === "tools/call") {
588
- const callParams = body.params;
550
+ const toolCallTarget = (message, enforcement) => {
551
+ if (isToolCall(message)) {
552
+ const callParams = message.params;
589
553
  const definition = typeof callParams?.name === "string" ? enforcement.tools.get(callParams.name) : void 0;
590
554
  if (definition !== void 0) {
591
555
  const requirements = (0, kizunajs_adapter.resolveSecurityRequirements)(definition.route);
@@ -608,17 +572,33 @@ const toolCallTarget = (body, enforcement) => {
608
572
  };
609
573
  };
610
574
  /**
611
- * What answers the MCP endpoint: the tool list built from the routes that
612
- * declared `tool`, and the calls a model makes against them.
575
+ * What answers one MCP endpoint: the tool list built from the routes that
576
+ * declared `tool`, and the calls a model makes against them. The OAuth setup
577
+ * reads the app's identities, so it's prepared once the api has assembled:
578
+ * `validate` prepares it at startup, and the handlers reuse it.
613
579
  */
614
- const mcpServe = (props, api) => {
580
+ const mcpEndpoint = (props, api) => {
615
581
  const serverApi = api;
616
- const enforcement = props.oauth === void 0 ? void 0 : prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
617
- return { router: {
618
- endpoint: async (args) => {
582
+ let prepared;
583
+ const enforcementOf = () => {
584
+ if (props.oauth === void 0) return void 0;
585
+ prepared ??= prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
586
+ return prepared;
587
+ };
588
+ return {
589
+ validate: () => {
590
+ enforcementOf();
591
+ },
592
+ handle: async (args) => {
593
+ const enforcement = enforcementOf();
619
594
  let transportAuth;
620
595
  if (enforcement !== void 0) {
621
- const target = toolCallTarget(args.body, enforcement);
596
+ const calls = (Array.isArray(args.body) ? args.body : [args.body]).filter(isToolCall);
597
+ if (calls.length > 1) return denialResponse({
598
+ status: 400,
599
+ body: { detail: "Send one tools/call per request." }
600
+ });
601
+ const target = toolCallTarget(calls[0], enforcement);
622
602
  const outcome = await enforceOAuth({
623
603
  scheme: enforcement.oauth.scheme,
624
604
  guard: enforcement.guard,
@@ -650,60 +630,95 @@ const mcpServe = (props, api) => {
650
630
  body: JSON.stringify(args.body)
651
631
  })));
652
632
  },
653
- ...enforcement === void 0 ? {} : { protectedResourceMetadata: () => (0, kizunajs_adapter.rawResponse)(new Response(JSON.stringify(enforcement.metadata), {
633
+ protectedResourceMetadata: () => (0, kizunajs_adapter.rawResponse)(new Response(JSON.stringify(enforcementOf()?.metadata), {
654
634
  status: 200,
655
635
  headers: { "content-type": "application/json" }
656
- })) }
657
- } };
636
+ }))
637
+ };
658
638
  };
659
639
  //#endregion
660
640
  //#region src/plugin.ts
661
- const declare = (slug, props) => {
662
- const endpointPath = props.path ?? "/mcp";
663
- return (0, kizunajs_plugin.createPlugin)({
664
- slug,
665
- routes: {
666
- endpoint: {
667
- method: "POST",
668
- path: endpointPath,
669
- summary: "MCP (Model Context Protocol) endpoint",
670
- body: zod.z.unknown(),
671
- responses: { 200: zod.z.unknown() }
672
- },
673
- ...props.oauth === void 0 ? {} : { protectedResourceMetadata: {
674
- method: "GET",
675
- path: protectedResourceMetadataPath(endpointPath),
676
- summary: "OAuth protected resource metadata",
677
- responses: { 200: kizunajs_schemas.ProtectedResourceMetadataSchema }
678
- } }
679
- },
680
- props,
681
- serve: (pluginProps, api) => mcpServe(pluginProps, api)
682
- });
683
- };
641
+ /**
642
+ * What the MCP endpoint is, and where. Which routes it publishes is each
643
+ * route's own business: declare `tool` on the ones a model may call.
644
+ */
645
+ const McpPluginOptionsSchema = zod.z.object({
646
+ /**
647
+ * Path the endpoint is served from.
648
+ *
649
+ * @default '/mcp'
650
+ */
651
+ path: kizunajs_plugin.RoutePathSchema.optional(),
652
+ /**
653
+ * Human-readable name shown to AI assistants.
654
+ *
655
+ * @default 'MCP Server'
656
+ */
657
+ name: zod.z.string().optional(),
658
+ /**
659
+ * Semantic version string (e.g. "1.0.0").
660
+ *
661
+ * @default '1.0.0'
662
+ */
663
+ version: zod.z.string().optional(),
664
+ /**
665
+ * Guidance for the model, appended to the overview built from the
666
+ * API's groups.
667
+ */
668
+ instructions: zod.z.string().optional(),
669
+ /**
670
+ * Serve the endpoint as an OAuth 2.1 resource server, per the MCP
671
+ * authorization specification: RFC 9728 metadata on a well-known route,
672
+ * and HTTP `401`/`403` challenges built from the named identity.
673
+ */
674
+ oauth: McpOAuthSchema.optional()
675
+ });
684
676
  /**
685
677
  * Let AI assistants use the API. Serves an MCP (Model Context Protocol)
686
678
  * endpoint where every route declaring `tool` is one an assistant can discover
687
679
  * and call, behind the same guards as the HTTP endpoints.
688
680
  *
689
681
  * The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
690
- * adapter, and it stays out of `api.routes` so the client and the generators do
691
- * not see it.
682
+ * adapter.
692
683
  *
693
684
  * @example
694
685
  * ```ts
695
686
  * export default defineConfig({
696
687
  * routes,
697
- * plugins: [mcpPlugin({ name: 'My API' })],
688
+ * plugins: [
689
+ * mcpPlugin({
690
+ * name: 'My API',
691
+ * }),
692
+ * ],
698
693
  * });
699
694
  * ```
700
695
  */
701
- function mcpPlugin(props) {
702
- const settings = props ?? {};
703
- return declare(settings.slug ?? "mcp", settings);
704
- }
696
+ const mcpPlugin = (0, kizunajs_plugin.definePlugin)({
697
+ slug: "mcp",
698
+ options: McpPluginOptionsSchema,
699
+ setup: ({ options, api }) => {
700
+ const endpointPath = options.path ?? "/mcp";
701
+ const endpoint = mcpEndpoint(options, api);
702
+ const routes = { endpoint: (0, kizunajs_plugin.route)({
703
+ method: "POST",
704
+ path: endpointPath,
705
+ summary: "MCP (Model Context Protocol) endpoint",
706
+ body: zod.z.unknown(),
707
+ responses: { 200: zod.z.unknown() }
708
+ }).handler(endpoint.handle) };
709
+ if (options.oauth !== void 0) routes.protectedResourceMetadata = (0, kizunajs_plugin.route)({
710
+ method: "GET",
711
+ path: protectedResourceMetadataPath(endpointPath),
712
+ summary: "OAuth protected resource metadata",
713
+ responses: { 200: kizunajs_schemas.ProtectedResourceMetadataSchema }
714
+ }).handler(endpoint.protectedResourceMetadata);
715
+ return {
716
+ routes,
717
+ validate: endpoint.validate
718
+ };
719
+ }
720
+ });
705
721
  //#endregion
706
722
  exports.buildInstructions = buildInstructions;
707
- exports.buildToolDefinitions = buildToolDefinitions;
708
723
  exports.createMcpServer = createMcpServer;
709
724
  exports.mcpPlugin = mcpPlugin;