-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
340 lines (311 loc) · 9.02 KB
/
server.ts
File metadata and controls
340 lines (311 loc) · 9.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import { Client } from "@modelcontextprotocol/sdk/client";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import Bun from "bun";
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const showForm = (url: string, formItems: string[]) =>
new Response(
`<html>
<title>MCP Testing Harness</title>
<body>
<h1>MCP Testing Harness</h1>
<a href="/?url=${encodeURIComponent(url)}">Reset</a>
<form method="GET" action="/">
${formItems.join("<br/>\n")}
<button type="submit">Next</button>
</form>
</body>`,
{
headers: { "Content-type": "text/html" },
},
);
const showIframeForm = (url: string, formItems: string[], initialUrl: string) =>
new Response(
`<html>
<title>MCP Testing Harness</title>
<body>
<h1>MCP Testing Harness</h1>
<a href="/?url=${encodeURIComponent(url)}">Reset</a>
<form method="GET" action="/embed" target="embed">
${formItems.join("<br/>\n")}
<button type="submit">Submit</button>
</form>
<iframe name="embed" style="width: 50vw;min-width:300px;min-height:500px;height:50vh" src="${initialUrl}" />
</body>`,
{
headers: { "Content-type": "text/html" },
},
);
const server = Bun.serve({
port: 3112,
// `routes` requires Bun v1.2.3+
routes: {
"/": async (req) => {
const formItems: string[] = [];
const url = new URL(req.url);
const serverUrl = url.searchParams.get("url");
formItems.push(
`URL: <input style="width:600px" name="url" value="${serverUrl ?? ""}" placeholder="MCP URL" />`,
);
if (!serverUrl) {
return showForm("", formItems);
}
const transport = new SSEClientTransport(new URL(serverUrl));
const client = new Client({
name: "example-client",
version: "1.0.0",
});
try {
await client.connect(transport);
} catch (err) {
return new Response(
`Unable to connect. Retrying in 3 seconds. ${err}`,
{
headers: {
"Content-type": "text/html",
status: "400",
Refresh: "3",
},
},
);
}
const { tools } = await client.listTools();
const toolName = url.searchParams.get("tool");
formItems.push(`Tool: <select name="tool" value="${toolName}">
${tools.map((tool) => `<option value="${tool.name}">${tool.name}</option>`).join("\n")}
</select>`);
if (!toolName) {
return showForm(serverUrl, formItems);
}
const tool = tools.find((tool) => tool.name === toolName);
if (!tool) {
return new Response("tool not found", { status: 400 });
}
const tpl = tool._meta?.["openai/outputTemplate"] as string | null;
if (!tpl) {
console.log(tool._meta);
return new Response("tool doesn't have openai/outputTemplate defined", {
status: 400,
});
}
const fields = Object.entries(tool.inputSchema.properties!).map(
([key, defn]) => {
const value = url.searchParams.get(key);
const required = tool.inputSchema.required?.includes(key);
switch ((defn as { type: string }).type) {
case "integer":
return `${key}: <input name="${key}" type="number" value="${value ?? ""}" placeholder="${key}" />${
required ? ` - required` : ""
}`;
case "boolean":
return `${key}: <input name="${key}" type="checkbox" value="${value ?? ""}" placeholder="${key}" />${
required ? ` - required` : ""
}`;
case "string":
return `${key}: <input style="width:600px" name="${key}" value="${value ?? ""}" placeholder="${key}" />${
required ? ` - required` : ""
}`;
default:
throw new Error(
`not handling input property with schema ${JSON.stringify(defn)}`,
);
}
},
);
formItems.push(
`<ul>
${fields.map((item) => `<li>${item}</li>`).join("\n")}
</ul>`,
);
return showIframeForm(serverUrl, formItems, `/preview${url.search}`);
},
"/preview": async (req) => {
const url = new URL(req.url);
const serverUrl = url.searchParams.get("url");
if (!serverUrl) {
throw new Error(`No url`);
}
const transport = new SSEClientTransport(new URL(serverUrl));
const client = new Client({
name: "example-client",
version: "1.0.0",
});
try {
await client.connect(transport);
} catch (err) {
return new Response(
`Unable to connect. Retrying in 3 seconds. ${err}`,
{
headers: {
"Content-type": "text/html",
status: "400",
Refresh: "3",
},
},
);
}
const toolName = url.searchParams.get("tool");
if (!toolName) {
throw new Error(`tool`);
}
const { tools } = await client.listTools();
const tool = tools.find((tool) => tool.name === toolName);
if (!tool) {
return new Response("tool not found", { status: 400 });
}
const tpl = tool._meta?.["openai/outputTemplate"] as string | null;
if (!tpl) {
return new Response("tool doesn't have openai/outputTemplate defined", {
status: 400,
});
}
const resource = await client.readResource({
uri: tpl,
});
if (!resource.contents[0]) {
return new Response("Resource invalid", { status: 500 });
}
const resourceContent = resource.contents[0];
const widgetCSP = resourceContent._meta!["openai/widgetCSP"];
const csp =
typeof widgetCSP === "object" &&
widgetCSP &&
"resource_domains" in widgetCSP
? (widgetCSP.resource_domains as string[])
: [];
return new Response(resourceContent.text as string, {
headers: {
"content-type": "text/html",
"Content-Security-Policy": `default-src 'unsafe-inline' data: http://localhost:3112 wss://localhost:8225 https://localhost:8226 ${csp.join(
" ",
)}`,
},
});
},
"/embed": async (req) => {
const url = new URL(req.url);
const serverUrl = url.searchParams.get("url");
if (!serverUrl) {
throw new Error(`No url`);
}
const transport = new SSEClientTransport(new URL(serverUrl));
const client = new Client({
name: "example-client",
version: "1.0.0",
});
try {
await client.connect(transport);
} catch (err) {
return new Response(
`Unable to connect. Retrying in 3 seconds. ${err}`,
{
headers: {
"Content-type": "text/html",
status: "400",
Refresh: "3",
},
},
);
}
const toolName = url.searchParams.get("tool");
if (!toolName) {
throw new Error(`tool`);
}
const { tools } = await client.listTools();
const tool = tools.find((tool) => tool.name === toolName);
if (!tool) {
return new Response("tool not found", { status: 400 });
}
const tpl = tool._meta?.["openai/outputTemplate"] as string | null;
if (!tpl) {
return new Response("tool doesn't have openai/outputTemplate defined", {
status: 400,
});
}
const resource = await client.readResource({
uri: tpl,
});
if (!resource.contents[0]) {
return new Response("Resource invalid", { status: 500 });
}
const resourceContent = resource.contents[0];
const values: Record<string, string | boolean | number | undefined> = {};
const missing: string[] = [];
Object.entries(tool.inputSchema.properties!).forEach(([key, defn]) => {
const value = url.searchParams.get(key);
const required = tool.inputSchema.required?.includes(key);
switch ((defn as { type: string }).type) {
case "boolean":
values[key] = value === "true";
break;
case "integer":
values[key] = value ? +value : undefined;
break;
case "string":
if (value) {
values[key] = value;
} else if (required) {
missing.push(key);
}
break;
default:
throw new Error(
`not handling input property with schema ${JSON.stringify(defn)}`,
);
}
});
if (missing.length) {
throw new Error(`missing required values: ${missing}`);
}
const widgetCSP = resourceContent._meta!["openai/widgetCSP"];
const csp =
typeof widgetCSP === "object" &&
widgetCSP &&
"resource_domains" in widgetCSP
? (widgetCSP.resource_domains as string[])
: [];
console.log("got csp", csp);
// Call a tool
const result = await client.callTool({
name: tool.name,
arguments: values,
_meta: {
"openai/meta": "some-meta-value",
},
});
if (!result.structuredContent) {
return new Response(JSON.stringify(result));
}
return new Response(
(resourceContent.text as string)
.replace(
"</head>",
() =>
`<script>openai = {toolOutput: ${JSON.stringify(result.structuredContent)}}</script></head>`,
)
.replace(
"</body>",
() =>
`<pre>Structured content:\n\n${JSON.stringify(
result.structuredContent,
null,
2,
).replace(
"<",
"<",
)}\nMeta:\n${JSON.stringify(result._meta, null, 2)}</pre>
</body>`,
),
{
headers: {
"content-type": "text/html",
"Content-Security-Policy": `default-src 'unsafe-inline' data: http://localhost:3112 wss://localhost:8225 https://localhost:8226 ${csp.join(
" ",
)}`,
},
},
);
},
},
idleTimeout: 100,
});
console.log(`serving http://localhost:${server.port}`);