From 106952fcbc3f8ef085495c02fb94154d7371189b Mon Sep 17 00:00:00 2001 From: Chris Pyle Date: Sat, 21 Nov 2026 13:53:32 -0500 Subject: [PATCH 1/3] allow authentication on admin api keys via slack userid --- .../src/services/api-tokens.services.ts | 64 ++++++++++++++-- src/backend/src/utils/mcp-auth.utils.ts | 20 ++++- src/backend/tests/unit/api-tokens.test.ts | 76 ++++++++++++++++++- 3 files changed, 152 insertions(+), 8 deletions(-) diff --git a/src/backend/src/services/api-tokens.services.ts b/src/backend/src/services/api-tokens.services.ts index 86f93aa6f1..05e635d4e1 100644 --- a/src/backend/src/services/api-tokens.services.ts +++ b/src/backend/src/services/api-tokens.services.ts @@ -1,5 +1,5 @@ import { Organization, User as PrismaUser } from '@prisma/client'; -import { ApiTokenMetadata, GeneratedApiToken, notGuest, User } from 'shared'; +import { ApiTokenMetadata, GeneratedApiToken, isAdmin, notGuest, User } from 'shared'; import prisma from '../prisma/prisma.js'; import { AccessDeniedException, @@ -49,6 +49,36 @@ const getSoleOrganization = async (userId: string): Promise => { return organization; }; +/** + * Resolves the FinishLine user a Slack bot is acting on behalf of. + * + * Slack ids are only unique per workspace and nothing stops two users from entering the same id, so + * the lookup is scoped to the organization and must match exactly one user rather than picking one. + * + * @param slackUserId the Slack user id of the person who messaged the bot + * @param organizationId the organization the admin token resolved to + * @returns the matching user + * @throws if no user, or more than one user, in the organization has that Slack id + */ +const getUserBySlackId = async (slackUserId: string, organizationId: string): Promise => { + const users = await prisma.user.findMany({ + where: { + userSettings: { slackId: slackUserId }, + organizations: { some: { organizationId } } + }, + take: 2 + }); + + if (users.length === 0) { + throw new HttpException(401, 'Authentication Failed: No user in this organization is linked to that Slack id!'); + } + if (users.length > 1) { + throw new HttpException(401, 'Authentication Failed: Multiple users in this organization are linked to that Slack id!'); + } + + return users[0]; +}; + export default class ApiTokenService { /** * Gets the metadata for the given user's active API token, if they have one. @@ -96,14 +126,22 @@ export default class ApiTokenService { * The guest check runs on every call, so demoting someone to guest revokes their token's access * immediately rather than whenever the token is next rotated. * + * When a Slack user id is given, the request is being made by a shared bot on behalf of that Slack + * user. The token must then belong to an admin of the organization (anything else fails outright, + * never falling back to the token's own user), and the request runs as the organization member + * linked to that Slack id instead of as the token's owner. + * * @param token the raw API token the client sent * @param organizationId the organization the client asked for, or undefined to use the user's only organization - * @returns the token's user and the organization to scope the request to - * @throws if the token is missing, unknown, or revoked, the organization can't be resolved, or the user is a guest + * @param slackUserId the Slack user id the bot is acting for, or undefined for a normal token request + * @returns the user to act as and the organization to scope the request to + * @throws if the token is missing, unknown, or revoked, the organization can't be resolved, the user + * is a guest, or a Slack user id was given and the token isn't an admin's or the id doesn't resolve */ static async authenticateApiToken( token: string | undefined, - organizationId: string | undefined + organizationId: string | undefined, + slackUserId?: string ): Promise<{ user: PrismaUser; organization: Organization }> { if (!token) throw new HttpException(401, 'Authentication Failed: No API token provided!'); @@ -129,6 +167,22 @@ export default class ApiTokenService { .update({ where: { apiTokenId: apiToken.apiTokenId }, data: { lastUsedAt: new Date() } }) .catch(() => {}); - return { user, organization }; + if (slackUserId === undefined) return { user, organization }; + + // a header that was sent but is blank must not fall through to acting as the admin, and an empty + // string would otherwise match every user who never set a Slack id (the column defaults to '') + const trimmedSlackUserId = slackUserId.trim(); + if (!trimmedSlackUserId) throw new HttpException(401, 'Authentication Failed: Empty Slack user id!'); + + const isTokenAdmin = await userHasPermission(user.userId, organization.organizationId, isAdmin); + if (!isTokenAdmin) throw new AccessDeniedException('only admin API tokens can act on behalf of a Slack user'); + + const slackUser = await getUserBySlackId(trimmedSlackUserId, organization.organizationId); + + // the impersonated user is held to the same rule as a token owner + const slackUserHasPermission = await userHasPermission(slackUser.userId, organization.organizationId, notGuest); + if (!slackUserHasPermission) throw new AccessDeniedException('guests cannot use the API'); + + return { user: slackUser, organization }; } } diff --git a/src/backend/src/utils/mcp-auth.utils.ts b/src/backend/src/utils/mcp-auth.utils.ts index 08a39085d8..2856252cc6 100644 --- a/src/backend/src/utils/mcp-auth.utils.ts +++ b/src/backend/src/utils/mcp-auth.utils.ts @@ -1,24 +1,40 @@ import { NextFunction, Request, Response } from 'express'; import ApiTokenService from '../services/api-tokens.services.js'; -import { AccessDeniedException } from './errors.utils.js'; +import { AccessDeniedException, HttpException } from './errors.utils.js'; /** The header an API client sends its token in. */ const API_KEY_HEADER = 'x-api-key'; +/** + * The header a shared bot (the Slack bot) sends with an admin token to act as a specific Slack user. + * Node lowercases incoming header names, so this matches regardless of the casing the client used. + */ +const SLACKBOT_USER_ID_HEADER = 'x-slackbot-user-id'; + /** * Authenticates a request using a per-user API token instead of the session cookie. * * Populates req.currentUser and req.organization exactly like getUserAndOrganization does, so * downstream services are indistinguishable from the ones the cookie authenticated API calls. + * + * If an x-slackbot-user-id header is present, the token must be an admin's and the request runs as the + * organization member linked to that Slack id (see ApiTokenService.authenticateApiToken). */ export const requireApiToken = async (req: Request, _res: Response, next: NextFunction) => { try { const tokenHeader = req.headers[API_KEY_HEADER]; const organizationHeader = req.headers.organizationid; + const slackUserHeader = req.headers[SLACKBOT_USER_ID_HEADER]; + + // a repeated header arrives as an array; treat that as ambiguous rather than picking one + if (Array.isArray(slackUserHeader)) { + throw new HttpException(401, 'Authentication Failed: Multiple Slack user ids provided!'); + } const { user, organization } = await ApiTokenService.authenticateApiToken( typeof tokenHeader === 'string' ? tokenHeader.trim() : undefined, - typeof organizationHeader === 'string' ? organizationHeader : undefined + typeof organizationHeader === 'string' ? organizationHeader : undefined, + slackUserHeader ); req.currentUser = user; diff --git a/src/backend/tests/unit/api-tokens.test.ts b/src/backend/tests/unit/api-tokens.test.ts index 59744c3246..d68df79b8b 100644 --- a/src/backend/tests/unit/api-tokens.test.ts +++ b/src/backend/tests/unit/api-tokens.test.ts @@ -1,6 +1,14 @@ import { Organization, Role_Type } from '@prisma/client'; import { createTestOrganization, createTestUser, resetUsers } from '../test-utils.js'; -import { batmanAppAdmin, theVisitorGuest } from '../test-data/users.test-data.js'; +import { + batmanAppAdmin, + member, + supermanAdmin, + supermanSettings, + theVisitorGuest, + wonderwomanGuest, + wonderwomanSettings +} from '../test-data/users.test-data.js'; import { AccessDeniedException, AccessDeniedGuestException, HttpException } from '../../src/utils/errors.utils.js'; import prisma from '../../src/prisma/prisma.js'; import ApiTokenService from '../../src/services/api-tokens.services.js'; @@ -145,4 +153,70 @@ describe('Api Token Tests', () => { ); }); }); + + describe('Authenticate Api Token On Behalf Of A Slack User', () => { + it('resolves to the organization member linked to the slack id', async () => { + const batman = await createTestUser(batmanAppAdmin, orgId); + const superman = await createTestUser(supermanAdmin, orgId, supermanSettings); + const { token } = await ApiTokenService.generateApiToken(batman, organization); + + const { user, organization: resolved } = await ApiTokenService.authenticateApiToken( + token, + undefined, + supermanSettings.slackId + ); + + expect(user.userId).toBe(superman.userId); + expect(resolved.organizationId).toBe(orgId); + }); + + it('fails outright when the token is not an admin', async () => { + const regularMember = await createTestUser(member, orgId); + await createTestUser(supermanAdmin, orgId, supermanSettings); + const { token } = await ApiTokenService.generateApiToken(regularMember, organization); + + await expect(ApiTokenService.authenticateApiToken(token, undefined, supermanSettings.slackId)).rejects.toThrow( + new AccessDeniedException('only admin API tokens can act on behalf of a Slack user') + ); + }); + + it('fails when no user in the organization has the slack id', async () => { + const batman = await createTestUser(batmanAppAdmin, orgId); + const { token } = await ApiTokenService.generateApiToken(batman, organization); + + await expect(ApiTokenService.authenticateApiToken(token, undefined, 'unknownSlackId')).rejects.toThrow( + new HttpException(401, 'Authentication Failed: No user in this organization is linked to that Slack id!') + ); + }); + + it('fails when the slack user belongs to a different organization', async () => { + const otherOrganization = await createTestOrganization(); + const batman = await createTestUser(batmanAppAdmin, orgId); + await createTestUser(supermanAdmin, otherOrganization.organizationId, supermanSettings); + const { token } = await ApiTokenService.generateApiToken(batman, organization); + + await expect(ApiTokenService.authenticateApiToken(token, orgId, supermanSettings.slackId)).rejects.toThrow( + new HttpException(401, 'Authentication Failed: No user in this organization is linked to that Slack id!') + ); + }); + + it('fails for a blank slack id rather than acting as the admin', async () => { + const batman = await createTestUser(batmanAppAdmin, orgId); + const { token } = await ApiTokenService.generateApiToken(batman, organization); + + await expect(ApiTokenService.authenticateApiToken(token, undefined, ' ')).rejects.toThrow( + new HttpException(401, 'Authentication Failed: Empty Slack user id!') + ); + }); + + it('fails when the slack user is a guest', async () => { + const batman = await createTestUser(batmanAppAdmin, orgId); + await createTestUser(wonderwomanGuest, orgId, wonderwomanSettings); + const { token } = await ApiTokenService.generateApiToken(batman, organization); + + await expect(ApiTokenService.authenticateApiToken(token, undefined, wonderwomanSettings.slackId)).rejects.toThrow( + new AccessDeniedException('guests cannot use the API') + ); + }); + }); }); From b079e0f8502675019cae8ba049dba64bc1813679 Mon Sep 17 00:00:00 2001 From: Chris Pyle Date: Sat, 21 Nov 2026 14:34:51 -0500 Subject: [PATCH 2/3] scope mcp by car --- src/backend/index.ts | 5 ++- src/backend/src/mcp/projects.tools.ts | 30 +++----------- src/backend/src/mcp/tools.utils.ts | 7 +++- src/backend/src/utils/mcp-auth.utils.ts | 6 +-- src/backend/tests/unit/api-tokens.test.ts | 11 ++++- src/backend/tests/unit/mcp-tools.test.ts | 50 +++++++++++++---------- 6 files changed, 55 insertions(+), 54 deletions(-) diff --git a/src/backend/index.ts b/src/backend/index.ts index 88e7cf0b96..9e147772ee 100644 --- a/src/backend/index.ts +++ b/src/backend/index.ts @@ -114,9 +114,10 @@ app.use('/agent', agentRouter); // The MCP endpoint, authenticated with the same per-user API tokens. JSON-RPC requires POST, so it // cannot sit behind the readOnlyGuard the /agent router uses and is mounted separately. Its tools are // registered per domain in src/mcp; tools that change data use registerWriteTool, and the services -// they call do the permission checks. +// they call do the permission checks. getCurrentCar runs after requireApiToken, since it needs the +// organization, and scopes car specific tools to the carid header the same way the app does. // The handler is async, so its rejections are forwarded to the error handler rather than dropped. -app.all('/mcp', requireApiToken, attachAuthInfo, (req, res, next) => { +app.all('/mcp', requireApiToken, getCurrentCar, attachAuthInfo, (req, res, next) => { mcpNodeHandler(req, res, req.body).catch(next); }); diff --git a/src/backend/src/mcp/projects.tools.ts b/src/backend/src/mcp/projects.tools.ts index 69372d7631..0464e7266c 100644 --- a/src/backend/src/mcp/projects.tools.ts +++ b/src/backend/src/mcp/projects.tools.ts @@ -1,25 +1,10 @@ import * as z from 'zod/v4'; import { validateWBS } from 'shared'; import ProjectsService from '../services/projects.services.js'; -import CarsService from '../services/car.services.js'; import { withToolErrors } from './errors.js'; import { LIST_PROJECTS_HINT, registerReadOnlyTool, ToolRegistrar, wbsNumSchema } from './tools.utils.js'; -export const registerProjectTools: ToolRegistrar = (server, { user, organization }) => { - registerReadOnlyTool( - server, - 'finishline_list_cars', - { - title: 'List cars', - description: - "List the organization's cars with their ids, names, and WBS numbers. The car number is the first " + - 'part of every WBS number, and the highest car number is the newest car, which is almost always ' + - 'the one the user means. Use a car id from here to filter finishline_list_projects.', - inputSchema: z.object({}) - }, - async () => withToolErrors('', async () => CarsService.getAllCars(organization)) - ); - +export const registerProjectTools: ToolRegistrar = (server, { user, organization, currentCar }) => { registerReadOnlyTool( server, 'finishline_list_projects', @@ -28,16 +13,11 @@ export const registerProjectTools: ToolRegistrar = (server, { user, organization description: 'List projects newest first, with their names, WBS numbers, summaries, status, dates, and teams. ' + 'Start here when the user names a project in words rather than by number, then match the name to ' + - 'a WBS number and use the other tools. Pass carId to only list one car; without it, projects ' + - 'from every car come back, so prefer passing the newest car from finishline_list_cars.', - inputSchema: z.object({ - carId: z - .string() - .optional() - .describe('The id of the car to list projects for, from finishline_list_cars. Omit this for every car.') - }) + 'a WBS number and use the other tools. Only the projects on the car this connection is scoped to ' + + 'come back, or every car when it is not scoped to one.', + inputSchema: z.object({}) }, - async ({ carId }) => withToolErrors('', async () => ProjectsService.getAllProjects(organization, carId)) + async () => withToolErrors('', async () => ProjectsService.getAllProjects(organization, currentCar?.carId)) ); registerReadOnlyTool( diff --git a/src/backend/src/mcp/tools.utils.ts b/src/backend/src/mcp/tools.utils.ts index 2a3ab253c6..31974a0911 100644 --- a/src/backend/src/mcp/tools.utils.ts +++ b/src/backend/src/mcp/tools.utils.ts @@ -1,4 +1,4 @@ -import { Organization } from '@prisma/client'; +import { Organization, Prisma } from '@prisma/client'; import { CallToolResult, McpServer } from '@modelcontextprotocol/server'; import * as z from 'zod/v4'; import { User } from 'shared'; @@ -7,6 +7,11 @@ import { User } from 'shared'; export interface AgentContext { user: User; organization: Organization; + /** + * The car from the request's carid header, the same global car the app scopes to. Car specific tools + * filter by it and never take a car as input; undefined means every car, as it does in the app. + */ + currentCar?: Prisma.CarGetPayload<{ include: { wbsElement: true } }>; } /** diff --git a/src/backend/src/utils/mcp-auth.utils.ts b/src/backend/src/utils/mcp-auth.utils.ts index 2856252cc6..04ac1e6541 100644 --- a/src/backend/src/utils/mcp-auth.utils.ts +++ b/src/backend/src/utils/mcp-auth.utils.ts @@ -62,15 +62,15 @@ export const readOnlyGuard = (req: Request, _res: Response, next: NextFunction) * Hands the authenticated caller to the MCP handler. * * toNodeHandler forwards req.auth to the handler as its pass-through authInfo, and AuthInfo.extra - * is the documented place for data of our own, so the MCP server factory reads the user and - * organization back out of it. Must run after requireApiToken. + * is the documented place for data of our own, so the MCP server factory reads the user, + * organization, and current car back out of it. Must run after requireApiToken and getCurrentCar. */ export const attachAuthInfo = (req: Request, _res: Response, next: NextFunction) => { req.auth = { token: '', clientId: req.currentUser.userId, scopes: [], - extra: { user: req.currentUser, organization: req.organization } + extra: { user: req.currentUser, organization: req.organization, currentCar: req.currentCar } }; return next(); diff --git a/src/backend/tests/unit/api-tokens.test.ts b/src/backend/tests/unit/api-tokens.test.ts index d68df79b8b..315e765944 100644 --- a/src/backend/tests/unit/api-tokens.test.ts +++ b/src/backend/tests/unit/api-tokens.test.ts @@ -190,8 +190,17 @@ describe('Api Token Tests', () => { }); it('fails when the slack user belongs to a different organization', async () => { - const otherOrganization = await createTestOrganization(); const batman = await createTestUser(batmanAppAdmin, orgId); + // created inline rather than with createTestOrganization, which always uses the same unique creator and slug + const otherOrganization = await prisma.organization.create({ + data: { + name: 'Other Org', + slug: 'other-org', + description: 'A second organization', + applicationLink: '', + userCreated: { connect: { userId: batman.userId } } + } + }); await createTestUser(supermanAdmin, otherOrganization.organizationId, supermanSettings); const { token } = await ApiTokenService.generateApiToken(batman, organization); diff --git a/src/backend/tests/unit/mcp-tools.test.ts b/src/backend/tests/unit/mcp-tools.test.ts index 296090d36d..b776db5e52 100644 --- a/src/backend/tests/unit/mcp-tools.test.ts +++ b/src/backend/tests/unit/mcp-tools.test.ts @@ -14,6 +14,7 @@ import prisma from '../../src/prisma/prisma.js'; import ApiTokenService from '../../src/services/api-tokens.services.js'; import { mcpNodeHandler } from '../../src/mcp/handler.js'; import { attachAuthInfo, requireApiToken } from '../../src/utils/mcp-auth.utils.js'; +import { getCurrentCar } from '../../src/utils/car.utils.js'; import { errorHandler } from '../../src/utils/errors.utils.js'; /** @@ -42,7 +43,7 @@ describe('MCP Tools', () => { // mounted the way index.ts does app = express(); app.use(express.json()); - app.all('/mcp', requireApiToken, attachAuthInfo, (req, res, next) => { + app.all('/mcp', requireApiToken, getCurrentCar, attachAuthInfo, (req, res, next) => { mcpNodeHandler(req, res, req.body).catch(next); }); app.use(errorHandler); @@ -52,20 +53,23 @@ describe('MCP Tools', () => { await resetUsers(); }); - /** Sends one JSON-RPC request to /mcp and returns its result, whether it came back as JSON or SSE. */ - const rpc = async (method: string, params: object, token: string = adminToken) => { - const res = await request(app) + /** Sends one JSON-RPC request to /mcp as the admin, with any extra headers such as carid. */ + const post = (method: string, params: object, headers: Record = {}) => + request(app) .post('/mcp') - .set('x-api-key', token) - .set('Accept', 'application/json, text/event-stream') + .set({ 'x-api-key': adminToken, Accept: 'application/json, text/event-stream', ...headers }) .send({ jsonrpc: '2.0', id: 1, method, params }); + + /** Sends one JSON-RPC request to /mcp and returns its result, whether it came back as JSON or SSE. */ + const rpc = async (method: string, params: object, headers?: Record) => { + const res = await post(method, params, headers); const sseData = res.text.split('\n').find((line) => line.startsWith('data: ')); return (sseData ? JSON.parse(sseData.slice('data: '.length)) : res.body).result; }; /** Calls a tool and returns its parsed JSON payload, or the raw result when the call failed. */ - const callTool = async (name: string, args: object, token?: string) => { - const result = await rpc('tools/call', { name, arguments: args }, token); + const callTool = async (name: string, args: object, headers?: Record) => { + const result = await rpc('tools/call', { name, arguments: args }, headers); return { result, data: result.isError ? undefined : JSON.parse(result.content[0].text) }; }; @@ -95,35 +99,24 @@ describe('MCP Tools', () => { 'finishline_get_events', 'finishline_get_project', 'finishline_get_tasks', - 'finishline_list_cars', 'finishline_list_projects' ]); }); - describe('List Cars', () => { - it("lists the organization's cars", async () => { - await createTestCar(orgId, admin.userId, 2); - - const { data } = await callTool('finishline_list_cars', {}); - - expect(data.map((car: { wbsNum: { carNumber: number } }) => car.wbsNum.carNumber).sort()).toEqual([1, 2]); - }); - }); - describe('List Projects', () => { - it('lists only the requested car', async () => { + it('lists only the car from the carid header', async () => { const newerCarId = (await createTestCar(orgId, admin.userId, 2)).carId; await makeProject(1); await makeProject(1, newerCarId, 2); - const { data } = await callTool('finishline_list_projects', { carId: newerCarId }); + const { data } = await callTool('finishline_list_projects', {}, { carid: newerCarId }); expect(data.map((project: { wbsNum: object }) => project.wbsNum)).toEqual([ { carNumber: 2, projectNumber: 1, workPackageNumber: 0 } ]); }); - it('lists every car when no car is given', async () => { + it('lists every car when no carid header is sent', async () => { const newerCarId = (await createTestCar(orgId, admin.userId, 2)).carId; await makeProject(1); await makeProject(1, newerCarId, 2); @@ -132,6 +125,19 @@ describe('MCP Tools', () => { expect(data).toHaveLength(2); }); + + it('does not take a car as input', async () => { + const { tools } = await rpc('tools/list', {}); + const tool = tools.find((candidate: { name: string }) => candidate.name === 'finishline_list_projects'); + + expect(tool.inputSchema.properties ?? {}).toEqual({}); + }); + + it('rejects a carid header for a car outside the organization', async () => { + const res = await post('tools/call', { name: 'finishline_list_projects', arguments: {} }, { carid: 'not-a-car' }); + + expect(res.status).toBe(404); + }); }); describe('Get Project', () => { From 760fac13aa2760d6dbee4c47020e7f04d07e8fc0 Mon Sep 17 00:00:00 2001 From: Chris Pyle Date: Sat, 21 Nov 2026 14:51:24 -0500 Subject: [PATCH 3/3] slackid tool --- src/backend/src/mcp/server.ts | 3 +- src/backend/src/mcp/users.tools.ts | 34 ++++++++++++++++++++ src/backend/tests/unit/mcp-tools.test.ts | 41 +++++++++++++++++++++++- 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 src/backend/src/mcp/users.tools.ts diff --git a/src/backend/src/mcp/server.ts b/src/backend/src/mcp/server.ts index 39f581b582..38546f3d76 100644 --- a/src/backend/src/mcp/server.ts +++ b/src/backend/src/mcp/server.ts @@ -3,9 +3,10 @@ import { AgentContext, ToolRegistrar } from './tools.utils.js'; import { registerProjectTools } from './projects.tools.js'; import { registerTaskTools } from './tasks.tools.js'; import { registerEventTools } from './events.tools.js'; +import { registerUserTools } from './users.tools.js'; /** Every domain's tools. A new *.tools.ts file only becomes reachable once it is added here. */ -const registrars: ToolRegistrar[] = [registerProjectTools, registerTaskTools, registerEventTools]; +const registrars: ToolRegistrar[] = [registerProjectTools, registerTaskTools, registerEventTools, registerUserTools]; /** * Builds a FinishLine MCP server for one authenticated caller. Called once per request, so nothing diff --git a/src/backend/src/mcp/users.tools.ts b/src/backend/src/mcp/users.tools.ts new file mode 100644 index 0000000000..c41777e595 --- /dev/null +++ b/src/backend/src/mcp/users.tools.ts @@ -0,0 +1,34 @@ +import * as z from 'zod/v4'; +import UsersService from '../services/users.services.js'; +import { withToolErrors } from './errors.js'; +import { registerReadOnlyTool, ToolRegistrar } from './tools.utils.js'; + +export const registerUserTools: ToolRegistrar = (server, { organization }) => { + registerReadOnlyTool( + server, + 'finishline_get_user_slack_id', + { + title: 'Get user Slack id', + description: + "Get a FinishLine user's Slack member id so you can mention them in Slack. Users returned by the " + + 'other tools (leads, managers, assignees, event creators) carry a userId to pass here.\n\n' + + 'Whenever you refer to a person in a Slack message, prefer mentioning them over writing their name: ' + + 'look up their slackId here and write it as <@SLACK_ID>, for example <@U0123456789>, which Slack ' + + 'renders as a mention that notifies them. Use the slackId exactly as returned, inside the angle ' + + 'brackets with the @, and never the FinishLine userId. slackId is absent when the user has not ' + + 'linked their Slack account; only then fall back to writing their first and last name as plain text.', + inputSchema: z.object({ + userId: z.string().min(1).describe('The userId of a user returned by another FinishLine tool.') + }) + }, + async ({ userId }) => + withToolErrors('Pass a userId returned by another FinishLine tool.', async () => { + // getSingleUser is what confirms the user is in this organization; getUserSettings alone is not scoped + await UsersService.getSingleUser(userId, organization); + const { slackId } = await UsersService.getUserSettings(userId); + + // slackId defaults to an empty string, which means the user never linked Slack + return { userId, slackId: slackId || undefined }; + }) + ); +}; diff --git a/src/backend/tests/unit/mcp-tools.test.ts b/src/backend/tests/unit/mcp-tools.test.ts index b776db5e52..9f4ff43f54 100644 --- a/src/backend/tests/unit/mcp-tools.test.ts +++ b/src/backend/tests/unit/mcp-tools.test.ts @@ -9,7 +9,7 @@ import { createTestWorkPackage, resetUsers } from '../test-utils.js'; -import { batmanAppAdmin } from '../test-data/users.test-data.js'; +import { batmanAppAdmin, supermanAdmin, supermanSettings, wonderwomanGuest } from '../test-data/users.test-data.js'; import prisma from '../../src/prisma/prisma.js'; import ApiTokenService from '../../src/services/api-tokens.services.js'; import { mcpNodeHandler } from '../../src/mcp/handler.js'; @@ -99,6 +99,7 @@ describe('MCP Tools', () => { 'finishline_get_events', 'finishline_get_project', 'finishline_get_tasks', + 'finishline_get_user_slack_id', 'finishline_list_projects' ]); }); @@ -314,4 +315,42 @@ describe('MCP Tools', () => { expect(result.content[0].text).toContain('after startPeriod'); }); }); + + describe('Get User Slack Id', () => { + it("returns a user's linked slack id", async () => { + const superman = await createTestUser(supermanAdmin, orgId, supermanSettings); + + const { data } = await callTool('finishline_get_user_slack_id', { userId: superman.userId }); + + expect(data).toEqual({ userId: superman.userId, slackId: supermanSettings.slackId }); + }); + + it('leaves slackId out for a user who never linked slack', async () => { + const wonderwoman = await createTestUser(wonderwomanGuest, orgId); + + const { data } = await callTool('finishline_get_user_slack_id', { userId: wonderwoman.userId }); + + expect(data).toEqual({ userId: wonderwoman.userId }); + }); + + it('does not reveal users outside the organization', async () => { + // created inline rather than with createTestOrganization, which always uses the same unique creator and slug + const otherOrganization = await prisma.organization.create({ + data: { + name: 'Other Org', + slug: 'other-org', + description: 'A second organization', + applicationLink: '', + userCreated: { connect: { userId: admin.userId } } + } + }); + const outsider = await createTestUser(supermanAdmin, otherOrganization.organizationId, supermanSettings); + + const { result } = await callTool('finishline_get_user_slack_id', { userId: outsider.userId }); + + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain('not found'); + expect(result.content[0].text).not.toContain(supermanSettings.slackId); + }); + }); });