@biolibs/bionet-agent 0.0.0-stage → 0.1.1

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/lookup.ts ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Looking something up outside the lab: NCBI's databases, through `@biolibs/entrez`.
3
+ *
4
+ * Everything else an adviser has works on what the lab already holds. These two reach out to a
5
+ * public database, which makes them different in kind, so they are kept apart and say so in their
6
+ * own descriptions.
7
+ *
8
+ * Two things follow from reaching outside, and both are decided here rather than left to the agent:
9
+ *
10
+ * - **Nothing of the lab's goes out.** A search term is a few words the agent writes, and it is
11
+ * capped short enough that a sequence cannot be pasted into one. Nothing reads the freezer.
12
+ * - **Nothing comes in by itself.** A record that is fetched is handed back to be read. It becomes a
13
+ * part only if the adviser then says so with `add_part`, which is written in its own name like
14
+ * anything else it writes, and what a record claims is marked on a sequence does not come with it.
15
+ */
16
+ import { efetch, esearch, esummary, settings, HTTPError, URLError } from "@biolibs/entrez";
17
+ import { readSequenceFile } from "@biolibs/bionet-tools";
18
+ import type { AgentTool, ToolInput } from "./tools.js";
19
+
20
+ /** The databases that may be asked. Nothing else is reachable through these tools. */
21
+ export const DATABASES = ["nucleotide", "protein", "gene", "pubmed"] as const;
22
+
23
+ /** One of them. */
24
+ export type Database = (typeof DATABASES)[number];
25
+
26
+ /** The most results one search gives back, and the most it may be asked for. */
27
+ export const MOST_FOUND = 25;
28
+
29
+ /** The longest a search term may be. Short enough that a sequence cannot be put in one. */
30
+ export const LONGEST_TERM = 200;
31
+
32
+ /** The most bases one fetch brings back. Longer records have to be asked for a stretch at a time. */
33
+ export const MOST_FETCHED = 100_000;
34
+
35
+ /** How an adviser reaches NCBI. */
36
+ export interface LookupOptions {
37
+ /**
38
+ * Whether to offer these tools at all. On unless a host says otherwise: they read a public
39
+ * database and send nothing of the lab's.
40
+ */
41
+ outside?: boolean;
42
+ /** What to call this software to NCBI. Never a person's name. */
43
+ tool?: string;
44
+ /**
45
+ * An address NCBI can use to get in touch about heavy use, if the person has given one for that.
46
+ * It is never taken from the lab or from the device: somebody has to pass it in on purpose.
47
+ */
48
+ email?: string | null;
49
+ /** An NCBI API key, which raises how often it may be asked. */
50
+ apiKey?: string | null;
51
+ }
52
+
53
+ const text = (value: unknown, what: string): string => {
54
+ if (typeof value !== "string" || value.trim() === "") throw new Error(`${what} has to be given, as text.`);
55
+ return value.trim();
56
+ };
57
+ const whole = (value: unknown, what: string): number => {
58
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new Error(`${what} has to be a whole number.`);
59
+ return value;
60
+ };
61
+ const database = (value: unknown): Database => {
62
+ const given = text(value, "The database");
63
+ if (!(DATABASES as readonly string[]).includes(given)) throw new Error(`There is no database called ${JSON.stringify(given)} here. There are: ${DATABASES.join(", ")}.`);
64
+ return given as Database;
65
+ };
66
+
67
+ /** What NCBI said went wrong, in words the agent can do something about. */
68
+ const asTrouble = (cause: unknown): Error => {
69
+ if (cause instanceof HTTPError) {
70
+ return new Error(cause.code === 429 ? "NCBI is being asked too often just now. Wait a little and ask again."
71
+ : `NCBI answered ${cause.code}. The database or the identifier may not be one it has.`);
72
+ }
73
+ if (cause instanceof URLError) return new Error("NCBI could not be reached. This device may be offline.");
74
+ return cause instanceof Error ? cause : new Error(String(cause));
75
+ };
76
+
77
+ /** The summaries NCBI returns, which are JSON of a shape that differs by database. */
78
+ interface Summary { [field: string]: unknown }
79
+
80
+ const said = (summary: Summary, field: string): string | null => {
81
+ const value = summary[field];
82
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
83
+ };
84
+
85
+ /** One result, said the same way whichever database it came from. */
86
+ function oneFound(db: Database, uid: string, summary: Summary): Record<string, unknown> {
87
+ const organism = said(summary, "organism")
88
+ ?? (typeof summary["organism"] === "object" && summary["organism"] !== null ? said(summary["organism"] as Summary, "scientificname") : null);
89
+ if (db === "pubmed") {
90
+ const authors = Array.isArray(summary["authors"]) ? (summary["authors"] as Summary[]).map((one) => said(one, "name")).filter((one) => one !== null) : [];
91
+ return { id: uid, title: said(summary, "title"), journal: said(summary, "source"), published: said(summary, "pubdate"),
92
+ authors: authors.slice(0, 6), doi: said(summary, "elocationid"), look_at: `https://pubmed.ncbi.nlm.nih.gov/${uid}/` };
93
+ }
94
+ if (db === "gene") {
95
+ return { id: uid, symbol: said(summary, "name"), description: said(summary, "description"), organism,
96
+ summary: said(summary, "summary"), chromosome: said(summary, "chromosome"), look_at: `https://www.ncbi.nlm.nih.gov/gene/${uid}` };
97
+ }
98
+ const accession = said(summary, "accessionversion") ?? said(summary, "caption") ?? uid;
99
+ return { accession, title: said(summary, "title"), organism, length: typeof summary["slen"] === "number" ? summary["slen"] : null,
100
+ updated: said(summary, "updatedate"), look_at: `https://www.ncbi.nlm.nih.gov/${db}/${accession}` };
101
+ }
102
+
103
+ /**
104
+ * The tools that look something up at NCBI.
105
+ *
106
+ * @param options - Whether to offer them, and what to tell NCBI about who is asking.
107
+ * @returns The tools, or none if a host asked for none.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * import { lookupTools } from "@biolibs/bionet-agent";
112
+ *
113
+ * const outside = lookupTools({ tool: "bionet-adviser" });
114
+ * outside.map((one) => one.name); // ["search_ncbi", "fetch_from_ncbi"]
115
+ * ```
116
+ */
117
+ export function lookupTools(options: LookupOptions = {}): AgentTool[] {
118
+ if (options.outside === false) return [];
119
+ // Said once, before anything is asked. NCBI wants to know what software is calling; it is told
120
+ // the software's name and nothing about the lab or the person at it.
121
+ settings.tool = options.tool ?? "bionet-adviser";
122
+ if (options.email !== undefined) settings.email = options.email;
123
+ if (options.apiKey !== undefined) settings.apiKey = options.apiKey;
124
+
125
+ const dbField: ToolInput["properties"][string] = { type: "string", enum: [...DATABASES], description: "Which database: nucleotide, protein, gene (what a gene is and where), or pubmed (papers)." };
126
+
127
+ return [
128
+ {
129
+ name: "search_ncbi", title: "Search NCBI", readOnly: true,
130
+ description: [
131
+ "Search a public NCBI database by keyword, in Entrez's own syntax, such as `CSN2 AND Bos taurus[orgn]` or `casein AND biosynthesis[title]`.",
132
+ "Use it to find out what is known outside this lab: which genes a protein is made by, what a reference sequence for one is called, what has been published about it.",
133
+ "Gives the accession (or gene or paper), what it is, which organism, and how long it is. To read a sequence itself, use fetch_from_ncbi with the accession.",
134
+ "This reaches the internet. The search term is sent to NCBI, so write it yourself and do not put the lab's own sequences, part names or notes in it; nothing is read from the freezer.",
135
+ ].join(" "),
136
+ input: { type: "object", required: ["database", "term"], additionalProperties: false, properties: {
137
+ database: dbField,
138
+ term: { type: "string", description: `What to search for, at most ${LONGEST_TERM} characters.` },
139
+ limit: { type: "integer", description: `How many to give back, up to ${MOST_FOUND}. 10 if not given.` },
140
+ } },
141
+ run: async (args) => {
142
+ const db = database(args["database"]);
143
+ const term = text(args["term"], "The search term");
144
+ if (term.length > LONGEST_TERM) throw new Error(`A search term is at most ${LONGEST_TERM} characters. This is for searching by keyword; a sequence is not something to put in one.`);
145
+ const limit = Math.max(1, Math.min(MOST_FOUND, args["limit"] === undefined ? 10 : whole(args["limit"], "The limit")));
146
+ try {
147
+ const found = JSON.parse((await esearch(db, term, { retmax: limit, retmode: "json" })).readText()) as { esearchresult?: { count?: string; idlist?: string[] } };
148
+ const ids = found.esearchresult?.idlist ?? [];
149
+ const all = Number(found.esearchresult?.count ?? ids.length);
150
+ if (ids.length === 0) return { database: db, term, found: 0, results: [], note: "Nothing matched. Entrez syntax is strict: try fewer words, or an organism as `Bos taurus[orgn]`." };
151
+ const summaries = JSON.parse((await esummary({ db, id: ids, retmode: "json" })).readText()) as { result?: Record<string, Summary> };
152
+ return {
153
+ database: db, term, found: all, showing: ids.length,
154
+ results: ids.map((uid) => oneFound(db, uid, summaries.result?.[uid] ?? {})),
155
+ ...(all > ids.length ? { note: `${all.toLocaleString("en-US")} matched in all; the first ${ids.length} are here. Narrow the term rather than asking for more.` } : {}),
156
+ };
157
+ } catch (cause) { throw asTrouble(cause); }
158
+ },
159
+ },
160
+ {
161
+ name: "fetch_from_ncbi", title: "Read a sequence from NCBI", readOnly: true,
162
+ description: [
163
+ "Fetch one nucleotide or protein record from NCBI by accession, and read it: what it is called, how long, which organism, and what the record says is marked on it.",
164
+ "Nothing is added to the lab by this. To keep a sequence, read it first and then use add_part, putting the accession in the name so that whoever sees it later knows where it came from.",
165
+ `A record longer than ${MOST_FETCHED.toLocaleString("en-US")} bases has to be asked for a stretch at a time with from and to; a whole chromosome is not something to read in one go.`,
166
+ "What a record says about itself was written by whoever deposited it. It is what someone claims, not something this lab has checked.",
167
+ "This reaches the internet. Only the accession is sent.",
168
+ ].join(" "),
169
+ input: { type: "object", required: ["database", "accession"], additionalProperties: false, properties: {
170
+ database: { type: "string", enum: ["nucleotide", "protein"], description: "Which database the accession is in." },
171
+ accession: { type: "string", description: "The accession, such as NM_181008.2." },
172
+ from: { type: "integer", description: "The first base or residue wanted, counting from 1. The start if not given." },
173
+ to: { type: "integer", description: "The last one wanted. The end if not given." },
174
+ } },
175
+ run: async (args) => {
176
+ const db = database(args["database"]);
177
+ if (db !== "nucleotide" && db !== "protein") throw new Error("A sequence is fetched from nucleotide or protein. Use search_ncbi for genes and papers.");
178
+ const accession = text(args["accession"], "The accession");
179
+ if (!/^[A-Za-z0-9_.]{3,40}$/.test(accession)) throw new Error("That is not an accession. One looks like NM_181008.2 or P02666.");
180
+ const from = args["from"] === undefined ? undefined : Math.max(1, whole(args["from"], "`from`"));
181
+ const to = args["to"] === undefined ? undefined : Math.max(1, whole(args["to"], "`to`"));
182
+ let record;
183
+ try {
184
+ const handle = await efetch(db, {
185
+ id: accession, rettype: db === "protein" ? "gp" : "gb", retmode: "text",
186
+ ...(from === undefined ? {} : { seq_start: from }), ...(to === undefined ? {} : { seq_stop: to }),
187
+ });
188
+ const body = handle.readText();
189
+ if (body.trim() === "") throw new Error(`NCBI has nothing under ${accession} in ${db}.`);
190
+ record = readSequenceFile(`${accession}.gb`, new TextEncoder().encode(body));
191
+ } catch (cause) { throw asTrouble(cause); }
192
+ if (record.sequence.length > MOST_FETCHED) {
193
+ throw new Error(`${accession} is ${record.sequence.length.toLocaleString("en-US")} long, which is more than one fetch brings back. Ask for a stretch of it with from and to.`);
194
+ }
195
+ return {
196
+ accession, database: db, name: record.name, description: record.description,
197
+ length: record.sequence.length, circular: record.circular,
198
+ ...(from === undefined && to === undefined ? {} : { stretch: { from: from ?? 1, to: to ?? record.sequence.length } }),
199
+ // As people count them, like everywhere else an adviser is told where something lies.
200
+ marked: record.features.map((one) => ({ label: one.label, type: one.type, strand: one.strand === 1 ? "forward" : one.strand === -1 ? "reverse" : "either",
201
+ lies: one.parts.map((part) => ({ from: part.start + 1, to: part.end })) })),
202
+ sequence: record.sequence,
203
+ from_outside: "This came from NCBI and says what whoever deposited it says. Nothing has been added to the lab.",
204
+ };
205
+ },
206
+ },
207
+ ];
208
+ }
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
+ }