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