@kizunajs/mcp 2.0.0-beta.2 → 2.0.0-beta.20
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 +129 -148
- package/dist/index.d.cts +70 -101
- package/dist/index.d.mts +70 -101
- package/dist/index.mjs +126 -151
- package/package.json +6 -6
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
|
|
103
|
+
const APPROVAL_KEY = "approved";
|
|
148
104
|
/**
|
|
149
|
-
* Ask before running, when the
|
|
150
|
-
*
|
|
151
|
-
*
|
|
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
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
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: {
|
|
116
|
+
properties: { approved: {
|
|
162
117
|
type: "boolean",
|
|
163
|
-
title: "
|
|
118
|
+
title: "Allow"
|
|
164
119
|
} },
|
|
165
|
-
required: [
|
|
120
|
+
required: [APPROVAL_KEY]
|
|
166
121
|
}
|
|
167
122
|
}) } });
|
|
168
|
-
if (answer.
|
|
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,47 +145,24 @@ const buildToolAnnotations = (route) => {
|
|
|
190
145
|
...declared.openWorldHint === void 0 ? {} : { openWorldHint: declared.openWorldHint }
|
|
191
146
|
};
|
|
192
147
|
};
|
|
193
|
-
const
|
|
194
|
-
const
|
|
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"
|
|
221
153
|
})));
|
|
222
154
|
const definitions = [];
|
|
223
|
-
for (const { routeKey, route,
|
|
155
|
+
for (const { routeKey, route, routeGroups } of selected) {
|
|
224
156
|
const name = names.get(routeKey);
|
|
225
157
|
definitions.push({
|
|
226
158
|
name,
|
|
227
159
|
title: route.summary,
|
|
228
|
-
description:
|
|
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,
|
|
233
|
-
|
|
165
|
+
groups: routeGroups
|
|
234
166
|
});
|
|
235
167
|
}
|
|
236
168
|
return definitions;
|
|
@@ -241,10 +173,13 @@ const buildToolDefinitions = (routes) => {
|
|
|
241
173
|
const buildInstructions = (contract, definitions, authored) => {
|
|
242
174
|
const sections = [];
|
|
243
175
|
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
|
|
245
|
-
if (
|
|
246
|
-
const exposed = new Set(definitions.flatMap((definition) => definition.
|
|
247
|
-
const groups =
|
|
176
|
+
const declared = contract?.groups?.groups;
|
|
177
|
+
if (declared !== void 0) {
|
|
178
|
+
const exposed = new Set(definitions.flatMap((definition) => definition.groups));
|
|
179
|
+
const groups = [...declared.values()].filter((group) => exposed.has(group.path)).map((group) => {
|
|
180
|
+
const name = group.lineage.map((path) => declared.get(path).title).join(" / ");
|
|
181
|
+
return group.description ? `- ${name}: ${group.description}` : `- ${name}`;
|
|
182
|
+
});
|
|
248
183
|
if (groups.length > 0) sections.push(`Groups:\n${groups.join("\n")}`);
|
|
249
184
|
}
|
|
250
185
|
if (authored) sections.push(authored);
|
|
@@ -447,7 +382,7 @@ const createMcpServer = (api, options) => {
|
|
|
447
382
|
const guardSchema = api[kizunajs_adapter.GUARD_SCHEMA_META];
|
|
448
383
|
const contextResolvers = api[kizunajs_adapter.REQUEST_CONTEXT_META];
|
|
449
384
|
const contract = (0, kizunajs_adapter.contractOf)(api);
|
|
450
|
-
const definitions =
|
|
385
|
+
const definitions = buildMcpTools(api.routes);
|
|
451
386
|
const server = new _modelcontextprotocol_server.McpServer({
|
|
452
387
|
name: options?.name ?? "MCP Server",
|
|
453
388
|
version: options?.version ?? "1.0.0"
|
|
@@ -459,7 +394,7 @@ const createMcpServer = (api, options) => {
|
|
|
459
394
|
outputSchema: definition.outputSchema,
|
|
460
395
|
annotations: buildToolAnnotations(definition.route)
|
|
461
396
|
}, async (args, context) => {
|
|
462
|
-
const refusal =
|
|
397
|
+
const refusal = approval(definition.route, context);
|
|
463
398
|
if (refusal !== void 0) return refusal;
|
|
464
399
|
return executeToolCall(definition.route, definition.routeKey, args ?? {}, router, options?.handlerContext, guards, schemes, options?.credentialHeaders, contextResolvers, options?.transportAuth, guardSchema);
|
|
465
400
|
});
|
|
@@ -573,7 +508,7 @@ const prepareOAuth = (oauth, endpointPath, api) => {
|
|
|
573
508
|
}),
|
|
574
509
|
metadataUrl: protectedResourceMetadataUrl(oauth, endpointPath),
|
|
575
510
|
scopesSupported: (0, kizunajs.declaredScopes)(schemeDefinition),
|
|
576
|
-
tools: new Map(
|
|
511
|
+
tools: new Map(buildMcpTools(api.routes).map((definition) => [definition.name, definition]))
|
|
577
512
|
};
|
|
578
513
|
};
|
|
579
514
|
/**
|
|
@@ -608,14 +543,25 @@ const toolCallTarget = (body, enforcement) => {
|
|
|
608
543
|
};
|
|
609
544
|
};
|
|
610
545
|
/**
|
|
611
|
-
* What answers
|
|
612
|
-
* declared `tool`, and the calls a model makes against them.
|
|
546
|
+
* What answers one MCP endpoint: the tool list built from the routes that
|
|
547
|
+
* declared `tool`, and the calls a model makes against them. The OAuth setup
|
|
548
|
+
* reads the app's identities, so it's prepared once the api has assembled:
|
|
549
|
+
* `validate` prepares it at startup, and the handlers reuse it.
|
|
613
550
|
*/
|
|
614
|
-
const
|
|
551
|
+
const mcpEndpoint = (props, api) => {
|
|
615
552
|
const serverApi = api;
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
553
|
+
let prepared;
|
|
554
|
+
const enforcementOf = () => {
|
|
555
|
+
if (props.oauth === void 0) return void 0;
|
|
556
|
+
prepared ??= prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
|
|
557
|
+
return prepared;
|
|
558
|
+
};
|
|
559
|
+
return {
|
|
560
|
+
validate: () => {
|
|
561
|
+
enforcementOf();
|
|
562
|
+
},
|
|
563
|
+
handle: async (args) => {
|
|
564
|
+
const enforcement = enforcementOf();
|
|
619
565
|
let transportAuth;
|
|
620
566
|
if (enforcement !== void 0) {
|
|
621
567
|
const target = toolCallTarget(args.body, enforcement);
|
|
@@ -650,60 +596,95 @@ const mcpServe = (props, api) => {
|
|
|
650
596
|
body: JSON.stringify(args.body)
|
|
651
597
|
})));
|
|
652
598
|
},
|
|
653
|
-
|
|
599
|
+
protectedResourceMetadata: () => (0, kizunajs_adapter.rawResponse)(new Response(JSON.stringify(enforcementOf()?.metadata), {
|
|
654
600
|
status: 200,
|
|
655
601
|
headers: { "content-type": "application/json" }
|
|
656
|
-
}))
|
|
657
|
-
}
|
|
602
|
+
}))
|
|
603
|
+
};
|
|
658
604
|
};
|
|
659
605
|
//#endregion
|
|
660
606
|
//#region src/plugin.ts
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
607
|
+
/**
|
|
608
|
+
* What the MCP endpoint is, and where. Which routes it publishes is each
|
|
609
|
+
* route's own business: declare `tool` on the ones a model may call.
|
|
610
|
+
*/
|
|
611
|
+
const McpPluginOptionsSchema = zod.z.object({
|
|
612
|
+
/**
|
|
613
|
+
* Path the endpoint is served from.
|
|
614
|
+
*
|
|
615
|
+
* @default '/mcp'
|
|
616
|
+
*/
|
|
617
|
+
path: kizunajs_plugin.RoutePathSchema.optional(),
|
|
618
|
+
/**
|
|
619
|
+
* Human-readable name shown to AI assistants.
|
|
620
|
+
*
|
|
621
|
+
* @default 'MCP Server'
|
|
622
|
+
*/
|
|
623
|
+
name: zod.z.string().optional(),
|
|
624
|
+
/**
|
|
625
|
+
* Semantic version string (e.g. "1.0.0").
|
|
626
|
+
*
|
|
627
|
+
* @default '1.0.0'
|
|
628
|
+
*/
|
|
629
|
+
version: zod.z.string().optional(),
|
|
630
|
+
/**
|
|
631
|
+
* Guidance for the model, appended to the overview built from the
|
|
632
|
+
* API's groups.
|
|
633
|
+
*/
|
|
634
|
+
instructions: zod.z.string().optional(),
|
|
635
|
+
/**
|
|
636
|
+
* Serve the endpoint as an OAuth 2.1 resource server, per the MCP
|
|
637
|
+
* authorization specification: RFC 9728 metadata on a well-known route,
|
|
638
|
+
* and HTTP `401`/`403` challenges built from the named identity.
|
|
639
|
+
*/
|
|
640
|
+
oauth: McpOAuthSchema.optional()
|
|
641
|
+
});
|
|
684
642
|
/**
|
|
685
643
|
* Let AI assistants use the API. Serves an MCP (Model Context Protocol)
|
|
686
644
|
* endpoint where every route declaring `tool` is one an assistant can discover
|
|
687
645
|
* and call, behind the same guards as the HTTP endpoints.
|
|
688
646
|
*
|
|
689
647
|
* The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
|
|
690
|
-
* adapter
|
|
691
|
-
* not see it.
|
|
648
|
+
* adapter.
|
|
692
649
|
*
|
|
693
650
|
* @example
|
|
694
651
|
* ```ts
|
|
695
652
|
* export default defineConfig({
|
|
696
653
|
* routes,
|
|
697
|
-
* plugins: [
|
|
654
|
+
* plugins: [
|
|
655
|
+
* mcpPlugin({
|
|
656
|
+
* name: 'My API',
|
|
657
|
+
* }),
|
|
658
|
+
* ],
|
|
698
659
|
* });
|
|
699
660
|
* ```
|
|
700
661
|
*/
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
}
|
|
662
|
+
const mcpPlugin = (0, kizunajs_plugin.definePlugin)({
|
|
663
|
+
slug: "mcp",
|
|
664
|
+
options: McpPluginOptionsSchema,
|
|
665
|
+
setup: ({ options, api }) => {
|
|
666
|
+
const endpointPath = options.path ?? "/mcp";
|
|
667
|
+
const endpoint = mcpEndpoint(options, api);
|
|
668
|
+
const routes = { endpoint: (0, kizunajs_plugin.route)({
|
|
669
|
+
method: "POST",
|
|
670
|
+
path: endpointPath,
|
|
671
|
+
summary: "MCP (Model Context Protocol) endpoint",
|
|
672
|
+
body: zod.z.unknown(),
|
|
673
|
+
responses: { 200: zod.z.unknown() }
|
|
674
|
+
}).handler(endpoint.handle) };
|
|
675
|
+
if (options.oauth !== void 0) routes.protectedResourceMetadata = (0, kizunajs_plugin.route)({
|
|
676
|
+
method: "GET",
|
|
677
|
+
path: protectedResourceMetadataPath(endpointPath),
|
|
678
|
+
summary: "OAuth protected resource metadata",
|
|
679
|
+
responses: { 200: kizunajs_schemas.ProtectedResourceMetadataSchema }
|
|
680
|
+
}).handler(endpoint.protectedResourceMetadata);
|
|
681
|
+
return {
|
|
682
|
+
routes,
|
|
683
|
+
validate: endpoint.validate
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
});
|
|
705
687
|
//#endregion
|
|
706
688
|
exports.buildInstructions = buildInstructions;
|
|
707
|
-
exports.buildToolDefinitions = buildToolDefinitions;
|
|
708
689
|
exports.createMcpServer = createMcpServer;
|
|
709
690
|
exports.mcpPlugin = mcpPlugin;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,122 +1,89 @@
|
|
|
1
|
+
import * as _$kizunajs_plugin0 from "kizunajs/plugin";
|
|
2
|
+
import { PluginRoutes } from "kizunajs/plugin";
|
|
1
3
|
import * as _$kizunajs from "kizunajs";
|
|
2
|
-
import { ApiDefinition, RouteDefinition
|
|
4
|
+
import { ApiDefinition, RouteDefinition } from "kizunajs";
|
|
3
5
|
import { z } from "zod";
|
|
4
|
-
import { RoutePath, WithSlug } from "kizunajs/plugin";
|
|
5
6
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
6
|
-
import { ApiWithRouter } from "kizunajs/adapter";
|
|
7
|
+
import { ApiWithRouter, ToolInputSchema } from "kizunajs/adapter";
|
|
7
8
|
|
|
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
9
|
//#region src/plugin.d.ts
|
|
24
10
|
/**
|
|
25
11
|
* What the MCP endpoint is, and where. Which routes it publishes is each
|
|
26
12
|
* route's own business: declare `tool` on the ones a model may call.
|
|
27
13
|
*/
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
}>;
|
|
14
|
+
declare const McpPluginOptionsSchema: z.ZodObject<{
|
|
15
|
+
path: z.ZodOptional<z.ZodCustom<`/${string}`, `/${string}`>>;
|
|
16
|
+
name: z.ZodOptional<z.ZodString>;
|
|
17
|
+
version: z.ZodOptional<z.ZodString>;
|
|
18
|
+
instructions: z.ZodOptional<z.ZodString>;
|
|
19
|
+
oauth: z.ZodOptional<z.ZodObject<{
|
|
20
|
+
resource: z.ZodString;
|
|
21
|
+
scheme: z.ZodString;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
/**
|
|
25
|
+
* What the MCP endpoint is, and where.
|
|
26
|
+
*/
|
|
27
|
+
type McpPluginProps = z.output<typeof McpPluginOptionsSchema>;
|
|
94
28
|
/**
|
|
95
29
|
* Let AI assistants use the API. Serves an MCP (Model Context Protocol)
|
|
96
30
|
* endpoint where every route declaring `tool` is one an assistant can discover
|
|
97
31
|
* and call, behind the same guards as the HTTP endpoints.
|
|
98
32
|
*
|
|
99
33
|
* The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
|
|
100
|
-
* adapter
|
|
101
|
-
* not see it.
|
|
34
|
+
* adapter.
|
|
102
35
|
*
|
|
103
36
|
* @example
|
|
104
37
|
* ```ts
|
|
105
38
|
* export default defineConfig({
|
|
106
39
|
* routes,
|
|
107
|
-
* plugins: [
|
|
40
|
+
* plugins: [
|
|
41
|
+
* mcpPlugin({
|
|
42
|
+
* name: 'My API',
|
|
43
|
+
* }),
|
|
44
|
+
* ],
|
|
108
45
|
* });
|
|
109
46
|
* ```
|
|
110
47
|
*/
|
|
111
|
-
declare
|
|
48
|
+
declare const mcpPlugin: {
|
|
49
|
+
<const Slug extends string>(options: {
|
|
50
|
+
path?: `/${string}` | undefined;
|
|
51
|
+
name?: string | undefined;
|
|
52
|
+
version?: string | undefined;
|
|
53
|
+
instructions?: string | undefined;
|
|
54
|
+
oauth?: {
|
|
55
|
+
resource: string;
|
|
56
|
+
scheme: string;
|
|
57
|
+
} | undefined;
|
|
58
|
+
} & {
|
|
59
|
+
basePath?: never;
|
|
60
|
+
} & _$kizunajs_plugin0.SlugOption<Slug>): _$kizunajs.PluginDeclaration<Slug, {
|
|
61
|
+
routes: PluginRoutes;
|
|
62
|
+
validate: () => void;
|
|
63
|
+
}>;
|
|
64
|
+
(options?: ({
|
|
65
|
+
path?: `/${string}` | undefined;
|
|
66
|
+
name?: string | undefined;
|
|
67
|
+
version?: string | undefined;
|
|
68
|
+
instructions?: string | undefined;
|
|
69
|
+
oauth?: {
|
|
70
|
+
resource: string;
|
|
71
|
+
scheme: string;
|
|
72
|
+
} | undefined;
|
|
73
|
+
} & {
|
|
74
|
+
basePath?: never;
|
|
75
|
+
}) | undefined): _$kizunajs.PluginDeclaration<"mcp", {
|
|
76
|
+
routes: PluginRoutes;
|
|
77
|
+
validate: () => void;
|
|
78
|
+
}>;
|
|
79
|
+
};
|
|
112
80
|
//#endregion
|
|
113
|
-
//#region src/
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
81
|
+
//#region src/oauth.d.ts
|
|
82
|
+
declare const McpOAuthSchema: z.ZodObject<{
|
|
83
|
+
resource: z.ZodString;
|
|
84
|
+
scheme: z.ZodString;
|
|
85
|
+
}, z.core.$strip>;
|
|
86
|
+
type McpOAuthProps = z.output<typeof McpOAuthSchema>;
|
|
120
87
|
//#endregion
|
|
121
88
|
//#region src/mcp-server.d.ts
|
|
122
89
|
interface McpServerOptions {
|
|
@@ -141,7 +108,7 @@ interface McpServerOptions {
|
|
|
141
108
|
onlyReadOnly?: boolean;
|
|
142
109
|
/**
|
|
143
110
|
* Guidance for the model, appended to the overview built from the
|
|
144
|
-
*
|
|
111
|
+
* API's groups. Use it for what belongs to no single route: the order
|
|
145
112
|
* operations happen in, the conventions every route shares.
|
|
146
113
|
*/
|
|
147
114
|
instructions?: string;
|
|
@@ -170,7 +137,7 @@ interface McpServerOptions {
|
|
|
170
137
|
context?: Record<string, unknown>;
|
|
171
138
|
};
|
|
172
139
|
}
|
|
173
|
-
interface
|
|
140
|
+
interface McpTool {
|
|
174
141
|
name: string;
|
|
175
142
|
title: string | undefined;
|
|
176
143
|
description: string;
|
|
@@ -178,13 +145,15 @@ interface ToolDefinition {
|
|
|
178
145
|
outputSchema: z.ZodType;
|
|
179
146
|
route: RouteDefinition;
|
|
180
147
|
routeKey: string;
|
|
181
|
-
|
|
148
|
+
/**
|
|
149
|
+
* The route's groups, as dotted paths.
|
|
150
|
+
*/
|
|
151
|
+
groups: string[];
|
|
182
152
|
}
|
|
183
|
-
declare const buildToolDefinitions: (routes: Routes) => ToolDefinition[];
|
|
184
153
|
/**
|
|
185
154
|
* What a client puts in front of the model before it picks a tool.
|
|
186
155
|
*/
|
|
187
|
-
declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly
|
|
156
|
+
declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly McpTool[], authored: string | undefined) => string;
|
|
188
157
|
/**
|
|
189
158
|
* Create an MCP server from a kizuna API.
|
|
190
159
|
*
|
|
@@ -200,4 +169,4 @@ declare const buildInstructions: (contract: ApiDefinition | undefined, definitio
|
|
|
200
169
|
*/
|
|
201
170
|
declare const createMcpServer: (api: ApiWithRouter, options?: McpServerOptions) => McpServer;
|
|
202
171
|
//#endregion
|
|
203
|
-
export { type McpOAuthProps, type McpPluginProps, type McpServerOptions,
|
|
172
|
+
export { type McpOAuthProps, type McpPluginProps, type McpServerOptions, buildInstructions, createMcpServer, mcpPlugin };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,122 +1,89 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import
|
|
2
|
+
import * as _$kizunajs_plugin0 from "kizunajs/plugin";
|
|
3
|
+
import { PluginRoutes } from "kizunajs/plugin";
|
|
3
4
|
import * as _$kizunajs from "kizunajs";
|
|
4
|
-
import { ApiDefinition, RouteDefinition
|
|
5
|
+
import { ApiDefinition, RouteDefinition } from "kizunajs";
|
|
5
6
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
6
|
-
import { ApiWithRouter } from "kizunajs/adapter";
|
|
7
|
+
import { ApiWithRouter, ToolInputSchema } from "kizunajs/adapter";
|
|
7
8
|
|
|
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
9
|
//#region src/plugin.d.ts
|
|
24
10
|
/**
|
|
25
11
|
* What the MCP endpoint is, and where. Which routes it publishes is each
|
|
26
12
|
* route's own business: declare `tool` on the ones a model may call.
|
|
27
13
|
*/
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
}>;
|
|
14
|
+
declare const McpPluginOptionsSchema: z.ZodObject<{
|
|
15
|
+
path: z.ZodOptional<z.ZodCustom<`/${string}`, `/${string}`>>;
|
|
16
|
+
name: z.ZodOptional<z.ZodString>;
|
|
17
|
+
version: z.ZodOptional<z.ZodString>;
|
|
18
|
+
instructions: z.ZodOptional<z.ZodString>;
|
|
19
|
+
oauth: z.ZodOptional<z.ZodObject<{
|
|
20
|
+
resource: z.ZodString;
|
|
21
|
+
scheme: z.ZodString;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
/**
|
|
25
|
+
* What the MCP endpoint is, and where.
|
|
26
|
+
*/
|
|
27
|
+
type McpPluginProps = z.output<typeof McpPluginOptionsSchema>;
|
|
94
28
|
/**
|
|
95
29
|
* Let AI assistants use the API. Serves an MCP (Model Context Protocol)
|
|
96
30
|
* endpoint where every route declaring `tool` is one an assistant can discover
|
|
97
31
|
* and call, behind the same guards as the HTTP endpoints.
|
|
98
32
|
*
|
|
99
33
|
* The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
|
|
100
|
-
* adapter
|
|
101
|
-
* not see it.
|
|
34
|
+
* adapter.
|
|
102
35
|
*
|
|
103
36
|
* @example
|
|
104
37
|
* ```ts
|
|
105
38
|
* export default defineConfig({
|
|
106
39
|
* routes,
|
|
107
|
-
* plugins: [
|
|
40
|
+
* plugins: [
|
|
41
|
+
* mcpPlugin({
|
|
42
|
+
* name: 'My API',
|
|
43
|
+
* }),
|
|
44
|
+
* ],
|
|
108
45
|
* });
|
|
109
46
|
* ```
|
|
110
47
|
*/
|
|
111
|
-
declare
|
|
48
|
+
declare const mcpPlugin: {
|
|
49
|
+
<const Slug extends string>(options: {
|
|
50
|
+
path?: `/${string}` | undefined;
|
|
51
|
+
name?: string | undefined;
|
|
52
|
+
version?: string | undefined;
|
|
53
|
+
instructions?: string | undefined;
|
|
54
|
+
oauth?: {
|
|
55
|
+
resource: string;
|
|
56
|
+
scheme: string;
|
|
57
|
+
} | undefined;
|
|
58
|
+
} & {
|
|
59
|
+
basePath?: never;
|
|
60
|
+
} & _$kizunajs_plugin0.SlugOption<Slug>): _$kizunajs.PluginDeclaration<Slug, {
|
|
61
|
+
routes: PluginRoutes;
|
|
62
|
+
validate: () => void;
|
|
63
|
+
}>;
|
|
64
|
+
(options?: ({
|
|
65
|
+
path?: `/${string}` | undefined;
|
|
66
|
+
name?: string | undefined;
|
|
67
|
+
version?: string | undefined;
|
|
68
|
+
instructions?: string | undefined;
|
|
69
|
+
oauth?: {
|
|
70
|
+
resource: string;
|
|
71
|
+
scheme: string;
|
|
72
|
+
} | undefined;
|
|
73
|
+
} & {
|
|
74
|
+
basePath?: never;
|
|
75
|
+
}) | undefined): _$kizunajs.PluginDeclaration<"mcp", {
|
|
76
|
+
routes: PluginRoutes;
|
|
77
|
+
validate: () => void;
|
|
78
|
+
}>;
|
|
79
|
+
};
|
|
112
80
|
//#endregion
|
|
113
|
-
//#region src/
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}
|
|
81
|
+
//#region src/oauth.d.ts
|
|
82
|
+
declare const McpOAuthSchema: z.ZodObject<{
|
|
83
|
+
resource: z.ZodString;
|
|
84
|
+
scheme: z.ZodString;
|
|
85
|
+
}, z.core.$strip>;
|
|
86
|
+
type McpOAuthProps = z.output<typeof McpOAuthSchema>;
|
|
120
87
|
//#endregion
|
|
121
88
|
//#region src/mcp-server.d.ts
|
|
122
89
|
interface McpServerOptions {
|
|
@@ -141,7 +108,7 @@ interface McpServerOptions {
|
|
|
141
108
|
onlyReadOnly?: boolean;
|
|
142
109
|
/**
|
|
143
110
|
* Guidance for the model, appended to the overview built from the
|
|
144
|
-
*
|
|
111
|
+
* API's groups. Use it for what belongs to no single route: the order
|
|
145
112
|
* operations happen in, the conventions every route shares.
|
|
146
113
|
*/
|
|
147
114
|
instructions?: string;
|
|
@@ -170,7 +137,7 @@ interface McpServerOptions {
|
|
|
170
137
|
context?: Record<string, unknown>;
|
|
171
138
|
};
|
|
172
139
|
}
|
|
173
|
-
interface
|
|
140
|
+
interface McpTool {
|
|
174
141
|
name: string;
|
|
175
142
|
title: string | undefined;
|
|
176
143
|
description: string;
|
|
@@ -178,13 +145,15 @@ interface ToolDefinition {
|
|
|
178
145
|
outputSchema: z.ZodType;
|
|
179
146
|
route: RouteDefinition;
|
|
180
147
|
routeKey: string;
|
|
181
|
-
|
|
148
|
+
/**
|
|
149
|
+
* The route's groups, as dotted paths.
|
|
150
|
+
*/
|
|
151
|
+
groups: string[];
|
|
182
152
|
}
|
|
183
|
-
declare const buildToolDefinitions: (routes: Routes) => ToolDefinition[];
|
|
184
153
|
/**
|
|
185
154
|
* What a client puts in front of the model before it picks a tool.
|
|
186
155
|
*/
|
|
187
|
-
declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly
|
|
156
|
+
declare const buildInstructions: (contract: ApiDefinition | undefined, definitions: readonly McpTool[], authored: string | undefined) => string;
|
|
188
157
|
/**
|
|
189
158
|
* Create an MCP server from a kizuna API.
|
|
190
159
|
*
|
|
@@ -200,4 +169,4 @@ declare const buildInstructions: (contract: ApiDefinition | undefined, definitio
|
|
|
200
169
|
*/
|
|
201
170
|
declare const createMcpServer: (api: ApiWithRouter, options?: McpServerOptions) => McpServer;
|
|
202
171
|
//#endregion
|
|
203
|
-
export { type McpOAuthProps, type McpPluginProps, type McpServerOptions,
|
|
172
|
+
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 {
|
|
2
|
+
import { RoutePathSchema, definePlugin, route } from "kizunajs/plugin";
|
|
3
3
|
import { ProtectedResourceMetadataSchema } from "kizunajs/schemas";
|
|
4
|
-
import { assertCanonicalResourceUri, buildProtectedResourceMetadata, declaredScopes, problemDetails, problemFromBody
|
|
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,
|
|
7
|
-
import { deriveToolNames, isJsonMediaType, isStreamResponse, isSuccessStatus, isVoidSchema,
|
|
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
|
|
102
|
+
const APPROVAL_KEY = "approved";
|
|
147
103
|
/**
|
|
148
|
-
* Ask before running, when the
|
|
149
|
-
*
|
|
150
|
-
*
|
|
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
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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: {
|
|
115
|
+
properties: { approved: {
|
|
161
116
|
type: "boolean",
|
|
162
|
-
title: "
|
|
117
|
+
title: "Allow"
|
|
163
118
|
} },
|
|
164
|
-
required: [
|
|
119
|
+
required: [APPROVAL_KEY]
|
|
165
120
|
}
|
|
166
121
|
}) } });
|
|
167
|
-
if (answer.
|
|
122
|
+
if (answer.approved === true) return void 0;
|
|
168
123
|
return {
|
|
169
124
|
content: [{
|
|
170
125
|
type: "text",
|
|
@@ -189,47 +144,24 @@ const buildToolAnnotations = (route) => {
|
|
|
189
144
|
...declared.openWorldHint === void 0 ? {} : { openWorldHint: declared.openWorldHint }
|
|
190
145
|
};
|
|
191
146
|
};
|
|
192
|
-
const
|
|
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,
|
|
219
151
|
origin: "route"
|
|
220
152
|
})));
|
|
221
153
|
const definitions = [];
|
|
222
|
-
for (const { routeKey, route,
|
|
154
|
+
for (const { routeKey, route, routeGroups } of selected) {
|
|
223
155
|
const name = names.get(routeKey);
|
|
224
156
|
definitions.push({
|
|
225
157
|
name,
|
|
226
158
|
title: route.summary,
|
|
227
|
-
description:
|
|
159
|
+
description: describeTool(route),
|
|
228
160
|
inputSchema: buildToolInputSchema(route),
|
|
229
161
|
outputSchema: buildToolOutputSchema(route),
|
|
230
162
|
route,
|
|
231
163
|
routeKey,
|
|
232
|
-
|
|
164
|
+
groups: routeGroups
|
|
233
165
|
});
|
|
234
166
|
}
|
|
235
167
|
return definitions;
|
|
@@ -240,10 +172,13 @@ const buildToolDefinitions = (routes) => {
|
|
|
240
172
|
const buildInstructions = (contract, definitions, authored) => {
|
|
241
173
|
const sections = [];
|
|
242
174
|
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
|
|
244
|
-
if (
|
|
245
|
-
const exposed = new Set(definitions.flatMap((definition) => definition.
|
|
246
|
-
const groups =
|
|
175
|
+
const declared = contract?.groups?.groups;
|
|
176
|
+
if (declared !== void 0) {
|
|
177
|
+
const exposed = new Set(definitions.flatMap((definition) => definition.groups));
|
|
178
|
+
const groups = [...declared.values()].filter((group) => exposed.has(group.path)).map((group) => {
|
|
179
|
+
const name = group.lineage.map((path) => declared.get(path).title).join(" / ");
|
|
180
|
+
return group.description ? `- ${name}: ${group.description}` : `- ${name}`;
|
|
181
|
+
});
|
|
247
182
|
if (groups.length > 0) sections.push(`Groups:\n${groups.join("\n")}`);
|
|
248
183
|
}
|
|
249
184
|
if (authored) sections.push(authored);
|
|
@@ -446,7 +381,7 @@ const createMcpServer = (api, options) => {
|
|
|
446
381
|
const guardSchema = api[GUARD_SCHEMA_META];
|
|
447
382
|
const contextResolvers = api[REQUEST_CONTEXT_META];
|
|
448
383
|
const contract = contractOf(api);
|
|
449
|
-
const definitions =
|
|
384
|
+
const definitions = buildMcpTools(api.routes);
|
|
450
385
|
const server = new McpServer({
|
|
451
386
|
name: options?.name ?? "MCP Server",
|
|
452
387
|
version: options?.version ?? "1.0.0"
|
|
@@ -458,7 +393,7 @@ const createMcpServer = (api, options) => {
|
|
|
458
393
|
outputSchema: definition.outputSchema,
|
|
459
394
|
annotations: buildToolAnnotations(definition.route)
|
|
460
395
|
}, async (args, context) => {
|
|
461
|
-
const refusal =
|
|
396
|
+
const refusal = approval(definition.route, context);
|
|
462
397
|
if (refusal !== void 0) return refusal;
|
|
463
398
|
return executeToolCall(definition.route, definition.routeKey, args ?? {}, router, options?.handlerContext, guards, schemes, options?.credentialHeaders, contextResolvers, options?.transportAuth, guardSchema);
|
|
464
399
|
});
|
|
@@ -572,7 +507,7 @@ const prepareOAuth = (oauth, endpointPath, api) => {
|
|
|
572
507
|
}),
|
|
573
508
|
metadataUrl: protectedResourceMetadataUrl(oauth, endpointPath),
|
|
574
509
|
scopesSupported: declaredScopes(schemeDefinition),
|
|
575
|
-
tools: new Map(
|
|
510
|
+
tools: new Map(buildMcpTools(api.routes).map((definition) => [definition.name, definition]))
|
|
576
511
|
};
|
|
577
512
|
};
|
|
578
513
|
/**
|
|
@@ -607,14 +542,25 @@ const toolCallTarget = (body, enforcement) => {
|
|
|
607
542
|
};
|
|
608
543
|
};
|
|
609
544
|
/**
|
|
610
|
-
* What answers
|
|
611
|
-
* declared `tool`, and the calls a model makes against them.
|
|
545
|
+
* What answers one MCP endpoint: the tool list built from the routes that
|
|
546
|
+
* declared `tool`, and the calls a model makes against them. The OAuth setup
|
|
547
|
+
* reads the app's identities, so it's prepared once the api has assembled:
|
|
548
|
+
* `validate` prepares it at startup, and the handlers reuse it.
|
|
612
549
|
*/
|
|
613
|
-
const
|
|
550
|
+
const mcpEndpoint = (props, api) => {
|
|
614
551
|
const serverApi = api;
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
552
|
+
let prepared;
|
|
553
|
+
const enforcementOf = () => {
|
|
554
|
+
if (props.oauth === void 0) return void 0;
|
|
555
|
+
prepared ??= prepareOAuth(props.oauth, props.path ?? "/mcp", serverApi);
|
|
556
|
+
return prepared;
|
|
557
|
+
};
|
|
558
|
+
return {
|
|
559
|
+
validate: () => {
|
|
560
|
+
enforcementOf();
|
|
561
|
+
},
|
|
562
|
+
handle: async (args) => {
|
|
563
|
+
const enforcement = enforcementOf();
|
|
618
564
|
let transportAuth;
|
|
619
565
|
if (enforcement !== void 0) {
|
|
620
566
|
const target = toolCallTarget(args.body, enforcement);
|
|
@@ -649,36 +595,11 @@ const mcpServe = (props, api) => {
|
|
|
649
595
|
body: JSON.stringify(args.body)
|
|
650
596
|
})));
|
|
651
597
|
},
|
|
652
|
-
|
|
598
|
+
protectedResourceMetadata: () => rawResponse(new Response(JSON.stringify(enforcementOf()?.metadata), {
|
|
653
599
|
status: 200,
|
|
654
600
|
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
|
-
});
|
|
601
|
+
}))
|
|
602
|
+
};
|
|
682
603
|
};
|
|
683
604
|
/**
|
|
684
605
|
* Let AI assistants use the API. Serves an MCP (Model Context Protocol)
|
|
@@ -686,20 +607,74 @@ const declare = (slug, props) => {
|
|
|
686
607
|
* and call, behind the same guards as the HTTP endpoints.
|
|
687
608
|
*
|
|
688
609
|
* The endpoint is an ordinary kizuna route, so `api.mount` serves it on any
|
|
689
|
-
* adapter
|
|
690
|
-
* not see it.
|
|
610
|
+
* adapter.
|
|
691
611
|
*
|
|
692
612
|
* @example
|
|
693
613
|
* ```ts
|
|
694
614
|
* export default defineConfig({
|
|
695
615
|
* routes,
|
|
696
|
-
* plugins: [
|
|
616
|
+
* plugins: [
|
|
617
|
+
* mcpPlugin({
|
|
618
|
+
* name: 'My API',
|
|
619
|
+
* }),
|
|
620
|
+
* ],
|
|
697
621
|
* });
|
|
698
622
|
* ```
|
|
699
623
|
*/
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
624
|
+
const mcpPlugin = definePlugin({
|
|
625
|
+
slug: "mcp",
|
|
626
|
+
options: z.object({
|
|
627
|
+
/**
|
|
628
|
+
* Path the endpoint is served from.
|
|
629
|
+
*
|
|
630
|
+
* @default '/mcp'
|
|
631
|
+
*/
|
|
632
|
+
path: RoutePathSchema.optional(),
|
|
633
|
+
/**
|
|
634
|
+
* Human-readable name shown to AI assistants.
|
|
635
|
+
*
|
|
636
|
+
* @default 'MCP Server'
|
|
637
|
+
*/
|
|
638
|
+
name: z.string().optional(),
|
|
639
|
+
/**
|
|
640
|
+
* Semantic version string (e.g. "1.0.0").
|
|
641
|
+
*
|
|
642
|
+
* @default '1.0.0'
|
|
643
|
+
*/
|
|
644
|
+
version: z.string().optional(),
|
|
645
|
+
/**
|
|
646
|
+
* Guidance for the model, appended to the overview built from the
|
|
647
|
+
* API's groups.
|
|
648
|
+
*/
|
|
649
|
+
instructions: z.string().optional(),
|
|
650
|
+
/**
|
|
651
|
+
* Serve the endpoint as an OAuth 2.1 resource server, per the MCP
|
|
652
|
+
* authorization specification: RFC 9728 metadata on a well-known route,
|
|
653
|
+
* and HTTP `401`/`403` challenges built from the named identity.
|
|
654
|
+
*/
|
|
655
|
+
oauth: McpOAuthSchema.optional()
|
|
656
|
+
}),
|
|
657
|
+
setup: ({ options, api }) => {
|
|
658
|
+
const endpointPath = options.path ?? "/mcp";
|
|
659
|
+
const endpoint = mcpEndpoint(options, api);
|
|
660
|
+
const routes = { endpoint: route({
|
|
661
|
+
method: "POST",
|
|
662
|
+
path: endpointPath,
|
|
663
|
+
summary: "MCP (Model Context Protocol) endpoint",
|
|
664
|
+
body: z.unknown(),
|
|
665
|
+
responses: { 200: z.unknown() }
|
|
666
|
+
}).handler(endpoint.handle) };
|
|
667
|
+
if (options.oauth !== void 0) routes.protectedResourceMetadata = route({
|
|
668
|
+
method: "GET",
|
|
669
|
+
path: protectedResourceMetadataPath(endpointPath),
|
|
670
|
+
summary: "OAuth protected resource metadata",
|
|
671
|
+
responses: { 200: ProtectedResourceMetadataSchema }
|
|
672
|
+
}).handler(endpoint.protectedResourceMetadata);
|
|
673
|
+
return {
|
|
674
|
+
routes,
|
|
675
|
+
validate: endpoint.validate
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
});
|
|
704
679
|
//#endregion
|
|
705
|
-
export { buildInstructions,
|
|
680
|
+
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
|
+
"version": "2.0.0-beta.20",
|
|
4
4
|
"description": "MCP endpoint for Kizuna.js, so AI assistants can call your routes",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kizunajs",
|
|
@@ -60,18 +60,18 @@
|
|
|
60
60
|
"@modelcontextprotocol/server": "^2.0.0"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
|
-
"
|
|
64
|
-
"
|
|
63
|
+
"kizunajs": "2.0.0-beta.20",
|
|
64
|
+
"zod": "^4.0.0"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@modelcontextprotocol/client": "^2.0.0",
|
|
68
|
+
"kizunajs": "2.0.0-beta.20",
|
|
69
|
+
"@kizunajs/express": "2.0.0-beta.20",
|
|
68
70
|
"@types/express": "^5.0.0",
|
|
69
71
|
"express": "^5.0.0",
|
|
70
72
|
"tsdown": "^0.21.0",
|
|
71
73
|
"typescript": "^6.0.3",
|
|
72
|
-
"zod": "^4.0.0"
|
|
73
|
-
"kizunajs": "2.0.0-beta.2",
|
|
74
|
-
"@kizunajs/express": "2.0.0-beta.2"
|
|
74
|
+
"zod": "^4.0.0"
|
|
75
75
|
},
|
|
76
76
|
"scripts": {
|
|
77
77
|
"build": "tsdown src/index.ts --format esm,cjs --dts --clean --external kizunajs --external zod --external @modelcontextprotocol/sdk",
|