Litelead-mcp

getRoles Tool

Overview

The getRoles tool retrieves role definitions from the Firebase/Firestore database with support for pagination and sorting.

Location

tools/getRoles.js

Description

Retrieves role definitions for the authenticated account with cursor-based pagination support. Roles define permission sets that can be assigned to users. Roles are retrieved from the Firestore path: /Accounts/{accountId}/Roles.

Input Schema

{
  limit?: number;                    // Number of records to retrieve (1-100, default: 50)
  cursor?: string;                   // Document ID for cursor-based pagination
  orderBy?: string;                  // Field to order by (default: "name")
  orderDirection?: "asc" | "desc";   // Sort direction (default: "asc")
  cursorDirection?: "next" | "previous";  // Direction for pagination (default: "next")
  includeTotal?: boolean;            // Include total count of all roles (default: false)
}

Parameters

Parameter Type Required Default Description
limit number No 50 Maximum number of roles to return (1-100)
cursor string No - Document ID to start pagination from
orderBy string No “name” Field name to sort by
orderDirection enum No “asc” Sort direction: “asc” or “desc”
cursorDirection enum No “next” Pagination direction: “next” or “previous”
includeTotal boolean No false Whether to include total count (expensive)

Output Schema

{
  roles: Role[];
  pagination: PaginationMetadata;
}

Role Object

{
  id: string;                    // Firestore document ID
  path: string;                  // Full Firestore path
  name: string;                  // Role name
  permissions: string[];         // Array of permission strings
  readonly: boolean;             // Whether this role is read-only (system role)
  updatedAt: string | Date;      // Last update timestamp
}

Pagination Metadata

{
  limit: number;                 // Applied limit
  hasMore: boolean;              // Whether more results exist
  nextCursor: string | null;     // Cursor for next page
  previousCursor: string | null; // Cursor for previous page
  total?: number | null;         // Total count (if includeTotal was true)
}

Usage Examples

Basic Usage

// Get all roles
const result = await getRoles(context, {
  limit: 100
});

console.log(result.roles);         // Array of roles
console.log(result.pagination);    // Pagination metadata

Paginated Retrieval

// First page
const page1 = await getRoles(context, {
  limit: 10,
  orderBy: "name",
  orderDirection: "asc"
});

// Next page
const page2 = await getRoles(context, {
  limit: 10,
  cursor: page1.pagination.nextCursor,
  cursorDirection: "next"
});

Find Specific Role

// Get all roles and find by name
const result = await getRoles(context, { limit: 100 });
const adminRole = result.roles.find(role => role.name === "Administrator");
console.log(adminRole.permissions);  // List of permissions

Filter System Roles

// Get all roles and filter for system roles
const result = await getRoles(context, { limit: 100 });
const systemRoles = result.roles.filter(role => role.readonly);
const customRoles = result.roles.filter(role => !role.readonly);

With Total Count

const result = await getRoles(context, {
  limit: 10,
  includeTotal: true
});

console.log(`Account has ${result.pagination.total} total roles`);

Implementation Details

Data Transformation

The tool transforms Firestore documents by:

  1. Adding the document id and full path
  2. Converting updatedAt timestamp to Date object
  3. Preserving all other fields as-is
const transformRole = (doc) => {
  const data = doc.data();
  return {
    id: doc.id,
    path: doc.ref.path,
    ...data,
    updatedAt: safeToDate(data.updatedAt) || data.updatedAt,
  };
};

Default Ordering

By default, roles are ordered by name in ascending order for alphabetical listing.

Read-Only Roles

Roles with readonly: true are system-defined roles that cannot be modified or deleted. These typically include:

Custom roles created by account administrators have readonly: false.

Error Handling

Common Errors

Error Cause Solution
“Error fetching roles: [message]” Firestore query failed Check Firebase connection and permissions
Validation error Invalid input parameters Ensure parameters match the input schema
Authentication error Invalid auth token Verify authentication is successful

Error Response

Errors are logged and re-thrown with the original message:

catch (error) {
  console.error("Error fetching roles:", error);
  throw new Error(error.message);
}

Performance Considerations

  1. Small Dataset: Most accounts have fewer than 20 roles
  2. Full Retrieval: Consider fetching all roles at once (limit: 100)
  3. Caching: Roles change infrequently and can be cached
  4. Total Count: Usually not necessary due to small dataset size

Firestore Collection Structure

/Accounts/{accountId}/Roles/{roleId}
  - name: string
  - permissions: string[]
  - readonly: boolean
  - updatedAt: timestamp

Permissions

Common permission strings include:

Use Cases

  1. Role Management: List all available roles for administration
  2. Permission Setup: Configure permissions for custom roles
  3. User Assignment: Display role options when creating/editing users
  4. Access Control: Check available permissions for authorization logic
  5. Audit: Track role definitions and changes over time

Example: Role-Based Access Control

// Get user and their role
const users = await getUsers(context, { limit: 1 });
const user = users.users[0];

// Get role definition
const roles = await getRoles(context, { limit: 100 });
const userRole = roles.roles.find(role => role.id === user.role);

// Check permission
const canEditCustomers = userRole.permissions.includes("customers.edit");
console.log(`User can edit customers: ${canEditCustomers}`);

See Also