@kizunajs/mcp 2.0.0-beta.1 → 2.0.0-beta.11

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,27 @@ 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";
148
104
  /**
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.
105
+ * Ask the person before running, when the call needs approval. Returns the
106
+ * elicitation on the first call, a refusal when they declined, and nothing once
107
+ * they approved.
152
108
  */
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,
109
+ const approval = (route, context) => {
110
+ if ((0, kizunajs_adapter.toolOptionsOf)(route)?.needsApproval !== true) return void 0;
111
+ const answer = (0, _modelcontextprotocol_server.acceptedContent)(context.mcpReq?.inputResponses, APPROVAL_KEY);
112
+ if (answer === void 0) return (0, _modelcontextprotocol_server.inputRequired)({ inputRequests: { [APPROVAL_KEY]: _modelcontextprotocol_server.inputRequired.elicit({
113
+ message: `Allow "${(0, kizunajs_adapter.toolOptionsOf)(route)?.title ?? route.summary ?? `${route.method} ${route.path}`}"?`,
159
114
  requestedSchema: {
160
115
  type: "object",
161
- properties: { confirm: {
116
+ properties: { approved: {
162
117
  type: "boolean",
163
- title: "Go ahead"
118
+ title: "Allow"
164
119
  } },
165
- required: [CONFIRM_KEY]
120
+ required: [APPROVAL_KEY]
166
121
  }
167
122
  }) } });
168
- if (answer.confirm === true) return void 0;
123
+ if (answer.approved === true) return void 0;
169
124
  return {
170
125
  content: [{
171
126
  type: "text",
@@ -178,7 +133,7 @@ const confirmed = (route, context) => {
178
133
  * What the route says about itself, over what its method already implies.
179
134
  */
180
135
  const buildToolAnnotations = (route) => {
181
- const declared = toolOptionsOf(route) ?? {};
136
+ const declared = (0, kizunajs_adapter.toolOptionsOf)(route) ?? {};
182
137
  return {
183
138
  ...isSafeMethod(route.method) ? { readOnlyHint: true } : {},
184
139
  ...isIdempotentMethod(route.method) ? { idempotentHint: true } : {},
@@ -190,31 +145,8 @@ const buildToolAnnotations = (route) => {
190
145
  ...declared.openWorldHint === void 0 ? {} : { openWorldHint: declared.openWorldHint }
191
146
  };
192
147
  };
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));
148
+ const buildMcpTools = (routes) => {
149
+ const selected = (0, kizunajs_adapter.selectToolRoutes)((0, kizunajs_adapter.flattenRoutes)(routes));
218
150
  const names = (0, kizunajs_generator.deriveToolNames)(selected.map(({ routeKey }) => ({
219
151
  key: routeKey,
220
152
  origin: "route"
@@ -225,8 +157,8 @@ const buildToolDefinitions = (routes) => {
225
157
  definitions.push({
226
158
  name,
227
159
  title: route.summary,
228
- description: buildToolDescription(route),
229
- inputSchema: buildToolInputSchema(route),
160
+ description: (0, kizunajs_adapter.describeTool)(route),
161
+ inputSchema: (0, kizunajs_adapter.buildToolInputSchema)(route),
230
162
  outputSchema: buildToolOutputSchema(route),
231
163
  route,
232
164
  routeKey,
@@ -447,7 +379,7 @@ const createMcpServer = (api, options) => {
447
379
  const guardSchema = api[kizunajs_adapter.GUARD_SCHEMA_META];
448
380
  const contextResolvers = api[kizunajs_adapter.REQUEST_CONTEXT_META];
449
381
  const contract = (0, kizunajs_adapter.contractOf)(api);
450
- const definitions = buildToolDefinitions(api.routes);
382
+ const definitions = buildMcpTools(api.routes);
451
383
  const server = new _modelcontextprotocol_server.McpServer({
452
384
  name: options?.name ?? "MCP Server",
453
385
  version: options?.version ?? "1.0.0"
@@ -459,7 +391,7 @@ const createMcpServer = (api, options) => {
459
391
  outputSchema: definition.outputSchema,
460
392
  annotations: buildToolAnnotations(definition.route)
461
393
  }, async (args, context) => {
462
- const refusal = confirmed(definition.route, context);
394
+ const refusal = approval(definition.route, context);
463
395
  if (refusal !== void 0) return refusal;
464
396
  return executeToolCall(definition.route, definition.routeKey, args ?? {}, router, options?.handlerContext, guards, schemes, options?.credentialHeaders, contextResolvers, options?.transportAuth, guardSchema);
465
397
  });
@@ -573,7 +505,7 @@ const prepareOAuth = (oauth, endpointPath, api) => {
573
505
  }),
574
506
  metadataUrl: protectedResourceMetadataUrl(oauth, endpointPath),
575
507
  scopesSupported: (0, kizunajs.declaredScopes)(schemeDefinition),
576
- tools: new Map(buildToolDefinitions(api.routes).map((definition) => [definition.name, definition]))
508
+ tools: new Map(buildMcpTools(api.routes).map((definition) => [definition.name, definition]))
577
509
  };
578
510
  };
579
511
  /**
@@ -608,14 +540,25 @@ const toolCallTarget = (body, enforcement) => {
608
540
  };
609
541
  };
610
542
  /**
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.
543
+ * What answers one MCP endpoint: the tool list built from the routes that
544
+ * declared `tool`, and the calls a model makes against them. The OAuth setup
545
+ * reads the app's identities, so it's prepared once the api has assembled:
546
+ * `validate` prepares it at startup, and the handlers reuse it.
613
547
  */
614
- const mcpServe = (props, api) => {
548
+ const mcpEndpoint = (props, api) => {
615
549
  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) => {
550
+ let prepared;
551
+ const enforcementOf = () => {
552
+ if (props.oauth === void 0) return void 0;
553
+ prepared ??= prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
554
+ return prepared;
555
+ };
556
+ return {
557
+ validate: () => {
558
+ enforcementOf();
559
+ },
560
+ handle: async (args) => {
561
+ const enforcement = enforcementOf();
619
562
  let transportAuth;
620
563
  if (enforcement !== void 0) {
621
564
  const target = toolCallTarget(args.body, enforcement);
@@ -650,60 +593,95 @@ const mcpServe = (props, api) => {
650
593
  body: JSON.stringify(args.body)
651
594
  })));
652
595
  },
653
- ...enforcement === void 0 ? {} : { protectedResourceMetadata: () => (0, kizunajs_adapter.rawResponse)(new Response(JSON.stringify(enforcement.metadata), {
596
+ protectedResourceMetadata: () => (0, kizunajs_adapter.rawResponse)(new Response(JSON.stringify(enforcementOf()?.metadata), {
654
597
  status: 200,
655
598
  headers: { "content-type": "application/json" }
656
- })) }
657
- } };
599
+ }))
600
+ };
658
601
  };
659
602
  //#endregion
660
603
  //#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
- };
604
+ /**
605
+ * What the MCP endpoint is, and where. Which routes it publishes is each
606
+ * route's own business: declare `tool` on the ones a model may call.
607
+ */
608
+ const McpPluginOptionsSchema = zod.z.object({
609
+ /**
610
+ * Path the endpoint is served from.
611
+ *
612
+ * @default '/mcp'
613
+ */
614
+ path: kizunajs_plugin.RoutePathSchema.optional(),
615
+ /**
616
+ * Human-readable name shown to AI assistants.
617
+ *
618
+ * @default 'MCP Server'
619
+ */
620
+ name: zod.z.string().optional(),
621
+ /**
622
+ * Semantic version string (e.g. "1.0.0").
623
+ *
624
+ * @default '1.0.0'
625
+ */
626
+ version: zod.z.string().optional(),
627
+ /**
628
+ * Guidance for the model, appended to the overview built from the
629
+ * contract's tags.
630
+ */
631
+ instructions: zod.z.string().optional(),
632
+ /**
633
+ * Serve the endpoint as an OAuth 2.1 resource server, per the MCP
634
+ * authorization specification: RFC 9728 metadata on a well-known route,
635
+ * and HTTP `401`/`403` challenges built from the named identity.
636
+ */
637
+ oauth: McpOAuthSchema.optional()
638
+ });
684
639
  /**
685
640
  * Let AI assistants use the API. Serves an MCP (Model Context Protocol)
686
641
  * endpoint where every route declaring `tool` is one an assistant can discover
687
642
  * and call, behind the same guards as the HTTP endpoints.
688
643
  *
689
644
  * 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.
645
+ * adapter.
692
646
  *
693
647
  * @example
694
648
  * ```ts
695
649
  * export default defineConfig({
696
650
  * routes,
697
- * plugins: [mcpPlugin({ name: 'My API' })],
651
+ * plugins: [
652
+ * mcpPlugin({
653
+ * name: 'My API',
654
+ * }),
655
+ * ],
698
656
  * });
699
657
  * ```
700
658
  */
701
- function mcpPlugin(props) {
702
- const settings = props ?? {};
703
- return declare(settings.slug ?? "mcp", settings);
704
- }
659
+ const mcpPlugin = (0, kizunajs_plugin.definePlugin)({
660
+ slug: "mcp",
661
+ options: McpPluginOptionsSchema,
662
+ setup: ({ options, api }) => {
663
+ const endpointPath = options.path ?? "/mcp";
664
+ const endpoint = mcpEndpoint(options, api);
665
+ const routes = { endpoint: (0, kizunajs_plugin.route)({
666
+ method: "POST",
667
+ path: endpointPath,
668
+ summary: "MCP (Model Context Protocol) endpoint",
669
+ body: zod.z.unknown(),
670
+ responses: { 200: zod.z.unknown() }
671
+ }).handler(endpoint.handle) };
672
+ if (options.oauth !== void 0) routes.protectedResourceMetadata = (0, kizunajs_plugin.route)({
673
+ method: "GET",
674
+ path: protectedResourceMetadataPath(endpointPath),
675
+ summary: "OAuth protected resource metadata",
676
+ responses: { 200: kizunajs_schemas.ProtectedResourceMetadataSchema }
677
+ }).handler(endpoint.protectedResourceMetadata);
678
+ return {
679
+ routes,
680
+ validate: endpoint.validate
681
+ };
682
+ }
683
+ });
705
684
  //#endregion
706
685
  exports.buildInstructions = buildInstructions;
707
- exports.buildToolDefinitions = buildToolDefinitions;
708
686
  exports.createMcpServer = createMcpServer;
709
687
  exports.mcpPlugin = mcpPlugin;
package/dist/index.d.cts CHANGED
@@ -1,122 +1,86 @@
1
1
  import * as _$kizunajs from "kizunajs";
2
- import { ApiDefinition, RouteDefinition, Routes } from "kizunajs";
2
+ import { ApiDefinition, RouteDefinition } from "kizunajs";
3
3
  import { z } from "zod";
4
- import { RoutePath, WithSlug } from "kizunajs/plugin";
4
+ import { PluginRoutes } from "kizunajs/plugin";
5
5
  import { McpServer } from "@modelcontextprotocol/server";
6
- import { ApiWithRouter } from "kizunajs/adapter";
6
+ import { ApiWithRouter, ToolInputSchema } from "kizunajs/adapter";
7
7
 
8
- //#region src/oauth.d.ts
9
- interface McpOAuthProps {
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: 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: string;
21
- }
22
- //#endregion
23
8
  //#region src/plugin.d.ts
24
9
  /**
25
10
  * What the MCP endpoint is, and where. Which routes it publishes is each
26
11
  * route's own business: declare `tool` on the ones a model may call.
27
12
  */
28
- interface McpPluginProps<Slug extends string = 'mcp'> {
29
- /**
30
- * What handlers reach this plugin under. Give a second MCP endpoint its own.
31
- *
32
- * @default 'mcp'
33
- */
34
- slug?: Slug;
35
- /**
36
- * Path the endpoint is served from.
37
- *
38
- * @default '/mcp'
39
- */
40
- path?: RoutePath;
41
- /**
42
- * Human-readable name shown to AI assistants.
43
- *
44
- * @default 'MCP Server'
45
- */
46
- name?: string;
47
- /**
48
- * Semantic version string (e.g. "1.0.0").
49
- *
50
- * @default '1.0.0'
51
- */
52
- version?: string;
53
- /**
54
- * Guidance for the model, appended to the overview built from the
55
- * contract's tags.
56
- */
57
- instructions?: string;
58
- /**
59
- * Serve the endpoint as an OAuth 2.1 resource server, per the MCP
60
- * authorization specification: RFC 9728 metadata on a well-known route,
61
- * and HTTP `401`/`403` challenges built from the named identity.
62
- */
63
- oauth?: McpOAuthProps;
64
- }
65
- declare const declare: (slug: string, props: McpPluginProps<string>) => _$kizunajs.PluginDeclaration<{
66
- readonly protectedResourceMetadata?: {
67
- readonly method: "GET";
68
- readonly path: `/${string}`;
69
- readonly summary: "OAuth protected resource metadata";
70
- readonly responses: {
71
- readonly 200: z.ZodObject<{
72
- resource: z.ZodString;
73
- authorization_servers: z.ZodArray<z.ZodString>;
74
- scopes_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
75
- bearer_methods_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
76
- }, z.core.$strip>;
77
- };
78
- } | undefined;
79
- readonly endpoint: {
80
- readonly method: "POST";
81
- readonly path: `/${string}`;
82
- readonly summary: "MCP (Model Context Protocol) endpoint";
83
- readonly body: z.ZodUnknown;
84
- readonly responses: {
85
- readonly 200: z.ZodUnknown;
86
- };
87
- };
88
- }, McpPluginProps<string>, undefined, string, {
89
- [key: string]: unknown;
90
- body: unknown;
91
- headers: Record<string, string | string[] | undefined>;
92
- requestContext?: Record<string, unknown>;
93
- }>;
13
+ declare const McpPluginOptionsSchema: z.ZodObject<{
14
+ path: z.ZodOptional<z.ZodCustom<`/${string}`, `/${string}`>>;
15
+ name: z.ZodOptional<z.ZodString>;
16
+ version: z.ZodOptional<z.ZodString>;
17
+ instructions: z.ZodOptional<z.ZodString>;
18
+ oauth: z.ZodOptional<z.ZodObject<{
19
+ resource: z.ZodString;
20
+ scheme: z.ZodString;
21
+ }, z.core.$strip>>;
22
+ }, z.core.$strip>;
23
+ /**
24
+ * What the MCP endpoint is, and where.
25
+ */
26
+ type McpPluginProps = z.output<typeof McpPluginOptionsSchema>;
94
27
  /**
95
28
  * Let AI assistants use the API. Serves an MCP (Model Context Protocol)
96
29
  * endpoint where every route declaring `tool` is one an assistant can discover
97
30
  * and call, behind the same guards as the HTTP endpoints.
98
31
  *
99
32
  * The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
100
- * adapter, and it stays out of `api.routes` so the client and the generators do
101
- * not see it.
33
+ * adapter.
102
34
  *
103
35
  * @example
104
36
  * ```ts
105
37
  * export default defineConfig({
106
38
  * routes,
107
- * plugins: [mcpPlugin({ name: 'My API' })],
39
+ * plugins: [
40
+ * mcpPlugin({
41
+ * name: 'My API',
42
+ * }),
43
+ * ],
108
44
  * });
109
45
  * ```
110
46
  */
111
- declare function mcpPlugin<const Slug extends string = 'mcp'>(props?: McpPluginProps<Slug>): WithSlug<ReturnType<typeof declare>, Slug>;
47
+ declare const mcpPlugin: {
48
+ <const Slug extends string>(options: {
49
+ path?: `/${string}` | undefined;
50
+ name?: string | undefined;
51
+ version?: string | undefined;
52
+ instructions?: string | undefined;
53
+ oauth?: {
54
+ resource: string;
55
+ scheme: string;
56
+ } | undefined;
57
+ } & {
58
+ slug: Slug;
59
+ }): _$kizunajs.PluginDeclaration<Slug, {
60
+ routes: PluginRoutes;
61
+ validate: () => void;
62
+ }>;
63
+ (options?: {
64
+ path?: `/${string}` | undefined;
65
+ name?: string | undefined;
66
+ version?: string | undefined;
67
+ instructions?: string | undefined;
68
+ oauth?: {
69
+ resource: string;
70
+ scheme: string;
71
+ } | undefined;
72
+ } | undefined): _$kizunajs.PluginDeclaration<"mcp", {
73
+ routes: PluginRoutes;
74
+ validate: () => void;
75
+ }>;
76
+ };
112
77
  //#endregion
113
- //#region src/schema.d.ts
114
- interface ToolInputSchema {
115
- shape: Record<string, z.ZodType> | undefined;
116
- hasParams: boolean;
117
- hasQuery: boolean;
118
- hasBody: boolean;
119
- }
78
+ //#region src/oauth.d.ts
79
+ declare const McpOAuthSchema: z.ZodObject<{
80
+ resource: z.ZodString;
81
+ scheme: z.ZodString;
82
+ }, z.core.$strip>;
83
+ type McpOAuthProps = z.output<typeof McpOAuthSchema>;
120
84
  //#endregion
121
85
  //#region src/mcp-server.d.ts
122
86
  interface McpServerOptions {
@@ -170,7 +134,7 @@ interface McpServerOptions {
170
134
  context?: Record<string, unknown>;
171
135
  };
172
136
  }
173
- interface ToolDefinition {
137
+ interface McpTool {
174
138
  name: string;
175
139
  title: string | undefined;
176
140
  description: string;
@@ -180,11 +144,10 @@ interface ToolDefinition {
180
144
  routeKey: string;
181
145
  tags: string[];
182
146
  }
183
- declare const buildToolDefinitions: (routes: Routes) => ToolDefinition[];
184
147
  /**
185
148
  * What a client puts in front of the model before it picks a tool.
186
149
  */
187
- declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly ToolDefinition[], authored: string | undefined) => string;
150
+ declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly McpTool[], authored: string | undefined) => string;
188
151
  /**
189
152
  * Create an MCP server from a kizuna API.
190
153
  *
@@ -200,4 +163,4 @@ declare const buildInstructions: (contract: ApiDefinition | undefined, definitio
200
163
  */
201
164
  declare const createMcpServer: (api: ApiWithRouter, options?: McpServerOptions) => McpServer;
202
165
  //#endregion
203
- export { type McpOAuthProps, type McpPluginProps, type McpServerOptions, type ToolDefinition, buildInstructions, buildToolDefinitions, createMcpServer, mcpPlugin };
166
+ export { type McpOAuthProps, type McpPluginProps, type McpServerOptions, buildInstructions, createMcpServer, mcpPlugin };
package/dist/index.d.mts CHANGED
@@ -1,122 +1,86 @@
1
1
  import { z } from "zod";
2
- import { RoutePath, WithSlug } from "kizunajs/plugin";
2
+ import { PluginRoutes } from "kizunajs/plugin";
3
3
  import * as _$kizunajs from "kizunajs";
4
- import { ApiDefinition, RouteDefinition, Routes } from "kizunajs";
4
+ import { ApiDefinition, RouteDefinition } from "kizunajs";
5
5
  import { McpServer } from "@modelcontextprotocol/server";
6
- import { ApiWithRouter } from "kizunajs/adapter";
6
+ import { ApiWithRouter, ToolInputSchema } from "kizunajs/adapter";
7
7
 
8
- //#region src/oauth.d.ts
9
- interface McpOAuthProps {
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: 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: string;
21
- }
22
- //#endregion
23
8
  //#region src/plugin.d.ts
24
9
  /**
25
10
  * What the MCP endpoint is, and where. Which routes it publishes is each
26
11
  * route's own business: declare `tool` on the ones a model may call.
27
12
  */
28
- interface McpPluginProps<Slug extends string = 'mcp'> {
29
- /**
30
- * What handlers reach this plugin under. Give a second MCP endpoint its own.
31
- *
32
- * @default 'mcp'
33
- */
34
- slug?: Slug;
35
- /**
36
- * Path the endpoint is served from.
37
- *
38
- * @default '/mcp'
39
- */
40
- path?: RoutePath;
41
- /**
42
- * Human-readable name shown to AI assistants.
43
- *
44
- * @default 'MCP Server'
45
- */
46
- name?: string;
47
- /**
48
- * Semantic version string (e.g. "1.0.0").
49
- *
50
- * @default '1.0.0'
51
- */
52
- version?: string;
53
- /**
54
- * Guidance for the model, appended to the overview built from the
55
- * contract's tags.
56
- */
57
- instructions?: string;
58
- /**
59
- * Serve the endpoint as an OAuth 2.1 resource server, per the MCP
60
- * authorization specification: RFC 9728 metadata on a well-known route,
61
- * and HTTP `401`/`403` challenges built from the named identity.
62
- */
63
- oauth?: McpOAuthProps;
64
- }
65
- declare const declare: (slug: string, props: McpPluginProps<string>) => _$kizunajs.PluginDeclaration<{
66
- readonly protectedResourceMetadata?: {
67
- readonly method: "GET";
68
- readonly path: `/${string}`;
69
- readonly summary: "OAuth protected resource metadata";
70
- readonly responses: {
71
- readonly 200: z.ZodObject<{
72
- resource: z.ZodString;
73
- authorization_servers: z.ZodArray<z.ZodString>;
74
- scopes_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
75
- bearer_methods_supported: z.ZodOptional<z.ZodArray<z.ZodString>>;
76
- }, z.core.$strip>;
77
- };
78
- } | undefined;
79
- readonly endpoint: {
80
- readonly method: "POST";
81
- readonly path: `/${string}`;
82
- readonly summary: "MCP (Model Context Protocol) endpoint";
83
- readonly body: z.ZodUnknown;
84
- readonly responses: {
85
- readonly 200: z.ZodUnknown;
86
- };
87
- };
88
- }, McpPluginProps<string>, undefined, string, {
89
- [key: string]: unknown;
90
- body: unknown;
91
- headers: Record<string, string | string[] | undefined>;
92
- requestContext?: Record<string, unknown>;
93
- }>;
13
+ declare const McpPluginOptionsSchema: z.ZodObject<{
14
+ path: z.ZodOptional<z.ZodCustom<`/${string}`, `/${string}`>>;
15
+ name: z.ZodOptional<z.ZodString>;
16
+ version: z.ZodOptional<z.ZodString>;
17
+ instructions: z.ZodOptional<z.ZodString>;
18
+ oauth: z.ZodOptional<z.ZodObject<{
19
+ resource: z.ZodString;
20
+ scheme: z.ZodString;
21
+ }, z.core.$strip>>;
22
+ }, z.core.$strip>;
23
+ /**
24
+ * What the MCP endpoint is, and where.
25
+ */
26
+ type McpPluginProps = z.output<typeof McpPluginOptionsSchema>;
94
27
  /**
95
28
  * Let AI assistants use the API. Serves an MCP (Model Context Protocol)
96
29
  * endpoint where every route declaring `tool` is one an assistant can discover
97
30
  * and call, behind the same guards as the HTTP endpoints.
98
31
  *
99
32
  * The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
100
- * adapter, and it stays out of `api.routes` so the client and the generators do
101
- * not see it.
33
+ * adapter.
102
34
  *
103
35
  * @example
104
36
  * ```ts
105
37
  * export default defineConfig({
106
38
  * routes,
107
- * plugins: [mcpPlugin({ name: 'My API' })],
39
+ * plugins: [
40
+ * mcpPlugin({
41
+ * name: 'My API',
42
+ * }),
43
+ * ],
108
44
  * });
109
45
  * ```
110
46
  */
111
- declare function mcpPlugin<const Slug extends string = 'mcp'>(props?: McpPluginProps<Slug>): WithSlug<ReturnType<typeof declare>, Slug>;
47
+ declare const mcpPlugin: {
48
+ <const Slug extends string>(options: {
49
+ path?: `/${string}` | undefined;
50
+ name?: string | undefined;
51
+ version?: string | undefined;
52
+ instructions?: string | undefined;
53
+ oauth?: {
54
+ resource: string;
55
+ scheme: string;
56
+ } | undefined;
57
+ } & {
58
+ slug: Slug;
59
+ }): _$kizunajs.PluginDeclaration<Slug, {
60
+ routes: PluginRoutes;
61
+ validate: () => void;
62
+ }>;
63
+ (options?: {
64
+ path?: `/${string}` | undefined;
65
+ name?: string | undefined;
66
+ version?: string | undefined;
67
+ instructions?: string | undefined;
68
+ oauth?: {
69
+ resource: string;
70
+ scheme: string;
71
+ } | undefined;
72
+ } | undefined): _$kizunajs.PluginDeclaration<"mcp", {
73
+ routes: PluginRoutes;
74
+ validate: () => void;
75
+ }>;
76
+ };
112
77
  //#endregion
113
- //#region src/schema.d.ts
114
- interface ToolInputSchema {
115
- shape: Record<string, z.ZodType> | undefined;
116
- hasParams: boolean;
117
- hasQuery: boolean;
118
- hasBody: boolean;
119
- }
78
+ //#region src/oauth.d.ts
79
+ declare const McpOAuthSchema: z.ZodObject<{
80
+ resource: z.ZodString;
81
+ scheme: z.ZodString;
82
+ }, z.core.$strip>;
83
+ type McpOAuthProps = z.output<typeof McpOAuthSchema>;
120
84
  //#endregion
121
85
  //#region src/mcp-server.d.ts
122
86
  interface McpServerOptions {
@@ -170,7 +134,7 @@ interface McpServerOptions {
170
134
  context?: Record<string, unknown>;
171
135
  };
172
136
  }
173
- interface ToolDefinition {
137
+ interface McpTool {
174
138
  name: string;
175
139
  title: string | undefined;
176
140
  description: string;
@@ -180,11 +144,10 @@ interface ToolDefinition {
180
144
  routeKey: string;
181
145
  tags: string[];
182
146
  }
183
- declare const buildToolDefinitions: (routes: Routes) => ToolDefinition[];
184
147
  /**
185
148
  * What a client puts in front of the model before it picks a tool.
186
149
  */
187
- declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly ToolDefinition[], authored: string | undefined) => string;
150
+ declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly McpTool[], authored: string | undefined) => string;
188
151
  /**
189
152
  * Create an MCP server from a kizuna API.
190
153
  *
@@ -200,4 +163,4 @@ declare const buildInstructions: (contract: ApiDefinition | undefined, definitio
200
163
  */
201
164
  declare const createMcpServer: (api: ApiWithRouter, options?: McpServerOptions) => McpServer;
202
165
  //#endregion
203
- export { type McpOAuthProps, type McpPluginProps, type McpServerOptions, type ToolDefinition, buildInstructions, buildToolDefinitions, createMcpServer, mcpPlugin };
166
+ export { type McpOAuthProps, type McpPluginProps, type McpServerOptions, buildInstructions, createMcpServer, mcpPlugin };
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, contractOf, describeTool, extractCredential, flattenRoutes, guardDenyFor, insufficientScope, isGuardDenial, rawResponse, requiresDenial, resolveSecurityRequirements, selectToolRoutes, 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,27 @@ 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
+ * Ask the person before running, when the call needs approval. Returns the
105
+ * elicitation on the first call, a refusal when they declined, and nothing once
106
+ * they approved.
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 approval = (route, context) => {
109
+ if (toolOptionsOf(route)?.needsApproval !== true) return void 0;
110
+ const answer = acceptedContent(context.mcpReq?.inputResponses, APPROVAL_KEY);
111
+ if (answer === void 0) return inputRequired({ inputRequests: { [APPROVAL_KEY]: inputRequired.elicit({
112
+ message: `Allow "${toolOptionsOf(route)?.title ?? route.summary ?? `${route.method} ${route.path}`}"?`,
158
113
  requestedSchema: {
159
114
  type: "object",
160
- properties: { confirm: {
115
+ properties: { approved: {
161
116
  type: "boolean",
162
- title: "Go ahead"
117
+ title: "Allow"
163
118
  } },
164
- required: [CONFIRM_KEY]
119
+ required: [APPROVAL_KEY]
165
120
  }
166
121
  }) } });
167
- if (answer.confirm === true) return void 0;
122
+ if (answer.approved === true) return void 0;
168
123
  return {
169
124
  content: [{
170
125
  type: "text",
@@ -189,30 +144,7 @@ const buildToolAnnotations = (route) => {
189
144
  ...declared.openWorldHint === void 0 ? {} : { openWorldHint: declared.openWorldHint }
190
145
  };
191
146
  };
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) => {
147
+ const buildMcpTools = (routes) => {
216
148
  const selected = selectToolRoutes(flattenRoutes(routes));
217
149
  const names = deriveToolNames(selected.map(({ routeKey }) => ({
218
150
  key: routeKey,
@@ -224,7 +156,7 @@ const buildToolDefinitions = (routes) => {
224
156
  definitions.push({
225
157
  name,
226
158
  title: route.summary,
227
- description: buildToolDescription(route),
159
+ description: describeTool(route),
228
160
  inputSchema: buildToolInputSchema(route),
229
161
  outputSchema: buildToolOutputSchema(route),
230
162
  route,
@@ -446,7 +378,7 @@ const createMcpServer = (api, options) => {
446
378
  const guardSchema = api[GUARD_SCHEMA_META];
447
379
  const contextResolvers = api[REQUEST_CONTEXT_META];
448
380
  const contract = contractOf(api);
449
- const definitions = buildToolDefinitions(api.routes);
381
+ const definitions = buildMcpTools(api.routes);
450
382
  const server = new McpServer({
451
383
  name: options?.name ?? "MCP Server",
452
384
  version: options?.version ?? "1.0.0"
@@ -458,7 +390,7 @@ const createMcpServer = (api, options) => {
458
390
  outputSchema: definition.outputSchema,
459
391
  annotations: buildToolAnnotations(definition.route)
460
392
  }, async (args, context) => {
461
- const refusal = confirmed(definition.route, context);
393
+ const refusal = approval(definition.route, context);
462
394
  if (refusal !== void 0) return refusal;
463
395
  return executeToolCall(definition.route, definition.routeKey, args ?? {}, router, options?.handlerContext, guards, schemes, options?.credentialHeaders, contextResolvers, options?.transportAuth, guardSchema);
464
396
  });
@@ -572,7 +504,7 @@ const prepareOAuth = (oauth, endpointPath, api) => {
572
504
  }),
573
505
  metadataUrl: protectedResourceMetadataUrl(oauth, endpointPath),
574
506
  scopesSupported: declaredScopes(schemeDefinition),
575
- tools: new Map(buildToolDefinitions(api.routes).map((definition) => [definition.name, definition]))
507
+ tools: new Map(buildMcpTools(api.routes).map((definition) => [definition.name, definition]))
576
508
  };
577
509
  };
578
510
  /**
@@ -607,14 +539,25 @@ const toolCallTarget = (body, enforcement) => {
607
539
  };
608
540
  };
609
541
  /**
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.
542
+ * What answers one MCP endpoint: the tool list built from the routes that
543
+ * declared `tool`, and the calls a model makes against them. The OAuth setup
544
+ * reads the app's identities, so it's prepared once the api has assembled:
545
+ * `validate` prepares it at startup, and the handlers reuse it.
612
546
  */
613
- const mcpServe = (props, api) => {
547
+ const mcpEndpoint = (props, api) => {
614
548
  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) => {
549
+ let prepared;
550
+ const enforcementOf = () => {
551
+ if (props.oauth === void 0) return void 0;
552
+ prepared ??= prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
553
+ return prepared;
554
+ };
555
+ return {
556
+ validate: () => {
557
+ enforcementOf();
558
+ },
559
+ handle: async (args) => {
560
+ const enforcement = enforcementOf();
618
561
  let transportAuth;
619
562
  if (enforcement !== void 0) {
620
563
  const target = toolCallTarget(args.body, enforcement);
@@ -649,36 +592,11 @@ const mcpServe = (props, api) => {
649
592
  body: JSON.stringify(args.body)
650
593
  })));
651
594
  },
652
- ...enforcement === void 0 ? {} : { protectedResourceMetadata: () => rawResponse(new Response(JSON.stringify(enforcement.metadata), {
595
+ protectedResourceMetadata: () => rawResponse(new Response(JSON.stringify(enforcementOf()?.metadata), {
653
596
  status: 200,
654
597
  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
- });
598
+ }))
599
+ };
682
600
  };
683
601
  /**
684
602
  * Let AI assistants use the API. Serves an MCP (Model Context Protocol)
@@ -686,20 +604,74 @@ const declare = (slug, props) => {
686
604
  * and call, behind the same guards as the HTTP endpoints.
687
605
  *
688
606
  * 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.
607
+ * adapter.
691
608
  *
692
609
  * @example
693
610
  * ```ts
694
611
  * export default defineConfig({
695
612
  * routes,
696
- * plugins: [mcpPlugin({ name: 'My API' })],
613
+ * plugins: [
614
+ * mcpPlugin({
615
+ * name: 'My API',
616
+ * }),
617
+ * ],
697
618
  * });
698
619
  * ```
699
620
  */
700
- function mcpPlugin(props) {
701
- const settings = props ?? {};
702
- return declare(settings.slug ?? "mcp", settings);
703
- }
621
+ const mcpPlugin = definePlugin({
622
+ slug: "mcp",
623
+ options: z.object({
624
+ /**
625
+ * Path the endpoint is served from.
626
+ *
627
+ * @default '/mcp'
628
+ */
629
+ path: RoutePathSchema.optional(),
630
+ /**
631
+ * Human-readable name shown to AI assistants.
632
+ *
633
+ * @default 'MCP Server'
634
+ */
635
+ name: z.string().optional(),
636
+ /**
637
+ * Semantic version string (e.g. "1.0.0").
638
+ *
639
+ * @default '1.0.0'
640
+ */
641
+ version: z.string().optional(),
642
+ /**
643
+ * Guidance for the model, appended to the overview built from the
644
+ * contract's tags.
645
+ */
646
+ instructions: z.string().optional(),
647
+ /**
648
+ * Serve the endpoint as an OAuth 2.1 resource server, per the MCP
649
+ * authorization specification: RFC 9728 metadata on a well-known route,
650
+ * and HTTP `401`/`403` challenges built from the named identity.
651
+ */
652
+ oauth: McpOAuthSchema.optional()
653
+ }),
654
+ setup: ({ options, api }) => {
655
+ const endpointPath = options.path ?? "/mcp";
656
+ const endpoint = mcpEndpoint(options, api);
657
+ const routes = { endpoint: route({
658
+ method: "POST",
659
+ path: endpointPath,
660
+ summary: "MCP (Model Context Protocol) endpoint",
661
+ body: z.unknown(),
662
+ responses: { 200: z.unknown() }
663
+ }).handler(endpoint.handle) };
664
+ if (options.oauth !== void 0) routes.protectedResourceMetadata = route({
665
+ method: "GET",
666
+ path: protectedResourceMetadataPath(endpointPath),
667
+ summary: "OAuth protected resource metadata",
668
+ responses: { 200: ProtectedResourceMetadataSchema }
669
+ }).handler(endpoint.protectedResourceMetadata);
670
+ return {
671
+ routes,
672
+ validate: endpoint.validate
673
+ };
674
+ }
675
+ });
704
676
  //#endregion
705
- export { buildInstructions, buildToolDefinitions, createMcpServer, mcpPlugin };
677
+ 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.1",
3
+ "version": "2.0.0-beta.11",
4
4
  "description": "MCP endpoint for Kizuna.js, so AI assistants can call your routes",
5
5
  "keywords": [
6
6
  "kizunajs",
@@ -61,7 +61,7 @@
61
61
  },
62
62
  "peerDependencies": {
63
63
  "zod": "^4.0.0",
64
- "kizunajs": "2.0.0-beta.1"
64
+ "kizunajs": "2.0.0-beta.11"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@modelcontextprotocol/client": "^2.0.0",
@@ -70,8 +70,8 @@
70
70
  "tsdown": "^0.21.0",
71
71
  "typescript": "^6.0.3",
72
72
  "zod": "^4.0.0",
73
- "kizunajs": "2.0.0-beta.1",
74
- "@kizunajs/express": "2.0.0-beta.1"
73
+ "kizunajs": "2.0.0-beta.11",
74
+ "@kizunajs/express": "2.0.0-beta.11"
75
75
  },
76
76
  "scripts": {
77
77
  "build": "tsdown src/index.ts --format esm,cjs --dts --clean --external kizunajs --external zod --external @modelcontextprotocol/sdk",