@biolibs/bionet-agent 0.0.0-stage → 0.1.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/src/serve.ts ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The adviser's tools, served to an agent over the Model Context Protocol.
3
+ *
4
+ * It is the smallest server that speaks the protocol's HTTP transport honestly: an agent posts a
5
+ * request and gets a JSON answer. There are no sessions and nothing is streamed, because nothing
6
+ * here takes long or happens unasked.
7
+ *
8
+ * It is a way into somebody's lab, so it is shut by default in every way it can be:
9
+ *
10
+ * - it listens on this machine only, never on the network;
11
+ * - every request has to carry the token, compared in constant time;
12
+ * - a request that says it comes from a web page is refused, and so is one addressed to any name
13
+ * but this machine's, which is how a page in a browser would otherwise reach a server like this;
14
+ * - and behind it the tools themselves can only read, work things out and propose.
15
+ */
16
+ import { randomBytes, timingSafeEqual } from "node:crypto";
17
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
18
+ import type { AddressInfo } from "node:net";
19
+ import { AGENT_INSTRUCTIONS, type AgentTool } from "./tools.js";
20
+
21
+ /** The versions of the protocol this speaks, newest first. */
22
+ export const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"] as const;
23
+
24
+ /** The most one request may be, in bytes. A sequence is the largest thing an agent sends. */
25
+ const MOST_BYTES = 2_000_000;
26
+
27
+ /** A server that is up. */
28
+ export interface AgentServer {
29
+ /** Where an agent connects: `http://127.0.0.1:<port>/mcp`. */
30
+ url: string;
31
+ /** The port it took. */
32
+ port: number;
33
+ /** Stop it. */
34
+ close: () => Promise<void>;
35
+ }
36
+
37
+ /** @returns A new token: 32 random bytes, in base64url. Whoever has it can reach the adviser's tools. */
38
+ export const newAgentToken = (): string => randomBytes(32).toString("base64url");
39
+
40
+ const sameText = (a: string, b: string): boolean => {
41
+ const [left, right] = [Buffer.from(a), Buffer.from(b)];
42
+ return left.length === right.length && timingSafeEqual(left, right);
43
+ };
44
+
45
+ /** One JSON-RPC answer, or `null` for a message that wants none. */
46
+ type Answer = Record<string, unknown> | null;
47
+
48
+ /**
49
+ * Answer one message of the protocol.
50
+ *
51
+ * @param message - What arrived.
52
+ * @param tools - The tools on offer.
53
+ * @param about - What to call this server and its version.
54
+ * @returns The answer, or `null` if the message was a notification.
55
+ */
56
+ export async function answerAgent(message: unknown, tools: readonly AgentTool[], about: { name: string; version: string }): Promise<Answer> {
57
+ const asked = message as { jsonrpc?: unknown; id?: unknown; method?: unknown; params?: Record<string, unknown> } | null;
58
+ const id = asked !== null && typeof asked === "object" && (typeof asked.id === "string" || typeof asked.id === "number") ? asked.id : null;
59
+ const fail = (code: number, says: string): Answer => ({ jsonrpc: "2.0", id, error: { code, message: says } });
60
+ if (asked === null || typeof asked !== "object" || asked.jsonrpc !== "2.0" || typeof asked.method !== "string") return fail(-32600, "That is not a request.");
61
+ // A notification is told, not asked: it has no ID and gets no answer.
62
+ if (asked.id === undefined) return null;
63
+ const done = (result: Record<string, unknown>): Answer => ({ jsonrpc: "2.0", id, result });
64
+
65
+ switch (asked.method) {
66
+ case "initialize": {
67
+ const wanted = asked.params?.["protocolVersion"];
68
+ const version = (PROTOCOL_VERSIONS as readonly unknown[]).includes(wanted) ? (wanted as string) : PROTOCOL_VERSIONS[0];
69
+ return done({ protocolVersion: version, capabilities: { tools: { listChanged: false } }, serverInfo: { name: about.name, version: about.version }, instructions: AGENT_INSTRUCTIONS });
70
+ }
71
+ case "ping": return done({});
72
+ case "tools/list":
73
+ return done({ tools: tools.map((tool) => ({
74
+ name: tool.name, title: tool.title, description: tool.description, inputSchema: tool.input,
75
+ annotations: { title: tool.title, readOnlyHint: tool.readOnly, destructiveHint: false, idempotentHint: tool.readOnly, openWorldHint: false },
76
+ })) });
77
+ case "tools/call": {
78
+ const tool = tools.find((one) => one.name === asked.params?.["name"]);
79
+ if (tool === undefined) return fail(-32602, `There is no tool called ${JSON.stringify(asked.params?.["name"] ?? null)}.`);
80
+ const args = asked.params?.["arguments"];
81
+ if (!(args === undefined || (typeof args === "object" && args !== null && !Array.isArray(args)))) return fail(-32602, "A tool's arguments are given by name.");
82
+ const given = (args ?? {}) as Record<string, unknown>;
83
+ // Something the tool was not told to expect is refused, not ignored: an agent that sends it
84
+ // meant something by it, and going on without it would do other than it asked.
85
+ const stray = Object.keys(given).find((name) => !(name in tool.input.properties));
86
+ const missing = (tool.input.required ?? []).find((name) => given[name] === undefined);
87
+ try {
88
+ if (stray !== undefined) throw new Error(`${tool.name} takes nothing called ${JSON.stringify(stray)}. It takes: ${Object.keys(tool.input.properties).join(", ") || "nothing"}.`);
89
+ if (missing !== undefined) throw new Error(`${tool.name} needs ${JSON.stringify(missing)}.`);
90
+ return done({ content: [{ type: "text", text: JSON.stringify(await tool.run(given), null, 1) }] });
91
+ } catch (cause) {
92
+ // A tool that could not do what was asked says why to the agent, which can then do something about it.
93
+ return done({ content: [{ type: "text", text: cause instanceof Error ? cause.message : String(cause) }], isError: true });
94
+ }
95
+ }
96
+ default: return fail(-32601, `This server does not do ${JSON.stringify(asked.method)}.`);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Serve the adviser's tools on this machine.
102
+ *
103
+ * @param options - `tools` are the tools; `token` is what every request has to carry, as a bearer
104
+ * token; `port` is the port to take, or 0 for any that is free; `name` and `version` are what the
105
+ * server calls itself.
106
+ * @returns Where it is listening, and a way to stop it.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { agentTools, newAgentToken, serveAgent } from "@biolibs/bionet-agent";
111
+ *
112
+ * const token = newAgentToken();
113
+ * const server = await serveAgent({ tools: agentTools(lab), token });
114
+ * server.url; // http://127.0.0.1:53124/mcp — give this and the token to the agent
115
+ * ```
116
+ */
117
+ export async function serveAgent(options: { tools: readonly AgentTool[]; token: string; port?: number; name?: string; version?: string }): Promise<AgentServer> {
118
+ if (options.token.length < 32) throw new Error("The token is too short to keep anybody out.");
119
+ const about = { name: options.name ?? "bionet-adviser", version: options.version ?? "0.1.0" };
120
+ let port = 0;
121
+ const say = (response: ServerResponse, status: number, body: unknown, more: Record<string, string> = {}): void => {
122
+ const text = body === null ? "" : JSON.stringify(body);
123
+ response.writeHead(status, { ...(body === null ? {} : { "content-type": "application/json" }), "cache-control": "no-store", ...more });
124
+ response.end(text);
125
+ };
126
+ const read = (request: IncomingMessage): Promise<string | null> => new Promise((resolve) => {
127
+ const chunks: Buffer[] = [];
128
+ let size = 0;
129
+ request.on("data", (chunk: Buffer) => {
130
+ size += chunk.length;
131
+ // Past the limit the rest is let go by without being kept, so that whoever sent it can be
132
+ // told it was too much instead of having the line cut under them.
133
+ if (size <= MOST_BYTES) chunks.push(chunk); else chunks.length = 0;
134
+ });
135
+ request.on("end", () => resolve(size > MOST_BYTES ? null : Buffer.concat(chunks).toString("utf8")));
136
+ request.on("error", () => resolve(null));
137
+ });
138
+
139
+ const server: Server = createServer((request, response) => {
140
+ void (async () => {
141
+ // A browser says where a request comes from and which name it was sent to. Nothing that is
142
+ // meant to use this is a web page, and nothing that is meant to use it calls it by another name.
143
+ if (request.headers.origin !== undefined) return say(response, 403, { error: "This is not for web pages." });
144
+ const host = request.headers.host ?? "";
145
+ if (host !== `127.0.0.1:${port}` && host !== `localhost:${port}`) return say(response, 403, { error: "This answers only to this machine's own name." });
146
+ if (new URL(request.url ?? "/", "http://x").pathname !== "/mcp") return say(response, 404, { error: "There is nothing here." });
147
+ const given = /^Bearer (.+)$/.exec(request.headers.authorization ?? "")?.[1] ?? "";
148
+ if (!sameText(given, options.token)) return say(response, 401, { error: "That is not this adviser's token." }, { "www-authenticate": "Bearer" });
149
+ // Nothing is sent unasked, so there is no stream to open and no session to end.
150
+ if (request.method !== "POST") return say(response, 405, { error: "Ask by POST." }, { allow: "POST" });
151
+
152
+ const body = await read(request);
153
+ if (body === null) return say(response, 413, { error: "That is more than one request may be." });
154
+ let message: unknown;
155
+ try { message = JSON.parse(body); } catch { return say(response, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "That is not JSON." } }); }
156
+ if (Array.isArray(message)) {
157
+ const answers = (await Promise.all(message.map((one) => answerAgent(one, options.tools, about)))).filter((one) => one !== null);
158
+ return answers.length === 0 ? say(response, 202, null) : say(response, 200, answers);
159
+ }
160
+ const answer = await answerAgent(message, options.tools, about);
161
+ return answer === null ? say(response, 202, null) : say(response, 200, answer);
162
+ })().catch(() => { if (!response.headersSent) say(response, 500, { error: "Something went wrong here." }); });
163
+ });
164
+
165
+ await new Promise<void>((resolve, reject) => {
166
+ server.once("error", reject);
167
+ // This machine only: never every address the machine has.
168
+ server.listen(options.port ?? 0, "127.0.0.1", resolve);
169
+ });
170
+ port = (server.address() as AddressInfo).port;
171
+ return {
172
+ url: `http://127.0.0.1:${port}/mcp`, port,
173
+ close: () => new Promise<void>((resolve) => { server.close(() => resolve()); server.closeAllConnections(); }),
174
+ };
175
+ }