@donghanh/hono 0.1.0 → 0.2.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 +3 -6
- 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.2.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",
|
|
@@ -12,11 +12,8 @@
|
|
|
12
12
|
"url": "https://github.com/rezzahub/donghanh",
|
|
13
13
|
"directory": "packages/hono"
|
|
14
14
|
},
|
|
15
|
-
"dependencies": {
|
|
16
|
-
"@donghanh/core": "workspace:*",
|
|
17
|
-
"hono": "^4.7.0"
|
|
18
|
-
},
|
|
19
15
|
"peerDependencies": {
|
|
20
|
-
"
|
|
16
|
+
"@donghanh/core": "^0.2.0",
|
|
17
|
+
"hono": "^4.7.0"
|
|
21
18
|
}
|
|
22
19
|
}
|
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
|
+
}
|