toolpal 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/dist/mcp.js ADDED
@@ -0,0 +1,648 @@
1
+ import { inputRequired, inputResponse, McpServer, } from "@modelcontextprotocol/server";
2
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
3
+ import { canonicalJson, describePermissions, FILE_KEYWORD, fileFields, isValidToolName, mcpToolName, normalizePermissions, permissionsAdded, sha256Hex, splitToolName, visibilitySchema, } from "@toolpal/manifest";
4
+ import { ToolpalError, } from "@toolpal/runtime";
5
+ export const MCP_SERVER_VERSION = "0.1.1";
6
+ /**
7
+ * Exposes a manifest's JSON Schema to the MCP SDK as a Standard Schema. Real
8
+ * validation happens inside `Toolpal.execute`, so `validate` passes values through.
9
+ */
10
+ function jsonSchema(schema) {
11
+ return {
12
+ "~standard": {
13
+ version: 1,
14
+ vendor: "toolpal",
15
+ validate: (value) => ({ value: value }),
16
+ jsonSchema: { input: () => schema, output: () => schema },
17
+ },
18
+ };
19
+ }
20
+ async function entryFor(tp, ref, fetch = false) {
21
+ const info = await tp.describe(ref, { registryMetadata: false, fetch });
22
+ return { ref, mcpName: mcpToolName(info.name), info, tp };
23
+ }
24
+ /**
25
+ * The tools `toolpal mcp` serves: everything the signed-in user published or
26
+ * added to their account, synced from the registry. `account` comes from `Toolpal.forAccount()`,
27
+ * so the directory the server starts in makes no difference.
28
+ */
29
+ export async function accountMcpTools(account) {
30
+ const sync = await account.syncAccount();
31
+ const updates = new Map(sync.updates.map((update) => [update.name, update]));
32
+ const tools = [];
33
+ for (const name of sync.tools) {
34
+ tools.push({ ...(await entryFor(account, name)), update: updates.get(name) });
35
+ }
36
+ return { tools, sync };
37
+ }
38
+ /**
39
+ * Exactly the tools named (registry refs or paths to built tools), downloading them if
40
+ * needed: naming them on the command line is what adds them, for this server only.
41
+ */
42
+ export async function explicitMcpTools(tp, refs) {
43
+ const byName = new Map();
44
+ for (const ref of refs) {
45
+ const entry = await entryFor(tp, ref, true);
46
+ const taken = byName.get(entry.mcpName);
47
+ if (taken) {
48
+ throw new ToolpalError("INVALID_REF", `${taken.ref} and ${ref} are both ${entry.info.name}; name each tool once`);
49
+ }
50
+ byName.set(entry.mcpName, entry);
51
+ }
52
+ return [...byName.values()];
53
+ }
54
+ function newServer() {
55
+ return new McpServer({ name: "toolpal", version: MCP_SERVER_VERSION }, { capabilities: { tools: {} } });
56
+ }
57
+ function ok(result) {
58
+ return { content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
59
+ }
60
+ function failed(err) {
61
+ const code = err instanceof ToolpalError ? err.code : "TOOL_ERROR";
62
+ return { content: [{ type: "text", text: `${code}: ${err.message}` }], isError: true };
63
+ }
64
+ /**
65
+ * What a model reads about a tool. While another version is on the registry it
66
+ * says so, because the model is the one the user will ask about it.
67
+ */
68
+ function describeEntry({ info, update }) {
69
+ if (!update)
70
+ return info.description;
71
+ const note = [
72
+ `[toolpal] This is version ${info.version}${update.yanked ? ", which its authors withdrew" : ""}.`,
73
+ `Version ${update.newest} is on the registry and is not installed.`,
74
+ ...(update.addedPermissions.length > 0
75
+ ? [`It adds permissions: ${update.addedPermissions.join(", ")}.`]
76
+ : []),
77
+ `Call ${UPDATE_TOOL} only if the user asks to update it.`,
78
+ ];
79
+ return `${info.description}\n\n${note.join(" ")}`;
80
+ }
81
+ /**
82
+ * A schema as a model should read it: each file field is a plain string, said to
83
+ * be a path on the machine the server runs on.
84
+ */
85
+ function describeFiles(schema, note) {
86
+ const fields = fileFields(schema);
87
+ if (fields.length === 0)
88
+ return schema;
89
+ const properties = { ...schema.properties };
90
+ const noted = (node, text) => ({
91
+ ...node,
92
+ description: typeof node.description === "string" ? `${node.description} ${text}` : text,
93
+ });
94
+ for (const { name, many } of fields) {
95
+ const property = properties[name];
96
+ const { [FILE_KEYWORD]: _marker, ...path } = (many ? property.items : property);
97
+ properties[name] = many
98
+ ? noted({ ...property, items: path }, `Each item: ${note}`)
99
+ : noted(path, note);
100
+ }
101
+ return { ...schema, properties };
102
+ }
103
+ function registerEntry(server, entry) {
104
+ const { ref, mcpName, info, tp } = entry;
105
+ return server.registerTool(mcpName, {
106
+ title: `${info.name}@${info.version}`,
107
+ description: describeEntry(entry),
108
+ inputSchema: jsonSchema(describeFiles(info.inputSchema, "Absolute path of an existing file on this machine.")),
109
+ outputSchema: jsonSchema(describeFiles(info.outputSchema, "Absolute path of the file that was written.")),
110
+ annotations: { openWorldHint: info.permissions.net },
111
+ }, async (args) => {
112
+ try {
113
+ return ok((await tp.execute({ tool: ref, input: args })));
114
+ }
115
+ catch (err) {
116
+ return failed(err);
117
+ }
118
+ });
119
+ }
120
+ export function buildMcpServer(tools) {
121
+ const server = newServer();
122
+ for (const entry of tools)
123
+ registerEntry(server, entry);
124
+ return server;
125
+ }
126
+ /** `toolpal mcp <tools…>`: serve exactly the collected tools over stdio. */
127
+ export function serveMcpStdio(tools) {
128
+ // The factory only runs once a client connects, where a failure would reach the
129
+ // client as an opaque internal error; building once here fails at startup instead.
130
+ buildMcpServer(tools);
131
+ return serveStdio(() => buildMcpServer(tools));
132
+ }
133
+ // Tool names are `scope__name`, and neither part can hold an underscore, so these never clash.
134
+ export const SEARCH_TOOL = "search_tools";
135
+ export const INSTALL_TOOL = "install_tool";
136
+ export const UPDATE_TOOL = "update_tool";
137
+ export const PUBLISH_TOOL = "publish_tool";
138
+ const MAX_SEARCH_RESULTS = 20;
139
+ const searchInput = {
140
+ type: "object",
141
+ required: ["query"],
142
+ properties: {
143
+ query: {
144
+ type: "string",
145
+ minLength: 1,
146
+ maxLength: 200,
147
+ description: "Words describing what the tool should do, for example: weather forecast",
148
+ },
149
+ limit: { type: "integer", minimum: 1, maximum: MAX_SEARCH_RESULTS, default: 10 },
150
+ },
151
+ };
152
+ const searchOutput = {
153
+ type: "object",
154
+ required: ["results"],
155
+ properties: {
156
+ results: {
157
+ type: "array",
158
+ items: {
159
+ type: "object",
160
+ required: ["name", "description", "version", "permissions", "installed"],
161
+ properties: {
162
+ name: { type: "string" },
163
+ description: { type: "string" },
164
+ version: { type: "string", description: "The newest version" },
165
+ permissions: { type: "array", items: { type: "string" } },
166
+ flags: { type: "array", items: { type: "string" } },
167
+ verified: { type: "boolean" },
168
+ addedBy: { type: "number", description: "How many Toolpal accounts added it" },
169
+ downloads: { type: "number" },
170
+ installed: { type: "boolean" },
171
+ installedVersion: {
172
+ type: "string",
173
+ description: "The version installed here, which can be older than `version`",
174
+ },
175
+ },
176
+ },
177
+ },
178
+ },
179
+ };
180
+ const installInput = {
181
+ type: "object",
182
+ required: ["tool"],
183
+ properties: {
184
+ tool: {
185
+ type: "string",
186
+ description: "The tool's name as search_tools returned it: @scope/name",
187
+ },
188
+ },
189
+ };
190
+ const installOutput = {
191
+ type: "object",
192
+ required: ["installed", "tool", "permissions"],
193
+ properties: {
194
+ installed: { type: "string", description: "name@version" },
195
+ tool: { type: "string", description: "The name to call it by on this server" },
196
+ permissions: { type: "array", items: { type: "string" } },
197
+ flags: { type: "array", items: { type: "string" } },
198
+ },
199
+ };
200
+ const updateInput = {
201
+ type: "object",
202
+ required: ["tool"],
203
+ properties: {
204
+ tool: { type: "string", description: "The installed tool's name: @scope/name" },
205
+ },
206
+ };
207
+ const updateOutput = {
208
+ type: "object",
209
+ required: ["installed", "tool", "permissions"],
210
+ properties: {
211
+ installed: { type: "string", description: "name@version, the version installed now" },
212
+ from: {
213
+ type: "string",
214
+ description: "The version it replaced. Left out when the newest was already installed.",
215
+ },
216
+ tool: { type: "string", description: "The name to call it by on this server" },
217
+ permissions: { type: "array", items: { type: "string" } },
218
+ flags: { type: "array", items: { type: "string" } },
219
+ },
220
+ };
221
+ const publishInput = {
222
+ type: "object",
223
+ required: ["name", "code"],
224
+ properties: {
225
+ name: {
226
+ type: "string",
227
+ description: "Lowercase letters, digits and dashes, for example: word-count. It is published in the user's own scope.",
228
+ },
229
+ code: {
230
+ type: "string",
231
+ description: "The whole tool: one module whose default export is defineTool({...})",
232
+ },
233
+ visibility: {
234
+ type: "string",
235
+ enum: ["private", "public"],
236
+ description: "For a new tool: private (the default) or public. Leave it out when publishing a new version.",
237
+ },
238
+ },
239
+ };
240
+ const publishOutput = {
241
+ type: "object",
242
+ required: ["published", "visibility", "permissions"],
243
+ properties: {
244
+ published: { type: "string", description: "name@version" },
245
+ visibility: { type: "string", enum: ["private", "public"] },
246
+ tool: { type: "string", description: "The name to call it by on this server" },
247
+ unavailable: {
248
+ type: "string",
249
+ description: "Given instead of `tool` when it was published but could not be loaded here: the reason. Publishing it again does not help.",
250
+ },
251
+ permissions: { type: "array", items: { type: "string" } },
252
+ flags: { type: "array", items: { type: "string" } },
253
+ },
254
+ };
255
+ const PUBLISH_DESCRIPTION = `Create a Toolpal tool from source code and publish it to the user's account, or publish a new version of one of their tools. It can then be called here straight away, and in later sessions.
256
+
257
+ \`code\` is one TypeScript or JavaScript module whose default export is defineTool(...):
258
+
259
+ import { defineTool, Type } from "@toolpal/tool";
260
+
261
+ export default defineTool({
262
+ description: "Counts the words in a piece of text.",
263
+ input: Type.Object({ text: Type.String({ maxLength: 100000 }) }),
264
+ output: Type.Object({ words: Type.Integer() }),
265
+ handler: async ({ text }, ctx) => ({ words: text.split(/\\s+/).filter(Boolean).length }),
266
+ });
267
+
268
+ Rules:
269
+ - One tool is one function. Its description is what a model reads to decide when to call it, so say plainly what it does.
270
+ - input and output are Type.Object(...) schemas, built with Type.String, Type.Number, Type.Integer, Type.Boolean, Type.Array, Type.Optional, Type.Union and Type.Literal. The output is checked against its schema.
271
+ - Import only from "@toolpal/tool" and Node's built-in modules. npm packages and other files are not available here; a tool that needs them is built with the Toolpal CLI.
272
+ - For a file, use FilePath() from "@toolpal/tool" as a top-level field: input: Type.Object({ file: FilePath() }). In the handler an input file is the path of a private copy, to read with node:fs. To return one, write it inside ctx.outputDir and return its path in a FilePath() field of the output. The tool cannot read or write any other path.
273
+ - Use fetch for HTTP and process.env.NAME for a secret. What the tool may access (network, the env vars it names, temporary files) is derived from the code and returned in the result. Child processes, workers and native addons are never allowed.
274
+ - ctx.log(level, message) writes a log line.
275
+
276
+ A new tool is private, meaning only the user can see or run it, unless visibility is "public". A public tool is visible to everyone and a published version cannot be changed. Tell the user what the tool does and what it may access before calling this. Where their client can ask, the user is asked to confirm.`;
277
+ /** Key of the confirmation among a request's input requests. */
278
+ const CONFIRM = "confirm";
279
+ /**
280
+ * Asks the user to confirm through their client. The model supplies a tool call's
281
+ * arguments but not this answer, so it cannot give it on the user's behalf.
282
+ *
283
+ * Returns the question to hand back, or `undefined` to go ahead: the user accepted
284
+ * exactly what `fingerprint` stands for, or the client has no way to ask, which
285
+ * leaves the decision to the client's own approval of the tool call. A refusal
286
+ * throws.
287
+ */
288
+ function confirmation(server, ctx, ask) {
289
+ if (!server.server.getClientCapabilities()?.elicitation)
290
+ return undefined;
291
+ const answer = inputResponse(ctx.mcpReq.inputResponses, CONFIRM);
292
+ const accepted = answer.kind === "elicit" && answer.action === "accept" && answer.content?.confirm === true;
293
+ if (answer.kind === "elicit" && !accepted)
294
+ throw new ToolpalError("ACCESS_DENIED", ask.declined);
295
+ // Ask, or ask again when what is being confirmed changed while the question was open.
296
+ if (accepted && ctx.mcpReq.requestState() === ask.fingerprint)
297
+ return undefined;
298
+ return inputRequired({
299
+ inputRequests: {
300
+ [CONFIRM]: inputRequired.elicit({
301
+ message: ask.message,
302
+ requestedSchema: {
303
+ type: "object",
304
+ properties: { confirm: { type: "boolean", title: ask.title, description: ask.effect } },
305
+ required: ["confirm"],
306
+ },
307
+ }),
308
+ },
309
+ requestState: ask.fingerprint,
310
+ });
311
+ }
312
+ /** What the user's client shows before anything is installed. */
313
+ function installQuestion(tool) {
314
+ const publisher = `${tool.publisher} (${tool.verified ? "verified" : "unverified"} publisher)`;
315
+ return [
316
+ `Install the Toolpal tool ${tool.name}@${tool.version}, published by ${publisher}?`,
317
+ `What it does, in the publisher's words: ${tool.description.slice(0, 300)}`,
318
+ `What it may access: ${tool.permissionSummary.join("; ")}`,
319
+ ...(tool.flags.length > 0 ? [`Flags from code analysis: ${tool.flags.join(", ")}`] : []),
320
+ "Accepting adds it to your Toolpal account and lets this assistant run it.",
321
+ ].join("\n");
322
+ }
323
+ /** What the user's client shows before an installed tool is moved to another version. */
324
+ function updateQuestion(from, tool, added) {
325
+ const publisher = `${tool.publisher} (${tool.verified ? "verified" : "unverified"} publisher)`;
326
+ return [
327
+ `Update the Toolpal tool ${tool.name} from ${from} to ${tool.version}, published by ${publisher}?`,
328
+ `What it does, in the publisher's words: ${tool.description.slice(0, 300)}`,
329
+ `What it may access: ${tool.permissionSummary.join("; ")}`,
330
+ added.length > 0
331
+ ? `New in this version: ${added.join(", ")}`
332
+ : `That is no more than version ${from} may access.`,
333
+ ...(tool.flags.length > 0 ? [`Flags from code analysis: ${tool.flags.join(", ")}`] : []),
334
+ `Accepting replaces version ${from}: this assistant then runs ${tool.version}.`,
335
+ ].join("\n");
336
+ }
337
+ /** What the user's client shows before anything is published. */
338
+ function publishQuestion(name, tool, to) {
339
+ return [
340
+ to.isNew
341
+ ? `Publish the new Toolpal tool ${name} to your account?`
342
+ : `Publish a new version of your Toolpal tool ${name}?`,
343
+ to.visibility === "private"
344
+ ? "It is private: only you can see, install or run it."
345
+ : "It is PUBLIC: anyone can see, install and run it, and a published version cannot be changed, only withdrawn.",
346
+ `What it does, as this assistant wrote it: ${tool.description.slice(0, 300)}`,
347
+ `What it may access: ${describePermissions(tool.permissions).join("; ")}`,
348
+ ...(tool.flags.length > 0 ? [`Flags from code analysis: ${tool.flags.join(", ")}`] : []),
349
+ `Its source (${to.lines} lines) is in this request's arguments. Accepting publishes it and lets this assistant run it.`,
350
+ ].join("\n");
351
+ }
352
+ /**
353
+ * The server `toolpal mcp` runs: the account's tools, plus `search_tools` and
354
+ * `install_tool` so the model can find a public tool and add it for the user, and
355
+ * with `authoring` also `publish_tool`, so it can write one. Installing adds the
356
+ * tool to the user's account and publishing puts it in their scope, which is what
357
+ * makes either one of their tools; it is then registered here without a restart.
358
+ * `update_tool` moves a tool someone else owns to its newest version, which
359
+ * nothing else here does. All three first ask the user through their client,
360
+ * where the client can do that.
361
+ */
362
+ export function accountMcpServerFactory(account, initial, authoring) {
363
+ let tools = initial;
364
+ const live = [];
365
+ let queue = Promise.resolve();
366
+ /**
367
+ * Re-reads the account from the registry and makes every connected server match
368
+ * it. `change` runs first, so nothing else touches the account's pins meanwhile.
369
+ */
370
+ const refresh = (change) => {
371
+ const run = queue.then(async () => {
372
+ await change?.();
373
+ const next = await accountMcpTools(account);
374
+ tools = next.tools;
375
+ const wanted = new Map(tools.map((entry) => [entry.mcpName, entry]));
376
+ for (const { server, registered } of live) {
377
+ for (const [name, { entry, handle }] of registered) {
378
+ const now = wanted.get(name);
379
+ const same = now?.info.version === entry.info.version && describeEntry(now) === describeEntry(entry);
380
+ if (same)
381
+ continue;
382
+ handle.remove();
383
+ registered.delete(name);
384
+ }
385
+ for (const [name, entry] of wanted) {
386
+ if (!registered.has(name)) {
387
+ registered.set(name, { entry, handle: registerEntry(server, entry) });
388
+ }
389
+ }
390
+ }
391
+ return next.sync;
392
+ });
393
+ queue = run.catch(() => undefined);
394
+ return run;
395
+ };
396
+ const signedIn = async () => {
397
+ const client = await account.client();
398
+ if (!client.signedIn) {
399
+ throw new ToolpalError("UNAUTHORIZED", `not signed in to ${client.baseUrl}; ask the user to run \`toolpal login\` in a terminal, then try again`);
400
+ }
401
+ return client;
402
+ };
403
+ const search = async (args) => {
404
+ try {
405
+ const query = typeof args.query === "string" ? args.query.trim() : "";
406
+ if (query === "")
407
+ throw new ToolpalError("INPUT_INVALID", "query must be a non-empty string");
408
+ const asked = Number.isInteger(args.limit) ? args.limit : 10;
409
+ const limit = Math.min(Math.max(asked, 1), MAX_SEARCH_RESULTS);
410
+ const hits = await (await account.client()).search(query, limit);
411
+ const installed = new Map(tools.map((entry) => [entry.info.name, entry.info.version]));
412
+ return ok({
413
+ results: hits.map((hit) => ({
414
+ name: hit.name,
415
+ description: hit.description,
416
+ version: hit.latest,
417
+ permissions: describePermissions(normalizePermissions(hit.permissions)),
418
+ flags: hit.flags ?? [],
419
+ verified: hit.verified,
420
+ addedBy: hit.stars,
421
+ downloads: hit.downloads,
422
+ installed: installed.has(hit.name),
423
+ ...(installed.has(hit.name) ? { installedVersion: installed.get(hit.name) } : {}),
424
+ })),
425
+ });
426
+ }
427
+ catch (err) {
428
+ return failed(err);
429
+ }
430
+ };
431
+ /** The `tool` argument of a call: a registry name, never a path or a version. */
432
+ const toolNamed = (args) => {
433
+ const name = typeof args.tool === "string" ? args.tool.trim() : "";
434
+ if (!isValidToolName(name)) {
435
+ throw new ToolpalError("INVALID_REF", `expected a tool name like @scope/name, got "${name}"`);
436
+ }
437
+ return name;
438
+ };
439
+ const installed = (entry, from) => ok({
440
+ installed: `${entry.info.name}@${entry.info.version}`,
441
+ ...(from === undefined ? {} : { from }),
442
+ tool: entry.mcpName,
443
+ permissions: entry.info.permissionSummary,
444
+ flags: entry.info.flags,
445
+ });
446
+ const install = async (server, args, ctx) => {
447
+ try {
448
+ const name = toolNamed(args);
449
+ const client = await signedIn();
450
+ // Already one of the user's tools, perhaps added by hand since the server started.
451
+ // It keeps the version it has: only update_tool moves it.
452
+ await refresh();
453
+ const already = tools.find((t) => t.info.name === name);
454
+ if (already)
455
+ return installed(already);
456
+ const preview = await account.preview(name);
457
+ const question = confirmation(server, ctx, {
458
+ fingerprint: preview.version,
459
+ message: installQuestion(preview),
460
+ title: "Install this tool",
461
+ effect: "Add it to my Toolpal account and let this assistant run it",
462
+ declined: `the user declined to install ${name}; do not install it another way`,
463
+ });
464
+ if (question)
465
+ return question;
466
+ await client.star(name, true);
467
+ const sync = await refresh();
468
+ const entry = tools.find((t) => t.info.name === name);
469
+ if (!entry) {
470
+ throw new ToolpalError("REGISTRY_ERROR", sync.status === "stale"
471
+ ? `${name} was added to the account, but the registry could not be reached to install it`
472
+ : `${name} was added to the account, but it has no version that can be installed`);
473
+ }
474
+ // The answer covered one version; a newer one that asks for more is not what was accepted.
475
+ const extra = permissionsAdded(preview.permissions, entry.info.permissions);
476
+ if (extra.length > 0) {
477
+ await client.star(name, false);
478
+ await refresh();
479
+ throw new ToolpalError("ACCESS_DENIED", `${name}@${entry.info.version} asks for more than the user accepted (${extra.join(", ")}), so it was not installed; call ${INSTALL_TOOL} again to ask about this version`);
480
+ }
481
+ return installed(entry);
482
+ }
483
+ catch (err) {
484
+ return failed(err);
485
+ }
486
+ };
487
+ const update = async (server, args, ctx) => {
488
+ try {
489
+ const name = toolNamed(args);
490
+ await signedIn();
491
+ let sync = await refresh();
492
+ // The pin, not what is served: a version the moderators withheld can be moved off.
493
+ const pinned = (await account.list()).find((t) => t.name === name);
494
+ if (!pinned) {
495
+ throw new ToolpalError("TOOL_NOT_FOUND", `${name} is not installed here; add it with ${INSTALL_TOOL}`);
496
+ }
497
+ const preview = await account.preview(name);
498
+ const moves = preview.version !== pinned.version;
499
+ if (moves) {
500
+ const question = confirmation(server, ctx, {
501
+ fingerprint: `${pinned.version} ${preview.version}`,
502
+ message: updateQuestion(pinned.version, preview, permissionsAdded(pinned.permissions, preview.permissions)),
503
+ title: "Update this tool",
504
+ effect: "Replace the installed version and let this assistant run the new one",
505
+ declined: `the user declined to update ${name}; do not update it another way`,
506
+ });
507
+ if (question)
508
+ return question;
509
+ // Exactly the version asked about, with no more access than the question said.
510
+ sync = await refresh(() => account.updateAccount(name, preview));
511
+ }
512
+ const entry = tools.find((t) => t.info.name === name);
513
+ if (!entry) {
514
+ throw new ToolpalError("REGISTRY_ERROR", sync.unavailable[name] ?? `${name}@${preview.version} could not be loaded`);
515
+ }
516
+ return installed(entry, moves ? pinned.version : undefined);
517
+ }
518
+ catch (err) {
519
+ return failed(err);
520
+ }
521
+ };
522
+ const publish = async (author, server, args, ctx) => {
523
+ let prepared;
524
+ try {
525
+ const code = typeof args.code === "string" ? args.code : "";
526
+ if (code.trim() === "")
527
+ throw new ToolpalError("INPUT_INVALID", "code must be the source");
528
+ if (args.visibility !== undefined && !visibilitySchema.safeParse(args.visibility).success) {
529
+ throw new ToolpalError("INPUT_INVALID", 'visibility must be "private" or "public"');
530
+ }
531
+ const client = await signedIn();
532
+ const me = await client.me();
533
+ const given = typeof args.name === "string" ? args.name.trim() : "";
534
+ const name = given.startsWith("@") ? given : `@${me.login}/${given}`;
535
+ if (!isValidToolName(name)) {
536
+ throw new ToolpalError("INVALID_REF", `"${given}" is not a valid tool name: use lowercase letters, digits and dashes, for example word-count`);
537
+ }
538
+ if (!me.scopes.includes(splitToolName(name).scope)) {
539
+ throw new ToolpalError("UNAUTHORIZED", `${name} is not in a scope the user owns; they are signed in as ${me.login}`);
540
+ }
541
+ // A new tool is private unless asked otherwise; a new version keeps what the tool is.
542
+ const existing = await client.packument(name).catch((err) => {
543
+ if (err instanceof ToolpalError && err.code === "TOOL_NOT_FOUND")
544
+ return undefined;
545
+ throw err;
546
+ });
547
+ const asked = args.visibility;
548
+ const visibility = asked ?? (existing ? undefined : "private");
549
+ const becomes = visibility ?? existing?.visibility ?? "public";
550
+ prepared = await author.prepare(name, code);
551
+ const question = confirmation(server, ctx, {
552
+ fingerprint: sha256Hex(canonicalJson({ name, code, becomes })),
553
+ message: publishQuestion(name, prepared, {
554
+ visibility: becomes,
555
+ isNew: !existing,
556
+ lines: code.split("\n").length,
557
+ }),
558
+ title: "Publish this tool",
559
+ effect: "Publish it under my Toolpal account and let this assistant run it",
560
+ declined: `the user declined to publish ${name}; do not publish it another way`,
561
+ });
562
+ if (question)
563
+ return question;
564
+ const published = await prepared.publish(visibility);
565
+ const sync = await refresh();
566
+ const entry = tools.find((t) => t.info.name === name);
567
+ // It is published either way, so this is not a failure; but without `tool`
568
+ // it cannot be called here, and the reason is the only way to find out why.
569
+ const unavailable = sync.unavailable[name] ??
570
+ (sync.status === "stale"
571
+ ? "the registry could not be reached to load it"
572
+ : "the registry does not list it among the user's tools");
573
+ return ok({
574
+ published: `${name}@${published.version}`,
575
+ visibility: published.visibility,
576
+ ...(entry ? { tool: entry.mcpName } : { unavailable }),
577
+ permissions: describePermissions(prepared.permissions),
578
+ flags: prepared.flags,
579
+ });
580
+ }
581
+ catch (err) {
582
+ return failed(err);
583
+ }
584
+ finally {
585
+ await prepared?.dispose().catch(() => undefined);
586
+ }
587
+ };
588
+ return () => {
589
+ const server = newServer();
590
+ const registered = new Map();
591
+ for (const entry of tools) {
592
+ registered.set(entry.mcpName, { entry, handle: registerEntry(server, entry) });
593
+ }
594
+ server.registerTool(SEARCH_TOOL, {
595
+ title: "Search Toolpal tools",
596
+ description: "Search the public Toolpal registry for tools that are not installed here yet. Use it when none of the available tools can do what the user asks. Each result says what the tool may access (network, environment variables, temporary files) and whether it is already installed, and then at which version. To use a result, add it with install_tool.",
597
+ inputSchema: jsonSchema(searchInput),
598
+ outputSchema: jsonSchema(searchOutput),
599
+ annotations: { readOnlyHint: true, openWorldHint: true },
600
+ }, search);
601
+ server.registerTool(INSTALL_TOOL, {
602
+ title: "Install a Toolpal tool",
603
+ description: "Add a public Toolpal tool to the user's account so it can be called here; it is added to their Toolpal account and stays available in later sessions, on the version installed now. Say which tool you want to add, who publishes it and what it may access before calling this. Where their client can ask, the user is asked to confirm and nothing is installed unless they accept. The result gives the name the tool is then callable by on this server.",
604
+ inputSchema: jsonSchema(installInput),
605
+ outputSchema: jsonSchema(installOutput),
606
+ annotations: {
607
+ readOnlyHint: false,
608
+ destructiveHint: false,
609
+ idempotentHint: true,
610
+ openWorldHint: true,
611
+ },
612
+ }, (args, ctx) => install(server, args, ctx));
613
+ server.registerTool(UPDATE_TOOL, {
614
+ title: "Update a Toolpal tool",
615
+ description: "Move an installed Toolpal tool that someone else publishes to its newest version. Such a tool stays on the version that was installed, because a new version is new code from its owner and may access more; the tool's description says when another version exists. Call this only when the user asks for the update, after saying which tool, from which version to which, and what the new version adds. Where their client can ask, the user is asked to confirm and nothing changes unless they accept. The user's own tools need no update: they follow their newest version.",
616
+ inputSchema: jsonSchema(updateInput),
617
+ outputSchema: jsonSchema(updateOutput),
618
+ annotations: {
619
+ readOnlyHint: false,
620
+ destructiveHint: true,
621
+ idempotentHint: true,
622
+ openWorldHint: true,
623
+ },
624
+ }, (args, ctx) => update(server, args, ctx));
625
+ if (authoring) {
626
+ server.registerTool(PUBLISH_TOOL, {
627
+ title: "Create and publish a Toolpal tool",
628
+ description: PUBLISH_DESCRIPTION,
629
+ inputSchema: jsonSchema(publishInput),
630
+ outputSchema: jsonSchema(publishOutput),
631
+ annotations: {
632
+ readOnlyHint: false,
633
+ destructiveHint: false,
634
+ idempotentHint: false,
635
+ openWorldHint: true,
636
+ },
637
+ }, (args, ctx) => publish(authoring, server, args, ctx));
638
+ }
639
+ live.push({ server, registered });
640
+ return server;
641
+ };
642
+ }
643
+ /** `toolpal mcp`: serve the account's tools, with search, install, update and publish, over stdio. */
644
+ export function serveAccountMcp(account, initial, authoring) {
645
+ buildMcpServer(initial); // as in serveMcpStdio: fail at startup, not on the first request
646
+ return serveStdio(accountMcpServerFactory(account, initial, authoring));
647
+ }
648
+ //# sourceMappingURL=mcp.js.map