@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/catalog.ts ADDED
@@ -0,0 +1,212 @@
1
+ import type { OperationDetail, Registry } from "@donghanh/core";
2
+ import type { ResolvedExposure } from "./exposure";
3
+
4
+ export const META_TOOL_NAMES = [
5
+ "find_operations",
6
+ "get_operation",
7
+ "run_read",
8
+ "run_write",
9
+ "run_destructive",
10
+ ] as const;
11
+
12
+ export type MetaToolName = (typeof META_TOOL_NAMES)[number];
13
+
14
+ export type SecurityScheme =
15
+ | { type: "noauth" }
16
+ | { type: "oauth2"; scopes: string[] };
17
+
18
+ export interface McpTool {
19
+ name: string;
20
+ title: string;
21
+ description: string;
22
+ inputSchema: object;
23
+ annotations: {
24
+ readOnlyHint: boolean;
25
+ destructiveHint: boolean;
26
+ openWorldHint: boolean;
27
+ idempotentHint: boolean;
28
+ };
29
+ securitySchemes: SecurityScheme[];
30
+ }
31
+
32
+ export function isMetaTool(name: string): name is MetaToolName {
33
+ return (META_TOOL_NAMES as readonly string[]).includes(name);
34
+ }
35
+
36
+ export function securitySchemesFor(
37
+ detail: OperationDetail | null,
38
+ defaultScopes: string[],
39
+ ): SecurityScheme[] {
40
+ const auth = detail?.auth ?? "required";
41
+ const scopes = detail?.scopes ?? defaultScopes;
42
+ if (auth === "none") return [{ type: "noauth" }];
43
+ if (auth === "optional")
44
+ return [{ type: "noauth" }, { type: "oauth2", scopes }];
45
+ return [{ type: "oauth2", scopes }];
46
+ }
47
+
48
+ /** Which `run_*` tool runs an operation. */
49
+ export function runToolFor(detail: OperationDetail): MetaToolName {
50
+ if (detail.type === "query") return "run_read";
51
+ return detail.destructive ? "run_destructive" : "run_write";
52
+ }
53
+
54
+ export const RUN_CLASS: Record<string, string> = {
55
+ run_read: "query",
56
+ run_write: "mutation",
57
+ run_destructive: "destructive mutation",
58
+ };
59
+
60
+ function unionSchemes(
61
+ details: OperationDetail[],
62
+ defaultScopes: string[],
63
+ ): SecurityScheme[] {
64
+ let noauth = false;
65
+ const scopes = new Set<string>(defaultScopes);
66
+ let oauth = false;
67
+ for (const d of details) {
68
+ for (const s of securitySchemesFor(d, defaultScopes)) {
69
+ if (s.type === "noauth") noauth = true;
70
+ else {
71
+ oauth = true;
72
+ for (const sc of s.scopes) scopes.add(sc);
73
+ }
74
+ }
75
+ }
76
+ return [
77
+ ...(noauth ? [{ type: "noauth" as const }] : []),
78
+ ...(oauth ? [{ type: "oauth2" as const, scopes: [...scopes] }] : []),
79
+ ];
80
+ }
81
+
82
+ const READ_HINTS = {
83
+ readOnlyHint: true,
84
+ destructiveHint: false,
85
+ openWorldHint: false,
86
+ idempotentHint: true,
87
+ };
88
+
89
+ const WRITE_HINTS = {
90
+ readOnlyHint: false,
91
+ destructiveHint: false,
92
+ openWorldHint: false,
93
+ idempotentHint: false,
94
+ };
95
+
96
+ const idProp = { type: "string", description: "Operation id." };
97
+ const variablesProp = {
98
+ type: "object",
99
+ description: "Arguments for the operation, as described by get_operation.",
100
+ };
101
+ const intentProp = {
102
+ type: "string",
103
+ minLength: 1,
104
+ description:
105
+ "One sentence saying what this call does for the user. Shown in approval dialogs.",
106
+ };
107
+
108
+ /** Meta-tools that apply to this endpoint's catalog (none when the catalog is empty). */
109
+ export function catalogTools(
110
+ registry: Registry,
111
+ exposure: ResolvedExposure,
112
+ defaultScopes: string[],
113
+ ): McpTool[] {
114
+ const details = exposure
115
+ .catalogIds()
116
+ .map((id) => registry.detail(id))
117
+ .filter((d): d is OperationDetail => d !== null);
118
+ if (details.length === 0) return [];
119
+
120
+ const forClass = (name: MetaToolName) =>
121
+ details.filter((d) => runToolFor(d) === name);
122
+ const tools: McpTool[] = [
123
+ {
124
+ name: "find_operations",
125
+ title: "Find operations",
126
+ description:
127
+ "Search the operations available through this endpoint by id, title, description or tag. Returns a compact list.",
128
+ inputSchema: {
129
+ type: "object",
130
+ properties: {
131
+ query: { type: "string", description: "Keywords to match." },
132
+ tags: { type: "array", items: { type: "string" } },
133
+ },
134
+ },
135
+ annotations: READ_HINTS,
136
+ securitySchemes: unionSchemes(details, defaultScopes),
137
+ },
138
+ {
139
+ name: "get_operation",
140
+ title: "Get operation",
141
+ description:
142
+ "Get an operation's input schema, instruction and response schema. Call this before running an operation.",
143
+ inputSchema: {
144
+ type: "object",
145
+ properties: { id: idProp },
146
+ required: ["id"],
147
+ },
148
+ annotations: READ_HINTS,
149
+ securitySchemes: unionSchemes(details, defaultScopes),
150
+ },
151
+ ];
152
+
153
+ const runs: [MetaToolName, string, string, object, object][] = [
154
+ [
155
+ "run_read",
156
+ "Run read operation",
157
+ "Run a read-only (query) operation found with find_operations.",
158
+ READ_HINTS,
159
+ {
160
+ type: "object",
161
+ properties: { id: idProp, variables: variablesProp },
162
+ required: ["id", "variables"],
163
+ },
164
+ ],
165
+ [
166
+ "run_write",
167
+ "Run write operation",
168
+ "Run a non-destructive write (mutation) operation found with find_operations.",
169
+ WRITE_HINTS,
170
+ {
171
+ type: "object",
172
+ properties: {
173
+ id: idProp,
174
+ variables: variablesProp,
175
+ intent: intentProp,
176
+ },
177
+ required: ["id", "variables", "intent"],
178
+ },
179
+ ],
180
+ [
181
+ "run_destructive",
182
+ "Run destructive operation",
183
+ "Run a destructive write (delete, forget, revoke or overwrite) operation found with find_operations.",
184
+ { ...WRITE_HINTS, destructiveHint: true },
185
+ {
186
+ type: "object",
187
+ properties: {
188
+ id: idProp,
189
+ variables: variablesProp,
190
+ intent: intentProp,
191
+ },
192
+ required: ["id", "variables", "intent"],
193
+ },
194
+ ],
195
+ ];
196
+ for (const [name, title, description, annotations, inputSchema] of runs) {
197
+ const subset = forClass(name);
198
+ if (subset.length === 0) continue;
199
+ tools.push({
200
+ name,
201
+ title,
202
+ description,
203
+ inputSchema,
204
+ annotations: {
205
+ ...(annotations as object),
206
+ openWorldHint: subset.some((d) => d.external),
207
+ } as McpTool["annotations"],
208
+ securitySchemes: unionSchemes(subset, defaultScopes),
209
+ });
210
+ }
211
+ return tools;
212
+ }
@@ -0,0 +1,20 @@
1
+ import { App, buildRegistry } from "@donghanh/core";
2
+ import { describe, expect, test } from "vitest";
3
+ import { resolveSystemPrompt } from "./chat";
4
+
5
+ describe("resolveSystemPrompt", () => {
6
+ test("prefers explicit, then app instructions, then the default", () => {
7
+ const withInstructions = buildRegistry(
8
+ App({ operations: {}, instructions: "Play." }),
9
+ );
10
+ const without = buildRegistry(App({ operations: {} }));
11
+
12
+ expect(
13
+ resolveSystemPrompt({ systemPrompt: "Explicit." }, withInstructions),
14
+ ).toBe("Explicit.");
15
+ expect(resolveSystemPrompt({}, withInstructions)).toBe("Play.");
16
+ expect(resolveSystemPrompt({}, without)).toBe(
17
+ "You are a helpful assistant. Use the tools to help the user.",
18
+ );
19
+ });
20
+ });
package/src/chat.ts CHANGED
@@ -29,6 +29,18 @@ export interface ChatRoutesConfig {
29
29
  baseUrl?: string;
30
30
  }
31
31
 
32
+ /** Explicit `systemPrompt` > the app's `instructions` > a generic default. */
33
+ export function resolveSystemPrompt(
34
+ config: { systemPrompt?: string },
35
+ registry: Registry,
36
+ ): string {
37
+ return (
38
+ config.systemPrompt ??
39
+ registry.instructions() ??
40
+ "You are a helpful assistant. Use the tools to help the user."
41
+ );
42
+ }
43
+
32
44
  export interface ChatMessage {
33
45
  role: "user" | "assistant";
34
46
  content: string;
@@ -119,9 +131,7 @@ export function chatRoutes(config: ChatRoutesConfig): Hono {
119
131
  });
120
132
 
121
133
  const model = config.model ?? "google/gemini-2.5-flash";
122
- const systemPrompt =
123
- config.systemPrompt ??
124
- "You are a helpful assistant. Use the tools to help the user.";
134
+ const systemPrompt = resolveSystemPrompt(config, registry);
125
135
 
126
136
  // Init operation context
127
137
  let initContext = "";
@@ -0,0 +1,137 @@
1
+ import type { OperationComponent, OperationConfig } from "@donghanh/core";
2
+ import { App, buildRegistry } from "@donghanh/core";
3
+ import { describe, expect, test } from "vitest";
4
+ import { resolveExposure } from "./exposure";
5
+
6
+ function op(
7
+ id: string,
8
+ overrides: Partial<OperationConfig> = {},
9
+ ): OperationComponent {
10
+ const c = (() => null) as unknown as OperationComponent;
11
+ c.operationConfig = {
12
+ id,
13
+ type: "query",
14
+ description: `${id} desc`,
15
+ instruction: `call ${id}`,
16
+ input: { type: "object", properties: {} },
17
+ responseKey: id,
18
+ ...overrides,
19
+ };
20
+ return c;
21
+ }
22
+
23
+ const reg = buildRegistry(
24
+ App({
25
+ operations: {
26
+ w: op("w", { widget: "board" }),
27
+ p: op("p"),
28
+ q: op("q"),
29
+ m: op("m", { type: "mutation", tags: ["x"] }),
30
+ },
31
+ }),
32
+ );
33
+
34
+ describe("resolveExposure", () => {
35
+ test("no exposure: every operation is a tool", () => {
36
+ const r = resolveExposure(reg, undefined);
37
+ expect([...r.placement.values()].every((v) => v === "tool")).toBe(true);
38
+ expect(r.placement.size).toBe(4);
39
+ expect(r.catalogIds()).toEqual([]);
40
+ expect(r.pinned.size).toBe(0);
41
+ expect(r.appOnly.size).toBe(0);
42
+ });
43
+
44
+ test("order: widget > pin > tools > catalog > default", () => {
45
+ const r = resolveExposure(reg, {
46
+ default: "tool",
47
+ catalog: { type: "query" },
48
+ tools: { tags: ["x"] },
49
+ pin: ["p"],
50
+ });
51
+ expect(r.placement.get("w")).toBe("tool");
52
+ expect(r.placement.get("p")).toBe("tool");
53
+ expect(r.placement.get("q")).toBe("catalog");
54
+ expect(r.placement.get("m")).toBe("tool");
55
+ expect(r.pinned.has("p")).toBe(true);
56
+ expect(r.catalogIds()).toEqual(["q"]);
57
+ });
58
+
59
+ test("tools selector beats catalog selector; default applies last", () => {
60
+ const r = resolveExposure(reg, {
61
+ default: "catalog",
62
+ tools: { ids: ["q"] },
63
+ catalog: { ids: ["q", "m"] },
64
+ });
65
+ expect(r.placement.get("q")).toBe("tool");
66
+ expect(r.placement.get("m")).toBe("catalog");
67
+ expect(r.placement.get("p")).toBe("catalog");
68
+ expect(r.placement.get("w")).toBe("tool");
69
+ });
70
+
71
+ test("selector fields AND together; tags match any", () => {
72
+ const r = resolveExposure(reg, {
73
+ default: "catalog",
74
+ tools: { type: "mutation", tags: ["y", "x"] },
75
+ });
76
+ expect(r.placement.get("m")).toBe("tool");
77
+ const r2 = resolveExposure(reg, {
78
+ default: "catalog",
79
+ tools: { type: "query", tags: ["x"] },
80
+ });
81
+ expect(r2.placement.get("m")).toBe("catalog");
82
+ expect(r2.placement.get("q")).toBe("catalog");
83
+ });
84
+
85
+ test("empty selector matches nothing", () => {
86
+ const r = resolveExposure(reg, { default: "catalog", tools: {} });
87
+ expect(r.placement.get("q")).toBe("catalog");
88
+ });
89
+
90
+ test("widget and destructive selectors", () => {
91
+ const r2 = buildRegistry(
92
+ App({
93
+ operations: {
94
+ a: op("a", { widget: "b" }),
95
+ b: op("b"),
96
+ c: op("c", { type: "mutation", destructive: true }),
97
+ d: op("d", { type: "mutation" }),
98
+ },
99
+ }),
100
+ );
101
+ const r = resolveExposure(r2, {
102
+ default: "tool",
103
+ catalog: { widget: false, destructive: false },
104
+ });
105
+ expect(r.placement.get("a")).toBe("tool");
106
+ expect(r.placement.get("b")).toBe("catalog");
107
+ expect(r.placement.get("c")).toBe("tool");
108
+ expect(r.placement.get("d")).toBe("catalog");
109
+ });
110
+
111
+ test("unknown ids in pin or selectors throw naming the id", () => {
112
+ expect(() => resolveExposure(reg, { pin: ["nope"] })).toThrow(/nope/);
113
+ expect(() => resolveExposure(reg, { tools: { ids: ["nah"] } })).toThrow(
114
+ /nah/,
115
+ );
116
+ expect(() => resolveExposure(reg, { catalog: { ids: ["zip"] } })).toThrow(
117
+ /zip/,
118
+ );
119
+ });
120
+
121
+ test("appCallable catalog operations are app-only", () => {
122
+ const r2 = buildRegistry(
123
+ App({
124
+ operations: {
125
+ a: op("a", { appCallable: true }),
126
+ b: op("b"),
127
+ c: op("c", { appCallable: true }),
128
+ },
129
+ }),
130
+ );
131
+ const r = resolveExposure(r2, {
132
+ default: "catalog",
133
+ tools: { ids: ["c"] },
134
+ });
135
+ expect([...r.appOnly]).toEqual(["a"]);
136
+ });
137
+ });
@@ -0,0 +1,93 @@
1
+ import type { OperationDetail, Registry } from "@donghanh/core";
2
+
3
+ export type Selector = {
4
+ type?: "query" | "mutation";
5
+ tags?: string[];
6
+ ids?: string[];
7
+ widget?: boolean;
8
+ destructive?: boolean;
9
+ };
10
+
11
+ export interface ExposureConfig {
12
+ default?: "tool" | "catalog";
13
+ tools?: Selector;
14
+ catalog?: Selector;
15
+ pin?: string[];
16
+ }
17
+
18
+ export type Placement = "tool" | "catalog";
19
+
20
+ export interface ResolvedExposure {
21
+ /** Every operation id. */
22
+ placement: Map<string, Placement>;
23
+ pinned: Set<string>;
24
+ /** Catalog-placed operations with `appCallable`: listed with visibility ["app"]. */
25
+ appOnly: Set<string>;
26
+ catalogIds(): string[];
27
+ }
28
+
29
+ function matches(sel: Selector | undefined, op: OperationDetail): boolean {
30
+ if (!sel) return false;
31
+ const checks: boolean[] = [];
32
+ if (sel.type !== undefined) checks.push(op.type === sel.type);
33
+ if (sel.tags !== undefined)
34
+ checks.push(sel.tags.some((t) => op.tags?.includes(t)));
35
+ if (sel.ids !== undefined) checks.push(sel.ids.includes(op.id));
36
+ if (sel.widget !== undefined)
37
+ checks.push(sel.widget === (op.widget !== undefined));
38
+ if (sel.destructive !== undefined)
39
+ checks.push(sel.destructive === (op.destructive === true));
40
+ return checks.length > 0 && checks.every(Boolean);
41
+ }
42
+
43
+ /**
44
+ * Place every operation as a `tool` or in the `catalog`.
45
+ * Order: widget > pin > tools selector > catalog selector > default (tool).
46
+ * Throws on ids in `pin`, `tools.ids` or `catalog.ids` that aren't operations.
47
+ */
48
+ export function resolveExposure(
49
+ registry: Registry,
50
+ exposure: ExposureConfig | undefined,
51
+ ): ResolvedExposure {
52
+ const details = registry
53
+ .list()
54
+ .map((o) => registry.detail(o.id))
55
+ .filter((d): d is OperationDetail => d !== null);
56
+ const known = new Set(details.map((d) => d.id));
57
+
58
+ const where: [string, string[] | undefined][] = [
59
+ ["pin", exposure?.pin],
60
+ ["tools.ids", exposure?.tools?.ids],
61
+ ["catalog.ids", exposure?.catalog?.ids],
62
+ ];
63
+ for (const [field, ids] of where) {
64
+ for (const id of ids ?? []) {
65
+ if (!known.has(id)) {
66
+ throw new Error(`Unknown operation id "${id}" in exposure ${field}`);
67
+ }
68
+ }
69
+ }
70
+
71
+ const pinned = new Set(exposure?.pin ?? []);
72
+ const fallback = exposure?.default ?? "tool";
73
+ const placement = new Map<string, Placement>();
74
+ const appOnly = new Set<string>();
75
+
76
+ for (const d of details) {
77
+ let p: Placement;
78
+ if (d.widget !== undefined || pinned.has(d.id)) p = "tool";
79
+ else if (matches(exposure?.tools, d)) p = "tool";
80
+ else if (matches(exposure?.catalog, d)) p = "catalog";
81
+ else p = fallback;
82
+ placement.set(d.id, p);
83
+ if (p === "catalog" && d.appCallable) appOnly.add(d.id);
84
+ }
85
+
86
+ return {
87
+ placement,
88
+ pinned,
89
+ appOnly,
90
+ catalogIds: () =>
91
+ [...placement].filter(([, p]) => p === "catalog").map(([id]) => id),
92
+ };
93
+ }
package/src/gpt.test.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { describe, expect, test } from "bun:test";
2
1
  import type {
3
2
  Executor,
4
3
  OperationComponent,
5
4
  OperationConfig,
6
5
  } from "@donghanh/core";
7
6
  import { App, Brief, buildRegistry, Message } from "@donghanh/core";
7
+ import { describe, expect, test } from "vitest";
8
8
  import { gptRoutes } from "./gpt";
9
9
  import type { Authenticate } from "./middleware";
10
10
 
@@ -325,3 +325,32 @@ describe("gptRoutes /public sub-paths", () => {
325
325
  expect(capture.userId).toBe("anonymous");
326
326
  });
327
327
  });
328
+
329
+ describe("gptRoutes GET /operations instructions", () => {
330
+ const base = {
331
+ executor: (async () => ({})) as Executor,
332
+ authenticate: async () => ({ userId: "x" }),
333
+ };
334
+
335
+ test("includes app instructions when present", async () => {
336
+ const app = gptRoutes({
337
+ ...base,
338
+ registry: buildRegistry(
339
+ App({ operations: { a: makeOp("a") }, instructions: "Play." }),
340
+ ),
341
+ });
342
+ expect(await (await app.request("/operations")).json()).toMatchObject({
343
+ instructions: "Play.",
344
+ operations: expect.any(Array),
345
+ });
346
+ });
347
+
348
+ test("omits instructions when the app has none", async () => {
349
+ const app = gptRoutes({ ...base, registry: makeApp({ a: makeOp("a") }) });
350
+ const body = (await (await app.request("/operations")).json()) as Record<
351
+ string,
352
+ unknown
353
+ >;
354
+ expect("instructions" in body).toBe(false);
355
+ });
356
+ });
package/src/gpt.ts CHANGED
@@ -76,7 +76,12 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
76
76
  });
77
77
  }
78
78
 
79
- return c.json({ operations });
79
+ const instructions = registry.instructions();
80
+ return c.json(
81
+ instructions === undefined
82
+ ? { operations }
83
+ : { instructions, operations },
84
+ );
80
85
  });
81
86
 
82
87
  // Operation detail
package/src/index.ts CHANGED
@@ -1,5 +1,12 @@
1
1
  export type { ChatMessage, ChatRoutesConfig } from "./chat";
2
- export { chatRoutes } from "./chat";
2
+ export { chatRoutes, resolveSystemPrompt } from "./chat";
3
+ export type {
4
+ ExposureConfig,
5
+ Placement,
6
+ ResolvedExposure,
7
+ Selector,
8
+ } from "./exposure";
9
+ export { resolveExposure } from "./exposure";
3
10
  export type { GptRoutesConfig } from "./gpt";
4
11
  export { gptRoutes } from "./gpt";
5
12
  export type { McpRoutesConfig, WidgetConfig } from "./mcp";
@@ -12,6 +19,10 @@ export type {
12
19
  OpenApiServer,
13
20
  } from "./openapi";
14
21
  export { generateOpenApi } from "./openapi";
22
+ export {
23
+ negotiateProtocolVersion,
24
+ SUPPORTED_PROTOCOL_VERSIONS,
25
+ } from "./protocol";
15
26
  export type { ChatGptResult, SuggestedAction } from "./renderers/chatgpt";
16
27
  export { renderForChatGpt } from "./renderers/chatgpt";
17
28
  export type { LlmAction, LlmResult } from "./renderers/llm";