Files
mcp-outline-postgresql/src/tools/users.ts
Emanuel Almeida 6f5d17516b fix: Adapt SQL queries to actual Outline database schema
- Users: Use role enum instead of isAdmin/isViewer/isSuspended booleans
- Users: Remove non-existent username column
- Groups: Fix group_users table (no deletedAt, composite PK)
- Attachments: Remove url and deletedAt columns, use hard delete

All 10/10 core queries now pass validation.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 13:32:41 +00:00

652 lines
16 KiB
TypeScript

/**
* MCP Outline PostgreSQL - Users Tools
* @author Descomplicar® | @link descomplicar.pt | @copyright 2026
*/
import { Pool } from 'pg';
import { BaseTool, ToolResponse, UserArgs, GetUserArgs, CreateUserArgs, UpdateUserArgs } from '../types/tools.js';
import { validatePagination, isValidUUID, isValidEmail, sanitizeInput } from '../utils/security.js';
/**
* users.list - List users with filtering
*/
const listUsers: BaseTool<UserArgs> = {
name: 'outline_list_users',
description: 'List users with optional filtering by query string, role, or status. Supports pagination and returns user profiles including roles and suspension status.',
inputSchema: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Search query to filter users by name or email',
},
filter: {
type: 'string',
enum: ['all', 'admins', 'members', 'suspended', 'invited'],
description: 'Filter users by role or status',
},
limit: {
type: 'number',
description: 'Maximum number of results to return (max 100)',
default: 25,
},
offset: {
type: 'number',
description: 'Number of results to skip for pagination',
default: 0,
},
},
},
handler: async (args, pgClient): Promise<ToolResponse> => {
const { limit, offset } = validatePagination(args.limit, args.offset);
const query = args.query ? sanitizeInput(args.query) : undefined;
const filter = args.filter || 'all';
let whereConditions = ['u."deletedAt" IS NULL'];
const queryParams: any[] = [limit, offset];
let paramIndex = 3;
// Add search query filter
if (query) {
whereConditions.push(`(LOWER(u.name) LIKE LOWER($${paramIndex}) OR LOWER(u.email) LIKE LOWER($${paramIndex}))`);
queryParams.push(`%${query}%`);
paramIndex++;
}
// Add role/status filters
switch (filter) {
case 'admins':
whereConditions.push("u.role = 'admin'");
break;
case 'members':
whereConditions.push("u.role = 'member'");
break;
case 'suspended':
whereConditions.push('u."suspendedAt" IS NOT NULL');
break;
case 'invited':
whereConditions.push('u."lastSignedInAt" IS NULL');
break;
}
const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';
const result = await pgClient.query(
`
SELECT
u.id,
u.email,
u.name,
u."avatarUrl",
u.language,
u.preferences,
u."notificationSettings",
u.timezone,
u.role,
u."lastActiveAt",
u."lastSignedInAt",
u."suspendedAt",
u."suspendedById",
u."teamId",
u."createdAt",
u."updatedAt",
t.name as "teamName",
(SELECT COUNT(*) FROM users u2 WHERE u2."deletedAt" IS NULL) as total
FROM users u
LEFT JOIN teams t ON u."teamId" = t.id
${whereClause}
ORDER BY u."createdAt" DESC
LIMIT $1 OFFSET $2
`,
queryParams
);
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: {
users: result.rows,
total: result.rows.length > 0 ? parseInt(result.rows[0].total) : 0,
limit,
offset,
},
},
null,
2
),
},
],
};
},
};
/**
* users.info - Get user details by ID
*/
const getUser: BaseTool<GetUserArgs> = {
name: 'outline_get_user',
description: 'Get detailed information about a specific user by their ID. Returns full user profile including preferences, permissions, and activity.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const result = await pgClient.query(
`
SELECT
u.id,
u.email,
u.name,
u."avatarUrl",
u.language,
u.preferences,
u."notificationSettings",
u.timezone,
u.role,
u."lastActiveAt",
u."lastSignedInAt",
u."suspendedAt",
u."suspendedById",
u."teamId",
u."createdAt",
u."updatedAt",
t.name as "teamName",
suspender.name as "suspendedByName",
(SELECT COUNT(*) FROM documents WHERE "createdById" = u.id AND "deletedAt" IS NULL) as "documentCount",
(SELECT COUNT(*) FROM collections WHERE "createdById" = u.id AND "deletedAt" IS NULL) as "collectionCount"
FROM users u
LEFT JOIN teams t ON u."teamId" = t.id
LEFT JOIN users suspender ON u."suspendedById" = suspender.id
WHERE u.id = $1 AND u."deletedAt" IS NULL
`,
[args.id]
);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
},
null,
2
),
},
],
};
},
};
/**
* users.create - Create new user
*/
const createUser: BaseTool<CreateUserArgs> = {
name: 'outline_create_user',
description: 'Create a new user with specified name, email, and optional role. User will be added to the team associated with the database.',
inputSchema: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'Full name of the user',
},
email: {
type: 'string',
description: 'Email address (must be unique)',
},
role: {
type: 'string',
enum: ['admin', 'member', 'viewer'],
description: 'User role (default: member)',
default: 'member',
},
},
required: ['name', 'email'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
const name = sanitizeInput(args.name);
const email = sanitizeInput(args.email);
const role = args.role || 'member';
if (!isValidEmail(email)) {
throw new Error('Invalid email format');
}
// Check if user already exists
const existingUser = await pgClient.query(
`SELECT id FROM users WHERE email = $1`,
[email]
);
if (existingUser.rows.length > 0) {
throw new Error('User with this email already exists');
}
// Get team ID (assuming first team, adjust as needed)
const teamResult = await pgClient.query(`SELECT id FROM teams LIMIT 1`);
if (teamResult.rows.length === 0) {
throw new Error('No team found');
}
const teamId = teamResult.rows[0].id;
const result = await pgClient.query(
`
INSERT INTO users (
id, email, name, "teamId", role,
"createdAt", "updatedAt"
)
VALUES (
gen_random_uuid(), $1, $2, $3, $4,
NOW(), NOW()
)
RETURNING *
`,
[email, name, teamId, role]
);
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User created successfully',
},
null,
2
),
},
],
};
},
};
/**
* users.update - Update user details
*/
const updateUser: BaseTool<UpdateUserArgs> = {
name: 'outline_update_user',
description: 'Update user profile information such as name, avatar, or language preferences.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID',
},
name: {
type: 'string',
description: 'Updated full name',
},
avatar_url: {
type: 'string',
description: 'URL to avatar image',
},
language: {
type: 'string',
description: 'Language code (e.g., en_US, pt_PT)',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const updates: string[] = [];
const values: any[] = [];
let paramIndex = 1;
if (args.name !== undefined) {
updates.push(`name = $${paramIndex++}`);
values.push(sanitizeInput(args.name));
}
if (args.avatar_url !== undefined) {
updates.push(`"avatarUrl" = $${paramIndex++}`);
values.push(sanitizeInput(args.avatar_url));
}
if (args.language !== undefined) {
updates.push(`language = $${paramIndex++}`);
values.push(sanitizeInput(args.language));
}
if (updates.length === 0) {
throw new Error('No updates provided');
}
updates.push(`"updatedAt" = NOW()`);
values.push(args.id);
const result = await pgClient.query(
`
UPDATE users
SET ${updates.join(', ')}
WHERE id = $${paramIndex} AND "deletedAt" IS NULL
RETURNING *
`,
values
);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User updated successfully',
},
null,
2
),
},
],
};
},
};
/**
* users.delete - Soft delete user
*/
const deleteUser: BaseTool<GetUserArgs> = {
name: 'outline_delete_user',
description: 'Soft delete a user. This marks the user as deleted but preserves their data for audit purposes.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID to delete',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const result = await pgClient.query(
`
UPDATE users
SET "deletedAt" = NOW()
WHERE id = $1 AND "deletedAt" IS NULL
RETURNING id, email, name
`,
[args.id]
);
if (result.rows.length === 0) {
throw new Error('User not found or already deleted');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User deleted successfully',
},
null,
2
),
},
],
};
},
};
/**
* users.suspend - Suspend user account
*/
const suspendUser: BaseTool<GetUserArgs> = {
name: 'outline_suspend_user',
description: 'Suspend a user account. Suspended users cannot access the system but their data is preserved.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID to suspend',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const result = await pgClient.query(
`
UPDATE users
SET "suspendedAt" = NOW()
WHERE id = $1 AND "deletedAt" IS NULL
RETURNING id, email, name, "suspendedAt"
`,
[args.id]
);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User suspended successfully',
},
null,
2
),
},
],
};
},
};
/**
* users.activate - Activate suspended user
*/
const activateUser: BaseTool<GetUserArgs> = {
name: 'outline_activate_user',
description: 'Reactivate a suspended user account, restoring their access to the system.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID to activate',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const result = await pgClient.query(
`
UPDATE users
SET "suspendedAt" = NULL, "suspendedById" = NULL
WHERE id = $1 AND "deletedAt" IS NULL
RETURNING id, email, name, "suspendedAt"
`,
[args.id]
);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User activated successfully',
},
null,
2
),
},
],
};
},
};
/**
* users.promote - Promote user to admin
*/
const promoteUser: BaseTool<GetUserArgs> = {
name: 'outline_promote_user',
description: 'Promote a user to admin role, granting them full administrative permissions.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID to promote',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const result = await pgClient.query(
`
UPDATE users
SET role = 'admin', "updatedAt" = NOW()
WHERE id = $1 AND "deletedAt" IS NULL
RETURNING id, email, name, role
`,
[args.id]
);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User promoted to admin successfully',
},
null,
2
),
},
],
};
},
};
/**
* users.demote - Demote admin to member
*/
const demoteUser: BaseTool<GetUserArgs> = {
name: 'outline_demote_user',
description: 'Demote an admin user to regular member role, removing administrative permissions.',
inputSchema: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'User UUID to demote',
},
},
required: ['id'],
},
handler: async (args, pgClient): Promise<ToolResponse> => {
if (!isValidUUID(args.id)) {
throw new Error('Invalid user ID format. Must be a valid UUID.');
}
const result = await pgClient.query(
`
UPDATE users
SET role = 'member', "updatedAt" = NOW()
WHERE id = $1 AND "deletedAt" IS NULL
RETURNING id, email, name, role
`,
[args.id]
);
if (result.rows.length === 0) {
throw new Error('User not found');
}
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
data: result.rows[0],
message: 'User demoted to member successfully',
},
null,
2
),
},
],
};
},
};
// Export all user tools
export const usersTools: BaseTool<any>[] = [
listUsers,
getUser,
createUser,
updateUser,
deleteUser,
suspendUser,
activateUser,
promoteUser,
demoteUser,
];