### Install and Run mcp-server-s3 Source: https://github.com/ofershap/mcp-server-s3/blob/main/README.md Install and run the mcp-server-s3 tool using npx. This command is used to start the server for AI assistant integration. Ensure your AWS credentials are set up. ```bash npx mcp-server-s3 ``` -------------------------------- ### Example JSON Configuration Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/INDEX.md An example of a JSON object used for configuration or requests, specifying a bucket name and a file key. ```json { "bucket": "my-bucket", "key": "file.txt" } ``` -------------------------------- ### JSON-RPC 2.0 Example Request Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md An example of a JSON-RPC 2.0 request message format used for client-server communication. This specific request is for calling a tool named 'list_buckets'. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "list_buckets" } } ``` -------------------------------- ### JSON: Success Response for list_objects Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a successful response from the list_objects tool, detailing objects and prefixes with metadata. ```json { "content": [ { "type": "text", "text": "Objects in s3://my-bucket/ (max 100):\n\n šŸ“ data/\n šŸ“ uploads/\n šŸ“„ readme.txt (256 B) — 2024-01-15T10:30:00.000Z\n šŸ“„ config.json (1024 B) — 2024-01-20T14:22:00.000Z" } ] } ``` -------------------------------- ### JSON-RPC 2.0 Example Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md An example of a JSON-RPC 2.0 response message format. This response indicates a successful call, returning a list of buckets. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "Buckets (2):\n • bucket-a\n • bucket-b" } ] } } ``` -------------------------------- ### bucket_info Success Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a successful response from the bucket_info tool, indicating the bucket name, its existence, and the region. ```json { "content": [ { "type": "text", "text": "Bucket: my-bucket\nāœ… Exists\nRegion: us-east-1" } ] } ``` -------------------------------- ### List S3 Buckets (TypeScript) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/INDEX.md Demonstrates how to import and use the `listBuckets` function to retrieve a list of S3 buckets. Ensure the `mcp-server-s3` package is installed. ```typescript import { listBuckets } from "mcp-server-s3"; const buckets = await listBuckets(); ``` -------------------------------- ### bucket_info Failure Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a failure response from the bucket_info tool, indicating that the bucket was not found or is inaccessible. ```json { "content": [ { "type": "text", "text": "Bucket: nonexistent-bucket\nāŒ Not found / no access" } ] } ``` -------------------------------- ### MCP Client Response for list_buckets Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of an MCP client receiving a response after calling the 'list_buckets' tool. This shows the structure of a successful result. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "Buckets (3):\n\n • my-data-bucket\n • backup-storage\n • logs-archive" } ] } } ``` -------------------------------- ### Configure Programmatic AWS Access Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md This bash example demonstrates setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION environment variables for programmatic authentication before running mcp-server-s3. ```bash export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY export AWS_REGION=us-east-1 npx mcp-server-s3 ``` -------------------------------- ### JSON: Error Response for list_objects Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of an error response from the list_objects tool, indicating an issue such as a non-existent bucket. ```json { "content": [ { "type": "text", "text": "Error: NoSuchBucket" } ], "isError": true } ``` -------------------------------- ### Development Commands for mcp-server-s3 Source: https://github.com/ofershap/mcp-server-s3/blob/main/README.md Common development commands for the mcp-server-s3 project, including installing dependencies, type checking, building, testing, formatting, and linting. ```bash npm install ``` ```bash npm run typecheck ``` ```bash npm run build ``` ```bash npm test ``` ```bash npm run format ``` ```bash npm run lint ``` -------------------------------- ### put_object Success Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a successful response from the put_object tool, confirming the upload. ```json { "content": [ { "type": "text", "text": "āœ… Uploaded 145 bytes to s3://my-bucket/documents/notes.txt" } ] } ``` -------------------------------- ### list_buckets Tool Success Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a successful response from the 'list_buckets' tool. The content field contains a text representation of the buckets and their creation dates. ```json { "content": [ { "type": "text", "text": "Buckets (2):\n\n • bucket-a (created: 2024-01-01T00:00:00.000Z)\n • bucket-b (created: 2024-02-01T00:00:00.000Z)" } ] } ``` -------------------------------- ### Define presigned_url tool Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Defines the presigned_url tool with its signature, parameters, and asynchronous handler. This setup is required for the tool to be available within the MCP server. ```typescript server.tool( "presigned_url", "Generate a presigned URL for temporary access to an S3 object.", { bucket: z.string().describe("Bucket name"), key: z.string().describe("Object key"), expiresIn: z .number() .int() .min(60) .max(604800) .default(3600) .describe("URL expiry in seconds (default: 1 hour)"), }, async ({ bucket, key, expiresIn }) => {...} ) ``` -------------------------------- ### Run Server with EU Region Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md Example of setting the AWS_REGION environment variable to 'eu-central-1' before running the mcp-server-s3 application. ```bash # Run server with EU region export AWS_REGION=eu-central-1 npx mcp-server-s3 ``` -------------------------------- ### MCP Client Call: put_object (plain text) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of calling the put_object tool from an MCP client with default content type. ```json { "jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": { "name": "put_object", "arguments": { "bucket": "my-bucket", "key": "notes.txt", "content": "Hello, S3!" } } } ``` -------------------------------- ### Success Response for presigned_url Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a successful response from the presigned_url tool, containing the generated presigned URL. The URL includes necessary AWS signature parameters for temporary access. ```json { "content": [ { "type": "text", "text": "Presigned URL for s3://my-bucket/document.pdf (valid ~1h):\n\nhttps://my-bucket.s3.us-east-1.amazonaws.com/document.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=..." } ] } ``` -------------------------------- ### MCP Client Call for delete_object Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of how an MCP client would call the delete_object tool, specifying the tool name and arguments. ```json { "jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": { "name": "delete_object", "arguments": { "bucket": "my-bucket", "key": "archive/old-backup.tar.gz" } } } ``` -------------------------------- ### Run Server with US West Region Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md Example of setting the AWS_REGION environment variable to 'us-west-2' before running the mcp-server-s3 application. ```bash # Run server with US West region export AWS_REGION=us-west-2 npx mcp-server-s3 ``` -------------------------------- ### MCP Client Call: put_object (JSON) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of calling the put_object tool from an MCP client with an explicit JSON content type. ```json { "jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": { "name": "put_object", "arguments": { "bucket": "my-bucket", "key": "config.json", "content": "{\"name\": \"Alice\", \"age\": 30}", "contentType": "application/json" } } } ``` -------------------------------- ### JSON: MCP Client Call - List Top-Level Items Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md An example JSON-RPC call to the MCP client to list top-level items in an S3 bucket using the list_objects tool with default settings. ```json { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "list_objects", "arguments": { "bucket": "my-bucket" } } } ``` -------------------------------- ### JSON: MCP Client Call - List Items in Prefix with Custom Limit Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md An example JSON-RPC call to the MCP client to list items within a specific prefix in an S3 bucket, with a custom limit on the number of results. ```json { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "list_objects", "arguments": { "bucket": "my-bucket", "prefix": "data/documents/", "maxKeys": 50 } } } ``` -------------------------------- ### list_buckets Tool Failure Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of an error response from the 'list_buckets' tool. The 'isError' flag is set to true, and the content field contains an error message. ```json { "content": [ { "type": "text", "text": "Error: InvalidAccessKeyId" } ], "isError": true } ``` -------------------------------- ### Using mcp-server-s3 as a Library Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md Demonstrates how to import and use functions like listBuckets, listObjects, and getObject from the mcp-server-s3 library to interact with S3. ```typescript import { listBuckets, listObjects, getObject } from "mcp-server-s3"; // List buckets const buckets = await listBuckets(); console.log(`Found ${buckets.length} buckets`); // List objects const objects = await listObjects("my-bucket", "data/"); objects.forEach(obj => { console.log(obj.key); }); // Get object const content = await getObject("my-bucket", "config.json"); const config = JSON.parse(content); ``` -------------------------------- ### Initialize McpServer with Metadata Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md Initializes the MCP server with its name and version. This metadata is used for server identification. ```typescript new McpServer({ name: "mcp-server-s3", version: "1.0.0", }) ``` -------------------------------- ### put_object Failure Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of an error response from the put_object tool. ```json { "content": [ { "type": "text", "text": "Error: AccessDenied" } ], "isError": true } ``` -------------------------------- ### Running mcp-server-s3 as an MCP Server Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md Shows how to configure and run mcp-server-s3 as an MCP server using environment variables and the npx command. The server listens on stdio for JSON-RPC tool calls. ```bash # Configure in Claude Desktop, Cursor, or VS Code export AWS_REGION=us-east-1 export AWS_ACCESS_KEY_ID=AKIA... export AWS_SECRET_ACCESS_KEY=... npx mcp-server-s3 ``` -------------------------------- ### Call bucket_info Tool via MCP Client Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Demonstrates how to call the bucket_info tool using the MCP client's 'tools/call' method. The 'arguments' object must include the 'bucket' parameter. ```json { "jsonrpc": "2.0", "id": 11, "method": "tools/call", "params": { "name": "bucket_info", "arguments": { "bucket": "my-bucket" } } } ``` -------------------------------- ### Delete Object Success Response Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Example of a successful response when an object is deleted from an S3 bucket. ```json { "content": [ { "type": "text", "text": "āœ… Deleted s3://my-bucket/old-file.txt" } ] } ``` -------------------------------- ### List Objects and Differentiate Folders/Files Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/types.md Fetches items from a specified bucket and prefix, then logs whether each item is a folder or a file, along with its details. Requires `listObjects` to be imported. ```typescript import { listObjects } from "./s3.js"; const items = await listObjects("my-bucket", "data/"); items.forEach(item => { if (item.isPrefix) { console.log(`šŸ“ Folder: ${item.key}`); } else { console.log(`šŸ“„ File: ${item.key}`); console.log(` Size: ${item.size} bytes`); console.log(` Modified: ${item.lastModified?.toISOString()}`); } }); ``` -------------------------------- ### List Buckets and Log Info Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/types.md Fetches a list of buckets and iterates through them, logging their names and creation dates if available. Ensure `listBuckets` is imported. ```typescript import { listBuckets } from "./s3.js"; const buckets = await listBuckets(); buckets.forEach(bucket => { console.log(`Bucket: ${bucket.name}`); if (bucket.creationDate) { console.log(`Created: ${bucket.creationDate.toISOString()}`); } }); ``` -------------------------------- ### Configure mcp-server-s3 for Claude Desktop Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md Add this configuration to `claude_desktop_config.json` to launch mcp-server-s3. Ensure AWS credentials and region are correctly set in the `env` object. ```json { "mcpServers": { "s3": { "command": "npx", "args": ["mcp-server-s3"], "env": { "AWS_REGION": "us-east-1", "AWS_ACCESS_KEY_ID": "your-access-key-id", "AWS_SECRET_ACCESS_KEY": "your-secret-access-key" } } } } ``` -------------------------------- ### Get Object Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/README.md Downloads the contents of an S3 object as text. This function can be called directly or via the `get_object` tool. ```APIDOC ## getObject(bucketName, objectKey) ### Description Downloads the contents of an S3 object as text. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters #### Path Parameters - **bucketName** (string) - Required - The name of the bucket containing the object. - **objectKey** (string) - Required - The key (path) of the object to download. ### Request Example ```javascript await getObject('my-bucket', 'data/file1.txt'); ``` ### Response #### Success Response - **content** (string) - The text content of the object. ### Response Example ```json { "content": "This is the content of the file." } ``` ``` -------------------------------- ### Set AWS Region and Run MCP Server (Bash) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/INDEX.md Shows how to set the AWS region environment variable and then run the MCP server using npx. This is typically used for local development or testing. ```bash export AWS_REGION=us-east-1 npx mcp-server-s3 ``` -------------------------------- ### Run MCP Server Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md Initializes and connects the MCP server using a StdioServerTransport. This code runs the server directly and is not exported as a named function. It includes basic error handling for fatal errors. ```typescript async function main() { const transport = new StdioServerTransport(); await server.connect(transport); } main().catch((err) => { console.error("Fatal error:", err); process.exit(1); }); ``` -------------------------------- ### Out-of-Range Parameter Example Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Illustrates an out-of-range parameter error where a numeric value exceeds the allowed bounds. This is also handled by Zod validation. ```json { "name": "list_objects", "arguments": { "bucket": "my-bucket", "maxKeys": 2000 } } ``` ```json { "content": [ { "type": "text", "text": "Error: Number must be less than or equal to 1000" } ], "isError": true } ``` -------------------------------- ### MCP Client Call: presigned_url (default expiry) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Demonstrates how to call the presigned_url tool using the MCP client with default expiry time (1 hour). This is the simplest way to obtain a presigned URL. ```json { "jsonrpc": "2.0", "id": 8, "method": "tools/call", "params": { "name": "presigned_url", "arguments": { "bucket": "my-bucket", "key": "documents/report.pdf" } } } ``` -------------------------------- ### Invalid Parameter Type Example Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Demonstrates an invalid parameter type error where a string is provided for a numeric argument. This is caught by Zod validation. ```json { "name": "list_objects", "arguments": { "bucket": "my-bucket", "maxKeys": "not-a-number" } } ``` ```json { "content": [ { "type": "text", "text": "Error: Expected number, received string" } ], "isError": true } ``` -------------------------------- ### Package JSON Bin Field Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md The 'bin' field in package.json specifies the executable entry point for the package. This allows the package to be run directly using npx. ```json { "bin": { "mcp-server-s3": "./dist/index.js" } } ``` -------------------------------- ### presigned_url Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Generates a temporary presigned URL for accessing an S3 object. This URL allows read-only GET access and can be shared for temporary public access. ```APIDOC ## presigned_url ### Description Generates a temporary presigned URL for accessing an S3 object without requiring AWS credentials. The URL is valid for read-only GET access and can be shared for temporary public access. ### Method server.tool("presigned_url", "Generate a presigned URL for temporary access to an S3 object.", { bucket: z.string().describe("Bucket name"), key: z.string().describe("Object key"), expiresIn: z.number().int().min(60).max(604800).default(3600).describe("URL expiry in seconds (default: 1 hour)") }, async ({ bucket, key, expiresIn }) => {...}) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | bucket | string | Yes | — | S3 bucket name | | key | string | Yes | — | Object key to generate a presigned URL for | | expiresIn | number | No | 3600 | URL expiry duration in seconds. Minimum 60 (1 minute), maximum 604800 (7 days). | ### Request Schema ```json { "bucket": "string", "key": "string", "expiresIn": "number" } ``` ### Response #### Success Response **Success**: A presigned HTTPS URL with the expiry duration noted. ```json { "content": [ { "type": "text", "text": "Presigned URL for s3://my-bucket/document.pdf (valid ~1h):\n\nhttps://my-bucket.s3.us-east-1.amazonaws.com/document.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=..." } ] } ``` #### Error Response **Failure**: An error response. ```json { "content": [ { "type": "text", "text": "Error: NoSuchBucket" } ], "isError": true } ``` ### Error Conditions | Condition | Error Message | |-----------|---------------| | Bucket does not exist | NoSuchBucket | | Missing `s3:GetObject` permission | AccessDenied | | expiresIn < 60 or > 604800 | Zod validation error | ### Example Usage **MCP Client Call** (1 hour expiry, the default): ```json { "jsonrpc": "2.0", "id": 8, "method": "tools/call", "params": { "name": "presigned_url", "arguments": { "bucket": "my-bucket", "key": "documents/report.pdf" } } } ``` **MCP Client Call** (15 minutes expiry): ```json { "jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { "name": "presigned_url", "arguments": { "bucket": "my-bucket", "key": "documents/report.pdf", "expiresIn": 900 } } } ``` **MCP Client Call** (7 days expiry): ```json { "jsonrpc": "2.0", "id": 10, "method": "tools/call", "params": { "name": "presigned_url", "arguments": { "bucket": "my-bucket", "key": "documents/report.pdf", "expiresIn": 604800 } } } ``` ``` -------------------------------- ### MCP Client Call: presigned_url (15 minutes expiry) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Shows how to call the presigned_url tool with a custom expiry time of 15 minutes (900 seconds). This allows for shorter access periods when needed. ```json { "jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { "name": "presigned_url", "arguments": { "bucket": "my-bucket", "key": "documents/report.pdf", "expiresIn": 900 } } } ``` -------------------------------- ### MCP Server S3 Project Structure Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md Illustrates the directory and file organization of the mcp-server-s3 project. Key files include source code, tests, build configurations, and documentation. ```tree mcp-server-s3/ ā”œā”€ā”€ src/ │ ā”œā”€ā”€ index.ts # MCP server and tool definitions │ └── s3.ts # AWS S3 core functions ā”œā”€ā”€ tests/ │ └── s3.test.ts # Vitest test suite ā”œā”€ā”€ dist/ # Compiled output (generated) ā”œā”€ā”€ package.json # npm package metadata ā”œā”€ā”€ tsconfig.json # TypeScript configuration ā”œā”€ā”€ tsup.config.ts # Build configuration ā”œā”€ā”€ vitest.config.ts # Test runner configuration └── README.md # User documentation ``` -------------------------------- ### Custom S3 Error Handling Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md Example of a custom error thrown for a defensive check within the S3 core layer. AWS SDK errors are generally propagated directly. ```typescript // Custom error if (!body) { throw new Error(`Object ${key} has no body`); } ``` -------------------------------- ### Configure mcp-server-s3 for VS Code Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md Configure mcp-server-s3 in `.vscode/settings.json` or via the VS Code extension settings. This JSON structure defines the server's name, command, arguments, and environment variables. ```json { "mcpServers": [ { "name": "s3", "command": "npx", "args": ["mcp-server-s3"], "env": { "AWS_REGION": "us-east-1", "AWS_ACCESS_KEY_ID": "your-access-key-id", "AWS_SECRET_ACCESS_KEY": "your-secret-access-key" } } ] } ``` -------------------------------- ### Get S3 Object Content Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-s3-core.md Reads the entire contents of an S3 object as a UTF-8 string. Rejects if the object does not exist, the caller lacks `s3:GetObject` permission, or if the object has no body. ```typescript export async function getObject(bucket: string, key: string): Promise ``` ```typescript import { getObject } from "./s3.js"; try { const config = await getObject("my-bucket", "config.json"); const parsed = JSON.parse(config); console.log(parsed); } catch (err) { console.error("Failed to download config:", err); } ``` -------------------------------- ### Enable AWS SDK Debugging Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Enable verbose logging from the AWS SDK to see all HTTP requests and responses. This is useful for diagnosing issues. ```bash export DEBUG=* npx mcp-server-s3 ``` -------------------------------- ### Handle SignatureDoesNotMatch Error Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Catch and handle the SignatureDoesNotMatch error when the AWS secret access key is incorrect or the request has been tampered with. This is vital for ensuring request integrity and correct credential setup. ```typescript import { listBuckets } from "./s3.js"; try { await listBuckets(); } catch (err: unknown) { const error = err as { Code?: string }; if (error.Code === "SignatureDoesNotMatch") { console.error("Invalid AWS secret key. Check AWS_SECRET_ACCESS_KEY."); } else { console.error("Error:", err); } } ``` -------------------------------- ### Test S3 Permissions with AWS CLI Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Use the AWS CLI to test basic S3 permissions. If these commands fail, the MCP server will likely encounter the same issues. ```bash aws s3 ls aws s3api head-bucket --bucket my-bucket ``` -------------------------------- ### Check Credentials Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Verify that your AWS access key ID and region are correctly set in your environment variables. Do not echo the secret access key for security reasons. ```bash echo "AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID" echo "AWS_REGION: $AWS_REGION" # Do NOT echo AWS_SECRET_ACCESS_KEY for security ``` -------------------------------- ### Define bucket_info Tool Signature Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Defines the signature for the bucket_info tool, specifying its name, description, request schema, and implementation. The request schema requires a 'bucket' string. ```typescript server.tool( "bucket_info", "Check if a bucket exists and get basic info.", { bucket: z.string().describe("Bucket name"), }, async ({ bucket }) => {...} ) ``` -------------------------------- ### Handling 'Object Body Missing' Error Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md Example of how to catch and specifically handle the custom 'Object Body Missing' error when calling the getObject function. It differentiates between the custom error and other potential errors. ```typescript import { getObject } from "./s3.js"; try { const content = await getObject("my-bucket", "file.txt"); } catch (err) { if (err instanceof Error && err.message.includes("no body")) { console.error("Object exists but has no content"); } else { console.error("Failed to get object:", err); } } ``` -------------------------------- ### MCP Client-Server Communication Diagram Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md Illustrates the communication flow between an MCP Client and the MCP Server (mcp-server-s3) using JSON-RPC 2.0 over stdin/stdout. ```text ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ MCP Client │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ │ │ (stdin/stdout) │ JSON-RPC 2.0 │ ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ MCP Server │ │ (mcp-server-s3) │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ``` -------------------------------- ### Register list_buckets Tool Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Registers the 'list_buckets' tool with the McpServer. This tool requires no input parameters and is used to list all S3 buckets in the AWS account. ```typescript server.tool( "list_buckets", "List all S3 buckets in your AWS account.", {}, async () => {...} ) ``` -------------------------------- ### Handle S3 Errors in TypeScript Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/errors.md When using S3 core functions, narrow down error types to handle custom, AWS SDK, or unknown errors gracefully. This example demonstrates checking for specific error messages and AWS SDK error codes. ```typescript import { getObject } from "./s3.js"; try { const content = await getObject("bucket", "key"); } catch (err) { // Narrow the error type if (err instanceof Error) { if (err.message.includes("no body")) { // Handle custom error console.error("Object has no content"); } else if ("Code" in err) { // Handle AWS SDK error const awsErr = err as { Code?: string; Message?: string }; console.error(`AWS Error (${awsErr.Code}): ${awsErr.Message}`); } else { // Handle unknown error console.error("Unknown error:", err.message); } } else { console.error("Non-Error thrown:", err); } } ``` -------------------------------- ### List S3 Buckets Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-s3-core.md Lists all S3 buckets in the AWS account. Rejects if credentials are invalid or the account lacks `s3:ListBuckets` permission. ```typescript export async function listBuckets(): Promise ``` ```typescript import { listBuckets } from "./s3.js"; const buckets = await listBuckets(); buckets.forEach(b => { console.log(`${b.name} - created ${b.creationDate?.toISOString()}`); }); ``` -------------------------------- ### listBuckets Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md Lists all S3 buckets in the account. Returns an array of BucketInfo objects. ```APIDOC ## listBuckets ### Description List all S3 buckets in the account. ### Signature `listBuckets(): Promise` ### Returns Array of buckets ``` -------------------------------- ### Configure Cursor for mcp-server-s3 Source: https://github.com/ofershap/mcp-server-s3/blob/main/README.md Configure Cursor to use mcp-server-s3 by adding the server details to your .cursor/mcp.json file. This includes the command to run, arguments, and environment variables like AWS_REGION and credentials. ```json { "mcpServers": { "s3": { "command": "npx", "args": ["mcp-server-s3"], "env": { "AWS_REGION": "us-east-1", "AWS_ACCESS_KEY_ID": "your-access-key", "AWS_SECRET_ACCESS_KEY": "your-secret-key" } } } } ``` -------------------------------- ### listObjects Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-s3-core.md Lists objects in an S3 bucket, optionally filtered by a key prefix and respecting a maximum count. Returns both objects and virtual folders (common prefixes). Errors are thrown if the bucket does not exist or permissions are insufficient. ```APIDOC ## listObjects ### Description Lists objects in an S3 bucket, optionally filtered by a key prefix and respecting a maximum count. Returns both objects and virtual folders (common prefixes). ### Method Not applicable (SDK function) ### Endpoint Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters - **bucket** (string) - Required - Bucket name - **prefix** (string) - Optional - Filter results to keys starting with this string (e.g. `'uploads/'`). Delimiter `/` is applied automatically for hierarchical browsing. - **maxKeys** (number) - Optional - Default: 100 - Maximum number of objects+prefixes to return (1–1000). The API enforces a hard cap of 1000. ### Response #### Success Response - **ObjectInfo[]** — An array of objects and common prefixes sorted in the response order. Empty array if bucket is empty or no results match the prefix. ### Throws - AWS SDK error if the bucket does not exist or the caller lacks `s3:ListBucket` and `s3:GetObject` permissions. ``` -------------------------------- ### Configure Stdio Transport for MCP Communication Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/configuration.md Sets up the server to use stdio transport for MCP communication. Clients send requests via stdin and receive responses via stdout, with JSON-RPC messages exchanged line-by-line. ```typescript const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Import from NPM Package Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md Import core S3 functions and types directly from the 'mcp-server-s3' NPM package. ```typescript import { listBuckets, listObjects, getObject, putObject, deleteObject, presignedUrl, bucketInfo, type BucketInfo, type ObjectInfo, type BucketDetails, } from "mcp-server-s3"; ``` -------------------------------- ### Add Custom S3 Operation Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md Demonstrates the steps to add a new S3 operation. This involves defining the core function, exporting necessary types, registering the tool with the server, and adding corresponding tests. ```typescript // 1. Add S3 core function in s3.ts export async function customOperation(): Promise { const client = createClient(); const result = await client.send(new CustomCommand(...)); return transformResult(result); } // 2. Export type (if needed) export interface CustomResult { ... } // 3. Register tool in index.ts server.tool("custom_operation", "...", { schema }, async (args) => { try { const result = await customOperation(); return { content: [{ type: "text", text: formatResult(result) }] }; } catch (err) { return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true }; } }); // 4. Add tests in s3.test.ts ``` -------------------------------- ### TypeScript: Define list_objects tool Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Defines the list_objects tool with its signature, description, and argument schema. This is used for server-side implementation. ```typescript server.tool( "list_objects", "List objects in an S3 bucket. Optionally filter by prefix and limit count.", { bucket: z.string().describe("Bucket name"), prefix: z.string().optional().describe("Key prefix (e.g. 'uploads/')"), maxKeys: z .number() .int() .min(1) .max(1000) .default(100) .describe("Max objects to return"), }, async ({ bucket, prefix, maxKeys }) => {...} ) ``` -------------------------------- ### Import from Local Source (Development) Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/module-exports-index.md Import S3 core functions and types from local source files during development. Supports importing from './src/s3.js' or the main entry point './src/index.js'. ```typescript // S3 core functions and types import { listBuckets, listObjects, getObject, putObject, deleteObject, presignedUrl, bucketInfo, type BucketInfo, type ObjectInfo, type BucketDetails, } from "./src/s3.js"; // Or from entry point (includes everything) import { listBuckets, listObjects, getObject, putObject, deleteObject, presignedUrl, bucketInfo, type ObjectInfo, } from "./src/index.js"; ``` -------------------------------- ### BucketInfo Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/types.md Represents a summary of an S3 bucket returned by `listBuckets()`. It includes the bucket's name and optionally its creation date. ```APIDOC ## BucketInfo ### Description Represents a summary of an S3 bucket returned by `listBuckets()`. ### Fields - **name** (string) - Required - The name of the bucket (e.g., `my-data-bucket`) - **creationDate** (Date) - Optional - The date and time when the bucket was created. If omitted, the creation date was not available in the API response. ### Used By - `listBuckets()` — returns `Promise` ### Example ```typescript import { listBuckets } from "./s3.js"; const buckets = await listBuckets(); buckets.forEach(bucket => { console.log(`Bucket: ${bucket.name}`); if (bucket.creationDate) { console.log(`Created: ${bucket.creationDate.toISOString()}`); } }); ``` ``` -------------------------------- ### ObjectInfo Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/types.md Represents either an S3 object or a common prefix (virtual folder) returned by `listObjects()`. It includes the key, size, last modified date, and a flag indicating if it's a prefix. ```APIDOC ## ObjectInfo ### Description Represents either an S3 object or a common prefix (virtual folder) returned by `listObjects()`. ### Fields - **key** (string) - Required - The object key or prefix path (e.g., `uploads/` for a folder or `config.json` for a file) - **size** (number) - Optional - The size of the object in bytes. Only present for actual objects, not for common prefixes. - **lastModified** (Date) - Optional - The date and time when the object was last modified. Only present for actual objects, not for common prefixes. - **isPrefix** (boolean) - Optional - True if this item is a common prefix (virtual folder), false if it is an actual object. Defaults to false. ### Semantics - If `isPrefix: true`, the item represents a virtual directory. `size` and `lastModified` are not present. - If `isPrefix: false` or not present, the item represents an actual S3 object. `size` and `lastModified` may be present. ### Used By - `listObjects()` — returns `Promise` ### Example ```typescript import { listObjects } from "./s3.js"; const items = await listObjects("my-bucket", "data/"); items.forEach(item => { if (item.isPrefix) { console.log(`šŸ“ Folder: ${item.key}`); } else { console.log(`šŸ“„ File: ${item.key}`); console.log(` Size: ${item.size} bytes`); console.log(` Modified: ${item.lastModified?.toISOString()}`); } }); ``` ``` -------------------------------- ### list_buckets Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md Lists all S3 buckets in your AWS account. This tool accepts no input parameters. ```APIDOC ## list_buckets ### Description Lists all S3 buckets in your AWS account. ### Signature ```typescript server.tool( "list_buckets", "List all S3 buckets in your AWS account.", {}, async () => {} ) ``` ### Parameters None. This tool accepts no input parameters. ### Request Schema ```typescript {} ``` No parameters required. ### Response **Success**: A text response containing the list of buckets with creation dates. ```json { "content": [ { "type": "text", "text": "Buckets (2):\n\n • bucket-a (created: 2024-01-01T00:00:00.000Z)\n • bucket-b (created: 2024-02-01T00:00:00.000Z)" } ] } ``` **Failure**: An error response with the error message. ```json { "content": [ { "type": "text", "text": "Error: InvalidAccessKeyId" } ], "isError": true } ``` ### Error Conditions | Condition | Error Message | |-----------|---------------| | Invalid AWS credentials | Error message from AWS SDK (e.g., "InvalidAccessKeyId") | | Missing `s3:ListBuckets` permission | AWS error (e.g., "User: arn:aws:iam::... is not authorized") | ### Example Usage **MCP Client Call**: ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "list_buckets" } } ``` **Response**: ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "Buckets (3):\n\n • my-data-bucket\n • backup-storage\n • logs-archive" } ] } } ``` ``` -------------------------------- ### List Buckets Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/README.md Lists all available S3 buckets. This function can be called directly or via the `list_buckets` tool. ```APIDOC ## listBuckets() ### Description Lists all S3 buckets accessible by the configured credentials. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```javascript await listBuckets(); ``` ### Response #### Success Response - **buckets** (array) - A list of bucket names. ### Response Example ```json { "buckets": ["my-bucket-1", "my-bucket-2"] } ``` ``` -------------------------------- ### Create S3 Client Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md Utility function to create a new S3Client instance. A new client is created per call to simplify testing and avoid connection pooling complexity. ```typescript function createClient(): S3Client { return new S3Client({ region: defaultRegion }); } ``` -------------------------------- ### Registering an MCP Tool Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/architecture-overview.md Defines a new tool with its identifier, description, Zod validation schema, and an asynchronous handler function. Use this to integrate new functionalities into the MCP server. ```typescript server.tool( "tool_name", // Tool identifier "Description", // User-facing description { param: z.string() }, // Zod schema for validation async ({ param }) => { try { const result = await s3Function(param); return { content: [{ type: "text", text: formatResult(result) }] }; } catch (err) { return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true }; } } ); ``` -------------------------------- ### Call get_object Tool via MCP Client Source: https://github.com/ofershap/mcp-server-s3/blob/main/_autodocs/api-reference-mcp-tools.md This JSON payload demonstrates how to call the get_object tool using the MCP client's tools/call method, specifying the tool name and its arguments. ```json { "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { "name": "get_object", "arguments": { "bucket": "my-bucket", "key": "config/settings.json" } } } ```