@shelby-protocol/mcp 0.1.2-dogfood.3 → 0.1.2

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.
@@ -5,7 +5,7 @@ import { ShelbyAdmin } from "../services/ShelbyAdmin.js";
5
5
  import { s3BucketOf } from "../utils/bucketName.js";
6
6
  import { formatError } from "../utils/errors.js";
7
7
  import { run } from "./run.js";
8
- import { BucketRefToolScheme, CreateBucketToolScheme, EmptyToolScheme, RenameBucketToolScheme, } from "./schemas.js";
8
+ import { BucketRefToolScheme, CreateBucketToolScheme, EmptyToolScheme, } from "./schemas.js";
9
9
  const DEFAULT_API_KEY_NAME = "api-key-01";
10
10
  export function accountScope(bucket) {
11
11
  return {
@@ -103,73 +103,36 @@ export const createBucketTool = {
103
103
  project_id: project.project_id,
104
104
  application_id: app.id,
105
105
  };
106
+ // Bot keys can't delete buckets, so a failed step can't be rolled back here.
107
+ let account;
106
108
  try {
107
- const account = await new ShelbyAccount().createAccount(scope, name);
108
- const apiKey = catalog.legacy
109
- ? await admin.createApiKey({
110
- ...scope,
111
- name: api_key_name ?? DEFAULT_API_KEY_NAME,
112
- })
113
- : undefined;
114
- return {
115
- name: app.name,
116
- ...place(project),
117
- s3_bucket: s3BucketOf(account),
118
- account_address: account.accountAddress,
119
- fee_payer_address: account.feePayerAddress,
120
- ...(apiKey
121
- ? { api_key: { name: apiKey.name, key_secret: apiKey.keySecret } }
122
- : {}),
123
- note: dataNote(catalog),
124
- };
109
+ account = await new ShelbyAccount().createAccount(scope, name);
125
110
  }
126
111
  catch (error) {
127
- // Roll back so a failed create doesn't leave an orphaned bucket.
128
- const cleanup = await new ShelbyAccount()
129
- .deleteAccount(scope)
130
- .then(() => admin.deleteApplication(scope))
131
- .then(() => "The partially created bucket was rolled back.")
132
- .catch((cleanupError) => `Rolling back the partially created bucket also failed (${formatError(cleanupError)}); delete bucket "${name}" in the console.`);
133
- throw new Error(`${formatError(error)}. ${cleanup}`);
112
+ throw new Error(`${formatError(error)}. Bucket "${name}" was created without its storage account, so it can't hold files. Tell the user to delete it in the Shelby console.`);
113
+ }
114
+ let apiKey;
115
+ if (catalog.legacy) {
116
+ try {
117
+ apiKey = await admin.createApiKey({
118
+ ...scope,
119
+ name: api_key_name ?? DEFAULT_API_KEY_NAME,
120
+ });
121
+ }
122
+ catch (error) {
123
+ throw new Error(`${formatError(error)}. Bucket "${name}" was created, but its API key wasn't. Tell the user to create one in the Shelby console.`);
124
+ }
134
125
  }
135
- }),
136
- };
137
- export const renameBucketTool = {
138
- name: "rename_shelby_bucket",
139
- description: "Rename a Shelby bucket's display name. Its S3 bucket name (s3_bucket) and account address do not change, so existing S3 clients keep working.",
140
- parameters: RenameBucketToolScheme,
141
- execute: ({ bucket, new_name, ...placement }) => run("Failed to rename bucket", async () => {
142
- const admin = new ShelbyAdmin();
143
- const record = findBucket(await loadCatalog(admin), bucket, placement);
144
- await admin.setApplicationName({ ...accountScope(record), new_name });
145
126
  return {
146
- ...place(record),
147
- name: new_name,
148
- note: "Only the display name changed. Keep using the bucket's s3_bucket in S3 clients.",
127
+ name: app.name,
128
+ ...place(project),
129
+ s3_bucket: s3BucketOf(account),
130
+ account_address: account.accountAddress,
131
+ fee_payer_address: account.feePayerAddress,
132
+ ...(apiKey
133
+ ? { api_key: { name: apiKey.name, key_secret: apiKey.keySecret } }
134
+ : {}),
135
+ note: dataNote(catalog),
149
136
  };
150
137
  }),
151
138
  };
152
- export const deleteBucketTool = {
153
- name: "delete_shelby_bucket",
154
- description: "Delete a Shelby bucket and everything in it. This cannot be undone. Retrying after a partial failure is safe.",
155
- parameters: BucketRefToolScheme,
156
- execute: ({ bucket, ...placement }) => run("Failed to delete bucket", async () => {
157
- const admin = new ShelbyAdmin();
158
- const record = findBucket(await loadCatalog(admin), bucket, placement);
159
- const scope = accountScope(record);
160
- // The account must be deleted first: its scoped auth resolves through the app.
161
- try {
162
- await new ShelbyAccount().deleteAccount(scope);
163
- }
164
- catch (error) {
165
- throw new Error(`Deleting the bucket account failed: ${formatError(error)}. Retrying is safe.`);
166
- }
167
- try {
168
- await admin.deleteApplication(scope);
169
- }
170
- catch (error) {
171
- throw new Error(`The bucket account was deleted, but deleting the bucket failed: ${formatError(error)}. Retry to finish the deletion.`);
172
- }
173
- return { ...place(record), name: record.name, deleted: true };
174
- }),
175
- };
@@ -1,67 +1,14 @@
1
- import { LiveVaultCatalog } from "../services/liveVaultCatalog.js";
2
- import { createBucketTool, deleteBucketTool, getBucketTool, listBucketsTool, renameBucketTool, } from "./buckets.js";
1
+ import { createBucketTool, getBucketTool, listBucketsTool } from "./buckets.js";
3
2
  import { s3ConnectionGuideTool } from "./guide.js";
4
3
  import { agentKeyInfoTool } from "./key.js";
5
4
  import { downloadObjectTool, listObjectsTool, uploadObjectTool, } from "./objects.js";
6
- import { appendRecordTool, createVaultTool, downloadArtifactTool, forgetRecordTool, getVaultTool, listVaultsTool, readRecordsTool, searchVaultTool, uploadArtifactTool, } from "./vaults.js";
7
- export function registerTools(server, options = {}) {
5
+ export function registerTools(server) {
8
6
  server.addTool(agentKeyInfoTool);
9
7
  server.addTool(listBucketsTool);
10
8
  server.addTool(getBucketTool);
11
9
  server.addTool(createBucketTool);
12
- server.addTool(renameBucketTool);
13
- server.addTool(deleteBucketTool);
14
10
  server.addTool(listObjectsTool);
15
11
  server.addTool(uploadObjectTool);
16
12
  server.addTool(downloadObjectTool);
17
13
  server.addTool(s3ConnectionGuideTool);
18
- server.addTool(uploadArtifactTool);
19
- server.addTool(downloadArtifactTool);
20
- const afterMutation = (execute) => async (args) => {
21
- try {
22
- return await execute(args);
23
- }
24
- finally {
25
- // Refresh even after failure: a multi-step operation may partially succeed.
26
- live.requestRefresh();
27
- }
28
- };
29
- server.addTool({
30
- ...createVaultTool,
31
- execute: afterMutation(createVaultTool.execute),
32
- });
33
- server.addTool({
34
- ...getVaultTool,
35
- execute: (args) => getVaultTool.execute(args, live),
36
- });
37
- server.addTool({
38
- ...readRecordsTool,
39
- execute: (args) => readRecordsTool.execute(args, live),
40
- });
41
- server.addTool({
42
- ...appendRecordTool,
43
- execute: (args) => appendRecordTool.execute(args, live),
44
- });
45
- server.addTool({
46
- ...forgetRecordTool,
47
- execute: afterMutation(forgetRecordTool.execute),
48
- });
49
- server.addTool({
50
- ...searchVaultTool,
51
- execute: (args) => searchVaultTool.execute(args, live),
52
- });
53
- const live = new LiveVaultCatalog(server, (catalog) => {
54
- // addTool replaces a same-name definition, refreshes session handlers and
55
- // emits tools/list_changed. Only the catalog-bearing tool is replaced;
56
- // unrelated tools remain untouched and context is not repeated nine times.
57
- server.addTool({
58
- ...listVaultsTool,
59
- description: `${listVaultsTool.description}\n${catalog}`,
60
- execute: async (args) => {
61
- await live.refreshIfUnavailable();
62
- return listVaultsTool.execute(args, live);
63
- },
64
- });
65
- }, options);
66
- return live;
67
14
  }
@@ -10,6 +10,7 @@ import { accountScope, place } from "./buckets.js";
10
10
  import { run } from "./run.js";
11
11
  import { DownloadObjectToolScheme, ListObjectsToolScheme, UploadObjectToolScheme, } from "./schemas.js";
12
12
  const allowedDirs = new AllowedDirs(config.allowedDirs);
13
+ const allowedDirsShown = config.allowedDirs.join(", ") || "none set";
13
14
  async function resolveTarget({ bucket, project, organization }, { write }) {
14
15
  const catalog = await loadCatalog(new ShelbyAdmin());
15
16
  if (catalog.legacy)
@@ -42,7 +43,7 @@ export const listObjectsTool = {
42
43
  };
43
44
  export const uploadObjectTool = {
44
45
  name: "upload_shelby_object",
45
- description: `Upload a local file to a Shelby bucket. Streams the file, using a multipart upload for large files. Only files inside the allowed directories can be read (${config.allowedDirs.join(", ")}).`,
46
+ description: `Upload a local file to a Shelby bucket. Streams the file, using a multipart upload for large files. Only files inside the allowed directories can be read (${allowedDirsShown}).`,
46
47
  parameters: UploadObjectToolScheme,
47
48
  execute: ({ local_path, key, content_type, ...ref }) => run("Failed to upload", async () => {
48
49
  const file = await allowedDirs.readableFile(local_path);
@@ -53,7 +54,7 @@ export const uploadObjectTool = {
53
54
  };
54
55
  export const downloadObjectTool = {
55
56
  name: "download_shelby_object",
56
- description: `Download an object from a Shelby bucket to a local file. Only paths inside the allowed directories can be written (${config.allowedDirs.join(", ")}). Won't replace an existing file unless overwrite is set.`,
57
+ description: `Download an object from a Shelby bucket to a local file. Only paths inside the allowed directories can be written (${allowedDirsShown}). Won't replace an existing file unless overwrite is set.`,
57
58
  parameters: DownloadObjectToolScheme,
58
59
  execute: ({ key, local_path, overwrite, ...ref }) => run("Failed to download", async () => {
59
60
  const destination = await allowedDirs.writableFile(local_path ?? (key.split("/").pop() || key), overwrite ?? false);
package/dist/tools/run.js CHANGED
@@ -1,7 +1,5 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { redactAgentKey } from "../services/agentKey.js";
3
2
  import { expiryWarning } from "../services/catalog.js";
4
- import { diagnosticLog, errorKind, withDiagnostics, } from "../utils/diagnostics.js";
5
3
  import { formatError } from "../utils/errors.js";
6
4
  /**
7
5
  * Run a tool, turning a failure into a message for the agent. Every result passes
@@ -9,40 +7,19 @@ import { formatError } from "../utils/errors.js";
9
7
  * key expires soon, a second text block warns about it, leaving the first one as is.
10
8
  */
11
9
  export async function run(failure, body) {
12
- const operationId = randomUUID();
13
- return withDiagnostics(operationId, async () => {
14
- const started = performance.now();
15
- diagnosticLog().write({
16
- event: "tool",
17
- operation: failure.replace(/^Failed to /, ""),
18
- });
19
- let text;
20
- try {
21
- const result = await body();
22
- text = typeof result === "string" ? result : JSON.stringify(result);
23
- diagnosticLog().write({
24
- event: "tool",
25
- operation: failure.replace(/^Failed to /, ""),
26
- outcome: "ok",
27
- duration_ms: Math.round(performance.now() - started),
28
- });
29
- }
30
- catch (error) {
31
- diagnosticLog().write({
32
- event: "tool",
33
- operation: failure.replace(/^Failed to /, ""),
34
- outcome: "error",
35
- duration_ms: Math.round(performance.now() - started),
36
- ...errorKind(error),
37
- });
38
- text = `❌ ${failure}: ${formatError(error)}\nDiagnostic ID: ${operationId}\nLog: ${diagnosticLog().location}`;
39
- }
40
- const warning = expiryWarning();
41
- return {
42
- content: [
43
- { type: "text", text: redactAgentKey(text) },
44
- ...(warning ? [{ type: "text", text: warning }] : []),
45
- ],
46
- };
47
- });
10
+ let text;
11
+ try {
12
+ const result = await body();
13
+ text = typeof result === "string" ? result : JSON.stringify(result);
14
+ }
15
+ catch (error) {
16
+ text = `❌ ${failure}: ${formatError(error)}`;
17
+ }
18
+ const warning = expiryWarning();
19
+ return {
20
+ content: [
21
+ { type: "text", text: redactAgentKey(text) },
22
+ ...(warning ? [{ type: "text", text: warning }] : []),
23
+ ],
24
+ };
48
25
  }
@@ -30,9 +30,6 @@ export const CreateBucketToolScheme = z.object({
30
30
  .optional()
31
31
  .describe("Unscoped bot keys only: name of the API key created with the bucket. Defaults to 'api-key-01'."),
32
32
  });
33
- export const RenameBucketToolScheme = BucketRefToolScheme.extend({
34
- new_name: resourceName.describe("The new bucket name. Must be 3-32 characters: lowercase letters, numbers, dashes and underscores."),
35
- });
36
33
  export const ListObjectsToolScheme = BucketRefToolScheme.extend({
37
34
  prefix: z.string().optional().describe("Only list keys starting with this."),
38
35
  delimiter: z
@@ -1,5 +1,6 @@
1
1
  import { lstat, realpath, stat } from "node:fs/promises";
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve, sep, } from "node:path";
3
+ const ADD_DIRECTORY_HINT = "In Claude Desktop, add one under Settings → Extensions → Shelby → Allowed directories; elsewhere, start the server with --allow-dir.";
3
4
  function isInside(dir, path) {
4
5
  const rel = relative(dir, path);
5
6
  return (rel === "" ||
@@ -14,12 +15,15 @@ export class AllowedDirs {
14
15
  realDirs;
15
16
  constructor(dirs) {
16
17
  this.dirs = dirs;
17
- if (dirs.length === 0)
18
- throw new Error("No allowed directories");
19
18
  }
20
19
  get list() {
21
20
  return [...this.dirs];
22
21
  }
22
+ assertAny() {
23
+ if (this.dirs.length === 0) {
24
+ throw new Error(`No allowed directories are set, so no local file can be read or written. ${ADD_DIRECTORY_HINT}`);
25
+ }
26
+ }
23
27
  async real() {
24
28
  this.realDirs ??= Promise.all(this.dirs.map(async (dir) => {
25
29
  try {
@@ -34,11 +38,12 @@ export class AllowedDirs {
34
38
  async assertInside(path, shown) {
35
39
  const dirs = await this.real();
36
40
  if (!dirs.some((dir) => isInside(dir, path))) {
37
- throw new Error(`${shown} is outside the directories this MCP may use (${this.dirs.join(", ")}). Start it with --allow-dir to allow another directory.`);
41
+ throw new Error(`${shown} is outside the directories this MCP may use (${this.dirs.join(", ")}). ${ADD_DIRECTORY_HINT}`);
38
42
  }
39
43
  }
40
44
  /** Relative paths are taken from the first allowed directory. */
41
45
  absolute(path) {
46
+ this.assertAny();
42
47
  return resolve(this.dirs[0], path);
43
48
  }
44
49
  /** An existing regular file to read. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shelby-protocol/mcp",
3
- "version": "0.1.2-dogfood.3",
3
+ "version": "0.1.2",
4
4
  "main": "dist/server.js",
5
5
  "module": "dist/server.js",
6
6
  "bin": {
@@ -10,16 +10,11 @@
10
10
  "mcp",
11
11
  "shelby",
12
12
  "s3",
13
- "storage",
14
- "memory"
13
+ "storage"
15
14
  ],
16
15
  "license": "Apache-2.0",
17
16
  "type": "module",
18
- "publishConfig": {
19
- "access": "public",
20
- "tag": "dogfood"
21
- },
22
- "description": "An MCP server for Shelby Console",
17
+ "description": "An MCP server that lets agents manage Shelby buckets",
23
18
  "engines": {
24
19
  "node": ">=22.12.0"
25
20
  },
@@ -39,8 +34,7 @@
39
34
  "format": "biome check --write ."
40
35
  },
41
36
  "dependencies": {
42
- "@aptos-labs/api-gateway-admin-api-client": "4.10.0",
43
- "@shelby-protocol/data-vault-client": "0.1.0-rc.3",
37
+ "@aptos-labs/api-gateway-admin-api-client": "^4.9.0",
44
38
  "fastmcp": "^4.3.2",
45
39
  "zod": "^4.4.3"
46
40
  },
@@ -1,41 +0,0 @@
1
- import { readFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
- import { join } from "node:path";
4
- import { z } from "zod";
5
- const schema = z
6
- .object({
7
- memories: z
8
- .object({
9
- pinned: z.array(z.string().min(1).max(256)).max(40).default([]),
10
- frequentCount: z.number().int().min(0).max(40).default(5),
11
- descriptionBytes: z.number().int().min(2048).max(12000).default(6000),
12
- })
13
- .strict()
14
- .prefault({}),
15
- })
16
- .strict();
17
- export function parseMemoryConfig(value) {
18
- return schema.parse(value).memories;
19
- }
20
- export function loadMemoryConfig() {
21
- const explicit = process.env.SHELBY_MCP_CONFIG;
22
- const path = explicit ??
23
- join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "shelby-mcp", "config.json");
24
- try {
25
- const content = readFileSync(path);
26
- if (content.length > 64 * 1024)
27
- throw new Error("oversized configuration");
28
- return parseMemoryConfig(JSON.parse(content.toString("utf8")));
29
- }
30
- catch (error) {
31
- if (!explicit &&
32
- error &&
33
- typeof error === "object" &&
34
- "code" in error &&
35
- error.code === "ENOENT") {
36
- return parseMemoryConfig({});
37
- }
38
- // Do not echo file contents or schema values that may contain credentials.
39
- throw new Error("Invalid Shelby MCP configuration: check memories.pinned, frequentCount (0–40), and descriptionBytes (2048–12000).");
40
- }
41
- }
@@ -1,56 +0,0 @@
1
- """Interactive setup through Atlas's native CLI. Credentials never enter argv."""
2
-
3
- import argparse
4
- import getpass
5
- import json
6
- import os
7
- from pathlib import Path
8
- import shlex
9
- import shutil
10
- import subprocess
11
- import tempfile
12
-
13
-
14
- def main():
15
- parser = argparse.ArgumentParser(description=__doc__)
16
- parser.add_argument("--env", choices=("staging", "beta"), required=True)
17
- parser.add_argument("--allow-dir", type=Path, default=Path.cwd())
18
- args = parser.parse_args()
19
- if not shutil.which("atlas"):
20
- raise SystemExit("Atlas not found on PATH. Install Atlas, open a new terminal, then retry.")
21
- if not shutil.which("npx"):
22
- raise SystemExit("Install Node >=22.12 (including npx), then retry.")
23
- allowed = args.allow_dir.expanduser().resolve()
24
- if not allowed.is_dir():
25
- raise SystemExit("--allow-dir must be an existing directory")
26
- version = json.loads((Path(__file__).resolve().parents[2] / "package.json").read_text())["version"]
27
- package = "@shelby-protocol/mcp@" + version
28
- print("Shelby environment: " + args.env + "; file access limited to: " + str(allowed))
29
- key = getpass.getpass("Paste your Shelby agent key (hidden): ").strip()
30
- if not key.startswith("shelbyagent") or any(c.isspace() for c in key):
31
- raise SystemExit("Expected a Shelby agent key; configuration was not changed.")
32
- directory = Path.home() / ".config/shelby-mcp"
33
- directory.mkdir(parents=True, exist_ok=True, mode=0o700)
34
- key_path = directory / (args.env + "-agent-key")
35
- fd, temporary = tempfile.mkstemp(dir=directory)
36
- try:
37
- with os.fdopen(fd, "w") as output:
38
- output.write(key + "\n")
39
- os.replace(temporary, key_path)
40
- finally:
41
- if os.path.exists(temporary):
42
- os.unlink(temporary)
43
- atlas = ["atlas"]
44
- subprocess.run(atlas + ["mcp", "add", "--scope", "user",
45
- "--env", "SHELBY_ENV=" + args.env, "--env", "SHELBY_AGENT_KEY_FILE=" + str(key_path),
46
- "shelby", "--", "npx", "--yes", package, "--allow-dir", str(allowed)], check=True)
47
- subprocess.run(atlas + ["mcp", "list"], check=True)
48
- print("Configured. Start Atlas with: " + shlex.join(atlas))
49
- print("If Atlas is already running, use /mcp reload.")
50
-
51
-
52
- if __name__ == "__main__":
53
- try:
54
- main()
55
- except subprocess.CalledProcessError as error:
56
- raise SystemExit("Atlas setup command failed (exit " + str(error.returncode) + "); retry after resolving the error above.") from None