### Get Tool Response Example: Password Only Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example response when retrieving only the password for a vault item using the 'get' tool. ```text mypass ``` -------------------------------- ### Install and Build Locally for MCP Server Reference Source: https://github.com/bitwarden/mcp-server/blob/main/README.md If you prefer to reference a locally built version of the mcp-server, first install its dependencies and then build the project. This allows you to use a local path in your Claude Desktop configuration. ```bash npm install npm run build ``` -------------------------------- ### Response Example: status Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md An example JSON response from the 'status' tool, showing server URL, last sync time, user email, and vault status. ```json { "serverUrl": "https://bitwarden.com", "lastSync": "2025-06-12T10:30:00.000Z", "userEmail": "user@example.com", "status": "unlocked" } ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/bitwarden/mcp-server/blob/main/README.md Clone the MCP Server repository and install Node.js dependencies. ```bash git clone https://github.com/bitwarden/mcp-server.git cd mcp-server npm install ``` -------------------------------- ### Get Tool Response Example: Item Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example JSON response when retrieving a specific vault item using the 'get' tool. Includes details like object type, ID, name, and login credentials. ```json { "object": "item", "id": "550e8400-e29b-41d4-a716-446655440000", "name": "GitHub", "type": 1, "login": { "username": "myuser", "password": "mypass" } } ``` -------------------------------- ### Response on Success: sync Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example output when the 'sync' tool successfully synchronizes the vault with Bitwarden servers. ```text bw sync output (typically "Syncing with server...") ``` -------------------------------- ### Security Flow Example (CLI) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Illustrates the step-by-step security process for a CLI command, from input to safe execution, including sanitization. ```text Input: { type: 'items'; search: '$(whoami)' } ↓ Schema validation: ✓ (valid enum, valid string) ↓ Sanitize: '$(whoami)' → 'whoami' (removes $, (, )) ↓ Build command: ['list', 'items', '--search', 'whoami'] ↓ spawn('bw', ['list', 'items', '--search', 'whoami'], { shell: false }) ↓ Result: searches for items matching "whoami" literally (safe) ``` -------------------------------- ### Start MCP Inspector for Interactive Testing Source: https://github.com/bitwarden/mcp-server/blob/main/README.md Build the project and launch the MCP Inspector for interactive testing and debugging. ```bash npm run build npm run inspect ``` -------------------------------- ### List Tool Response Example Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example JSON response when using the 'list' tool. It shows a list of vault objects, each with an 'object' type, 'id', and 'name'. ```json [ { "object": "item", "id": "550e8400-e29b-41d4-a716-446655440000", "name": "My Login", "type": 1 }, { "object": "folder", "id": "660e8400-e29b-41d4-a716-446655440001", "name": "Work" } ] ``` -------------------------------- ### Bitwarden API Request Examples Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/types.md Provides examples of API responses using the ApiResponse interface. Demonstrates successful responses with data, API-level errors, and network errors. ```typescript // Successful response { status: 200, data: { collections: [...], continuationToken: null } } // API error response { status: 403, errorMessage: 'API request failed: 403 Forbidden', data: { error: 'InvalidApiKey', errorDescription: '...' } } // Network error { status: 500, errorMessage: 'API request error: Failed to fetch' } ``` -------------------------------- ### List Organization Collections API Response Example Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example JSON response when listing organization collections, showing a list of collection objects. ```json { "data": [ { "id": "550e8400-e29b-41d4-a716-446655440000", "organizationId": "660e8400-e29b-41d4-a716-446655440001", "name": "Development", "externalId": "dev-collection" } ], "continuationToken": null } ``` -------------------------------- ### CLI Handler Example: handleList Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Demonstrates a CLI handler that validates input, constructs command parameters, executes a CLI command, and formats the response. ```typescript export const handleList = withValidation(listSchema, async (validatedArgs) => { const { type, search, organizationid, url, folderid, collectionid, trash } = validatedArgs; const params: string[] = [type]; if (search) { params.push('--search', search); } // ... add more optional parameters const response = await executeCliCommand('list', params); return toMcpFormat(response); }); ``` -------------------------------- ### Bitwarden CLI Command Execution Examples Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/types.md Illustrates possible outputs from executing a Bitwarden CLI command using the CliResponse interface. Covers successful, failed, and no-output scenarios. ```typescript // Successful command { output: 'vault item json data...' } // Failed command { errorOutput: 'Invalid master password.' } // Command with no output {} ``` -------------------------------- ### Response on Success: unlock Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example output when the 'unlock' tool successfully unlocks the Bitwarden vault. ```text Vault unlocked successfully. ``` -------------------------------- ### Full MCP Server Configuration (All Features) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/README.md An example of a comprehensive JSON configuration for the MCP Server, enabling all features including API access and directory restrictions. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-token", "BW_CLIENT_ID": "organization.xxx", "BW_CLIENT_SECRET": "secret", "BW_ALLOWED_DIRECTORIES": "/home/user/Downloads,/tmp" } } } } ``` -------------------------------- ### Response on Success: lock Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example output when the 'lock' tool successfully locks the Bitwarden vault. ```text bw lock output (typically "Vault locked.") ``` -------------------------------- ### Retrieve Specific Collection API Response Example Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example JSON response for retrieving a single collection, detailing its properties. ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "organizationId": "660e8400-e29b-41d4-a716-446655440001", "name": "Development", "externalId": "dev-collection" } ``` -------------------------------- ### MCP Server Configuration Example Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/INDEX.md Set these environment variables to configure the Bitwarden MCP Server for CLI or API operations. The session token is for personal vault access, while client ID and secret are for organization administration. ```bash # For CLI operations (personal vault) export BW_SESSION="" # For API operations (organization administration) export BW_CLIENT_ID="organization." export BW_CLIENT_SECRET="" ``` -------------------------------- ### MCP Server Configuration with BW_SESSION Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Example of how to include the BW_SESSION environment variable within the MCP server configuration for Claude Desktop. Replace 'your-token-here' with your actual session token. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-token-here" } } } } ``` -------------------------------- ### Endpoints & Tool Definitions Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/README.md Details all available CLI and API tools, including their request/response schemas, parameter documentation, examples, and status codes. ```APIDOC ## Endpoints & Tool Definitions ### Description Details all available CLI and API tools, including their request/response schemas, parameter documentation, examples, and status codes. ### Content - All 53 tools: 28 CLI + 25 API - Tool definitions with request/response schemas - Parameter documentation with tables - Examples and status codes - Environment variable configuration ``` -------------------------------- ### API Handler Example: handleListOrgCollections Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Shows an API handler that performs schema validation, makes an authenticated HTTP request using executeApiRequest, and formats the response. ```typescript export const handleListOrgCollections = withValidation( listCollectionsRequestSchema, async () => { const response = await executeApiRequest(`/public/collections`, 'GET'); return toMcpFormat(response); }, ); ``` -------------------------------- ### Mocking `spawn` in Tests Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-unlock.md Demonstrates how to mock the `spawn` function using Jest when testing functions that rely on it. This setup ensures that child processes are controlled during test execution. ```typescript import { __testable } from '../utils/unlock.js'; // Mock spawn const mockSpawn = jest.fn().mockImplementation(...); __testable.spawn = mockSpawn; // Now `runUnlockFlow()` uses the mock ``` -------------------------------- ### Get Bitwarden Session Token Source: https://github.com/bitwarden/mcp-server/blob/main/README.md Use these commands to log in to your Bitwarden account and retrieve your session token, which is required for MCP server authentication. ```bash bw login bw unlock --raw ``` -------------------------------- ### Usage Example for withValidation Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-validation.md Demonstrates how to use the `withValidation` higher-order function to create a type-safe handler. It includes defining a Zod schema and passing it along with the handler function to `withValidation`. ```typescript // Define schema const myToolSchema = z.object({ userId: z.string().uuid(), name: z.string().min(1), }); // Create handler with withValidation export const handleMyTool = withValidation( myToolSchema, async (validatedArgs) => { // validatedArgs is typed: { userId: string, name: string } const result = await executeCliCommand('mycommand', [ validatedArgs.userId, validatedArgs.name, ]); return { content: [{ type: 'text', text: result.output }], isError: false, }; }, ); ``` -------------------------------- ### List Organization Collections API Request Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example HTTP request to list all collections within an organization. Authentication is required using an access token. ```http GET /public/collections HTTP/1.1 Authorization: Bearer {access_token} ``` -------------------------------- ### Response on Error: unlock Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Examples of error messages returned by the 'unlock' tool, indicating various failure conditions such as concurrent attempts, cooldowns, invalid passwords, or cancellation. ```text "Another unlock attempt is already in progress." - "Too many failed unlock attempts. Please wait before retrying." - "Please wait a moment before retrying unlock." - "Invalid master password." - "You are not logged in. Run \"bw login\" first." - "Unlock cancelled." - "No password entered." - "Interactive unlock is not supported in this environment." ``` -------------------------------- ### Build and Test Commands Source: https://github.com/bitwarden/mcp-server/blob/main/README.md Common npm scripts for building the project, running tests, and linting. ```bash npm run build # Compile TypeScript npm test # Run test suite npm run lint # Check code style npm run lint:fix # Auto-fix linting issues npm run inspect # Test with MCP Inspector ``` -------------------------------- ### MCP Tool Definition: get Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Defines the 'get' tool for retrieving specific vault objects. It requires the object type and an identifier, with optional parameters for organization and item IDs, and output directory for attachments. ```json { "name": "get", "description": "Retrieve a specific vault object by ID or search term", "inputSchema": { "type": "object", "properties": { "object": { "type": "string", "enum": ["item", "username", "password", "uri", "totp", "notes", "exposed", "attachment", "folder", "collection", "organization", "org-collection", "fingerprint"], "description": "Type of object to retrieve" }, "id": { "type": "string", "description": "Object ID, search term, filename, or 'me' for fingerprint" }, "organizationid": { "type": "string", "description": "Organization ID (required for org-collection)" }, "itemid": { "type": "string", "description": "Item ID (required for attachment)" }, "output": { "type": "string", "description": "Output directory for attachment downloads (must be in BW_ALLOWED_DIRECTORIES)" } }, "required": ["object", "id"] } } ``` -------------------------------- ### Configure Claude Desktop with Organization Admin Features Source: https://github.com/bitwarden/mcp-server/blob/main/README.md To enable organization administration features, include your Bitwarden organization API credentials (Client ID and Client Secret) in the configuration. Replace placeholders with your actual credentials. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-session-token-here", "BW_CLIENT_ID": "organization.your-client-id", "BW_CLIENT_SECRET": "your-client-secret" } } } } ``` -------------------------------- ### GET /public/collections/{collectionId} Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Retrieves a specific collection by its unique ID. Authentication is required. ```APIDOC ## GET /public/collections/{collectionId} ### Description Retrieves a specific collection by ID. ### Method GET ### Endpoint /public/collections/{collectionId} ### Parameters #### Path Parameters - **collectionId** (string (UUID)) - Required - Collection UUID #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **id** (string) - Collection UUID - **organizationId** (string) - Organization UUID - **name** (string) - Collection name - **externalId** (string) - External identifier #### Response Example ```json { "id": "550e8400-e29b-41d4-a716-446655440000", "organizationId": "660e8400-e29b-41d4-a716-446655440001", "name": "Development", "externalId": "dev-collection" } ``` ``` -------------------------------- ### GET /public/collections Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Lists all collections within the organization. Requires authentication and a 'Member' role or higher. ```APIDOC ## GET /public/collections ### Description Lists all collections in the organization. ### Method GET ### Endpoint /public/collections ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```http GET /public/collections HTTP/1.1 Authorization: Bearer {access_token} ``` ### Response #### Success Response (200) - **data** (array) - Array of collection objects - **continuationToken** (string) - Token for pagination, null if no more results #### Response Example ```json { "data": [ { "id": "550e8400-e29b-41d4-a716-446655440000", "organizationId": "660e8400-e29b-41d4-a716-446655440001", "name": "Development", "externalId": "dev-collection" } ], "continuationToken": null } ``` ``` -------------------------------- ### Initialize MCP Server Instance Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Creates an instance of the MCP Server, specifying its name and version, and advertising its capabilities, such as tool support. ```typescript const server = new Server( { name: 'Bitwarden MCP Server', version: '2026.5.1', }, { capabilities: { tools: {}, }, }, ); ``` -------------------------------- ### CLI Execution Flow Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Illustrates the step-by-step process of executing a CLI command, from initial request sanitization to child process spawning and response collection. This ensures secure and controlled execution of Bitwarden CLI commands. ```text ┌─────────────────────────────────────────────────────────────┐ │ MCP Client (Claude) │ ├─────────────────────────────────────────────────────────────┤ │ CallToolRequest │ │ { name: "list", arguments: { type: "items", search: "github" } } └────────────────────────┬────────────────────────────────────┘ │ ↓ ┌───────────────────────────────┐ │ src/index.ts - Tool Router │ │ switch(name) case 'list': │ └──────────┬────────────────────┘ │ ↓ ┌──────────────────────────────────────────┐ │ src/handlers/cli.ts - handleList │ │ withValidation(listSchema, ...) └──────────┬───────────────────────────────┘ │ ├─→ Validation: Zod schema check │ ✓ type is enum value │ ✓ search is string │ ├─→ Build parameters │ params = ['items', '--search', 'github'] │ ├─→ Call executeCliCommand │ executeCliCommand('list', params) │ ↓ ┌─────────────────────────────────────────────┐ │ src/utils/cli.ts - executeCliCommand │ │ │ │ 1. Sanitize: 'list' → 'list' │ │ 2. Validate: 'list' in allowlist ✓ │ │ 3. Validate params: no nullbytes ✓ │ │ 4. Build safe cmd: ['list', 'items', ...] │ │ 5. buildBwChildEnv() for filtered env │ │ 6. spawn('bw', [...], { shell: false }) │ │ 7. Collect stdout/stderr │ │ 8. Return { output: '...' } └────────────┬────────────────────────────────┘ │ ↓ (back to handleList) ┌──────────────────────────────┐ │ toMcpFormat(response) │ │ Returns: │ { │ content: [{ │ type: 'text', │ text: '[{...}, ...]' │ │ }], │ │ isError: false │ │ } └──────────┬─────────────────┘ │ ↓ ┌─────────────────────────────────────────────────────────────┐ │ MCP Client Response │ ├─────────────────────────────────────────────────────────────┤ │ { "content": [{ "type": "text", "text": "[...]" }], │ "isError": false │ } └─────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Delete Collection API Request Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example HTTP request to delete a specific collection by its ID. Requires authentication. ```http DELETE /public/collections/{collectionId} HTTP/1.1 Authorization: Bearer {access_token} ``` -------------------------------- ### Configure Claude Desktop with Locally Built MCP Server Source: https://github.com/bitwarden/mcp-server/blob/main/README.md Reference the locally built `dist/index.js` file in your Claude Desktop configuration. This method is useful for development or when you need to use a custom build of the mcp-server. Remember to replace 'local/path/to/mcp-server' with the actual path. ```json { "mcpServers": { "bitwarden": { "command": "node", "args": ["local/path/to/mcp-server/dist/index.js"], "env": { "BW_SESSION": "your-session-token-here" } } } } ``` -------------------------------- ### Local Use Configuration (Claude Desktop) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Basic configuration for local use with Claude Desktop, setting the Bitwarden session token. This enables core functionality without organization-specific settings. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-session-token-here" } } } } ``` -------------------------------- ### Retrieve Specific Collection API Request Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example HTTP request to retrieve a specific collection by its ID. Requires authentication. ```http GET /public/collections/{collectionId} HTTP/1.1 Authorization: Bearer {access_token} ``` -------------------------------- ### buildSafeCommand(baseCommand, parameters) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-security.md Constructs a safe command array for use with spawn(). It sanitizes the base command and validates all parameters, returning an immutable array ready for use. ```APIDOC ## buildSafeCommand(baseCommand, parameters) ### Description Constructs a safe command array for use with `spawn()`. Sanitizes the base command and validates all parameters. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method - Not applicable (function call) ### Endpoint - Not applicable (function call) ### Parameters #### Path Parameters - **baseCommand** (string) - Required - Base command to sanitize - **parameters** (readonly string[]) - Optional - Array of parameters (each validated independently) ### Request Example ```typescript const cmd = buildSafeCommand('list', ['items', '--search', 'github']); // → ['list', 'items', '--search', 'github'] spawn('bw', [...cmd], { shell: false }); ``` ### Response #### Success Response - **command array** (readonly [string, ...string[]]) - Immutable array `[sanitizedCommand, ...parameters]` ready to pass to `spawn(command, args)`. #### Response Example - Not applicable (function return value) ### Throws - Error if any parameter fails validation. ``` -------------------------------- ### Run All Tests Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/INDEX.md Execute all tests in the project using npm. This command runs the full test suite. ```bash npm test ``` -------------------------------- ### Get Vault Status Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Retrieves the current status of the Bitwarden vault, including whether it is locked or unlocked, the configured server URL, and login status. ```APIDOC ## GET /status ### Description Returns vault status including unlock state, server URL, and login status. ### Method GET ### Endpoint /status ### Parameters #### Query Parameters - **BW_SESSION** (string) - Optional - The session token for authentication. ### Response #### Success Response (200) - **serverUrl** (string) - The URL of the Bitwarden server. - **lastSync** (string) - The timestamp of the last successful sync. - **userEmail** (string) - The email address of the logged-in user. - **status** (string) - The current status of the vault (e.g., "unlocked", "locked"). ### Response Example ```json { "serverUrl": "https://bitwarden.com", "lastSync": "2025-06-12T10:30:00.000Z", "userEmail": "user@example.com", "status": "unlocked" } ``` ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/bitwarden/mcp-server/blob/main/README.md Set environment variables to enable verbose debug logging for the Bitwarden MCP server. ```bash export DEBUG=bitwarden:* export NODE_ENV=development ``` -------------------------------- ### buildSafeApiRequest(endpoint, method, data?) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-api-requests.md Constructs a safe `RequestInit` object for use with `fetch()`. It validates the endpoint against an allowlist, ensures the HTTP method is allowed, and attaches the necessary authentication headers. ```APIDOC ## buildSafeApiRequest(endpoint, method, data?) ### Description Constructs a safe `RequestInit` object for use with `fetch()`. Validates the endpoint against the API allowlist, ensures the HTTP method is allowed, and attaches authentication headers. ### Method `async` ### Parameters #### Path Parameters - **endpoint** (`string`) - Required - API endpoint path (e.g., `/public/collections`). Validated against a pattern allowlist. - **method** (`string`) - Required - HTTP method (`GET`, `POST`, `PUT`, `DELETE`). Case-insensitive; converted to uppercase. - **data** (`unknown`) - Optional - Request body (for POST/PUT). Optional; sanitized before encoding. ### Returns - **Promise** - A configuration object ready to pass to `fetch(url, requestConfig)`. ### Validation 1. **Endpoint validation:** Checked against patterns in `validateApiEndpoint()`: - `/public/collections` — collection operations - `/public/members` — member management - `/public/groups` — group management - `/public/policies` — organization policies - `/public/events` — audit logs - `/public/organization/subscription` — billing 2. **Method validation:** Only `GET`, `POST`, `PUT`, `DELETE` are allowed. 3. **Authentication:** Access token is obtained via `getAccessToken()` and attached as `Authorization: Bearer `. 4. **Data sanitization:** If data is provided and method is POST/PUT, it is passed through `sanitizeApiParameters()`. ### Returned RequestInit Structure ```json { "method": "GET" | "POST" | "PUT" | "DELETE", "headers": { "Authorization": "Bearer ", "Content-Type": "application/json", "User-Agent": "Bitwarden-MCP-Server/2026.5.1" }, "body": "string" // JSON-encoded data (for POST/PUT only) } ``` ### Example ```typescript const requestConfig = await buildSafeApiRequest( '/public/collections/550e8400-e29b-41d4-a716-446655440000', 'GET' ); // Returns: // { // method: 'GET', // headers: { // Authorization: 'Bearer eyJhbGci...', // 'Content-Type': 'application/json', // 'User-Agent': 'Bitwarden-MCP-Server/2026.5.1' // } // } ``` ``` -------------------------------- ### get Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Retrieves a specific vault object by ID or search term. This tool can fetch various types of vault data, including items, attachments, and organizational details. ```APIDOC ## get ### Description Retrieves a specific vault object by ID or search term. This tool can fetch various types of vault data, including items, attachments, and organizational details. ### Method Not Applicable (CLI Tool) ### Parameters #### Query Parameters - **object** (string enum) - Required - Type to retrieve: `item`, `username`, `password`, `uri`, `totp`, `notes`, `exposed`, `attachment`, `folder`, `collection`, `organization`, `org-collection`, `fingerprint` - **id** (string) - Required - Object ID, search term (for items), filename (for attachments), or `'me'` (for fingerprint) - **organizationid** (string) - Optional - Organization UUID (required if object is `org-collection`) - **itemid** (string) - Optional - Item UUID (required if object is `attachment`) - **output** (string) - Optional - Directory for attachment download (must be within `BW_ALLOWED_DIRECTORIES`) ### Response Examples Item (object type): ```json { "object": "item", "id": "550e8400-e29b-41d4-a716-446655440000", "name": "GitHub", "type": 1, "login": { "username": "myuser", "password": "mypass" } } ``` Password only: ``` mypass ``` ``` -------------------------------- ### Configuration with File Operations Enabled Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Configuration enabling file operations by setting the BW_ALLOWED_DIRECTORIES environment variable. This allows the server to handle file uploads and downloads. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-session-token-here", "BW_ALLOWED_DIRECTORIES": "/home/user/Downloads,/tmp/bitwarden" } } } } ``` -------------------------------- ### Configuration with Organization Administration Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Configuration for using the Bitwarden MCP Server with organization administration features. Includes BW_CLIENT_ID and BW_CLIENT_SECRET for authentication. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-session-token-here", "BW_CLIENT_ID": "organization.550e8400-e29b-41d4-a716-446655440000", "BW_CLIENT_SECRET": "your-client-secret-here" } } } } ``` -------------------------------- ### Update Collection API Request Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/endpoints.md Example HTTP request to update an existing collection. It includes the collection ID in the path and a JSON body for the update payload. Authentication is required. ```http PUT /public/collections/{collectionId} HTTP/1.1 Authorization: Bearer {access_token} Content-Type: application/json { "externalId": "string (optional)", "groups": [ { "id": "string (UUID)", "readOnly": boolean, "hidePasswords": boolean (optional), "manage": boolean (optional) } ] } ``` -------------------------------- ### Minimal MCP Server Configuration (CLI Only) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/README.md Provides a basic JSON configuration for the MCP Server, suitable for CLI-only operations. It specifies the command to run and essential environment variables. ```json { "mcpServers": { "bitwarden": { "command": "npx", "args": ["-y", "@bitwarden/mcp-server"], "env": { "BW_SESSION": "your-token" } } } } ``` -------------------------------- ### Set BW_ALLOWED_DIRECTORIES on Windows (forward slashes) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Configures the comma-separated allowlist of directories for file uploads and downloads on Windows using forward slashes. This is crucial for enabling file-based tools. ```bash set BW_ALLOWED_DIRECTORIES=C:/Users/YourName/Documents,C:/Temp/Bitwarden ``` -------------------------------- ### Run MCP Server Tests Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/README.md Commands to execute tests for the MCP Server project using npm. Includes options for running all tests, watching for changes, and generating a coverage report. ```bash npm test # Run all tests npm run test:watch # Watch mode npm test -- --coverage # Coverage report ``` -------------------------------- ### executeCliCommand Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-cli-execution.md Safely executes a Bitwarden CLI command with isolated arguments. Uses `spawn()` (not `exec()`) to ensure parameters are treated as literal values, not shell code. It handles command sanitization, parameter validation, and environment filtering for secure execution. ```APIDOC ## executeCliCommand(baseCommand, parameters) ### Description Safely executes a Bitwarden CLI command with isolated arguments. Uses `spawn()` (not `exec()`) to ensure parameters are treated as literal values, not shell code. ### Method `async function executeCliCommand(baseCommand: string, parameters: readonly string[] = []): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **baseCommand** (`string`) - Required - Base Bitwarden CLI command (e.g., `'list'`, `'get'`, `'create'`). Sanitized and validated against an allowlist of safe commands. - **parameters** (`readonly string[]`) - Optional - Command arguments. Each parameter is validated with `validateParameter()` and passed to `spawn()` as an isolated array element. Defaults to `[]`. ### Returns `Promise` where `CliResponse` has the structure: ```typescript { output?: string; errorOutput?: string; } ``` ### Example Usage ```typescript // List all vault items const response = await executeCliCommand('list', ['items']); if (response.output) { console.log(response.output); // JSON array of items } else { console.error(response.errorOutput); } // Create a folder (with name parameter) const result = await executeCliCommand('create', ['folder', 'My Folder']); // Get a specific item (by ID) const item = await executeCliCommand('get', ['item', 'item-uuid-here']); ``` ### Error Handling - **Invalid command:** Returns `{ errorOutput: 'Invalid or unsafe command...' }` - **Spawn error:** Returns `{ errorOutput: 'Failed to execute command: ...' }` - **Non-zero exit:** Returns `{ errorOutput: 'Command exited with code X' }` - **Exception:** Returns `{ errorOutput: 'Unknown error occurred' }` ``` -------------------------------- ### TypeScript Type Safety Example: Input Validation Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Demonstrates how Zod schema validation in TypeScript narrows down types for discriminated unions, ensuring type safety for success and error responses. ```typescript // Zod schema validation returns discriminated tuple const [success, validatedArgs] = validateInput(schema, args); if (!success) { // TypeScript narrows type: validatedArgs is error response return validatedArgs; // ✓ Type matches return type } // Outside if block: validatedArgs is validated data return handlerFn(validatedArgs); // ✓ Type matches handler signature ``` -------------------------------- ### Server Initialization Code Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md The TypeScript code snippet showing the server initialization process. It defines the server name, version, and capabilities, using stdio for transport. ```typescript const server = new Server( { name: 'Bitwarden MCP Server', version: '2026.5.1', }, { capabilities: { tools: {}, }, }, ); ``` -------------------------------- ### runUnlockFlow() Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-unlock.md Main entry point for the unlock operation. Manages session state, rate limiting, and orchestrates the unlock process by collecting the master password via a native OS dialog and passing it to `bw unlock --raw`. ```APIDOC ## runUnlockFlow() ### Description Initiates and manages the out-of-band vault unlock process. This function ensures secure collection of the master password through native operating system dialogs, preventing exposure to the MCP protocol or AI client. It handles session state, rate limiting, and orchestrates the interaction with the `bw` command-line tool. ### Method ``` async function runUnlockFlow(): Promise ``` ### Parameters None ### Returns `UnlockResult`: An object indicating success or failure. - `{ readonly success: true; readonly message: string }`: On successful unlock or if the vault is already unlocked. - `{ readonly success: false; readonly error: string }`: On failure, with a descriptive error message. ### Execution Flow 1. Checks for concurrent unlock attempts using a mutex. 2. Enforces cooldown periods based on previous failures. 3. Verifies if the vault is already unlocked via `bw status`. 4. If not unlocked, calls `collectPasswordViaDialog()` to display a native OS password prompt. 5. Executes the `bw unlock --raw` command with the collected password. 6. Records the outcome and updates internal state. ### Returned Messages **Success:** - `'Vault is already unlocked.'` - `'Vault unlocked successfully.'` **Errors:** - `'Another unlock attempt is already in progress.'` - `'Too many failed unlock attempts. Please wait before retrying.'` - `'Please wait a moment before retrying unlock.'` - `'Invalid master password.'` - `'You are not logged in. Run "bw login" first.'` - `'Unlock cancelled.'` - `'No password entered.'` - `'Password prompt timed out.'` - `'Unlock failed.'` ### Example ```typescript const result = await runUnlockFlow(); if (result.success) { console.log(result.message); } else { console.error(result.error); } ``` ``` -------------------------------- ### Get OAuth2 Access Token Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-api-requests.md Obtains and caches an OAuth2 access token using the client credentials flow. Automatically refreshes expired tokens and deduplicates concurrent requests. Uses BW_CLIENT_ID and BW_CLIENT_SECRET from environment variables. ```typescript async function getAccessToken(): Promise ``` ```typescript try { const token = await getAccessToken(); // token is a valid OAuth2 access token, ready to use const authHeader = `Bearer ${token}`; } catch (error) { console.error('Failed to obtain token:', error.message); } ``` -------------------------------- ### Run Tests with Coverage Report Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/INDEX.md Execute all tests and generate a coverage report to analyze the extent of code tested. This helps identify areas that may need more test cases. ```bash npm test -- --coverage ``` -------------------------------- ### isLinuxHeadless() Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-unlock.md Determines if the current Linux environment is headless (lacks a graphical display). ```APIDOC ## isLinuxHeadless() ### Description Checks whether the Linux environment is headless, meaning it lacks an active X11 or Wayland display server. ### Method ```typescript function isLinuxHeadless(): boolean ``` ### Returns `true` if both the `DISPLAY` and `WAYLAND_DISPLAY` environment variables are unset; `false` otherwise. ``` -------------------------------- ### Execute CLI Command with Filtered Environment Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-child-environment.md Demonstrates how `executeCliCommand` in `src/utils/cli.ts` utilizes `buildBwChildEnv` to spawn `bw` commands with a secure environment, passing `BW_SESSION` if available. ```typescript const childEnv = buildBwChildEnv( process.env['BW_SESSION'] ? { BW_SESSION: process.env['BW_SESSION'] } : undefined, ); const child = spawn('bw', [command, ...args], { env: childEnv, shell: false, }); ``` -------------------------------- ### Build Safe Command for spawn() Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-security.md Constructs a safe command array for use with `spawn()`. It sanitizes the base command and validates all parameters. Throws an error if any parameter fails validation. ```typescript function buildSafeCommand( baseCommand: string, parameters: readonly string[] = [] ): readonly [string, ...string[]] ``` ```typescript const cmd = buildSafeCommand('list', ['items', '--search', 'github']); // → ['list', 'items', '--search', 'github'] spawn('bw', [...cmd], { shell: false }); ``` -------------------------------- ### collectPasswordLinux() Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-unlock.md Collects the master password on Linux, attempting to use zenity or kdialog, with a fallback for headless systems. ```APIDOC ## collectPasswordLinux() ### Description Collects the master password on Linux using `zenity` (GNOME) or `kdialog` (KDE). Includes fallback logic for headless systems. ### Method ```typescript async function collectPasswordLinux(): Promise ``` ### Detection Logic 1. If the environment is headless (no `DISPLAY` or `WAYLAND_DISPLAY`), an error is returned directing the user to use `bw unlock --raw`. 2. Attempts to use `zenity --password --title="Bitwarden MCP"`. 3. If `zenity` is not available or fails, it falls back to `kdialog --password "Enter your Bitwarden master password"`. 4. If neither graphical tool is available, an error is returned. ``` -------------------------------- ### MCP Server Dependency Graph Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Illustrates the dependency relationships between different modules within the MCP server, showing how components import and utilize each other. ```plaintext index.ts (server) ├── imports: tools/index.ts (definitions) ├── imports: handlers/cli.ts (CLI implementations) └── imports: handlers/api.ts (API implementations) tools/cli.ts (CLI definitions) tools/api.ts (API definitions) handlers/cli.ts (CLI handlers) ├── imports: utils/cli.ts (executeCliCommand) ├── imports: utils/unlock.ts (runUnlockFlow) ├── imports: utils/validation.ts (withValidation) ├── imports: schemas/cli.ts (Zod schemas) └── imports: utils/types.ts (interfaces) handlers/api.ts (API handlers) ├── imports: utils/api.ts (executeApiRequest) ├── imports: utils/validation.ts (withValidation) ├── imports: schemas/api.ts (Zod schemas) └── imports: utils/types.ts (interfaces) utils/cli.ts ├── imports: utils/security.ts (buildSafeCommand, isValidBitwardenCommand) ├── imports: utils/bw-env.ts (buildBwChildEnv) └── imports: utils/types.ts (CliResponse) utils/api.ts ├── imports: utils/config.ts (API_BASE_URL, IDENTITY_URL, CLIENT_ID, CLIENT_SECRET) ├── imports: utils/security.ts (validateApiEndpoint, sanitizeApiParameters) └── imports: utils/types.ts (TokenResponse, ApiResponse) utils/unlock.ts ├── imports: utils/bw-env.ts (buildBwChildEnv) └── uses: __testable.spawn (mockable for tests) utils/security.ts └── (no internal imports; only fs, path, process) utils/validation.ts └── imports: zod ``` -------------------------------- ### MCP Server Source Tree Structure Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/server-architecture.md Overview of the directory structure for the MCP server project, including entry points, tool definitions, handlers, schemas, and utility modules. ```plaintext src/ ├── index.ts # Server entry point, tool routing ├── tools/ │ ├── index.ts # Re-export CLI and API tools │ ├── cli.ts # 28 tool definitions (vault) │ └── api.ts # 25 tool definitions (organization) ├── schemas/ │ ├── cli.ts # Zod schemas for CLI tools │ └── api.ts # Zod schemas for API tools ├── handlers/ │ ├── cli.ts # CLI tool implementations (28 handlers) │ └── api.ts # API tool implementations (25 handlers) └── utils/ ├── types.ts # Shared TypeScript interfaces ├── validation.ts # Input validation and withValidation wrapper ├── security.ts # Sanitization and allowlist functions ├── cli.ts # CLI command execution (executeCliCommand) ├── api.ts # API request execution (executeApiRequest, OAuth2) ├── unlock.ts # Out-of-band unlock flow ├── config.ts # Configuration constants (from env vars) └── bw-env.ts # Build filtered child environment ``` -------------------------------- ### Set BW_ALLOWED_DIRECTORIES on Windows (backslashes) Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Configures the comma-separated allowlist of directories for file uploads and downloads on Windows using backslashes. This is crucial for enabling file-based tools. ```powershell $env:BW_ALLOWED_DIRECTORIES = "C:\Users\YourName\Documents,C:\Temp\Bitwarden" ``` -------------------------------- ### Standard Handler Pattern in TypeScript Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/README.md Demonstrates the consistent pattern used for implementing tool handlers, emphasizing validation boilerplate reduction and type inference from Zod schemas. ```typescript export const handleToolName = withValidation( zodSchema, async (validatedArgs) => { // Business logic const result = await executeCliCommand(/* ... */); return { content: [{ type: 'text', text: /* response */ }], isError: false, }; }, ); ``` -------------------------------- ### Normal CLI Execution with BW_SESSION Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/api-reference-child-environment.md Use this snippet for standard CLI commands when a `BW_SESSION` token is available. The child process will have access to essential system variables and the provided session token, but not sensitive API credentials. ```typescript const childEnv = buildBwChildEnv( process.env['BW_SESSION'] ? { BW_SESSION: process.env['BW_SESSION'] } : undefined, ); const child = spawn('bw', ['list', 'items'], { env: childEnv, shell: false, }); ``` -------------------------------- ### Set BW_ALLOWED_DIRECTORIES on Linux/macOS Source: https://github.com/bitwarden/mcp-server/blob/main/_autodocs/configuration.md Configures the comma-separated allowlist of directories for file uploads and downloads on Linux or macOS systems. This is crucial for enabling file-based tools. ```bash export BW_ALLOWED_DIRECTORIES="/home/user/Downloads,/tmp/bitwarden-upload" ```