@shelby-protocol/mcp 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.
@@ -0,0 +1,63 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { MISSING_AGENT_KEY_MESSAGE } from "../utils/errors.js";
3
+ /** The keychain entry `shelby-mcp keychain` style setups store the key under. */
4
+ export const KEYCHAIN_SERVICE = "shelby-mcp";
5
+ export const KEYCHAIN_ACCOUNT = "SHELBY_AGENT_KEY";
6
+ function readKeychain() {
7
+ const commands = {
8
+ darwin: [
9
+ "security",
10
+ [
11
+ "find-generic-password",
12
+ "-s",
13
+ KEYCHAIN_SERVICE,
14
+ "-a",
15
+ KEYCHAIN_ACCOUNT,
16
+ "-w",
17
+ ],
18
+ ],
19
+ linux: [
20
+ "secret-tool",
21
+ ["lookup", "service", KEYCHAIN_SERVICE, "account", KEYCHAIN_ACCOUNT],
22
+ ],
23
+ };
24
+ const command = commands[process.platform];
25
+ if (!command)
26
+ return undefined;
27
+ try {
28
+ const value = execFileSync(command[0], command[1], {
29
+ encoding: "utf8",
30
+ stdio: ["ignore", "pipe", "ignore"],
31
+ timeout: 10_000,
32
+ }).trim();
33
+ return value || undefined;
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ let cached;
40
+ /**
41
+ * The agent key, from `SHELBY_AGENT_KEY`, the older `SHELBY_BOT_KEY`, or the OS
42
+ * keychain, in that order.
43
+ */
44
+ export function getAgentKey() {
45
+ cached ??=
46
+ process.env.SHELBY_AGENT_KEY ||
47
+ process.env.SHELBY_BOT_KEY ||
48
+ readKeychain();
49
+ if (!cached)
50
+ throw new Error(MISSING_AGENT_KEY_MESSAGE);
51
+ return cached;
52
+ }
53
+ /** Replace the agent key anywhere in `text`, so no tool output can carry it. */
54
+ export function redactAgentKey(text) {
55
+ return cached ? text.replaceAll(cached, "<agent-key>") : text;
56
+ }
57
+ /** Headers that authenticate a request as the agent key. */
58
+ export function agentKeyHeaders() {
59
+ return {
60
+ Authorization: `Bearer ${getAgentKey()}`,
61
+ "x-is-aptos-bot": "true",
62
+ };
63
+ }
@@ -0,0 +1,135 @@
1
+ import { config } from "../config.js";
2
+ export function catalogFromSelf(self) {
3
+ const scope = self.scope;
4
+ if (!scope) {
5
+ return {
6
+ legacy: true,
7
+ readOnly: false,
8
+ key: self,
9
+ buckets: [],
10
+ creatableProjects: [],
11
+ };
12
+ }
13
+ const projectNames = new Map(scope.projects.map((p) => [p.id, p.name]));
14
+ const project = (project_id) => ({
15
+ organization_id: scope.organization_id,
16
+ project_id,
17
+ project_name: projectNames.get(project_id) ?? project_id,
18
+ });
19
+ return {
20
+ legacy: false,
21
+ readOnly: scope.permission === "ReadOnly",
22
+ key: self,
23
+ buckets: scope.applications
24
+ .filter((app) => app.service_type === config.shelby.serviceType)
25
+ .map((app) => ({
26
+ ...project(app.project_id),
27
+ application_id: app.id,
28
+ name: app.name,
29
+ })),
30
+ creatableProjects: scope.projects
31
+ .filter((p) => p.whole_project)
32
+ .map((p) => project(p.id)),
33
+ };
34
+ }
35
+ export function catalogFromOrganizations(orgs, key) {
36
+ const projects = orgs.flatMap(({ Organization: org }) => org.Project.map((project) => ({
37
+ org,
38
+ project,
39
+ record: {
40
+ organization_id: org.id,
41
+ organization_name: org.name,
42
+ project_id: project.id,
43
+ project_name: project.name,
44
+ },
45
+ })));
46
+ return {
47
+ legacy: true,
48
+ readOnly: false,
49
+ key,
50
+ buckets: projects.flatMap(({ project, record }) => project.Application.filter((app) => app.serviceType === config.shelby.serviceType).map((app) => ({
51
+ ...record,
52
+ application_id: app.id,
53
+ name: app.name,
54
+ api_keys: app.apiKeys.map((apiKey) => ({
55
+ name: apiKey.name,
56
+ key_secret: apiKey.keySecret,
57
+ created_at: apiKey.createdAt,
58
+ })),
59
+ }))),
60
+ creatableProjects: projects.map(({ record }) => record),
61
+ };
62
+ }
63
+ const EXPIRY_WARNING_DAYS = 7;
64
+ const ONE_DAY_MS = 24 * 60 * 60 * 1000;
65
+ /** The key as of the last `loadCatalog`, so every tool result can warn before it expires. */
66
+ let lastSelf;
67
+ export function expiryWarning(key = lastSelf, now = new Date()) {
68
+ if (!key?.expires_at)
69
+ return undefined;
70
+ const msLeft = new Date(key.expires_at).getTime() - now.getTime();
71
+ if (msLeft <= 0 || msLeft > EXPIRY_WARNING_DAYS * ONE_DAY_MS) {
72
+ return undefined;
73
+ }
74
+ const days = Math.ceil(msLeft / ONE_DAY_MS);
75
+ return `⚠️ This Shelby agent key expires in ${days === 1 ? "less than a day" : `${days} days`} (${key.expires_at}). Tell the user to create a new one in the Shelby console and update SHELBY_AGENT_KEY before then.`;
76
+ }
77
+ export async function loadCatalog(admin) {
78
+ let self;
79
+ let selfError;
80
+ try {
81
+ self = await admin.getBotApiKeySelf();
82
+ lastSelf = self;
83
+ }
84
+ catch (error) {
85
+ // Gateways older than agent keys don't have getBotApiKeySelf.
86
+ selfError = error;
87
+ }
88
+ if (self?.scope)
89
+ return catalogFromSelf(self);
90
+ try {
91
+ return catalogFromOrganizations(await admin.getOrganizationsRecursively(), self);
92
+ }
93
+ catch (error) {
94
+ throw selfError ?? error;
95
+ }
96
+ }
97
+ function matches(record, { project, organization }) {
98
+ return ((!project ||
99
+ record.project_name === project ||
100
+ record.project_id === project) &&
101
+ (!organization ||
102
+ record.organization_name === organization ||
103
+ record.organization_id === organization));
104
+ }
105
+ function describePlace(record) {
106
+ return record.organization_name
107
+ ? `project "${record.project_name}" in organization "${record.organization_name}"`
108
+ : `project "${record.project_name}"`;
109
+ }
110
+ export function findBucket(catalog, name, placement = {}) {
111
+ const candidates = catalog.buckets.filter((bucket) => bucket.name === name && matches(bucket, placement));
112
+ if (candidates.length === 1)
113
+ return candidates[0];
114
+ if (candidates.length === 0) {
115
+ throw new Error(`No bucket named "${name}" that this key can reach. Use list_shelby_buckets to see them.`);
116
+ }
117
+ throw new Error(`Several buckets are named "${name}": in ${candidates.map(describePlace).join(", ")}. Pass the project (and organization if needed).`);
118
+ }
119
+ export function findCreatableProject(catalog, placement = {}) {
120
+ if (catalog.readOnly) {
121
+ throw new Error("This agent key is read-only, so it can't create buckets.");
122
+ }
123
+ if (catalog.creatableProjects.length === 0) {
124
+ throw new Error(catalog.legacy
125
+ ? "This key doesn't reach any project."
126
+ : "This agent key is limited to specific buckets, so it can't create new ones. Use an agent key scoped to a project or the organization.");
127
+ }
128
+ const candidates = catalog.creatableProjects.filter((p) => matches(p, placement));
129
+ if (candidates.length === 1)
130
+ return candidates[0];
131
+ if (candidates.length === 0) {
132
+ throw new Error(`This key can't create buckets in ${placement.project ? `project "${placement.project}"` : "that organization"}. It can create them in: ${catalog.creatableProjects.map(describePlace).join(", ")}.`);
133
+ }
134
+ throw new Error(`Pass a project. This key can create buckets in: ${candidates.map(describePlace).join(", ")}.`);
135
+ }
@@ -0,0 +1,175 @@
1
+ import { config } from "../config.js";
2
+ import { findBucket, findCreatableProject, loadCatalog, } from "../services/catalog.js";
3
+ import { ShelbyAccount } from "../services/ShelbyAccount.js";
4
+ import { ShelbyAdmin } from "../services/ShelbyAdmin.js";
5
+ import { s3BucketOf } from "../utils/bucketName.js";
6
+ import { formatError } from "../utils/errors.js";
7
+ import { run } from "./run.js";
8
+ import { BucketRefToolScheme, CreateBucketToolScheme, EmptyToolScheme, RenameBucketToolScheme, } from "./schemas.js";
9
+ const DEFAULT_API_KEY_NAME = "api-key-01";
10
+ export function accountScope(bucket) {
11
+ return {
12
+ organization_id: bucket.organization_id,
13
+ project_id: bucket.project_id,
14
+ application_id: bucket.application_id,
15
+ };
16
+ }
17
+ /** How the agent sees a project: by name, never by id. */
18
+ export function place(record) {
19
+ return {
20
+ project: record.project_name,
21
+ ...(record.organization_name
22
+ ? { organization: record.organization_name }
23
+ : {}),
24
+ };
25
+ }
26
+ function bucketView(bucket) {
27
+ return {
28
+ name: bucket.name,
29
+ ...place(bucket),
30
+ ...(bucket.api_keys ? { api_keys: bucket.api_keys } : {}),
31
+ };
32
+ }
33
+ function dataNote(catalog) {
34
+ return catalog.legacy
35
+ ? `To read/write objects, point any S3-compatible client at ${config.shelby.s3EndpointUrl} with path-style addressing, use an API key secret as BOTH access_key_id and secret_access_key, and use the bucket's s3_bucket as the S3 Bucket name (its account_address also works). Call get_shelby_s3_connection_guide for sample code.`
36
+ : "Use list_shelby_objects, upload_shelby_object and download_shelby_object to read and write objects.";
37
+ }
38
+ export const listBucketsTool = {
39
+ name: "list_shelby_buckets",
40
+ description: "List the Shelby buckets this key can reach, with the project each is in, its S3 bucket name (s3_bucket) and its account address. Also says where new buckets can be created.",
41
+ parameters: EmptyToolScheme,
42
+ execute: () => run("Failed to list buckets", async () => {
43
+ const catalog = await loadCatalog(new ShelbyAdmin());
44
+ const account = new ShelbyAccount();
45
+ const buckets = await Promise.all(catalog.buckets.map(async (bucket) => {
46
+ try {
47
+ const info = await account.getAccount(accountScope(bucket));
48
+ return {
49
+ ...bucketView(bucket),
50
+ s3_bucket: s3BucketOf(info),
51
+ account_address: info.accountAddress,
52
+ };
53
+ }
54
+ catch (error) {
55
+ return {
56
+ ...bucketView(bucket),
57
+ account_address_error: formatError(error),
58
+ };
59
+ }
60
+ }));
61
+ return {
62
+ buckets,
63
+ can_create_in: catalog.readOnly
64
+ ? []
65
+ : catalog.creatableProjects.map(place),
66
+ read_only: catalog.readOnly,
67
+ note: dataNote(catalog),
68
+ };
69
+ }),
70
+ };
71
+ export const getBucketTool = {
72
+ name: "get_shelby_bucket",
73
+ description: "Get one Shelby bucket by name: its project, S3 bucket name (s3_bucket) and on-chain account.",
74
+ parameters: BucketRefToolScheme,
75
+ execute: ({ bucket, ...placement }) => run("Failed to get bucket", async () => {
76
+ const catalog = await loadCatalog(new ShelbyAdmin());
77
+ const record = findBucket(catalog, bucket, placement);
78
+ const account = await new ShelbyAccount().getAccount(accountScope(record));
79
+ return {
80
+ ...bucketView(record),
81
+ s3_bucket: s3BucketOf(account),
82
+ account_address: account.accountAddress,
83
+ fee_payer_address: account.feePayerAddress,
84
+ note: dataNote(catalog),
85
+ };
86
+ }),
87
+ };
88
+ export const createBucketTool = {
89
+ name: "create_shelby_bucket",
90
+ description: "Create a Shelby bucket and the managed on-chain account that owns its data. Pass a project when the key can create in several (list_shelby_buckets shows where). With an unscoped bot key this also creates an API key, the S3 credential, and returns its secret once.",
91
+ parameters: CreateBucketToolScheme,
92
+ execute: ({ name, api_key_name, ...placement }) => run("Failed to create bucket", async () => {
93
+ const admin = new ShelbyAdmin();
94
+ const catalog = await loadCatalog(admin);
95
+ const project = findCreatableProject(catalog, placement);
96
+ const app = await admin.createBucketApplication({
97
+ name,
98
+ organization_id: project.organization_id,
99
+ project_id: project.project_id,
100
+ });
101
+ const scope = {
102
+ organization_id: project.organization_id,
103
+ project_id: project.project_id,
104
+ application_id: app.id,
105
+ };
106
+ 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
+ };
125
+ }
126
+ 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}`);
134
+ }
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
+ 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.",
149
+ };
150
+ }),
151
+ };
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
+ };
@@ -0,0 +1,21 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { config } from "../config.js";
3
+ import { formatError } from "../utils/errors.js";
4
+ import { S3GuideToolScheme } from "./schemas.js";
5
+ const GUIDE_URL = new URL("../resources/how_to_connect_to_a_shelby_bucket_with_s3.md", import.meta.url);
6
+ export const s3ConnectionGuideTool = {
7
+ name: "get_shelby_s3_connection_guide",
8
+ description: "Get the guide and sample code (boto3, AWS SDK v3, AWS CLI) for reading and writing objects in a Shelby bucket over the S3 API. Use this before writing any code that uploads to or downloads from a Shelby bucket.",
9
+ parameters: S3GuideToolScheme,
10
+ execute: async ({ bucket }) => {
11
+ try {
12
+ const template = await readFile(GUIDE_URL, "utf8");
13
+ return template
14
+ .replaceAll("{{S3_ENDPOINT}}", config.shelby.s3EndpointUrl)
15
+ .replaceAll("{{BUCKET}}", bucket ?? "<s3-bucket>");
16
+ }
17
+ catch (error) {
18
+ return `❌ Failed to load S3 connection guide: ${formatError(error)}`;
19
+ }
20
+ },
21
+ };
@@ -0,0 +1,16 @@
1
+ import { createBucketTool, deleteBucketTool, getBucketTool, listBucketsTool, renameBucketTool, } from "./buckets.js";
2
+ import { s3ConnectionGuideTool } from "./guide.js";
3
+ import { agentKeyInfoTool } from "./key.js";
4
+ import { downloadObjectTool, listObjectsTool, uploadObjectTool, } from "./objects.js";
5
+ export function registerTools(server) {
6
+ server.addTool(agentKeyInfoTool);
7
+ server.addTool(listBucketsTool);
8
+ server.addTool(getBucketTool);
9
+ server.addTool(createBucketTool);
10
+ server.addTool(renameBucketTool);
11
+ server.addTool(deleteBucketTool);
12
+ server.addTool(listObjectsTool);
13
+ server.addTool(uploadObjectTool);
14
+ server.addTool(downloadObjectTool);
15
+ server.addTool(s3ConnectionGuideTool);
16
+ }
@@ -0,0 +1,32 @@
1
+ import { config } from "../config.js";
2
+ import { loadCatalog } from "../services/catalog.js";
3
+ import { ShelbyAdmin } from "../services/ShelbyAdmin.js";
4
+ import { place } from "./buckets.js";
5
+ import { run } from "./run.js";
6
+ import { EmptyToolScheme } from "./schemas.js";
7
+ export const agentKeyInfoTool = {
8
+ name: "get_shelby_agent_key_info",
9
+ description: "Describe the configured agent key: its name, expiry, whether it's read-only, the projects and buckets it reaches, and the local directories this MCP may use. Never returns the key itself.",
10
+ parameters: EmptyToolScheme,
11
+ execute: () => run("Failed to read the agent key", async () => {
12
+ const catalog = await loadCatalog(new ShelbyAdmin());
13
+ const scope = catalog.key?.scope;
14
+ return {
15
+ name: catalog.key?.name,
16
+ display_prefix: catalog.key?.display_prefix,
17
+ expires_at: catalog.key
18
+ ? (catalog.key.expires_at ?? "never")
19
+ : undefined,
20
+ kind: catalog.legacy ? "unscoped bot key" : "agent key",
21
+ scope: scope?.scope_type,
22
+ permission: catalog.legacy
23
+ ? "read-write (management only)"
24
+ : catalog.readOnly
25
+ ? "read-only"
26
+ : "read-write",
27
+ whole_projects: catalog.creatableProjects.map(place),
28
+ buckets: catalog.buckets.map((b) => ({ name: b.name, ...place(b) })),
29
+ allowed_dirs: config.allowedDirs,
30
+ };
31
+ }),
32
+ };
@@ -0,0 +1,69 @@
1
+ import { basename } from "node:path";
2
+ import { config } from "../config.js";
3
+ import { findBucket, loadCatalog } from "../services/catalog.js";
4
+ import { ShelbyAccount } from "../services/ShelbyAccount.js";
5
+ import { ShelbyAdmin } from "../services/ShelbyAdmin.js";
6
+ import { ShelbyObjects } from "../services/ShelbyObjects.js";
7
+ import { LEGACY_KEY_DATA_MESSAGE } from "../utils/errors.js";
8
+ import { AllowedDirs } from "../utils/paths.js";
9
+ import { accountScope, place } from "./buckets.js";
10
+ import { run } from "./run.js";
11
+ import { DownloadObjectToolScheme, ListObjectsToolScheme, UploadObjectToolScheme, } from "./schemas.js";
12
+ const allowedDirs = new AllowedDirs(config.allowedDirs);
13
+ async function resolveTarget({ bucket, project, organization }, { write }) {
14
+ const catalog = await loadCatalog(new ShelbyAdmin());
15
+ if (catalog.legacy)
16
+ throw new Error(LEGACY_KEY_DATA_MESSAGE);
17
+ if (write && catalog.readOnly) {
18
+ throw new Error("This agent key is read-only, so it can't upload.");
19
+ }
20
+ const record = findBucket(catalog, bucket, { project, organization });
21
+ const account = await new ShelbyAccount().getAccount(accountScope(record));
22
+ const target = {
23
+ applicationId: record.application_id,
24
+ bucketAddress: account.accountAddress,
25
+ };
26
+ return { record, target };
27
+ }
28
+ export const listObjectsTool = {
29
+ name: "list_shelby_objects",
30
+ description: "List objects in a Shelby bucket, optionally under a prefix. Pages of up to 1000; pass next_continuation_token to get the next page.",
31
+ parameters: ListObjectsToolScheme,
32
+ execute: ({ prefix, delimiter, continuation_token, max_keys, ...ref }) => run("Failed to list objects", async () => {
33
+ const { record, target } = await resolveTarget(ref, { write: false });
34
+ const listed = await new ShelbyObjects().list(target, {
35
+ prefix,
36
+ delimiter,
37
+ continuationToken: continuation_token,
38
+ maxKeys: max_keys,
39
+ });
40
+ return { bucket: record.name, ...place(record), ...listed };
41
+ }),
42
+ };
43
+ export const uploadObjectTool = {
44
+ 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
+ parameters: UploadObjectToolScheme,
47
+ execute: ({ local_path, key, content_type, ...ref }) => run("Failed to upload", async () => {
48
+ const file = await allowedDirs.readableFile(local_path);
49
+ const { record, target } = await resolveTarget(ref, { write: true });
50
+ const uploaded = await new ShelbyObjects().upload(target, key ?? basename(file), file, content_type);
51
+ return { bucket: record.name, ...place(record), ...uploaded };
52
+ }),
53
+ };
54
+ export const downloadObjectTool = {
55
+ 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
+ parameters: DownloadObjectToolScheme,
58
+ execute: ({ key, local_path, overwrite, ...ref }) => run("Failed to download", async () => {
59
+ const destination = await allowedDirs.writableFile(local_path ?? (key.split("/").pop() || key), overwrite ?? false);
60
+ const { record, target } = await resolveTarget(ref, { write: false });
61
+ const downloaded = await new ShelbyObjects().download(target, key, destination);
62
+ return {
63
+ bucket: record.name,
64
+ ...place(record),
65
+ ...downloaded,
66
+ local_path: destination,
67
+ };
68
+ }),
69
+ };
@@ -0,0 +1,25 @@
1
+ import { redactAgentKey } from "../services/agentKey.js";
2
+ import { expiryWarning } from "../services/catalog.js";
3
+ import { formatError } from "../utils/errors.js";
4
+ /**
5
+ * Run a tool, turning a failure into a message for the agent. Every result passes
6
+ * through `redactAgentKey`, so neither output nor errors can carry the key. When the
7
+ * key expires soon, a second text block warns about it, leaving the first one as is.
8
+ */
9
+ export async function run(failure, body) {
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
+ };
25
+ }
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { BUCKET_NAME_RULES, isValidBucketName } from "../utils/bucketName.js";
3
+ const resourceName = z
4
+ .string()
5
+ .regex(/^[a-z0-9_-]{3,32}$/, "Must be 3-32 characters: lowercase letters, numbers, dashes and underscores.");
6
+ const placement = {
7
+ project: z
8
+ .string()
9
+ .optional()
10
+ .describe("The project name. Only needed when the key reaches several buckets with the same name, or several projects to create in."),
11
+ organization: z
12
+ .string()
13
+ .optional()
14
+ .describe("The organization name. Only needed for unscoped bot keys that reach several organizations."),
15
+ };
16
+ export const EmptyToolScheme = z.object({});
17
+ export const BucketRefToolScheme = z.object({
18
+ bucket: z
19
+ .string()
20
+ .describe("The bucket name, as shown by list_shelby_buckets."),
21
+ ...placement,
22
+ });
23
+ export const CreateBucketToolScheme = z.object({
24
+ name: z
25
+ .string()
26
+ .refine(isValidBucketName, `Invalid bucket name. Must be ${BUCKET_NAME_RULES}`)
27
+ .describe(`The bucket name, which is also its S3 bucket name. Must be ${BUCKET_NAME_RULES}.`),
28
+ ...placement,
29
+ api_key_name: resourceName
30
+ .optional()
31
+ .describe("Unscoped bot keys only: name of the API key created with the bucket. Defaults to 'api-key-01'."),
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
+ export const ListObjectsToolScheme = BucketRefToolScheme.extend({
37
+ prefix: z.string().optional().describe("Only list keys starting with this."),
38
+ delimiter: z
39
+ .string()
40
+ .optional()
41
+ .describe('Group keys by this, usually "/", to list one level at a time.'),
42
+ continuation_token: z
43
+ .string()
44
+ .optional()
45
+ .describe("next_continuation_token from the previous page."),
46
+ max_keys: z.number().int().min(1).max(1000).optional(),
47
+ });
48
+ export const UploadObjectToolScheme = BucketRefToolScheme.extend({
49
+ local_path: z
50
+ .string()
51
+ .describe("The file to upload. Relative paths start at the first allowed directory."),
52
+ key: z
53
+ .string()
54
+ .optional()
55
+ .describe("The object key. Defaults to the file's name."),
56
+ content_type: z.string().optional(),
57
+ });
58
+ export const DownloadObjectToolScheme = BucketRefToolScheme.extend({
59
+ key: z.string().describe("The object key to download."),
60
+ local_path: z
61
+ .string()
62
+ .optional()
63
+ .describe("Where to save it. Relative paths start at the first allowed directory. Defaults to the key's last segment."),
64
+ overwrite: z
65
+ .boolean()
66
+ .optional()
67
+ .describe("Replace an existing file. Defaults to false."),
68
+ });
69
+ export const S3GuideToolScheme = z.object({
70
+ bucket: z
71
+ .string()
72
+ .optional()
73
+ .describe("The bucket's S3 bucket name (`s3_bucket` from list/get/create). Filled into the sample code when provided."),
74
+ });
@@ -0,0 +1,33 @@
1
+ const RESERVED_PREFIXES = ["xn--", "sthree-", "amzn-s3-demo-"];
2
+ const RESERVED_NAMES = ["health", "ready", "metrics", "internal"];
3
+ const RESERVED_SUFFIXES = [
4
+ "-s3alias",
5
+ "--ol-s3",
6
+ "--x-s3",
7
+ "--table-s3",
8
+ "-an",
9
+ ];
10
+ export const BUCKET_NAME_RULES = "3-32 characters: lowercase letters, numbers and dashes, starting and ending with a letter or number, with at least one letter. Must not look like an account address (0x followed by hex) or use an AWS-reserved prefix (xn--, sthree-, amzn-s3-demo-) or suffix (-s3alias, --ol-s3, --x-s3, --table-s3, -an). health, ready, metrics and internal are reserved";
11
+ /**
12
+ * A bucket's name is also its S3 bucket name. Mirrors `validateBucketAlias` in the s3-gateway
13
+ * admin-api, which rejects anything that fails here, plus the API Gateway's application name rules.
14
+ */
15
+ export function isValidBucketName(name) {
16
+ if (!/^[a-z0-9][a-z0-9-]{1,30}[a-z0-9]$/.test(name))
17
+ return false;
18
+ if (!/[a-z]/.test(name))
19
+ return false;
20
+ if (/^0x[0-9a-f]+$/.test(name))
21
+ return false;
22
+ if (RESERVED_NAMES.includes(name))
23
+ return false;
24
+ if (RESERVED_PREFIXES.some((prefix) => name.startsWith(prefix)))
25
+ return false;
26
+ return !RESERVED_SUFFIXES.some((suffix) => name.endsWith(suffix));
27
+ }
28
+ /** The S3 `Bucket` value for an account: its name, or its address when the name isn't a valid bucket name. */
29
+ export function s3BucketOf(account) {
30
+ return account.name && isValidBucketName(account.name)
31
+ ? account.name
32
+ : account.accountAddress;
33
+ }