Repository navigation
Expand file tree
/
Copy pathtest-mcp-oauth-server.mjs
More file actions
364 lines (327 loc) · 10 KB
/
Copy pathtest-mcp-oauth-server.mjs
File metadata and controls
364 lines (327 loc) · 10 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#!/usr/bin/env node
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
/**
* Minimal OAuth-protected Streamable HTTP MCP server for SDK E2E tests.
*
* The `/mcp` endpoint returns a WWW-Authenticate challenge until requests include
* an accepted test token, then serves enough JSON-RPC MCP methods for the runtime
* to initialize and list/call one tool. Specific tool-call scenarios trigger
* replacement-token challenges so SDK E2E tests can cover refresh, upscope, and
* reauth flows without relying on a real OAuth server.
*/
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
const DEFAULT_EXPECTED_TOKEN = "sdk-host-token";
const PROTOCOL_VERSION = "2025-03-26";
const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";
export async function startOAuthMcpServer({
expectedToken = DEFAULT_EXPECTED_TOKEN,
deferInitialChallenge = false,
host = "127.0.0.1",
port = 0,
cimdSupported = false,
} = {}) {
let releaseInitialChallenge = () => {};
const initialChallenge = deferInitialChallenge
? new Promise((resolve) => {
releaseInitialChallenge = resolve;
})
: Promise.resolve();
const requests = [];
const tokens = {
initial: expectedToken,
refresh: `${expectedToken}-refresh`,
upscope: `${expectedToken}-upscope`,
reauth: `${expectedToken}-reauth`,
rejected: `${expectedToken}-rejected`,
};
const acceptedTokens = new Set([
tokens.initial,
tokens.refresh,
tokens.upscope,
tokens.reauth,
]);
const server = http.createServer(async (req, res) => {
const url = new URL(
req.url ?? "/",
`http://${req.headers.host ?? `${host}:${port}`}`,
);
const baseUrl = url.origin;
const body = await readBody(req);
if (req.method === "GET" && url.pathname === "/__requests") {
respondJson(res, 200, requests);
return;
}
if (
req.method === "POST" &&
url.pathname === "/__release-initial-challenge"
) {
releaseInitialChallenge();
res.writeHead(204);
res.end();
return;
}
if (req.method === "GET" && url.pathname === PROTECTED_RESOURCE_PATH) {
respondJson(res, 200, {
resource: `${baseUrl}/mcp`,
authorization_servers: [baseUrl],
scopes_supported: ["mcp.read"],
bearer_methods_supported: ["header"],
});
return;
}
if (
req.method === "GET" &&
url.pathname === "/.well-known/oauth-authorization-server"
) {
respondJson(res, 200, {
issuer: baseUrl,
authorization_endpoint: `${baseUrl}/authorize`,
token_endpoint: `${baseUrl}/token`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
...(cimdSupported
? { client_id_metadata_document_supported: true }
: {}),
});
return;
}
if (req.method === "POST" && url.pathname === "/register") {
requests.push({
method: req.method,
path: url.pathname,
authorization: req.headers.authorization ?? null,
body,
});
respondJson(res, 201, {
client_id: "registered-client",
client_id_issued_at: Math.floor(Date.now() / 1000),
});
return;
}
if (url.pathname !== "/mcp") {
respondJson(res, 404, { error: "not_found" });
return;
}
requests.push({
method: req.method,
path: url.pathname,
authorization: req.headers.authorization ?? null,
body: body || null,
});
const token = parseBearerToken(req.headers.authorization);
if (!token || !acceptedTokens.has(token)) {
await initialChallenge;
challengeInitial(res, baseUrl);
return;
}
if (req.method !== "POST") {
respondJson(res, 405, { error: "method_not_allowed" });
return;
}
const parsedBody = parseJsonBody(body);
if (!parsedBody.ok) {
respondJson(res, 400, { error: "invalid_json" });
return;
}
const message = parsedBody.value;
const replacementChallenge = getReplacementChallenge(
message,
token,
tokens,
baseUrl,
);
if (replacementChallenge) {
res.writeHead(replacementChallenge.statusCode, {
"www-authenticate": replacementChallenge.wwwAuthenticate,
"content-type": "application/json",
});
res.end(JSON.stringify({ error: replacementChallenge.error }));
return;
}
const response = Array.isArray(message)
? message
.map((item) => handleJsonRpcMessage(item))
.filter((item) => item !== undefined)
: handleJsonRpcMessage(message);
if (
response === undefined ||
(Array.isArray(response) && response.length === 0)
) {
res.writeHead(202, { "mcp-session-id": "oauth-test-session" });
res.end();
return;
}
res.writeHead(200, {
"content-type": "application/json",
"mcp-session-id": "oauth-test-session",
});
res.end(JSON.stringify(response));
});
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(port, host, () => {
server.off("error", reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("Expected TCP server address");
}
return {
url: `http://${host}:${address.port}`,
requests,
close: () =>
new Promise((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
server.closeAllConnections();
}),
};
}
function getReplacementChallenge(message, token, tokens, baseUrl) {
const messages = Array.isArray(message) ? message : [message];
const toolCall = messages.find((item) => item?.method === "tools/call");
const scenario = toolCall?.params?.arguments?.scenario;
if (scenario === "refresh" && token !== tokens.refresh) {
return {
statusCode: 401,
wwwAuthenticate: 'Bearer error="invalid_token"',
error: "token_expired",
};
}
if (scenario === "upscope" && token !== tokens.upscope) {
return {
statusCode: 403,
wwwAuthenticate: `Bearer resource_metadata="${baseUrl}${PROTECTED_RESOURCE_PATH}", scope="mcp.write", error="insufficient_scope"`,
error: "insufficient_scope",
};
}
if (scenario === "reauth" && token !== tokens.reauth) {
return {
statusCode: 401,
wwwAuthenticate: 'Bearer error="invalid_token"',
error: "reauth_required",
};
}
if (scenario === "cancel" && token !== tokens.refresh) {
return {
statusCode: 401,
wwwAuthenticate: 'Bearer error="invalid_token"',
error: "token_expired",
};
}
return undefined;
}
function handleJsonRpcMessage(message) {
if (!message || typeof message !== "object" || !("id" in message)) {
return undefined;
}
switch (message.method) {
case "initialize":
return {
jsonrpc: "2.0",
id: message.id,
result: {
protocolVersion: message.params?.protocolVersion ?? PROTOCOL_VERSION,
capabilities: { tools: {} },
serverInfo: { name: "oauth-test-server", version: "1.0.0" },
},
};
case "tools/list":
return {
jsonrpc: "2.0",
id: message.id,
result: {
tools: [
{
name: "whoami",
description: "Returns the authenticated test principal.",
inputSchema: {
type: "object",
properties: {
scenario: {
type: "string",
enum: ["initial", "refresh", "upscope", "reauth", "cancel"],
},
},
additionalProperties: false,
},
_meta: { "ui.visibility": ["model", "app"] },
},
],
},
};
case "tools/call":
return {
jsonrpc: "2.0",
id: message.id,
result: {
content: [{ type: "text", text: "oauth-test-user" }],
isError: false,
},
};
default:
return {
jsonrpc: "2.0",
id: message.id,
error: { code: -32601, message: `Method not found: ${message.method}` },
};
}
}
function parseBearerToken(authorization) {
const match = /^Bearer (.+)$/.exec(authorization ?? "");
return match?.[1];
}
function challengeInitial(res, baseUrl) {
const resourceMetadataUrl = `${baseUrl}${PROTECTED_RESOURCE_PATH}`;
res.writeHead(401, {
"www-authenticate": `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp.read", error="invalid_token"`,
"content-type": "application/json",
});
res.end(JSON.stringify({ error: "missing_or_invalid_token" }));
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("error", reject);
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});
}
function parseJsonBody(body) {
if (!body) {
return { ok: true, value: undefined };
}
try {
return { ok: true, value: JSON.parse(body) };
} catch {
return { ok: false, value: undefined };
}
}
function respondJson(res, statusCode, body) {
const data = JSON.stringify(body);
res.writeHead(statusCode, {
"content-type": "application/json",
"content-length": Buffer.byteLength(data),
});
res.end(data);
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const server = await startOAuthMcpServer({
expectedToken: process.env.EXPECTED_TOKEN ?? DEFAULT_EXPECTED_TOKEN,
cimdSupported: process.env.CIMD_SUPPORTED === "true",
deferInitialChallenge: process.env.DEFER_INITIAL_CHALLENGE === "true",
});
console.log(`Listening: ${server.url}`);
process.on("SIGTERM", async () => {
await server.close();
process.exit(0);
});
}