@donghanh/hono 0.3.4 → 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,42 @@ 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;
73
+ /** Hook to enrich `structuredContent` after execution (e.g. inject display text) */
74
+ enrichResponse?: (
75
+ structured: Record<string, unknown>,
76
+ opts: {
77
+ operationId: string;
78
+ data: unknown;
79
+ variables: Record<string, unknown>;
80
+ userId: string | null;
81
+ request: Request;
82
+ },
83
+ ) => Promise<void>;
40
84
  }
41
85
 
42
86
  type JsonRpcRequest = {
@@ -84,28 +128,18 @@ function wwwAuthenticate(
84
128
  return `Bearer resource_metadata="${resource}/.well-known/oauth-protected-resource", error="${error}", error_description="${description}"`;
85
129
  }
86
130
 
87
- function securitySchemesFor(
88
- detail: OperationDetail | null,
89
- defaultScopes: string[],
90
- ): Array<{ type: "noauth" } | { type: "oauth2"; scopes: string[] }> {
91
- const auth = detail?.auth ?? "required";
92
- const scopes = detail?.scopes ?? defaultScopes;
93
- if (auth === "none") return [{ type: "noauth" }];
94
- if (auth === "optional")
95
- return [{ type: "noauth" }, { type: "oauth2", scopes }];
96
- return [{ type: "oauth2", scopes }];
97
- }
98
-
99
131
  function annotationsFor(detail: OperationDetail | null): {
100
132
  readOnlyHint: boolean;
101
133
  openWorldHint: boolean;
102
134
  destructiveHint: boolean;
135
+ idempotentHint: boolean;
103
136
  } {
104
137
  if (!detail) {
105
138
  return {
106
139
  readOnlyHint: false,
107
140
  openWorldHint: true,
108
141
  destructiveHint: false,
142
+ idempotentHint: false,
109
143
  };
110
144
  }
111
145
  const readOnly = detail.type === "query";
@@ -113,9 +147,39 @@ function annotationsFor(detail: OperationDetail | null): {
113
147
  readOnlyHint: readOnly,
114
148
  openWorldHint: readOnly ? false : (detail.external ?? false),
115
149
  destructiveHint: readOnly ? false : (detail.destructive ?? false),
150
+ idempotentHint: detail.idempotent ?? false,
116
151
  };
117
152
  }
118
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
+
119
183
  function widgetMetaFor(widget: WidgetConfig): Record<string, unknown> {
120
184
  const ui: Record<string, unknown> = {};
121
185
  if (widget.prefersBorder) ui.prefersBorder = true;
@@ -134,58 +198,355 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
134
198
  scopes = [],
135
199
  resourceDocumentation,
136
200
  serverInfo = { name: "donghanh-mcp", version: "0.1.0" },
201
+ path = "/mcp",
202
+ metadata = true,
203
+ instructionsSuffix = "",
137
204
  encodeVariables,
205
+ actionsInText = true,
138
206
  widgets = {},
207
+ enrichResponse,
208
+ outputSchema,
209
+ exposure,
139
210
  } = config;
140
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
+
141
472
  const app = new Hono();
142
473
 
143
474
  // RFC 9728 protected resource metadata
144
- app.get("/.well-known/oauth-protected-resource", (c) =>
145
- c.json({
146
- resource,
147
- authorization_servers: authorizationServers,
148
- ...(scopes.length > 0 && { scopes_supported: scopes }),
149
- ...(resourceDocumentation && {
150
- 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
+ }),
151
484
  }),
152
- }),
485
+ );
486
+ }
487
+
488
+ // Stateless server: no SSE stream to open
489
+ app.get(
490
+ path,
491
+ () => new Response(null, { status: 405, headers: { Allow: "POST" } }),
153
492
  );
154
493
 
155
- app.post("/mcp", async (c) => {
494
+ app.post(path, async (c) => {
156
495
  let body: JsonRpcRequest;
157
496
  try {
158
497
  body = await c.req.json();
159
498
  } catch {
160
499
  return c.json(failure(null, -32700, "Parse error"), 400);
161
500
  }
501
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
502
+ return c.json(failure(null, -32600, "Invalid Request"), 400);
503
+ }
162
504
 
163
505
  const id = body.id ?? null;
164
506
  const method = body.method;
165
507
 
166
- if (body.jsonrpc !== "2.0" || !method) {
508
+ if (body.jsonrpc !== "2.0" || typeof method !== "string" || !method) {
167
509
  return c.json(failure(id, -32600, "Invalid Request"), 400);
168
510
  }
169
511
 
512
+ if (method.startsWith("notifications/")) {
513
+ return new Response(null, { status: 202 });
514
+ }
515
+
170
516
  switch (method) {
171
517
  case "initialize":
172
518
  return c.json(
173
519
  success(id, {
174
- protocolVersion: MCP_PROTOCOL_VERSION,
520
+ protocolVersion: negotiateProtocolVersion(
521
+ body.params?.protocolVersion,
522
+ ),
175
523
  capabilities: {
176
524
  tools: {},
177
525
  ...(Object.keys(widgets).length > 0 && { resources: {} }),
178
526
  },
179
527
  serverInfo,
528
+ ...(instructions !== undefined && { instructions }),
180
529
  }),
181
530
  );
182
531
 
183
- case "notifications/initialized":
184
- case "notifications/cancelled":
185
- 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: [] }));
186
540
 
187
541
  case "tools/list": {
188
- 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) => {
189
550
  const detail = registry.detail(op.id);
190
551
  const widgetName = detail?.widget;
191
552
  const widget = widgetName ? widgets[widgetName] : undefined;
@@ -203,16 +564,44 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
203
564
  securitySchemes: securitySchemesFor(detail, scopes),
204
565
  };
205
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 };
206
590
  if (widget) {
207
- tool._meta = {
208
- ui: { resourceUri: widget.uri },
209
- "openai/outputTemplate": widget.uri,
210
- };
591
+ const ui = (meta.ui ?? {}) as Record<string, unknown>;
592
+ meta.ui = { ...ui, resourceUri: widget.uri };
593
+ meta["openai/outputTemplate"] = widget.uri;
211
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"] };
599
+ }
600
+ if (Object.keys(meta).length > 0) tool._meta = meta;
212
601
 
213
602
  return tool;
214
603
  });
215
- return c.json(success(id, { tools }));
604
+ return c.json(success(id, { tools: [...tools, ...metaTools] }));
216
605
  }
217
606
 
218
607
  case "resources/list": {
@@ -229,7 +618,7 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
229
618
  if (!uri) return c.json(failure(id, -32602, "Missing uri"), 400);
230
619
  const widget = Object.values(widgets).find((w) => w.uri === uri);
231
620
  if (!widget) {
232
- return c.json(failure(id, -32601, `Unknown resource "${uri}"`), 404);
621
+ return c.json(failure(id, -32601, `Unknown resource "${uri}"`));
233
622
  }
234
623
  return c.json(
235
624
  success(id, {
@@ -255,97 +644,56 @@ export function mcpRoutes(config: McpRoutesConfig): Hono {
255
644
  return c.json(failure(id, -32602, "Missing tool name"), 400);
256
645
  }
257
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
+
258
661
  const op = registry.get(toolName);
259
662
  if (!op) {
260
- return c.json(failure(id, -32601, `Unknown tool "${toolName}"`), 404);
663
+ return c.json(failure(id, -32601, `Unknown tool "${toolName}"`));
261
664
  }
262
665
 
263
666
  const detail = registry.detail(toolName);
264
- const authMode = detail?.auth ?? "required";
265
-
266
- let userId: string | null = null;
267
- if (authMode !== "none") {
268
- const authResult = await authenticate(c.req.raw);
269
- if ("error" in authResult) {
270
- if (authMode === "required") {
271
- const challenge = wwwAuthenticate(
272
- resource,
273
- "insufficient_scope",
274
- "You need to login to continue",
275
- );
276
- return c.json(
277
- success(id, {
278
- content: [{ type: "text", text: "Authentication required." }],
279
- isError: true,
280
- _meta: { "mcp/www_authenticate": [challenge] },
281
- }),
282
- {
283
- headers: { "WWW-Authenticate": challenge },
284
- },
285
- );
286
- }
287
- // optional: proceed anonymously
288
- } else {
289
- userId = authResult.userId;
290
- }
291
- }
292
-
293
- try {
294
- const { data, brief } = await executeOperation({
295
- registry,
296
- operationId: toolName,
297
- variables: params.arguments ?? {},
298
- executor,
299
- context: { userId, request: c.req.raw },
300
- });
301
-
302
- const rendered = renderForChatGpt(brief, {
303
- encodeVariables,
304
- getOperationInput: (opId) => registry.detail(opId)?.input,
305
- });
306
-
307
- const structured: Record<string, unknown> = {
308
- [op.operationConfig.responseKey]: data,
309
- };
310
- if (rendered.suggestedActions.length > 0) {
311
- structured.actions = rendered.suggestedActions;
312
- }
313
- if (rendered.display !== undefined) {
314
- structured.display = rendered.display;
315
- }
316
-
317
- const meta: Record<string, unknown> = {};
318
- if (rendered.context && rendered.context.length > 0) {
319
- meta["donghanh/context"] = rendered.context;
320
- }
321
-
322
- const widgetName = detail?.widget;
323
- const widget = widgetName ? widgets[widgetName] : undefined;
324
- if (widget) {
325
- meta.ui = { resourceUri: widget.uri };
326
- meta["openai/outputTemplate"] = widget.uri;
327
- }
328
-
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";
329
673
  return c.json(
330
- success(id, {
331
- content: [{ type: "text", text: rendered.nextSteps ?? "OK" }],
332
- structuredContent: structured,
333
- ...(Object.keys(meta).length > 0 && { _meta: meta }),
334
- }),
335
- );
336
- } catch (err) {
337
- const message = err instanceof Error ? err.message : "Internal error";
338
- return c.json(
339
- success(id, {
340
- content: [{ type: "text", text: message }],
341
- isError: true,
342
- }),
674
+ failure(
675
+ id,
676
+ -32601,
677
+ `Operation "${toolName}" is not a tool on this endpoint; call it with ${runner}`,
678
+ ),
343
679
  );
344
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
+ );
345
693
  }
346
694
 
347
695
  default:
348
- return c.json(failure(id, -32601, `Method not found: ${method}`), 404);
696
+ return c.json(failure(id, -32601, `Method not found: ${method}`));
349
697
  }
350
698
  });
351
699