@donghanh/hono 0.3.5 → 0.4.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/src/mcp.ts CHANGED
@@ -1,10 +1,21 @@
1
1
  import type { Executor, OperationDetail, Registry } from "@donghanh/core";
2
2
  import { executeOperation } from "@donghanh/core";
3
3
  import { Hono } from "hono";
4
+ import {
5
+ catalogTools,
6
+ isMetaTool,
7
+ RUN_CLASS,
8
+ runToolFor,
9
+ securitySchemesFor,
10
+ } from "./catalog";
11
+ import type { ExposureConfig } from "./exposure";
12
+ import { resolveExposure } from "./exposure";
4
13
  import type { Authenticate } from "./middleware";
14
+ import { negotiateProtocolVersion } from "./protocol";
15
+ import type { ChatGptResult } from "./renderers/chatgpt";
5
16
  import { renderForChatGpt } from "./renderers/chatgpt";
6
17
 
7
- const MCP_PROTOCOL_VERSION = "2026-01-26";
18
+ const INSTRUCTIONS_WARN_LENGTH = 4096;
8
19
  const UI_MIME_TYPE = "text/html;profile=mcp-app";
9
20
 
10
21
  export interface WidgetConfig {
@@ -34,9 +45,31 @@ export interface McpRoutesConfig {
34
45
  scopes?: string[];
35
46
  resourceDocumentation?: string;
36
47
  serverInfo?: { name: string; version: string };
48
+ /** Endpoint path for the JSON-RPC handler (default "/mcp"). */
49
+ path?: string;
50
+ /** Mount `/.well-known/oauth-protected-resource` (default true). */
51
+ metadata?: boolean;
52
+ /** Appended to the app's instructions in `initialize` (only when the app has instructions). */
53
+ instructionsSuffix?: string;
37
54
  encodeVariables?: (vars: Record<string, unknown>) => string;
55
+ /**
56
+ * Append the result's next-step actions to the tool text as a `Next:` block
57
+ * (default true). `structuredContent.actions` is unaffected.
58
+ */
59
+ actionsInText?: boolean;
60
+ /** Which operations are tools, and which only the catalog (default: all tools). */
61
+ exposure?: ExposureConfig;
38
62
  /** Named widgets. Operation's `widget` config key must match a name here. */
39
63
  widgets?: Record<string, WidgetConfig>;
64
+ /**
65
+ * Final say on a tool's `outputSchema`. Called for every tool with the default
66
+ * wrapped schema (or undefined when the operation has no response schema);
67
+ * the return value is used as is, undefined omits it.
68
+ */
69
+ outputSchema?: (
70
+ op: OperationDetail,
71
+ wrapped: object | undefined,
72
+ ) => object | undefined;
40
73
  /** Hook to enrich `structuredContent` after execution (e.g. inject display text) */
41
74
  enrichResponse?: (
42
75
  structured: Record<string, unknown>,
@@ -95,28 +128,18 @@ function wwwAuthenticate(
95
128
  return `Bearer resource_metadata="${resource}/.well-known/oauth-protected-resource", error="${error}", error_description="${description}"`;
96
129
  }
97
130
 
98
- function securitySchemesFor(
99
- detail: OperationDetail | null,
100
- defaultScopes: string[],
101
- ): Array<{ type: "noauth" } | { type: "oauth2"; scopes: string[] }> {
102
- const auth = detail?.auth ?? "required";
103
- const scopes = detail?.scopes ?? defaultScopes;
104
- if (auth === "none") return [{ type: "noauth" }];
105
- if (auth === "optional")
106
- return [{ type: "noauth" }, { type: "oauth2", scopes }];
107
- return [{ type: "oauth2", scopes }];
108
- }
109
-
110
131
  function annotationsFor(detail: OperationDetail | null): {
111
132
  readOnlyHint: boolean;
112
133
  openWorldHint: boolean;
113
134
  destructiveHint: boolean;
135
+ idempotentHint: boolean;
114
136
  } {
115
137
  if (!detail) {
116
138
  return {
117
139
  readOnlyHint: false,
118
140
  openWorldHint: true,
119
141
  destructiveHint: false,
142
+ idempotentHint: false,
120
143
  };
121
144
  }
122
145
  const readOnly = detail.type === "query";
@@ -124,9 +147,39 @@ function annotationsFor(detail: OperationDetail | null): {
124
147
  readOnlyHint: readOnly,
125
148
  openWorldHint: readOnly ? false : (detail.external ?? false),
126
149
  destructiveHint: readOnly ? false : (detail.destructive ?? false),
150
+ idempotentHint: detail.idempotent ?? false,
127
151
  };
128
152
  }
129
153
 
154
+ /**
155
+ * Model-visible text for a tool result: the brief's messages, then the next-step
156
+ * actions as a `Next:` list (`- label (operation id)`, or `run_*` for catalog operations). Falls back to "OK".
157
+ */
158
+ function toolText(
159
+ rendered: ChatGptResult,
160
+ actionsInText: boolean,
161
+ runTool: (operationId: string) => string | undefined = () => undefined,
162
+ ): string {
163
+ const blocks: string[] = [];
164
+ if (rendered.nextSteps) blocks.push(rendered.nextSteps);
165
+ if (actionsInText && rendered.suggestedActions.length > 0) {
166
+ blocks.push(
167
+ [
168
+ "Next:",
169
+ ...rendered.suggestedActions.map((a) => {
170
+ const vars = a.variables ? JSON.stringify(a.variables) : undefined;
171
+ const run = runTool(a.id);
172
+ if (run) {
173
+ return `- ${a.description} (${run} id="${a.id}"${vars ? ` variables=${vars}` : ""})`;
174
+ }
175
+ return `- ${a.description} (${a.id}${vars ? ` ${vars}` : ""})`;
176
+ }),
177
+ ].join("\n"),
178
+ );
179
+ }
180
+ return blocks.length > 0 ? blocks.join("\n\n") : "OK";
181
+ }
182
+
130
183
  function widgetMetaFor(widget: WidgetConfig): Record<string, unknown> {
131
184
  const ui: Record<string, unknown> = {};
132
185
  if (widget.prefersBorder) ui.prefersBorder = true;
@@ -145,65 +198,355 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
145
198
  scopes = [],
146
199
  resourceDocumentation,
147
200
  serverInfo = { name: "donghanh-mcp", version: "0.1.0" },
201
+ path = "/mcp",
202
+ metadata = true,
203
+ instructionsSuffix = "",
148
204
  encodeVariables,
205
+ actionsInText = true,
149
206
  widgets = {},
150
207
  enrichResponse,
208
+ outputSchema,
209
+ exposure,
151
210
  } = config;
152
211
 
212
+ const resolved = resolveExposure(registry, exposure);
213
+ const metaTools = catalogTools(registry, resolved, scopes);
214
+ const metaNames = new Set(metaTools.map((t) => t.name));
215
+ for (const name of metaNames) {
216
+ if (registry.get(name)) {
217
+ throw new Error(
218
+ `Operation id "${name}" collides with the generated catalog meta-tool of the same name`,
219
+ );
220
+ }
221
+ }
222
+
223
+ const authFailure = () => {
224
+ const challenge = wwwAuthenticate(
225
+ resource,
226
+ "insufficient_scope",
227
+ "You need to login to continue",
228
+ );
229
+ return {
230
+ body: {
231
+ content: [{ type: "text", text: "Authentication required." }],
232
+ isError: true,
233
+ _meta: { "mcp/www_authenticate": [challenge] },
234
+ },
235
+ challenge,
236
+ };
237
+ };
238
+
239
+ const errorResult = (text: string) => ({
240
+ content: [{ type: "text", text }],
241
+ isError: true,
242
+ });
243
+
244
+ /** Execute one operation exactly as a direct tool call does. */
245
+ async function runOperation(
246
+ request: Request,
247
+ operationId: string,
248
+ variables: Record<string, unknown>,
249
+ intent?: string,
250
+ ): Promise<{ body: Record<string, unknown>; challenge?: string }> {
251
+ const op = registry.get(operationId);
252
+ if (!op) return { body: errorResult(`Unknown operation "${operationId}"`) };
253
+ const detail = registry.detail(operationId);
254
+ const authMode = detail?.auth ?? "required";
255
+
256
+ let userId: string | null = null;
257
+ if (authMode !== "none") {
258
+ const authResult = await authenticate(request);
259
+ if ("error" in authResult) {
260
+ if (authMode === "required") return authFailure();
261
+ // optional: proceed anonymously
262
+ } else {
263
+ userId = authResult.userId;
264
+ }
265
+ }
266
+
267
+ try {
268
+ const { data, brief } = await executeOperation({
269
+ registry,
270
+ operationId,
271
+ variables,
272
+ executor,
273
+ context: {
274
+ userId,
275
+ request,
276
+ ...(intent !== undefined && { intent }),
277
+ },
278
+ });
279
+
280
+ const rendered = renderForChatGpt(brief, {
281
+ encodeVariables,
282
+ getOperationInput: (opId) => registry.detail(opId)?.input,
283
+ });
284
+
285
+ const structured: Record<string, unknown> = {
286
+ [op.operationConfig.responseKey]: data,
287
+ };
288
+ if (rendered.suggestedActions.length > 0) {
289
+ structured.actions = rendered.suggestedActions;
290
+ }
291
+ if (rendered.display !== undefined) {
292
+ structured.display = rendered.display;
293
+ }
294
+
295
+ if (enrichResponse) {
296
+ await enrichResponse(structured, {
297
+ operationId,
298
+ data,
299
+ variables,
300
+ userId,
301
+ request,
302
+ });
303
+ }
304
+
305
+ const meta: Record<string, unknown> = {};
306
+ if (rendered.context && rendered.context.length > 0) {
307
+ meta["donghanh/context"] = rendered.context;
308
+ }
309
+
310
+ const widgetName = detail?.widget;
311
+ const widget = widgetName ? widgets[widgetName] : undefined;
312
+ if (widget) {
313
+ meta.ui = { resourceUri: widget.uri };
314
+ meta["openai/outputTemplate"] = widget.uri;
315
+ }
316
+
317
+ return {
318
+ body: {
319
+ content: [
320
+ {
321
+ type: "text",
322
+ text: toolText(rendered, actionsInText, (opId) => {
323
+ if (
324
+ resolved.placement.get(opId) !== "catalog" ||
325
+ resolved.appOnly.has(opId)
326
+ ) {
327
+ return undefined;
328
+ }
329
+ const d = registry.detail(opId);
330
+ return d ? runToolFor(d) : undefined;
331
+ }),
332
+ },
333
+ ],
334
+ structuredContent: structured,
335
+ ...(Object.keys(meta).length > 0 && { _meta: meta }),
336
+ },
337
+ };
338
+ } catch (err) {
339
+ const message = err instanceof Error ? err.message : "Internal error";
340
+ return { body: errorResult(message) };
341
+ }
342
+ }
343
+
344
+ const catalogIdSet = new Set(resolved.catalogIds());
345
+
346
+ /** Resolve a meta-tool's target id to a catalog operation, or an error message. */
347
+ function catalogTarget(id: unknown): { detail: OperationDetail } | string {
348
+ if (typeof id !== "string" || !registry.get(id)) {
349
+ return `Unknown operation "${String(id)}". Call find_operations to list available operations.`;
350
+ }
351
+ if (!catalogIdSet.has(id)) {
352
+ return `"${id}" is a tool on this endpoint; call it directly.`;
353
+ }
354
+ const detail = registry.detail(id);
355
+ if (!detail)
356
+ return `Unknown operation "${id}". Call find_operations to list available operations.`;
357
+ return { detail };
358
+ }
359
+
360
+ const metaResult = (value: unknown) => ({
361
+ content: [{ type: "text", text: JSON.stringify(value) }],
362
+ structuredContent: value,
363
+ });
364
+
365
+ async function callMetaTool(
366
+ name: string,
367
+ args: Record<string, unknown>,
368
+ request: Request,
369
+ ): Promise<{ body: Record<string, unknown>; challenge?: string }> {
370
+ if (name === "find_operations") {
371
+ const authResult = await authenticate(request);
372
+ const anonymous = "error" in authResult;
373
+ const tokens =
374
+ typeof args.query === "string"
375
+ ? args.query.toLowerCase().split(/\s+/).filter(Boolean)
376
+ : [];
377
+ const tags = Array.isArray(args.tags)
378
+ ? args.tags.map((t) => String(t).toLowerCase())
379
+ : [];
380
+ const catalog = registry.list().filter((o) => catalogIdSet.has(o.id));
381
+ const visible = catalog.filter(
382
+ (o) => !anonymous || (o.auth ?? "required") !== "required",
383
+ );
384
+ if (anonymous && catalog.length > 0 && visible.length === 0) {
385
+ return authFailure();
386
+ }
387
+ const operations = visible
388
+ .filter((o) => {
389
+ const own = (o.tags ?? []).map((t) => t.toLowerCase());
390
+ if (tags.length > 0 && !tags.some((t) => own.includes(t)))
391
+ return false;
392
+ if (tokens.length === 0) return true;
393
+ const fields = [o.id, o.title ?? "", o.description, ...own].map((f) =>
394
+ f.toLowerCase(),
395
+ );
396
+ return tokens.some((tok) => fields.some((f) => f.includes(tok)));
397
+ })
398
+ .map((o) => ({
399
+ id: o.id,
400
+ ...(o.title !== undefined && { title: o.title }),
401
+ description: o.description,
402
+ type: o.type,
403
+ ...(o.destructive !== undefined && { destructive: o.destructive }),
404
+ ...(o.tags !== undefined && { tags: o.tags }),
405
+ }));
406
+ return {
407
+ body: metaResult({
408
+ operations,
409
+ hint: "Call get_operation with an id before running it.",
410
+ }),
411
+ };
412
+ }
413
+
414
+ const target = catalogTarget(args.id);
415
+ if (typeof target === "string") return { body: errorResult(target) };
416
+ const { detail } = target;
417
+
418
+ if (name === "get_operation") {
419
+ const authResult = await authenticate(request);
420
+ const anonymous = "error" in authResult;
421
+ if (anonymous && (detail.auth ?? "required") === "required") {
422
+ return authFailure();
423
+ }
424
+ const operations = registry
425
+ .list()
426
+ .filter((o) => catalogIdSet.has(o.id))
427
+ .filter((o) => !anonymous || (o.auth ?? "required") !== "required");
428
+ return { body: metaResult({ ...detail, operations }) };
429
+ }
430
+
431
+ const expected = runToolFor(detail);
432
+ if (name !== expected) {
433
+ return {
434
+ body: errorResult(
435
+ `"${detail.id}" is a ${RUN_CLASS[expected]}; use ${expected}.`,
436
+ ),
437
+ };
438
+ }
439
+ let intent: string | undefined;
440
+ if (name !== "run_read") {
441
+ intent = typeof args.intent === "string" ? args.intent.trim() : "";
442
+ if (intent === "") {
443
+ return {
444
+ body: errorResult(
445
+ "intent is required: one sentence saying what this call does for the user.",
446
+ ),
447
+ };
448
+ }
449
+ }
450
+ const raw = args.variables;
451
+ if (raw != null && (typeof raw !== "object" || Array.isArray(raw))) {
452
+ return { body: errorResult("variables must be an object.") };
453
+ }
454
+ const variables = (raw ?? {}) as Record<string, unknown>;
455
+ return runOperation(request, detail.id, variables, intent);
456
+ }
457
+
458
+ const appInstructions = registry.instructions();
459
+ const instructions =
460
+ appInstructions === undefined
461
+ ? undefined
462
+ : appInstructions + instructionsSuffix;
463
+ if (
464
+ instructions !== undefined &&
465
+ instructions.length > INSTRUCTIONS_WARN_LENGTH
466
+ ) {
467
+ console.warn(
468
+ `[donghanh] MCP instructions are ${instructions.length} characters; clients may truncate above ${INSTRUCTIONS_WARN_LENGTH}.`,
469
+ );
470
+ }
471
+
153
472
  const app = new Hono();
154
473
 
155
474
  // RFC 9728 protected resource metadata
156
- app.get("/.well-known/oauth-protected-resource", (c) =>
157
- c.json({
158
- resource,
159
- authorization_servers: authorizationServers,
160
- ...(scopes.length > 0 && { scopes_supported: scopes }),
161
- ...(resourceDocumentation && {
162
- resource_documentation: resourceDocumentation,
475
+ if (metadata) {
476
+ app.get("/.well-known/oauth-protected-resource", (c) =>
477
+ c.json({
478
+ resource,
479
+ authorization_servers: authorizationServers,
480
+ ...(scopes.length > 0 && { scopes_supported: scopes }),
481
+ ...(resourceDocumentation && {
482
+ resource_documentation: resourceDocumentation,
483
+ }),
163
484
  }),
164
- }),
165
- );
485
+ );
486
+ }
166
487
 
167
488
  // Stateless server: no SSE stream to open
168
489
  app.get(
169
- "/mcp",
490
+ path,
170
491
  () => new Response(null, { status: 405, headers: { Allow: "POST" } }),
171
492
  );
172
493
 
173
- app.post("/mcp", async (c) => {
494
+ app.post(path, async (c) => {
174
495
  let body: JsonRpcRequest;
175
496
  try {
176
497
  body = await c.req.json();
177
498
  } catch {
178
499
  return c.json(failure(null, -32700, "Parse error"), 400);
179
500
  }
501
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
502
+ return c.json(failure(null, -32600, "Invalid Request"), 400);
503
+ }
180
504
 
181
505
  const id = body.id ?? null;
182
506
  const method = body.method;
183
507
 
184
- if (body.jsonrpc !== "2.0" || !method) {
508
+ if (body.jsonrpc !== "2.0" || typeof method !== "string" || !method) {
185
509
  return c.json(failure(id, -32600, "Invalid Request"), 400);
186
510
  }
187
511
 
512
+ if (method.startsWith("notifications/")) {
513
+ return new Response(null, { status: 202 });
514
+ }
515
+
188
516
  switch (method) {
189
517
  case "initialize":
190
518
  return c.json(
191
519
  success(id, {
192
- protocolVersion: MCP_PROTOCOL_VERSION,
520
+ protocolVersion: negotiateProtocolVersion(
521
+ body.params?.protocolVersion,
522
+ ),
193
523
  capabilities: {
194
524
  tools: {},
195
525
  ...(Object.keys(widgets).length > 0 && { resources: {} }),
196
526
  },
197
527
  serverInfo,
528
+ ...(instructions !== undefined && { instructions }),
198
529
  }),
199
530
  );
200
531
 
201
- case "notifications/initialized":
202
- case "notifications/cancelled":
203
- return new Response(null, { status: 204 });
532
+ case "ping":
533
+ return c.json(success(id, {}));
534
+
535
+ case "resources/templates/list":
536
+ return c.json(success(id, { resourceTemplates: [] }));
537
+
538
+ case "prompts/list":
539
+ return c.json(success(id, { prompts: [] }));
204
540
 
205
541
  case "tools/list": {
206
- const tools = registry.list().map((op) => {
542
+ const listed = registry
543
+ .list()
544
+ .filter(
545
+ (op) =>
546
+ resolved.placement.get(op.id) !== "catalog" ||
547
+ resolved.appOnly.has(op.id),
548
+ );
549
+ const tools = listed.map((op) => {
207
550
  const detail = registry.detail(op.id);
208
551
  const widgetName = detail?.widget;
209
552
  const widget = widgetName ? widgets[widgetName] : undefined;
@@ -221,16 +564,44 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
221
564
  securitySchemes: securitySchemesFor(detail, scopes),
222
565
  };
223
566
 
567
+ if (detail?.title) tool.title = detail.title;
568
+
569
+ const responseKey = registry.get(op.id)?.operationConfig.responseKey;
570
+ const wrapped =
571
+ detail?.response && responseKey
572
+ ? {
573
+ type: "object",
574
+ properties: {
575
+ [responseKey]: detail.response,
576
+ actions: { type: "array" },
577
+ display: {},
578
+ },
579
+ required: [responseKey],
580
+ }
581
+ : undefined;
582
+ const out = outputSchema
583
+ ? detail && outputSchema(detail, wrapped)
584
+ : enrichResponse
585
+ ? undefined
586
+ : wrapped;
587
+ if (out) tool.outputSchema = out;
588
+
589
+ const meta: Record<string, unknown> = { ...detail?.meta };
224
590
  if (widget) {
225
- tool._meta = {
226
- ui: { resourceUri: widget.uri },
227
- "openai/outputTemplate": widget.uri,
228
- };
591
+ const ui = (meta.ui ?? {}) as Record<string, unknown>;
592
+ meta.ui = { ...ui, resourceUri: widget.uri };
593
+ meta["openai/outputTemplate"] = widget.uri;
594
+ }
595
+ if (resolved.pinned.has(op.id)) meta["anthropic/alwaysLoad"] = true;
596
+ if (resolved.placement.get(op.id) === "catalog") {
597
+ const ui = (meta.ui ?? {}) as Record<string, unknown>;
598
+ meta.ui = { ...ui, visibility: ["app"] };
229
599
  }
600
+ if (Object.keys(meta).length > 0) tool._meta = meta;
230
601
 
231
602
  return tool;
232
603
  });
233
- return c.json(success(id, { tools }));
604
+ return c.json(success(id, { tools: [...tools, ...metaTools] }));
234
605
  }
235
606
 
236
607
  case "resources/list": {
@@ -247,7 +618,7 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
247
618
  if (!uri) return c.json(failure(id, -32602, "Missing uri"), 400);
248
619
  const widget = Object.values(widgets).find((w) => w.uri === uri);
249
620
  if (!widget) {
250
- return c.json(failure(id, -32601, `Unknown resource "${uri}"`), 404);
621
+ return c.json(failure(id, -32601, `Unknown resource "${uri}"`));
251
622
  }
252
623
  return c.json(
253
624
  success(id, {
@@ -273,108 +644,56 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
273
644
  return c.json(failure(id, -32602, "Missing tool name"), 400);
274
645
  }
275
646
 
647
+ if (isMetaTool(toolName) && metaNames.has(toolName)) {
648
+ const out = await callMetaTool(
649
+ toolName,
650
+ params.arguments ?? {},
651
+ c.req.raw,
652
+ );
653
+ return c.json(
654
+ success(id, out.body),
655
+ out.challenge
656
+ ? { headers: { "WWW-Authenticate": out.challenge } }
657
+ : undefined,
658
+ );
659
+ }
660
+
276
661
  const op = registry.get(toolName);
277
662
  if (!op) {
278
- return c.json(failure(id, -32601, `Unknown tool "${toolName}"`), 404);
663
+ return c.json(failure(id, -32601, `Unknown tool "${toolName}"`));
279
664
  }
280
665
 
281
666
  const detail = registry.detail(toolName);
282
- const authMode = detail?.auth ?? "required";
283
-
284
- let userId: string | null = null;
285
- if (authMode !== "none") {
286
- const authResult = await authenticate(c.req.raw);
287
- if ("error" in authResult) {
288
- if (authMode === "required") {
289
- const challenge = wwwAuthenticate(
290
- resource,
291
- "insufficient_scope",
292
- "You need to login to continue",
293
- );
294
- return c.json(
295
- success(id, {
296
- content: [{ type: "text", text: "Authentication required." }],
297
- isError: true,
298
- _meta: { "mcp/www_authenticate": [challenge] },
299
- }),
300
- {
301
- headers: { "WWW-Authenticate": challenge },
302
- },
303
- );
304
- }
305
- // optional: proceed anonymously
306
- } else {
307
- userId = authResult.userId;
308
- }
309
- }
310
-
311
- const variables = params.arguments ?? {};
312
- try {
313
- const { data, brief } = await executeOperation({
314
- registry,
315
- operationId: toolName,
316
- variables,
317
- executor,
318
- context: { userId, request: c.req.raw },
319
- });
320
-
321
- const rendered = renderForChatGpt(brief, {
322
- encodeVariables,
323
- getOperationInput: (opId) => registry.detail(opId)?.input,
324
- });
325
-
326
- const structured: Record<string, unknown> = {
327
- [op.operationConfig.responseKey]: data,
328
- };
329
- if (rendered.suggestedActions.length > 0) {
330
- structured.actions = rendered.suggestedActions;
331
- }
332
- if (rendered.display !== undefined) {
333
- structured.display = rendered.display;
334
- }
335
-
336
- if (enrichResponse) {
337
- await enrichResponse(structured, {
338
- operationId: toolName,
339
- data,
340
- variables,
341
- userId,
342
- request: c.req.raw,
343
- });
344
- }
345
-
346
- const meta: Record<string, unknown> = {};
347
- if (rendered.context && rendered.context.length > 0) {
348
- meta["donghanh/context"] = rendered.context;
349
- }
350
-
351
- const widgetName = detail?.widget;
352
- const widget = widgetName ? widgets[widgetName] : undefined;
353
- if (widget) {
354
- meta.ui = { resourceUri: widget.uri };
355
- meta["openai/outputTemplate"] = widget.uri;
356
- }
357
-
667
+ if (
668
+ resolved.placement.get(toolName) === "catalog" &&
669
+ !resolved.appOnly.has(toolName) &&
670
+ op.operationConfig.type === "mutation"
671
+ ) {
672
+ const runner = detail?.destructive ? "run_destructive" : "run_write";
358
673
  return c.json(
359
- success(id, {
360
- content: [{ type: "text", text: rendered.nextSteps ?? "OK" }],
361
- structuredContent: structured,
362
- ...(Object.keys(meta).length > 0 && { _meta: meta }),
363
- }),
364
- );
365
- } catch (err) {
366
- const message = err instanceof Error ? err.message : "Internal error";
367
- return c.json(
368
- success(id, {
369
- content: [{ type: "text", text: message }],
370
- isError: true,
371
- }),
674
+ failure(
675
+ id,
676
+ -32601,
677
+ `Operation "${toolName}" is not a tool on this endpoint; call it with ${runner}`,
678
+ ),
372
679
  );
373
680
  }
681
+
682
+ const out = await runOperation(
683
+ c.req.raw,
684
+ toolName,
685
+ params.arguments ?? {},
686
+ );
687
+ return c.json(
688
+ success(id, out.body),
689
+ out.challenge
690
+ ? { headers: { "WWW-Authenticate": out.challenge } }
691
+ : undefined,
692
+ );
374
693
  }
375
694
 
376
695
  default:
377
- return c.json(failure(id, -32601, `Method not found: ${method}`), 404);
696
+ return c.json(failure(id, -32601, `Method not found: ${method}`));
378
697
  }
379
698
  });
380
699