@koneeric/onetool 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +76 -2
- package/auth/src/index.js +302 -0
- package/bin/onetool.js +4 -0
- package/core/src/index.js +843 -0
- package/guide/pages/INSTALL.md +810 -0
- package/guide/pages/settings.example.json +6 -0
- package/hosts/src/adapters/claude-code.js +136 -0
- package/hosts/src/index.js +107 -0
- package/library/src/index.js +544 -0
- package/package.json +36 -4
- package/practice/src/rows.js +15 -0
- package/practice/src/server.js +187 -0
- package/practice/src/signin.js +242 -0
- package/sandbox/src/child.mjs +441 -0
- package/sandbox/src/index.js +301 -0
- package/sandbox/src/last-expression.mjs +134 -0
- package/sandbox/src/probe.mjs +42 -0
- package/server/src/connect.js +190 -0
- package/server/src/descriptions.js +62 -0
- package/server/src/host.js +116 -0
- package/server/src/init.js +243 -0
- package/server/src/library.js +207 -0
- package/server/src/main.js +142 -0
- package/server/src/prompt.js +15 -0
- package/server/src/record.js +131 -0
- package/server/src/sign.js +98 -0
- package/server/src/tools.js +553 -0
- package/shell/src/index.js +270 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
5
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import { allRows } from "./rows.js";
|
|
7
|
+
import { createSignin } from "./signin.js";
|
|
8
|
+
|
|
9
|
+
const str = { type: "string" };
|
|
10
|
+
|
|
11
|
+
const TOOLS = [
|
|
12
|
+
{
|
|
13
|
+
name: "rows",
|
|
14
|
+
description: "Returns the practice table: 5,000 rows of id, name, city and amount. Use it to try programs on a large result.",
|
|
15
|
+
inputSchema: { type: "object", properties: { city: str } },
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
name: "count",
|
|
19
|
+
description: "Counts the rows of the practice table. Answers as JSON text.",
|
|
20
|
+
inputSchema: { type: "object", properties: { city: str } },
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "echo",
|
|
24
|
+
description: "Answers with the text it was given. Plain text.",
|
|
25
|
+
inputSchema: { type: "object", properties: { text: str }, required: ["text"] },
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
name: "fail",
|
|
29
|
+
description: "Always fails. Use it to try what a program does with a failing tool.",
|
|
30
|
+
inputSchema: { type: "object", properties: { reason: str } },
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
name: "wipe",
|
|
34
|
+
description: "Pretends to delete the practice table. It deletes nothing.",
|
|
35
|
+
inputSchema: { type: "object", properties: {} },
|
|
36
|
+
},
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const text = (t) => ({ content: [{ type: "text", text: t }] });
|
|
40
|
+
const failed = (t) => ({ isError: true, ...text(t) });
|
|
41
|
+
|
|
42
|
+
/** The rows of the table, or those of the city given; `undefined` when `city` is given and is not a string. */
|
|
43
|
+
function chosen(args) {
|
|
44
|
+
if (args.city !== undefined && typeof args.city !== "string") return undefined;
|
|
45
|
+
const rows = allRows();
|
|
46
|
+
return args.city === undefined ? rows : rows.filter((r) => r.city === args.city);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const notString = (property) => failed(`practice: ${property} must be a string`);
|
|
50
|
+
|
|
51
|
+
const HANDLERS = {
|
|
52
|
+
rows(args) {
|
|
53
|
+
const rows = chosen(args);
|
|
54
|
+
if (rows === undefined) return notString("city");
|
|
55
|
+
return { content: [{ type: "text", text: JSON.stringify({ rows }) }], structuredContent: { rows } };
|
|
56
|
+
},
|
|
57
|
+
count(args) {
|
|
58
|
+
const rows = chosen(args);
|
|
59
|
+
if (rows === undefined) return notString("city");
|
|
60
|
+
return text(JSON.stringify({ count: rows.length }));
|
|
61
|
+
},
|
|
62
|
+
echo(args) {
|
|
63
|
+
if (typeof args.text !== "string") return notString("text");
|
|
64
|
+
return text(args.text);
|
|
65
|
+
},
|
|
66
|
+
fail(args) {
|
|
67
|
+
if (args.reason !== undefined && typeof args.reason !== "string") return notString("reason");
|
|
68
|
+
return failed(`practice failure: ${args.reason ?? "asked to fail"}`);
|
|
69
|
+
},
|
|
70
|
+
wipe() {
|
|
71
|
+
return text("wiped");
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
function createServer() {
|
|
76
|
+
const server = new Server({ name: "practice", version: "1.0.0" }, { capabilities: { tools: {} } });
|
|
77
|
+
|
|
78
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
79
|
+
|
|
80
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
81
|
+
const { name, arguments: given } = request.params;
|
|
82
|
+
if (!Object.hasOwn(HANDLERS, name)) throw new McpError(ErrorCode.InvalidParams, `unknown tool: ${name}`);
|
|
83
|
+
const args = given !== null && typeof given === "object" ? given : {};
|
|
84
|
+
return HANDLERS[name](args);
|
|
85
|
+
});
|
|
86
|
+
return server;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const USAGE =
|
|
90
|
+
"usage: node practice/src/server.js [--port <number> [--token <text>] [--signin [--expires <seconds>] [--client <id> [--secret <text>]]]]";
|
|
91
|
+
|
|
92
|
+
const WITH_WORD = ["--port", "--token", "--expires", "--client", "--secret"];
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* `{port, token, signin}` from the arguments (`port` and `token` are `undefined` when not given; `signin` is
|
|
96
|
+
* `undefined` or `{expires, client, secret}`); `undefined` when they are not a form of the usage.
|
|
97
|
+
*/
|
|
98
|
+
function parseArguments(argv) {
|
|
99
|
+
const given = {};
|
|
100
|
+
for (let i = 0; i < argv.length; i++) {
|
|
101
|
+
const option = argv[i];
|
|
102
|
+
if (Object.hasOwn(given, option)) return undefined;
|
|
103
|
+
if (option === "--signin") given[option] = true;
|
|
104
|
+
else if (WITH_WORD.includes(option) && i + 1 < argv.length) given[option] = argv[++i];
|
|
105
|
+
else return undefined;
|
|
106
|
+
}
|
|
107
|
+
const { "--port": port, "--token": token, "--signin": signin, "--expires": expires, "--client": client, "--secret": secret } = given;
|
|
108
|
+
if (argv.length === 0) return { port: undefined, token: undefined, signin: undefined };
|
|
109
|
+
if (port === undefined || !/^[0-9]+$/.test(port) || Number(port) > 65535) return undefined;
|
|
110
|
+
if (token === "") return undefined;
|
|
111
|
+
if (signin === undefined) {
|
|
112
|
+
if (expires !== undefined || client !== undefined || secret !== undefined) return undefined;
|
|
113
|
+
return { port: Number(port), token, signin: undefined };
|
|
114
|
+
}
|
|
115
|
+
if (token !== undefined) return undefined;
|
|
116
|
+
if (expires !== undefined && (!/^[0-9]+$/.test(expires) || Number(expires) < 1 || Number(expires) > 86400)) return undefined;
|
|
117
|
+
if (client === "" || secret === "" || (secret !== undefined && client === undefined)) return undefined;
|
|
118
|
+
return { port: Number(port), token: undefined, signin: { expires: expires === undefined ? 3600 : Number(expires), client, secret } };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The header may reach us as Latin-1 text of the bytes a client wrote in UTF-8; both spellings of the token are accepted. */
|
|
122
|
+
function authorized(header, token) {
|
|
123
|
+
if (header === undefined) return false;
|
|
124
|
+
return header === `Bearer ${token}` || Buffer.from(header, "latin1").toString("utf8") === `Bearer ${token}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function serveRequest(req, res) {
|
|
128
|
+
const server = createServer();
|
|
129
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
130
|
+
res.on("close", () => {
|
|
131
|
+
transport.close().catch(() => {});
|
|
132
|
+
server.close().catch(() => {});
|
|
133
|
+
});
|
|
134
|
+
await server.connect(transport);
|
|
135
|
+
await transport.handleRequest(req, res);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function listen(port, token, signin) {
|
|
139
|
+
const sign = signin === undefined ? undefined : createSignin(signin);
|
|
140
|
+
const mcp = (req, res) =>
|
|
141
|
+
serveRequest(req, res).catch(() => {
|
|
142
|
+
if (!res.headersSent) res.writeHead(500);
|
|
143
|
+
res.end();
|
|
144
|
+
});
|
|
145
|
+
const httpServer = http.createServer((req, res) => {
|
|
146
|
+
if (sign !== undefined) {
|
|
147
|
+
sign.handle(req, res, () => mcp(req, res)).catch(() => {
|
|
148
|
+
if (!res.headersSent) res.writeHead(500);
|
|
149
|
+
res.end();
|
|
150
|
+
});
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const path = (req.url ?? "").split("?")[0];
|
|
154
|
+
if (path !== "/mcp") {
|
|
155
|
+
res.writeHead(404).end();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (token !== undefined && !authorized(req.headers.authorization, token)) {
|
|
159
|
+
res.writeHead(401).end();
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
mcp(req, res);
|
|
163
|
+
});
|
|
164
|
+
const cannot = () => {
|
|
165
|
+
process.stderr.write(`practice: cannot listen on port ${port}\n`);
|
|
166
|
+
process.exit(1);
|
|
167
|
+
};
|
|
168
|
+
httpServer.once("error", cannot);
|
|
169
|
+
httpServer.listen(port, "127.0.0.1", () => {
|
|
170
|
+
httpServer.off("error", cannot);
|
|
171
|
+
process.stdout.write(`practice: listening on http://127.0.0.1:${httpServer.address().port}/mcp\n`);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const options = parseArguments(process.argv.slice(2));
|
|
176
|
+
if (options === undefined) {
|
|
177
|
+
process.stderr.write(`${USAGE}\n`);
|
|
178
|
+
process.exit(2);
|
|
179
|
+
} else if (options.port !== undefined) {
|
|
180
|
+
listen(options.port, options.token, options.signin);
|
|
181
|
+
} else {
|
|
182
|
+
const server = createServer();
|
|
183
|
+
process.stdin.on("end", () => {
|
|
184
|
+
server.close().catch(() => {});
|
|
185
|
+
});
|
|
186
|
+
await server.connect(new StdioServerTransport());
|
|
187
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const MAX_BODY = 1024 * 1024;
|
|
4
|
+
|
|
5
|
+
/** 32 characters of `A-Z`, `a-z`, `0-9`, `_`, `-` after `prefix`. */
|
|
6
|
+
const drawn = (prefix) => prefix + randomBytes(24).toString("base64url");
|
|
7
|
+
|
|
8
|
+
function send(res, status, body, headers = {}) {
|
|
9
|
+
const text = body === undefined ? "" : JSON.stringify(body);
|
|
10
|
+
res.writeHead(status, { ...(body === undefined ? {} : { "Content-Type": "application/json" }), "Cache-Control": "no-store", ...headers });
|
|
11
|
+
res.end(text);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function readBody(req) {
|
|
15
|
+
return new Promise((resolve) => {
|
|
16
|
+
const chunks = [];
|
|
17
|
+
let size = 0;
|
|
18
|
+
req.on("data", (chunk) => {
|
|
19
|
+
size += chunk.length;
|
|
20
|
+
if (size <= MAX_BODY) chunks.push(chunk);
|
|
21
|
+
});
|
|
22
|
+
req.on("end", () => resolve(size > MAX_BODY ? undefined : Buffer.concat(chunks).toString("utf8")));
|
|
23
|
+
req.on("error", () => resolve(undefined));
|
|
24
|
+
req.on("aborted", () => resolve(undefined));
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const decoded = (text) => {
|
|
29
|
+
try {
|
|
30
|
+
return decodeURIComponent(text);
|
|
31
|
+
} catch {
|
|
32
|
+
return text;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** `{id, secret}` of an `Authorization: Basic` header, or `undefined`. */
|
|
37
|
+
function basicCredentials(header) {
|
|
38
|
+
if (header === undefined || !/^basic /i.test(header)) return undefined;
|
|
39
|
+
const pair = Buffer.from(header.slice(6).trim(), "base64").toString("utf8");
|
|
40
|
+
const colon = pair.indexOf(":");
|
|
41
|
+
if (colon < 0) return undefined;
|
|
42
|
+
return { id: decoded(pair.slice(0, colon)), secret: decoded(pair.slice(colon + 1)) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const isLocalHttp = (text) => {
|
|
46
|
+
try {
|
|
47
|
+
const url = new URL(text);
|
|
48
|
+
return url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "localhost");
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The sign-in server: `{handle(req, res, next)}` for `--signin`, `--expires`, `--client` and `--secret`.
|
|
56
|
+
* Everything is kept in memory.
|
|
57
|
+
*/
|
|
58
|
+
export function createSignin({ expires, client, secret }) {
|
|
59
|
+
const clients = new Map();
|
|
60
|
+
const codes = new Map();
|
|
61
|
+
const accessTokens = new Map();
|
|
62
|
+
const refreshTokens = new Map();
|
|
63
|
+
const counts = { registrations: 0, authorizations: 0, tokens: 0, refreshes: 0, refused: 0 };
|
|
64
|
+
|
|
65
|
+
const known = (id) => (client !== undefined ? id === client : clients.has(id));
|
|
66
|
+
|
|
67
|
+
function issue(client_id) {
|
|
68
|
+
const access_token = drawn("practice-at-");
|
|
69
|
+
const refresh_token = drawn("practice-rt-");
|
|
70
|
+
accessTokens.set(access_token, { client_id, expiresAt: Date.now() + expires * 1000, refresh_token });
|
|
71
|
+
refreshTokens.set(refresh_token, { client_id, access_token });
|
|
72
|
+
return { access_token, token_type: "Bearer", expires_in: expires, refresh_token };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** True when the `Authorization` header is `Bearer` and an access token that is good. */
|
|
76
|
+
function mcpAllowed(header) {
|
|
77
|
+
if (typeof header !== "string" || !header.startsWith("Bearer ")) return false;
|
|
78
|
+
const entry = accessTokens.get(header.slice(7));
|
|
79
|
+
if (entry === undefined) return false;
|
|
80
|
+
if (Date.now() >= entry.expiresAt) {
|
|
81
|
+
accessTokens.delete(header.slice(7));
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function documents(origin, path) {
|
|
88
|
+
if (path === "/.well-known/oauth-protected-resource/mcp" || path === "/.well-known/oauth-protected-resource") {
|
|
89
|
+
return { resource: `${origin}/mcp`, authorization_servers: [origin] };
|
|
90
|
+
}
|
|
91
|
+
if (path === "/.well-known/oauth-authorization-server") {
|
|
92
|
+
return {
|
|
93
|
+
issuer: origin,
|
|
94
|
+
authorization_endpoint: `${origin}/authorize`,
|
|
95
|
+
token_endpoint: `${origin}/token`,
|
|
96
|
+
...(client === undefined ? { registration_endpoint: `${origin}/register` } : {}),
|
|
97
|
+
response_types_supported: ["code"],
|
|
98
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
99
|
+
code_challenge_methods_supported: ["S256"],
|
|
100
|
+
token_endpoint_auth_methods_supported: secret === undefined ? ["none"] : ["client_secret_basic", "client_secret_post"],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function register(req, res) {
|
|
107
|
+
const text = await readBody(req);
|
|
108
|
+
let body;
|
|
109
|
+
try {
|
|
110
|
+
body = JSON.parse(text);
|
|
111
|
+
} catch {
|
|
112
|
+
body = undefined;
|
|
113
|
+
}
|
|
114
|
+
const uris = body?.redirect_uris;
|
|
115
|
+
if (
|
|
116
|
+
body === null ||
|
|
117
|
+
typeof body !== "object" ||
|
|
118
|
+
Array.isArray(body) ||
|
|
119
|
+
!Array.isArray(uris) ||
|
|
120
|
+
uris.length === 0 ||
|
|
121
|
+
!uris.every((u) => typeof u === "string")
|
|
122
|
+
) {
|
|
123
|
+
send(res, 400, { error: "invalid_client_metadata" });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const client_id = `practice-client-${clients.size + 1}`;
|
|
127
|
+
clients.set(client_id, { redirect_uris: uris });
|
|
128
|
+
counts.registrations++;
|
|
129
|
+
const { client_secret: _dropped, ...held } = body;
|
|
130
|
+
send(res, 201, { ...held, client_id });
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function authorize(query, res) {
|
|
134
|
+
const get = (key) => query.get(key) ?? "";
|
|
135
|
+
const client_id = get("client_id");
|
|
136
|
+
const redirect_uri = get("redirect_uri");
|
|
137
|
+
const code_challenge = get("code_challenge");
|
|
138
|
+
let target;
|
|
139
|
+
try {
|
|
140
|
+
target = new URL(redirect_uri);
|
|
141
|
+
} catch {
|
|
142
|
+
target = undefined;
|
|
143
|
+
}
|
|
144
|
+
const addressOk =
|
|
145
|
+
target !== undefined &&
|
|
146
|
+
(client !== undefined ? isLocalHttp(redirect_uri) : clients.get(client_id)?.redirect_uris.includes(redirect_uri));
|
|
147
|
+
if (
|
|
148
|
+
get("response_type") !== "code" ||
|
|
149
|
+
!known(client_id) ||
|
|
150
|
+
!addressOk ||
|
|
151
|
+
code_challenge === "" ||
|
|
152
|
+
get("code_challenge_method") !== "S256"
|
|
153
|
+
) {
|
|
154
|
+
send(res, 400, { error: "invalid_request" });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const code = drawn("practice-code-");
|
|
158
|
+
codes.set(code, { client_id, redirect_uri, code_challenge });
|
|
159
|
+
target.searchParams.append("code", code);
|
|
160
|
+
if (query.has("state")) target.searchParams.append("state", query.get("state"));
|
|
161
|
+
counts.authorizations++;
|
|
162
|
+
res.writeHead(302, { Location: target.toString(), "Cache-Control": "no-store" });
|
|
163
|
+
res.end();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function tokenEndpoint(req, res) {
|
|
167
|
+
const text = await readBody(req);
|
|
168
|
+
const isForm = /^application\/x-www-form-urlencoded\s*(;|$)/i.test(req.headers["content-type"] ?? "");
|
|
169
|
+
const body = new URLSearchParams(isForm && text !== undefined ? text : "");
|
|
170
|
+
const basic = basicCredentials(req.headers.authorization);
|
|
171
|
+
const client_id = basic?.id ?? body.get("client_id") ?? "";
|
|
172
|
+
if (secret !== undefined) {
|
|
173
|
+
const given = basic !== undefined ? basic.secret : body.get("client_secret");
|
|
174
|
+
if (given !== secret) {
|
|
175
|
+
send(res, 401, { error: "invalid_client" });
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const grant = body.get("grant_type");
|
|
180
|
+
if (grant === "authorization_code") {
|
|
181
|
+
const code = body.get("code") ?? "";
|
|
182
|
+
const entry = codes.get(code);
|
|
183
|
+
const verifier = body.get("code_verifier");
|
|
184
|
+
const good =
|
|
185
|
+
entry !== undefined &&
|
|
186
|
+
entry.client_id === client_id &&
|
|
187
|
+
entry.redirect_uri === body.get("redirect_uri") &&
|
|
188
|
+
verifier !== null &&
|
|
189
|
+
createHash("sha256").update(verifier).digest("base64url") === entry.code_challenge;
|
|
190
|
+
if (entry !== undefined) codes.delete(code);
|
|
191
|
+
if (!good) {
|
|
192
|
+
send(res, 400, { error: "invalid_grant" });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
counts.tokens++;
|
|
196
|
+
send(res, 200, issue(client_id));
|
|
197
|
+
} else if (grant === "refresh_token") {
|
|
198
|
+
const old = body.get("refresh_token") ?? "";
|
|
199
|
+
const entry = refreshTokens.get(old);
|
|
200
|
+
if (entry === undefined || entry.client_id !== client_id) {
|
|
201
|
+
send(res, 400, { error: "invalid_grant" });
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
refreshTokens.delete(old);
|
|
205
|
+
accessTokens.delete(entry.access_token);
|
|
206
|
+
counts.refreshes++;
|
|
207
|
+
send(res, 200, issue(client_id));
|
|
208
|
+
} else {
|
|
209
|
+
send(res, 400, { error: "unsupported_grant_type" });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Answers the requests of points 1 to 7 and 9; `next()` is called for `/mcp`, after the sign-in check of point 8. */
|
|
214
|
+
async function handle(req, res, next) {
|
|
215
|
+
const [path, ...rest] = (req.url ?? "").split("?");
|
|
216
|
+
const query = new URLSearchParams(rest.join("?"));
|
|
217
|
+
const origin = `http://127.0.0.1:${req.socket.localPort}`;
|
|
218
|
+
const { method } = req;
|
|
219
|
+
const document = method === "GET" ? documents(origin, path) : undefined;
|
|
220
|
+
if (document !== undefined) return send(res, 200, document);
|
|
221
|
+
if (path === "/register" && method === "POST" && client === undefined) return register(req, res);
|
|
222
|
+
if (path === "/authorize" && method === "GET") return authorize(query, res);
|
|
223
|
+
if (path === "/token" && method === "POST") return tokenEndpoint(req, res);
|
|
224
|
+
if (path === "/forget" && method === "POST") {
|
|
225
|
+
codes.clear();
|
|
226
|
+
accessTokens.clear();
|
|
227
|
+
refreshTokens.clear();
|
|
228
|
+
return send(res, 204);
|
|
229
|
+
}
|
|
230
|
+
if (path === "/seen" && method === "GET") return send(res, 200, counts);
|
|
231
|
+
if (path === "/mcp") {
|
|
232
|
+
if (mcpAllowed(req.headers.authorization)) return next();
|
|
233
|
+
counts.refused++;
|
|
234
|
+
return send(res, 401, undefined, {
|
|
235
|
+
"WWW-Authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"`,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
return send(res, 404);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return { handle };
|
|
242
|
+
}
|