@donghanh/hono 0.1.1 → 0.3.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/package.json +2 -2
- package/src/gpt.test.ts +276 -0
- package/src/gpt.ts +108 -34
- package/src/index.ts +2 -0
- package/src/mcp.test.ts +279 -0
- package/src/mcp.ts +353 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@donghanh/hono",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Hono routes for GPT Store and LLM chat — renderers for ChatGPT and OpenAI-compatible APIs",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"directory": "packages/hono"
|
|
14
14
|
},
|
|
15
15
|
"peerDependencies": {
|
|
16
|
-
"@donghanh/core": "^0.
|
|
16
|
+
"@donghanh/core": "^0.3.0",
|
|
17
17
|
"hono": "^4.7.0"
|
|
18
18
|
}
|
|
19
19
|
}
|
package/src/gpt.test.ts
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import type {
|
|
3
|
+
Executor,
|
|
4
|
+
OperationComponent,
|
|
5
|
+
OperationConfig,
|
|
6
|
+
} from "@donghanh/core";
|
|
7
|
+
import { App, Brief, buildRegistry, Message } from "@donghanh/core";
|
|
8
|
+
import { gptRoutes } from "./gpt";
|
|
9
|
+
import type { Authenticate } from "./middleware";
|
|
10
|
+
|
|
11
|
+
function makeOp(
|
|
12
|
+
id: string,
|
|
13
|
+
overrides: Partial<OperationConfig> = {},
|
|
14
|
+
): OperationComponent {
|
|
15
|
+
const op = ((_props: { data: unknown }) =>
|
|
16
|
+
Brief({
|
|
17
|
+
children: [Message({ children: "ok" })],
|
|
18
|
+
})) as unknown as OperationComponent;
|
|
19
|
+
op.operationConfig = {
|
|
20
|
+
id,
|
|
21
|
+
type: "query",
|
|
22
|
+
description: `${id} desc`,
|
|
23
|
+
instruction: `call ${id}`,
|
|
24
|
+
input: { type: "object", properties: {} },
|
|
25
|
+
responseKey: id,
|
|
26
|
+
...overrides,
|
|
27
|
+
};
|
|
28
|
+
return op;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function makeApp(ops: Record<string, OperationComponent>) {
|
|
32
|
+
return buildRegistry(App({ operations: ops }));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function makeExecutor(capture: { userId?: string; opId?: string }): Executor {
|
|
36
|
+
return async (opId, _vars, ctx) => {
|
|
37
|
+
capture.opId = opId;
|
|
38
|
+
capture.userId = (ctx.userId ?? "") as string;
|
|
39
|
+
return { ok: true };
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function makeAuth(
|
|
44
|
+
mode: "valid" | "invalid",
|
|
45
|
+
flag: { called: boolean },
|
|
46
|
+
): Authenticate {
|
|
47
|
+
return async (request) => {
|
|
48
|
+
flag.called = true;
|
|
49
|
+
const token = request.headers
|
|
50
|
+
.get("Authorization")
|
|
51
|
+
?.replace(/^Bearer\s+/i, "");
|
|
52
|
+
if (mode === "valid" && token) return { userId: `user:${token}` };
|
|
53
|
+
return { error: new Response("unauth", { status: 401 }) };
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function req(
|
|
58
|
+
app: ReturnType<typeof gptRoutes>,
|
|
59
|
+
path: string,
|
|
60
|
+
init: RequestInit = {},
|
|
61
|
+
) {
|
|
62
|
+
const res = await app.request(path, init);
|
|
63
|
+
let body: unknown = null;
|
|
64
|
+
try {
|
|
65
|
+
body = await res.clone().json();
|
|
66
|
+
} catch {
|
|
67
|
+
body = await res.text();
|
|
68
|
+
}
|
|
69
|
+
return { status: res.status, body };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
describe("gptRoutes /operations listing", () => {
|
|
73
|
+
test("includes auth for each op when set", async () => {
|
|
74
|
+
const registry = makeApp({
|
|
75
|
+
a: makeOp("a", { auth: "required" }),
|
|
76
|
+
b: makeOp("b", { auth: "optional" }),
|
|
77
|
+
c: makeOp("c", { auth: "none" }),
|
|
78
|
+
d: makeOp("d"), // no auth → omitted in compact form
|
|
79
|
+
});
|
|
80
|
+
const app = gptRoutes({
|
|
81
|
+
registry,
|
|
82
|
+
executor: (async () => ({})) as Executor,
|
|
83
|
+
authenticate: async () => ({ userId: "x" }),
|
|
84
|
+
});
|
|
85
|
+
const { status, body } = await req(app, "/operations");
|
|
86
|
+
expect(status).toBe(200);
|
|
87
|
+
const b = body as { operations: Array<{ id: string; auth?: string }> };
|
|
88
|
+
const authById = Object.fromEntries(
|
|
89
|
+
b.operations.map((o) => [o.id, o.auth]),
|
|
90
|
+
);
|
|
91
|
+
expect(authById).toEqual({
|
|
92
|
+
a: "required",
|
|
93
|
+
b: "optional",
|
|
94
|
+
c: "none",
|
|
95
|
+
d: undefined,
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe("gptRoutes default /query /mutate", () => {
|
|
101
|
+
test("auth=required + no token → 401", async () => {
|
|
102
|
+
const flag = { called: false };
|
|
103
|
+
const app = gptRoutes({
|
|
104
|
+
registry: makeApp({ op: makeOp("op", { auth: "required" }) }),
|
|
105
|
+
executor: (async () => ({})) as Executor,
|
|
106
|
+
authenticate: makeAuth("invalid", flag),
|
|
107
|
+
});
|
|
108
|
+
const r = await req(app, "/query/op");
|
|
109
|
+
expect(r.status).toBe(401);
|
|
110
|
+
expect(flag.called).toBe(true);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("auth=required + valid token → 200 w/ userId", async () => {
|
|
114
|
+
const capture: { userId?: string; opId?: string } = {};
|
|
115
|
+
const flag = { called: false };
|
|
116
|
+
const app = gptRoutes({
|
|
117
|
+
registry: makeApp({ op: makeOp("op", { auth: "required" }) }),
|
|
118
|
+
executor: makeExecutor(capture),
|
|
119
|
+
authenticate: makeAuth("valid", flag),
|
|
120
|
+
});
|
|
121
|
+
const r = await req(app, "/query/op", {
|
|
122
|
+
headers: { Authorization: "Bearer tok1" },
|
|
123
|
+
});
|
|
124
|
+
expect(r.status).toBe(200);
|
|
125
|
+
expect(capture.userId).toBe("user:tok1");
|
|
126
|
+
expect(flag.called).toBe(true);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
test("auth=optional + no token → 200 anonymous", async () => {
|
|
130
|
+
const capture: { userId?: string } = {};
|
|
131
|
+
const flag = { called: false };
|
|
132
|
+
const app = gptRoutes({
|
|
133
|
+
registry: makeApp({ op: makeOp("op", { auth: "optional" }) }),
|
|
134
|
+
executor: makeExecutor(capture),
|
|
135
|
+
authenticate: makeAuth("invalid", flag),
|
|
136
|
+
});
|
|
137
|
+
const r = await req(app, "/query/op");
|
|
138
|
+
expect(r.status).toBe(200);
|
|
139
|
+
expect(capture.userId).toBe("anonymous");
|
|
140
|
+
expect(flag.called).toBe(true);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("auth=optional + valid token → 200 w/ real userId", async () => {
|
|
144
|
+
const capture: { userId?: string } = {};
|
|
145
|
+
const flag = { called: false };
|
|
146
|
+
const app = gptRoutes({
|
|
147
|
+
registry: makeApp({ op: makeOp("op", { auth: "optional" }) }),
|
|
148
|
+
executor: makeExecutor(capture),
|
|
149
|
+
authenticate: makeAuth("valid", flag),
|
|
150
|
+
});
|
|
151
|
+
const r = await req(app, "/query/op", {
|
|
152
|
+
headers: { Authorization: "Bearer tok2" },
|
|
153
|
+
});
|
|
154
|
+
expect(r.status).toBe(200);
|
|
155
|
+
expect(capture.userId).toBe("user:tok2");
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("auth=none + no token → 200 anonymous", async () => {
|
|
159
|
+
const capture: { userId?: string } = {};
|
|
160
|
+
const flag = { called: false };
|
|
161
|
+
const app = gptRoutes({
|
|
162
|
+
registry: makeApp({ op: makeOp("op", { auth: "none" }) }),
|
|
163
|
+
executor: makeExecutor(capture),
|
|
164
|
+
authenticate: makeAuth("invalid", flag),
|
|
165
|
+
});
|
|
166
|
+
const r = await req(app, "/query/op");
|
|
167
|
+
expect(r.status).toBe(200);
|
|
168
|
+
expect(capture.userId).toBe("anonymous");
|
|
169
|
+
expect(flag.called).toBe(false);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("auth=none + valid token → 200 ANONYMOUS (authenticate not called)", async () => {
|
|
173
|
+
const capture: { userId?: string } = {};
|
|
174
|
+
const flag = { called: false };
|
|
175
|
+
const app = gptRoutes({
|
|
176
|
+
registry: makeApp({ op: makeOp("op", { auth: "none" }) }),
|
|
177
|
+
executor: makeExecutor(capture),
|
|
178
|
+
authenticate: makeAuth("valid", flag),
|
|
179
|
+
});
|
|
180
|
+
const r = await req(app, "/query/op", {
|
|
181
|
+
headers: { Authorization: "Bearer tok3" },
|
|
182
|
+
});
|
|
183
|
+
expect(r.status).toBe(200);
|
|
184
|
+
expect(capture.userId).toBe("anonymous");
|
|
185
|
+
expect(flag.called).toBe(false);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
describe("gptRoutes /public sub-paths", () => {
|
|
190
|
+
test("unknown op → 404", async () => {
|
|
191
|
+
const app = gptRoutes({
|
|
192
|
+
registry: makeApp({}),
|
|
193
|
+
executor: (async () => ({})) as Executor,
|
|
194
|
+
authenticate: async () => ({ userId: "x" }),
|
|
195
|
+
});
|
|
196
|
+
const r = await req(app, "/public/query/nope");
|
|
197
|
+
expect(r.status).toBe(404);
|
|
198
|
+
const b = r.body as { error: string };
|
|
199
|
+
expect(b.error).toContain("requires auth");
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test("auth=required op → 404 (does not leak existence)", async () => {
|
|
203
|
+
const app = gptRoutes({
|
|
204
|
+
registry: makeApp({ priv: makeOp("priv", { auth: "required" }) }),
|
|
205
|
+
executor: (async () => ({})) as Executor,
|
|
206
|
+
authenticate: async () => ({ userId: "x" }),
|
|
207
|
+
});
|
|
208
|
+
const r = await req(app, "/public/query/priv");
|
|
209
|
+
expect(r.status).toBe(404);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test("auth=none op → 200 anonymous", async () => {
|
|
213
|
+
const capture: { userId?: string } = {};
|
|
214
|
+
const flag = { called: false };
|
|
215
|
+
const app = gptRoutes({
|
|
216
|
+
registry: makeApp({ pub: makeOp("pub", { auth: "none" }) }),
|
|
217
|
+
executor: makeExecutor(capture),
|
|
218
|
+
authenticate: makeAuth("valid", flag),
|
|
219
|
+
});
|
|
220
|
+
const r = await req(app, "/public/query/pub");
|
|
221
|
+
expect(r.status).toBe(200);
|
|
222
|
+
expect(capture.userId).toBe("anonymous");
|
|
223
|
+
expect(flag.called).toBe(false);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
test("auth=optional + valid token → 200 w/ real userId", async () => {
|
|
227
|
+
const capture: { userId?: string } = {};
|
|
228
|
+
const flag = { called: false };
|
|
229
|
+
const app = gptRoutes({
|
|
230
|
+
registry: makeApp({ start: makeOp("start", { auth: "optional" }) }),
|
|
231
|
+
executor: makeExecutor(capture),
|
|
232
|
+
authenticate: makeAuth("valid", flag),
|
|
233
|
+
});
|
|
234
|
+
const r = await req(app, "/public/query/start", {
|
|
235
|
+
headers: { Authorization: "Bearer tok4" },
|
|
236
|
+
});
|
|
237
|
+
expect(r.status).toBe(200);
|
|
238
|
+
expect(capture.userId).toBe("user:tok4");
|
|
239
|
+
expect(flag.called).toBe(true);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
test("auth=optional + bad token → 200 anonymous (public swallows)", async () => {
|
|
243
|
+
const capture: { userId?: string } = {};
|
|
244
|
+
const flag = { called: false };
|
|
245
|
+
const app = gptRoutes({
|
|
246
|
+
registry: makeApp({ start: makeOp("start", { auth: "optional" }) }),
|
|
247
|
+
executor: makeExecutor(capture),
|
|
248
|
+
authenticate: makeAuth("invalid", flag),
|
|
249
|
+
});
|
|
250
|
+
const r = await req(app, "/public/query/start", {
|
|
251
|
+
headers: { Authorization: "Bearer badtok" },
|
|
252
|
+
});
|
|
253
|
+
expect(r.status).toBe(200);
|
|
254
|
+
expect(capture.userId).toBe("anonymous");
|
|
255
|
+
expect(flag.called).toBe(true);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test("public mutate routes", async () => {
|
|
259
|
+
const capture: { userId?: string; opId?: string } = {};
|
|
260
|
+
const app = gptRoutes({
|
|
261
|
+
registry: makeApp({
|
|
262
|
+
pubmut: makeOp("pubmut", { auth: "none", type: "mutation" }),
|
|
263
|
+
}),
|
|
264
|
+
executor: makeExecutor(capture),
|
|
265
|
+
authenticate: async () => ({ userId: "x" }),
|
|
266
|
+
});
|
|
267
|
+
const r = await req(app, "/public/mutate/pubmut", {
|
|
268
|
+
method: "POST",
|
|
269
|
+
headers: { "content-type": "application/json" },
|
|
270
|
+
body: JSON.stringify({ $variables: "{}" }),
|
|
271
|
+
});
|
|
272
|
+
expect(r.status).toBe(200);
|
|
273
|
+
expect(capture.opId).toBe("pubmut");
|
|
274
|
+
expect(capture.userId).toBe("anonymous");
|
|
275
|
+
});
|
|
276
|
+
});
|
package/src/gpt.ts
CHANGED
|
@@ -24,6 +24,11 @@ export interface GptRoutesConfig {
|
|
|
24
24
|
) => Promise<void>;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** Sentinel used when a request runs without an authenticated user. */
|
|
28
|
+
const ANONYMOUS: string = "anonymous";
|
|
29
|
+
|
|
30
|
+
type AuthMode = "none" | "optional" | "required";
|
|
31
|
+
|
|
27
32
|
function jsonError(message: string, status = 400): Response {
|
|
28
33
|
return new Response(JSON.stringify({ errors: [{ message }] }), {
|
|
29
34
|
status,
|
|
@@ -43,7 +48,7 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
43
48
|
|
|
44
49
|
const app = new Hono();
|
|
45
50
|
|
|
46
|
-
// List operations
|
|
51
|
+
// List operations (auth advertised per-op)
|
|
47
52
|
app.get("/operations", (c) => {
|
|
48
53
|
const url = new URL(c.req.url);
|
|
49
54
|
const search = url.searchParams.get("search")?.toLowerCase();
|
|
@@ -84,11 +89,36 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
84
89
|
return c.json(detail);
|
|
85
90
|
});
|
|
86
91
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Resolve the userId to execute with, given the op's auth posture and the
|
|
94
|
+
* inbound request. Returns either a string userId or a Response to short-circuit.
|
|
95
|
+
*/
|
|
96
|
+
async function resolveUser(
|
|
97
|
+
request: Request,
|
|
98
|
+
authMode: AuthMode,
|
|
99
|
+
public_: boolean,
|
|
100
|
+
): Promise<string | Response> {
|
|
101
|
+
// auth: "none" — always anonymous, never call authenticate
|
|
102
|
+
if (authMode === "none") return ANONYMOUS;
|
|
103
|
+
|
|
104
|
+
// Public sub-router: be lenient — swallow errors, fall back to anonymous
|
|
105
|
+
if (public_) {
|
|
106
|
+
const result = await authenticate(request);
|
|
107
|
+
if (isAuthError(result)) return ANONYMOUS;
|
|
108
|
+
return result.userId;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Default path: propagate auth error when required; swallow when optional
|
|
112
|
+
const result = await authenticate(request);
|
|
113
|
+
if (isAuthError(result)) {
|
|
114
|
+
if (authMode === "optional") return ANONYMOUS;
|
|
115
|
+
return result.error;
|
|
116
|
+
}
|
|
117
|
+
return result.userId;
|
|
118
|
+
}
|
|
91
119
|
|
|
120
|
+
// Execute query (default)
|
|
121
|
+
app.get("/query/:operation", async (c) => {
|
|
92
122
|
const operationId = c.req.param("operation");
|
|
93
123
|
const op = registry.get(operationId);
|
|
94
124
|
|
|
@@ -103,17 +133,18 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
103
133
|
);
|
|
104
134
|
}
|
|
105
135
|
|
|
106
|
-
|
|
136
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
137
|
+
const user = await resolveUser(c.req.raw, authMode, false);
|
|
138
|
+
if (user instanceof Response) return user;
|
|
139
|
+
|
|
140
|
+
return handleExecution(c.req.raw, user, operationId, () => {
|
|
107
141
|
const url = new URL(c.req.url);
|
|
108
142
|
return url.searchParams.get("$variables") ?? undefined;
|
|
109
143
|
});
|
|
110
144
|
});
|
|
111
145
|
|
|
112
|
-
// Execute mutation
|
|
146
|
+
// Execute mutation (default)
|
|
113
147
|
app.post("/mutate/:operation", async (c) => {
|
|
114
|
-
const authResult = await authenticate(c.req.raw);
|
|
115
|
-
if (isAuthError(authResult)) return authResult.error;
|
|
116
|
-
|
|
117
148
|
const operationId = c.req.param("operation");
|
|
118
149
|
const op = registry.get(operationId);
|
|
119
150
|
|
|
@@ -128,15 +159,73 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
128
159
|
);
|
|
129
160
|
}
|
|
130
161
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
162
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
163
|
+
const user = await resolveUser(c.req.raw, authMode, false);
|
|
164
|
+
if (user instanceof Response) return user;
|
|
165
|
+
|
|
166
|
+
return handleExecution(c.req.raw, user, operationId, async () => {
|
|
167
|
+
const body = await c.req.json();
|
|
168
|
+
return body.$variables;
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// ---------- /public sub-paths ----------
|
|
173
|
+
// OAS-friendly no-auth surface. Rejects ops whose auth posture is "required".
|
|
174
|
+
|
|
175
|
+
const notFound404 = (body: { error: string }): Response =>
|
|
176
|
+
new Response(JSON.stringify(body), {
|
|
177
|
+
status: 404,
|
|
178
|
+
headers: { "content-type": "application/json" },
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
app.get("/public/query/:operation", async (c) => {
|
|
182
|
+
const operationId = c.req.param("operation");
|
|
183
|
+
const op = registry.get(operationId);
|
|
184
|
+
if (!op) {
|
|
185
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
186
|
+
}
|
|
187
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
188
|
+
if (authMode === "required") {
|
|
189
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
190
|
+
}
|
|
191
|
+
if (op.operationConfig.type !== "query") {
|
|
192
|
+
return jsonError(
|
|
193
|
+
`"${operationId}" is a mutation. Use POST /public/mutate/${operationId} instead.`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const user = await resolveUser(c.req.raw, authMode, true);
|
|
198
|
+
if (user instanceof Response) return user;
|
|
199
|
+
|
|
200
|
+
return handleExecution(c.req.raw, user, operationId, () => {
|
|
201
|
+
const url = new URL(c.req.url);
|
|
202
|
+
return url.searchParams.get("$variables") ?? undefined;
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
app.post("/public/mutate/:operation", async (c) => {
|
|
207
|
+
const operationId = c.req.param("operation");
|
|
208
|
+
const op = registry.get(operationId);
|
|
209
|
+
if (!op) {
|
|
210
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
211
|
+
}
|
|
212
|
+
const authMode: AuthMode = op.operationConfig.auth ?? "required";
|
|
213
|
+
if (authMode === "required") {
|
|
214
|
+
return notFound404({ error: "Operation not found or requires auth." });
|
|
215
|
+
}
|
|
216
|
+
if (op.operationConfig.type !== "mutation") {
|
|
217
|
+
return jsonError(
|
|
218
|
+
`"${operationId}" is a query. Use GET /public/query/${operationId} instead.`,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const user = await resolveUser(c.req.raw, authMode, true);
|
|
223
|
+
if (user instanceof Response) return user;
|
|
224
|
+
|
|
225
|
+
return handleExecution(c.req.raw, user, operationId, async () => {
|
|
226
|
+
const body = await c.req.json();
|
|
227
|
+
return body.$variables;
|
|
228
|
+
});
|
|
140
229
|
});
|
|
141
230
|
|
|
142
231
|
async function handleExecution(
|
|
@@ -153,20 +242,11 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
153
242
|
}
|
|
154
243
|
|
|
155
244
|
let variables: Record<string, unknown> = {};
|
|
156
|
-
if (typeof rawVariables === "string" && encodeVariables) {
|
|
157
|
-
// Decode using the inverse - we expect TOON format
|
|
158
|
-
// The app provides its own decode in the executor or via a decode option
|
|
159
|
-
// For now, pass raw through and let the executor handle it
|
|
160
|
-
}
|
|
161
245
|
|
|
162
|
-
// We need a decode function. Let's accept raw variables as TOON or JSON.
|
|
163
246
|
if (typeof rawVariables === "string") {
|
|
164
247
|
try {
|
|
165
|
-
// Try JSON first
|
|
166
248
|
variables = JSON.parse(rawVariables);
|
|
167
249
|
} catch {
|
|
168
|
-
// Pass as-is, let the app's decode handle it
|
|
169
|
-
// Store raw so executor can decode
|
|
170
250
|
variables = { $raw: rawVariables };
|
|
171
251
|
}
|
|
172
252
|
}
|
|
@@ -180,7 +260,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
180
260
|
context: { userId, request },
|
|
181
261
|
});
|
|
182
262
|
|
|
183
|
-
// Render JSX tree through ChatGPT renderer
|
|
184
263
|
const rendered = renderForChatGpt(brief, {
|
|
185
264
|
encodeVariables,
|
|
186
265
|
getOperationInput: (id) => {
|
|
@@ -189,7 +268,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
189
268
|
},
|
|
190
269
|
});
|
|
191
270
|
|
|
192
|
-
// Build response
|
|
193
271
|
const result: Record<string, unknown> = {
|
|
194
272
|
data: {
|
|
195
273
|
[registry.get(operationId)!.operationConfig.responseKey]: data,
|
|
@@ -203,7 +281,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
203
281
|
result.nextSteps = rendered.nextSteps;
|
|
204
282
|
}
|
|
205
283
|
|
|
206
|
-
// Enrich response (inject display, etc)
|
|
207
284
|
if (enrichResponse) {
|
|
208
285
|
await enrichResponse(result, {
|
|
209
286
|
operationId,
|
|
@@ -214,12 +291,10 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
214
291
|
});
|
|
215
292
|
}
|
|
216
293
|
|
|
217
|
-
// Include response schema for start
|
|
218
294
|
if (operationId === "start" && responseSchemas?.start) {
|
|
219
295
|
result.responseSchema = responseSchemas.start;
|
|
220
296
|
}
|
|
221
297
|
|
|
222
|
-
// Always include operations list
|
|
223
298
|
result.operations = registry.list();
|
|
224
299
|
|
|
225
300
|
return new Response(JSON.stringify(result), {
|
|
@@ -232,7 +307,6 @@ export function gptRoutes(config: GptRoutesConfig): Hono {
|
|
|
232
307
|
errors: [{ message }],
|
|
233
308
|
};
|
|
234
309
|
|
|
235
|
-
// Include operation detail for self-correction
|
|
236
310
|
const detail = registry.detail(operationId);
|
|
237
311
|
if (detail) {
|
|
238
312
|
errorResult.operationDetail = {
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,8 @@ export type { ChatMessage, ChatRoutesConfig } from "./chat";
|
|
|
2
2
|
export { chatRoutes } from "./chat";
|
|
3
3
|
export type { GptRoutesConfig } from "./gpt";
|
|
4
4
|
export { gptRoutes } from "./gpt";
|
|
5
|
+
export type { McpRoutesConfig, WidgetConfig } from "./mcp";
|
|
6
|
+
export { mcpRoutes } from "./mcp";
|
|
5
7
|
export type { AuthError, Authenticate, AuthResult } from "./middleware";
|
|
6
8
|
export { isAuthError } from "./middleware";
|
|
7
9
|
export type { ChatGptResult, SuggestedAction } from "./renderers/chatgpt";
|
package/src/mcp.test.ts
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import type {
|
|
3
|
+
ChatNode,
|
|
4
|
+
Executor,
|
|
5
|
+
OperationComponent,
|
|
6
|
+
OperationConfig,
|
|
7
|
+
} from "@donghanh/core";
|
|
8
|
+
import { App, Brief, buildRegistry, Display, Message } from "@donghanh/core";
|
|
9
|
+
import { mcpRoutes } from "./mcp";
|
|
10
|
+
|
|
11
|
+
function makeOp(
|
|
12
|
+
id: string,
|
|
13
|
+
overrides: Partial<OperationConfig> = {},
|
|
14
|
+
render: (data: unknown) => ChatNode = () =>
|
|
15
|
+
Brief({ children: [Message({ children: "ok" })] }),
|
|
16
|
+
): OperationComponent {
|
|
17
|
+
const op = ((props: { data: unknown }) =>
|
|
18
|
+
render(props.data)) as unknown as OperationComponent;
|
|
19
|
+
op.operationConfig = {
|
|
20
|
+
id,
|
|
21
|
+
type: "query",
|
|
22
|
+
description: `${id} desc`,
|
|
23
|
+
instruction: `call ${id}`,
|
|
24
|
+
input: { type: "object", properties: {} },
|
|
25
|
+
responseKey: id,
|
|
26
|
+
...overrides,
|
|
27
|
+
};
|
|
28
|
+
return op;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function makeApp(ops: Record<string, OperationComponent>) {
|
|
32
|
+
return buildRegistry(App({ operations: ops }));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function rpc(
|
|
36
|
+
app: ReturnType<typeof mcpRoutes>,
|
|
37
|
+
method: string,
|
|
38
|
+
params?: Record<string, unknown>,
|
|
39
|
+
headers?: Record<string, string>,
|
|
40
|
+
) {
|
|
41
|
+
const res = await app.request("/mcp", {
|
|
42
|
+
method: "POST",
|
|
43
|
+
headers: { "content-type": "application/json", ...headers },
|
|
44
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
45
|
+
});
|
|
46
|
+
return res.json() as Promise<{ result?: any; error?: any }>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const baseConfig = {
|
|
50
|
+
resource: "https://app.example.com",
|
|
51
|
+
authorizationServers: ["https://auth.example.com"],
|
|
52
|
+
scopes: ["read", "write"],
|
|
53
|
+
authenticate: async () => ({ userId: "u1" }),
|
|
54
|
+
executor: (async (opId) => ({ opId })) as Executor,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
describe("mcpRoutes", () => {
|
|
58
|
+
test("initialize returns protocol version + capabilities", async () => {
|
|
59
|
+
const app = mcpRoutes({ ...baseConfig, registry: makeApp({}) });
|
|
60
|
+
const { result } = await rpc(app, "initialize");
|
|
61
|
+
expect(result.protocolVersion).toBe("2026-01-26");
|
|
62
|
+
expect(result.capabilities.tools).toEqual({});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("initialize advertises resources when widgets configured", async () => {
|
|
66
|
+
const app = mcpRoutes({
|
|
67
|
+
...baseConfig,
|
|
68
|
+
registry: makeApp({}),
|
|
69
|
+
widgets: {
|
|
70
|
+
boards: { uri: "ui://w/b.html", html: "<div/>" },
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
const { result } = await rpc(app, "initialize");
|
|
74
|
+
expect(result.capabilities.resources).toEqual({});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("tools/list annotations: query → readOnlyHint true", async () => {
|
|
78
|
+
const app = mcpRoutes({
|
|
79
|
+
...baseConfig,
|
|
80
|
+
registry: makeApp({ list: makeOp("list", { type: "query" }) }),
|
|
81
|
+
});
|
|
82
|
+
const { result } = await rpc(app, "tools/list");
|
|
83
|
+
expect(result.tools[0].annotations).toEqual({
|
|
84
|
+
readOnlyHint: true,
|
|
85
|
+
openWorldHint: false,
|
|
86
|
+
destructiveHint: false,
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("tools/list annotations: mutation + destructive flags", async () => {
|
|
91
|
+
const app = mcpRoutes({
|
|
92
|
+
...baseConfig,
|
|
93
|
+
registry: makeApp({
|
|
94
|
+
del: makeOp("del", {
|
|
95
|
+
type: "mutation",
|
|
96
|
+
destructive: true,
|
|
97
|
+
external: true,
|
|
98
|
+
}),
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
const { result } = await rpc(app, "tools/list");
|
|
102
|
+
expect(result.tools[0].annotations).toEqual({
|
|
103
|
+
readOnlyHint: false,
|
|
104
|
+
openWorldHint: true,
|
|
105
|
+
destructiveHint: true,
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test("tools/list securitySchemes: auth=none → noauth", async () => {
|
|
110
|
+
const app = mcpRoutes({
|
|
111
|
+
...baseConfig,
|
|
112
|
+
registry: makeApp({ public: makeOp("public", { auth: "none" }) }),
|
|
113
|
+
});
|
|
114
|
+
const { result } = await rpc(app, "tools/list");
|
|
115
|
+
expect(result.tools[0].securitySchemes).toEqual([{ type: "noauth" }]);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test("tools/list securitySchemes: auth=optional → both", async () => {
|
|
119
|
+
const app = mcpRoutes({
|
|
120
|
+
...baseConfig,
|
|
121
|
+
registry: makeApp({ maybe: makeOp("maybe", { auth: "optional" }) }),
|
|
122
|
+
});
|
|
123
|
+
const { result } = await rpc(app, "tools/list");
|
|
124
|
+
expect(result.tools[0].securitySchemes).toEqual([
|
|
125
|
+
{ type: "noauth" },
|
|
126
|
+
{ type: "oauth2", scopes: ["read", "write"] },
|
|
127
|
+
]);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("tools/list attaches resourceUri when widget configured", async () => {
|
|
131
|
+
const app = mcpRoutes({
|
|
132
|
+
...baseConfig,
|
|
133
|
+
registry: makeApp({ ui: makeOp("ui", { widget: "boards" }) }),
|
|
134
|
+
widgets: { boards: { uri: "ui://w/b.html", html: "<div/>" } },
|
|
135
|
+
});
|
|
136
|
+
const { result } = await rpc(app, "tools/list");
|
|
137
|
+
expect(result.tools[0]._meta.ui.resourceUri).toBe("ui://w/b.html");
|
|
138
|
+
expect(result.tools[0]._meta["openai/outputTemplate"]).toBe(
|
|
139
|
+
"ui://w/b.html",
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("tools/list omits resourceUri when op has no widget", async () => {
|
|
144
|
+
const app = mcpRoutes({
|
|
145
|
+
...baseConfig,
|
|
146
|
+
registry: makeApp({ data: makeOp("data") }),
|
|
147
|
+
widgets: { boards: { uri: "ui://w/b.html", html: "<div/>" } },
|
|
148
|
+
});
|
|
149
|
+
const { result } = await rpc(app, "tools/list");
|
|
150
|
+
expect(result.tools[0]._meta).toBeUndefined();
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test("resources/list enumerates widgets", async () => {
|
|
154
|
+
const app = mcpRoutes({
|
|
155
|
+
...baseConfig,
|
|
156
|
+
registry: makeApp({}),
|
|
157
|
+
widgets: {
|
|
158
|
+
boards: { uri: "ui://w/b.html", html: "<b/>" },
|
|
159
|
+
cards: { uri: "ui://w/c.html", html: "<c/>" },
|
|
160
|
+
},
|
|
161
|
+
});
|
|
162
|
+
const { result } = await rpc(app, "resources/list");
|
|
163
|
+
expect(result.resources).toHaveLength(2);
|
|
164
|
+
expect(result.resources[0].mimeType).toBe("text/html;profile=mcp-app");
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
test("resources/read returns widget contents + csp meta", async () => {
|
|
168
|
+
const app = mcpRoutes({
|
|
169
|
+
...baseConfig,
|
|
170
|
+
registry: makeApp({}),
|
|
171
|
+
widgets: {
|
|
172
|
+
boards: {
|
|
173
|
+
uri: "ui://w/b.html",
|
|
174
|
+
html: "<body>hi</body>",
|
|
175
|
+
domain: "https://app.example.com",
|
|
176
|
+
csp: { connectDomains: ["https://api.example.com"] },
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
const { result } = await rpc(app, "resources/read", {
|
|
181
|
+
uri: "ui://w/b.html",
|
|
182
|
+
});
|
|
183
|
+
expect(result.contents[0].text).toBe("<body>hi</body>");
|
|
184
|
+
expect(result.contents[0].mimeType).toBe("text/html;profile=mcp-app");
|
|
185
|
+
expect(result.contents[0]._meta.ui.domain).toBe("https://app.example.com");
|
|
186
|
+
expect(result.contents[0]._meta.ui.csp.connectDomains).toEqual([
|
|
187
|
+
"https://api.example.com",
|
|
188
|
+
]);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test("resources/read unknown uri → error", async () => {
|
|
192
|
+
const app = mcpRoutes({ ...baseConfig, registry: makeApp({}) });
|
|
193
|
+
const { error } = await rpc(app, "resources/read", { uri: "ui://nope" });
|
|
194
|
+
expect(error.code).toBe(-32601);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test("tools/call: auth required + no token → www_authenticate", async () => {
|
|
198
|
+
const app = mcpRoutes({
|
|
199
|
+
...baseConfig,
|
|
200
|
+
registry: makeApp({ priv: makeOp("priv") }),
|
|
201
|
+
authenticate: async () => ({
|
|
202
|
+
error: new Response("nope", { status: 401 }),
|
|
203
|
+
}),
|
|
204
|
+
});
|
|
205
|
+
const { result } = await rpc(app, "tools/call", { name: "priv" });
|
|
206
|
+
expect(result.isError).toBe(true);
|
|
207
|
+
expect(result._meta["mcp/www_authenticate"][0]).toContain(
|
|
208
|
+
"resource_metadata=",
|
|
209
|
+
);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test("tools/call: auth=none bypasses authenticate", async () => {
|
|
213
|
+
let authCalled = false;
|
|
214
|
+
const app = mcpRoutes({
|
|
215
|
+
...baseConfig,
|
|
216
|
+
registry: makeApp({ pub: makeOp("pub", { auth: "none" }) }),
|
|
217
|
+
authenticate: async () => {
|
|
218
|
+
authCalled = true;
|
|
219
|
+
return { error: new Response("x", { status: 401 }) };
|
|
220
|
+
},
|
|
221
|
+
executor: async () => ({ ok: 1 }),
|
|
222
|
+
});
|
|
223
|
+
const { result } = await rpc(app, "tools/call", { name: "pub" });
|
|
224
|
+
expect(authCalled).toBe(false);
|
|
225
|
+
expect(result.isError).toBeUndefined();
|
|
226
|
+
expect(result.structuredContent.pub).toEqual({ ok: 1 });
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("tools/call: auth=optional proceeds anon when no token", async () => {
|
|
230
|
+
const app = mcpRoutes({
|
|
231
|
+
...baseConfig,
|
|
232
|
+
registry: makeApp({ maybe: makeOp("maybe", { auth: "optional" }) }),
|
|
233
|
+
authenticate: async () => ({ error: new Response("x", { status: 401 }) }),
|
|
234
|
+
executor: async (_id, _vars, ctx) => ({ userId: ctx.userId }),
|
|
235
|
+
});
|
|
236
|
+
const { result } = await rpc(app, "tools/call", { name: "maybe" });
|
|
237
|
+
expect(result.isError).toBeUndefined();
|
|
238
|
+
expect(result.structuredContent.maybe).toEqual({ userId: null });
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
test("tools/call: returns structuredContent + content text", async () => {
|
|
242
|
+
const app = mcpRoutes({
|
|
243
|
+
...baseConfig,
|
|
244
|
+
registry: makeApp({
|
|
245
|
+
greet: makeOp("greet", {}, () =>
|
|
246
|
+
Brief({
|
|
247
|
+
children: [
|
|
248
|
+
Message({ children: "hello!" }),
|
|
249
|
+
Display({ data: { x: 1 } }),
|
|
250
|
+
],
|
|
251
|
+
}),
|
|
252
|
+
),
|
|
253
|
+
}),
|
|
254
|
+
executor: async () => ({ msg: "hi" }),
|
|
255
|
+
});
|
|
256
|
+
const { result } = await rpc(app, "tools/call", { name: "greet" });
|
|
257
|
+
expect(result.content[0].text).toBe("hello!");
|
|
258
|
+
expect(result.structuredContent.greet).toEqual({ msg: "hi" });
|
|
259
|
+
expect(result.structuredContent.display).toEqual({ x: 1 });
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
test("unknown tool → error", async () => {
|
|
263
|
+
const app = mcpRoutes({ ...baseConfig, registry: makeApp({}) });
|
|
264
|
+
const { error } = await rpc(app, "tools/call", { name: "nope" });
|
|
265
|
+
expect(error.code).toBe(-32601);
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
test("protected resource metadata endpoint", async () => {
|
|
269
|
+
const app = mcpRoutes({
|
|
270
|
+
...baseConfig,
|
|
271
|
+
registry: makeApp({}),
|
|
272
|
+
});
|
|
273
|
+
const res = await app.request("/.well-known/oauth-protected-resource");
|
|
274
|
+
const body = (await res.json()) as any;
|
|
275
|
+
expect(body.resource).toBe("https://app.example.com");
|
|
276
|
+
expect(body.authorization_servers).toEqual(["https://auth.example.com"]);
|
|
277
|
+
expect(body.scopes_supported).toEqual(["read", "write"]);
|
|
278
|
+
});
|
|
279
|
+
});
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import type { Executor, OperationDetail, Registry } from "@donghanh/core";
|
|
2
|
+
import { executeOperation } from "@donghanh/core";
|
|
3
|
+
import { Hono } from "hono";
|
|
4
|
+
import type { Authenticate } from "./middleware";
|
|
5
|
+
import { renderForChatGpt } from "./renderers/chatgpt";
|
|
6
|
+
|
|
7
|
+
const MCP_PROTOCOL_VERSION = "2026-01-26";
|
|
8
|
+
const UI_MIME_TYPE = "text/html;profile=mcp-app";
|
|
9
|
+
|
|
10
|
+
export interface WidgetConfig {
|
|
11
|
+
/** Stable URI, content-hashed for cache-bust (e.g. "ui://widget/boards-a1b2c3.html"). */
|
|
12
|
+
uri: string;
|
|
13
|
+
/** Full iframe HTML. */
|
|
14
|
+
html: string;
|
|
15
|
+
/** Domain for sandbox. Required for submission. */
|
|
16
|
+
domain?: string;
|
|
17
|
+
csp?: {
|
|
18
|
+
connectDomains?: string[];
|
|
19
|
+
resourceDomains?: string[];
|
|
20
|
+
frameDomains?: string[];
|
|
21
|
+
};
|
|
22
|
+
prefersBorder?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface McpRoutesConfig {
|
|
26
|
+
registry: Registry;
|
|
27
|
+
executor: Executor;
|
|
28
|
+
authenticate: Authenticate;
|
|
29
|
+
/** Canonical HTTPS identifier for this MCP server. */
|
|
30
|
+
resource: string;
|
|
31
|
+
/** Authorization server issuer base URL(s). */
|
|
32
|
+
authorizationServers: string[];
|
|
33
|
+
/** Scopes advertised in protected-resource metadata (default scopes). */
|
|
34
|
+
scopes?: string[];
|
|
35
|
+
resourceDocumentation?: string;
|
|
36
|
+
serverInfo?: { name: string; version: string };
|
|
37
|
+
encodeVariables?: (vars: Record<string, unknown>) => string;
|
|
38
|
+
/** Named widgets. Operation's `widget` config key must match a name here. */
|
|
39
|
+
widgets?: Record<string, WidgetConfig>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type JsonRpcRequest = {
|
|
43
|
+
jsonrpc: "2.0";
|
|
44
|
+
id?: number | string | null;
|
|
45
|
+
method: string;
|
|
46
|
+
params?: Record<string, unknown>;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
type JsonRpcSuccess = {
|
|
50
|
+
jsonrpc: "2.0";
|
|
51
|
+
id: number | string | null;
|
|
52
|
+
result: unknown;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
type JsonRpcFailure = {
|
|
56
|
+
jsonrpc: "2.0";
|
|
57
|
+
id: number | string | null;
|
|
58
|
+
error: { code: number; message: string; data?: unknown };
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
function success(id: number | string | null, result: unknown): JsonRpcSuccess {
|
|
62
|
+
return { jsonrpc: "2.0", id, result };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function failure(
|
|
66
|
+
id: number | string | null,
|
|
67
|
+
code: number,
|
|
68
|
+
message: string,
|
|
69
|
+
data?: unknown,
|
|
70
|
+
): JsonRpcFailure {
|
|
71
|
+
const error: { code: number; message: string; data?: unknown } = {
|
|
72
|
+
code,
|
|
73
|
+
message,
|
|
74
|
+
};
|
|
75
|
+
if (data !== undefined) error.data = data;
|
|
76
|
+
return { jsonrpc: "2.0", id, error };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function wwwAuthenticate(
|
|
80
|
+
resource: string,
|
|
81
|
+
error: string,
|
|
82
|
+
description: string,
|
|
83
|
+
): string {
|
|
84
|
+
return `Bearer resource_metadata="${resource}/.well-known/oauth-protected-resource", error="${error}", error_description="${description}"`;
|
|
85
|
+
}
|
|
86
|
+
|
|
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
|
+
function annotationsFor(detail: OperationDetail | null): {
|
|
100
|
+
readOnlyHint: boolean;
|
|
101
|
+
openWorldHint: boolean;
|
|
102
|
+
destructiveHint: boolean;
|
|
103
|
+
} {
|
|
104
|
+
if (!detail) {
|
|
105
|
+
return {
|
|
106
|
+
readOnlyHint: false,
|
|
107
|
+
openWorldHint: true,
|
|
108
|
+
destructiveHint: false,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const readOnly = detail.type === "query";
|
|
112
|
+
return {
|
|
113
|
+
readOnlyHint: readOnly,
|
|
114
|
+
openWorldHint: readOnly ? false : (detail.external ?? false),
|
|
115
|
+
destructiveHint: readOnly ? false : (detail.destructive ?? false),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function widgetMetaFor(widget: WidgetConfig): Record<string, unknown> {
|
|
120
|
+
const ui: Record<string, unknown> = {};
|
|
121
|
+
if (widget.prefersBorder) ui.prefersBorder = true;
|
|
122
|
+
if (widget.domain) ui.domain = widget.domain;
|
|
123
|
+
if (widget.csp) ui.csp = widget.csp;
|
|
124
|
+
return ui;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function mcpRoutes(config: McpRoutesConfig): Hono {
|
|
128
|
+
const {
|
|
129
|
+
registry,
|
|
130
|
+
executor,
|
|
131
|
+
authenticate,
|
|
132
|
+
resource,
|
|
133
|
+
authorizationServers,
|
|
134
|
+
scopes = [],
|
|
135
|
+
resourceDocumentation,
|
|
136
|
+
serverInfo = { name: "donghanh-mcp", version: "0.1.0" },
|
|
137
|
+
encodeVariables,
|
|
138
|
+
widgets = {},
|
|
139
|
+
} = config;
|
|
140
|
+
|
|
141
|
+
const app = new Hono();
|
|
142
|
+
|
|
143
|
+
// 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,
|
|
151
|
+
}),
|
|
152
|
+
}),
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
app.post("/mcp", async (c) => {
|
|
156
|
+
let body: JsonRpcRequest;
|
|
157
|
+
try {
|
|
158
|
+
body = await c.req.json();
|
|
159
|
+
} catch {
|
|
160
|
+
return c.json(failure(null, -32700, "Parse error"), 400);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const id = body.id ?? null;
|
|
164
|
+
const method = body.method;
|
|
165
|
+
|
|
166
|
+
if (body.jsonrpc !== "2.0" || !method) {
|
|
167
|
+
return c.json(failure(id, -32600, "Invalid Request"), 400);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
switch (method) {
|
|
171
|
+
case "initialize":
|
|
172
|
+
return c.json(
|
|
173
|
+
success(id, {
|
|
174
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
175
|
+
capabilities: {
|
|
176
|
+
tools: {},
|
|
177
|
+
...(Object.keys(widgets).length > 0 && { resources: {} }),
|
|
178
|
+
},
|
|
179
|
+
serverInfo,
|
|
180
|
+
}),
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
case "notifications/initialized":
|
|
184
|
+
case "notifications/cancelled":
|
|
185
|
+
return new Response(null, { status: 204 });
|
|
186
|
+
|
|
187
|
+
case "tools/list": {
|
|
188
|
+
const tools = registry.list().map((op) => {
|
|
189
|
+
const detail = registry.detail(op.id);
|
|
190
|
+
const widgetName = detail?.widget;
|
|
191
|
+
const widget = widgetName ? widgets[widgetName] : undefined;
|
|
192
|
+
|
|
193
|
+
const tool: Record<string, unknown> = {
|
|
194
|
+
name: op.id,
|
|
195
|
+
description: detail?.instruction
|
|
196
|
+
? `${op.description}\n\n${detail.instruction}`
|
|
197
|
+
: op.description,
|
|
198
|
+
inputSchema: detail?.input ?? {
|
|
199
|
+
type: "object",
|
|
200
|
+
properties: {},
|
|
201
|
+
},
|
|
202
|
+
annotations: annotationsFor(detail),
|
|
203
|
+
securitySchemes: securitySchemesFor(detail, scopes),
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
if (widget) {
|
|
207
|
+
tool._meta = {
|
|
208
|
+
ui: { resourceUri: widget.uri },
|
|
209
|
+
"openai/outputTemplate": widget.uri,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return tool;
|
|
214
|
+
});
|
|
215
|
+
return c.json(success(id, { tools }));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
case "resources/list": {
|
|
219
|
+
const resources = Object.entries(widgets).map(([name, w]) => ({
|
|
220
|
+
uri: w.uri,
|
|
221
|
+
name,
|
|
222
|
+
mimeType: UI_MIME_TYPE,
|
|
223
|
+
}));
|
|
224
|
+
return c.json(success(id, { resources }));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
case "resources/read": {
|
|
228
|
+
const uri = body.params?.uri as string | undefined;
|
|
229
|
+
if (!uri) return c.json(failure(id, -32602, "Missing uri"), 400);
|
|
230
|
+
const widget = Object.values(widgets).find((w) => w.uri === uri);
|
|
231
|
+
if (!widget) {
|
|
232
|
+
return c.json(failure(id, -32601, `Unknown resource "${uri}"`), 404);
|
|
233
|
+
}
|
|
234
|
+
return c.json(
|
|
235
|
+
success(id, {
|
|
236
|
+
contents: [
|
|
237
|
+
{
|
|
238
|
+
uri: widget.uri,
|
|
239
|
+
mimeType: UI_MIME_TYPE,
|
|
240
|
+
text: widget.html,
|
|
241
|
+
_meta: { ui: widgetMetaFor(widget) },
|
|
242
|
+
},
|
|
243
|
+
],
|
|
244
|
+
}),
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
case "tools/call": {
|
|
249
|
+
const params = (body.params ?? {}) as {
|
|
250
|
+
name?: string;
|
|
251
|
+
arguments?: Record<string, unknown>;
|
|
252
|
+
};
|
|
253
|
+
const toolName = params.name;
|
|
254
|
+
if (!toolName) {
|
|
255
|
+
return c.json(failure(id, -32602, "Missing tool name"), 400);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const op = registry.get(toolName);
|
|
259
|
+
if (!op) {
|
|
260
|
+
return c.json(failure(id, -32601, `Unknown tool "${toolName}"`), 404);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
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
|
+
|
|
329
|
+
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
|
+
}),
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
default:
|
|
348
|
+
return c.json(failure(id, -32601, `Method not found: ${method}`), 404);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
return app;
|
|
353
|
+
}
|