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

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